I had a really hard time to tell this question, but in a nutshell, I want to do this :
Model = MyModel.new model.title = "foo bar" model.title.to_id # = & gt; "Foo_bar"
I have an ActiveRecord class for MyModel
code MyModel & lt; ActiveRecord :: Base def to_id (str) str.downcase.gsub ("", "_") Ending
But, of course, it is looking for the to_id method on the string, And I do not want to override the string, because I do not need this behavior on every string. The wire associated with MyMold can make it simple and do something like this:
model.to_id (model.title)
but it Not very Ruby.
I know I have seen examples of this type of method first, I can not track them down.
Anyone?
You can use a specific object instance with a method, module.
module ToId def to_id self.downcase.gsub "", "_" and end class MyClass def title = (value) value.extend ToId @title = value end def title @title end end M = MyClass.new m.title = "foo bar" puts m.title # => foo bar, m.title.to_id # => foo_bar
Since value .title = Method, when we increase the string string with the ToId module, the methods of "self" modules have a string, therefore, we have direct access to the string, which was passed in the .title = method, And we can manipulate it directly Are there.
All this is done without modifying the string class directly. We are only expanding the specific example that represents the title.
Comments
Post a Comment