M
Matt Todd
Given the circumstance that you don't want to explicitly predefine
your methods for properties, etc, but that you're certain your
parameters won't somehow change to affect your design, would it be
beneficial to have method_missing define the method so that
method_missing doesn't have to be called in case the property special
method is called again?
For instance...
class Person
@attributes = {}
def initialize attributes
@attributes.merge! attributes
end
def method_missing name
if @attributes.has_key? name
class_eval do
define_method(name) do |name|
@attributes[name]
end
end
else
# other magic
end
end
end
So, if I do...
p = Person.new { :name => "Papa", :age => 66, hone => "404-932-3955" }
the first time I ask for...
p.age
the method :age is created. And the next time I call it, then it just
executes the method I juist created.
So, the point in all of this (and in not using attribute accessors and
the like) is to find out if it makes sense to dynamically define
methods for accessing it on use, as opposed to by default? Is there a
real benefit? Would it just make more sense to keep using
method_missing ?
And, consider that this example is very simple, but what if there are
more advanced methods having to be created for attributes or
what-have-you (such as Person#find_by_foo_and_bar)?
Just trying to see what the community believes to be a better
practice! (Despite the recent argument against best practices.)
M.T.
your methods for properties, etc, but that you're certain your
parameters won't somehow change to affect your design, would it be
beneficial to have method_missing define the method so that
method_missing doesn't have to be called in case the property special
method is called again?
For instance...
class Person
@attributes = {}
def initialize attributes
@attributes.merge! attributes
end
def method_missing name
if @attributes.has_key? name
class_eval do
define_method(name) do |name|
@attributes[name]
end
end
else
# other magic
end
end
end
So, if I do...
p = Person.new { :name => "Papa", :age => 66, hone => "404-932-3955" }
the first time I ask for...
p.age
the method :age is created. And the next time I call it, then it just
executes the method I juist created.
So, the point in all of this (and in not using attribute accessors and
the like) is to find out if it makes sense to dynamically define
methods for accessing it on use, as opposed to by default? Is there a
real benefit? Would it just make more sense to keep using
method_missing ?
And, consider that this example is very simple, but what if there are
more advanced methods having to be created for attributes or
what-have-you (such as Person#find_by_foo_and_bar)?
Just trying to see what the community believes to be a better
practice! (Despite the recent argument against best practices.)
M.T.