How to get attribute of a model saved in instance variable
I am writing a plugin, in which i define a new relation dynamically within plugin. Sample code is given below
module AttachDocumentsAs
@as = nil
def attach_documents_as(*attachment_as)
attachment_as = attachment_as.to_a.flatten.compact.map(&:to_sym)
@as = attachment_as.first
class_inheritable_reader(@as)
class_eval do
has_many @as, :as => :attachable, :class_name=>"AttachDocuments::Models::AttachedDocument"
accepts_nested_attributes_for @a开发者_如何转开发s
end
end
end
now in any model i used it as
class Person < AtiveRecord::Base
attach_documents_as :financial_documents
end
Now want to access want to access this attribute of the class in overloaded initialize method like this
def initialize(*args)
super(*args)
"#{@as}".build
end
But it is not getting required attribute, can any one help me in it. I want to build this relation and set some initial values.
Waiting for guidelines from all you guys.
You're likely confusing the @as
class instance variable, which is only available to class methods for Person, and the @as
instance variable, which is only available to instances of this class. Even that explanation sounds a bit complicated, I know.
Each object has instance variables, and a class is simply a type of object. Instances of this class are also objects and they have their own independent instance variables. To get a class instance variable from an instance of a class you will need a reader method, like you've defined. Maybe what you mean is:
def initialize(*args)
super(*args)
# self.class.as returns something like :financial_documents, so use this method
# to return a scope to build in.
send(self.class.as).build
end
The way you're using @as
suggests you're used to something like PHP or Perl where you can de-reference it like you might with ${$as}
. In Ruby you're usually de-referencing from a string or symbol into either a class, or a method.
It looks like you're trying to convert a symbol into a method call, and that's done through send
.
If you were trying to convert a string into a class, you use the constantize
method on String, a feature of the Rails environment.
精彩评论