Domanda

I've just seen this line of Ruby code in ruby-trello:

# Returns the member who created the action.
one :member_creator, :via => Member, :using => :member_creator_id

It seems to relate to a superclass method defined as:

def self.one(name, opts = {})
  class_eval do
    define_method(:"#{name}") do |*args|
      options = opts.dup
      klass   = options.delete(:via) || Trello.const_get(name.to_s.camelize)
      ident   = options.delete(:using) || :id
      klass.find(self.send(ident))
    end
  end
end

I understand that class_eval relates to reflection.

Could someone please explain the purpose of the subclass code line?

My guess would be that it's calling the class member one passing :member_creator as name and the two trailing args as the opts argument. But why would this be called at the class level?

È stato utile?

Soluzione

It is appears to be a way to DRY up some code used to find a single record by primary key.

You basically pass a class/model name and a method used to get the primary key.

This code:

one :member_creator, :via => Member, :using => :member_creator_id

Creates this method:

def member_creator 
  Member.find(self.member_creator_id)
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top