Active record accessor best practices?

Within an ActiveRecord sub-class I have seen several ways that people
access the model attributes. As I have wandered through various
blogs, my code now uses several different methods and I’m planning on
making my code consistent but I’m curious what the “best way”
is. :slight_smile:

If I have a ‘name’ attribute on a model there are at least 4 different
ways to get it from within the class (@name is not one of them) and at
least 3 ways to set it. (i suspect there are more but these are what
I am using.)

Example…
class CreateAttributes < ActiveRecord::Migration
def self.up
create_table :attributes do |t|
t.column :name, :string
t.timestamps
end
end

def self.down
drop_table :attributes
end
end

class Attribute < ActiveRecord::Base
########## Getters ############
def name_by_self_dot
self.name or ‘unlisted’
end
def name_by_self_bracket
self[:name] or ‘unlisted’
end

def name_by_read_attribute
read_attribute(:name) or ‘unlisted’
end

def name_by_name
name or ‘unlisted’ # I assume this is just calling the name
method
end

########## Setters ############
def name_by_self_dot=(txt)
self.name = txt
end
def name_by_self_bracket=(txt)
self[:name] = txt
end

def name_by_write_attribute=(txt)
write_attribute(:name, txt)
end

def name_by_name=(txt)
name=txt # THIS DOES NOT WORK. I guess it creates a local
variable instead of calling the setter.
end
end

Anyway. Which one is best? I personally like the self.attribute way
as it is short and it also works the same if you have an instance
variable you defined with attr_accessor. Any thoughts?

Tony

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs