Re: [Rails-core] Proposal for def_method_missing in ActiveSupport

16 views
Skip to first unread message

Ryan Bigg

unread,
Aug 9, 2012, 5:42:16 PM8/9/12
to rubyonra...@googlegroups.com
-1

I don't think this feature would be useful to the majority of Rails developers out there, sorry.

You could always release it as a separate gem and get people to use it that way.

--
Ryan Bigg

On Friday, 10 August 2012 at 0:59, Stephen Touset wrote:

In several places in Rails (e.g., ActiveRecord `find_by_#{attr2}_and_#{att2}` methods), you override `method_missing` to provide functionality. In all of those places, you follow the sane approach of handling `respond_to?` as well as actually defining the method body for future callers.

I've abstracted this logic out into a project called def_method_missing[1]. Examples:

class Foo
# regexp matchers yield the MatchData to the block, so you can modify the method
# body based on the regexp
def_method_missing /bar/ do |match|
-> { match.pre_match }
end

# without a regexp matcher, the name of the method is passed to the block, allowing
# you to decide whether or not to implement the method
def_method_missing do |name|
-> { name } if name.length == 4
-> { "bang!" } if name[-1] == '!'
end
end

foo = Foo.new

# regexp-based method_missing
foo.respond_to?(:bazbar) # => true
foo.bazbar # => "baz"
foo.methods.include? /bazbaz/ # => true

# arbitrary Ruby method_missing
foo.respond_to?(:wat) # => false
foo.respond_to?(:what) # => true
foo.what # => :what
foo.methods.include?(:what) # => true

foo.bang # => :bang # matches four-character method name
foo.bang! # => "bang!" # matches last-character bang
foo.wat! # => :wat! # matches four-character method name first

Is this something you'd be willing to consider including in ActiveSupport? Obviously, I'll have to put the logic into its own Module to avoid polluting default `Object`s and `Module`s. Plus documentation/tests. The current implementation was just a concept I threw together a few months back and promptly forgot about.


--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-core/-/ICy42NxOSOAJ.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-co...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.

Stephen Touset

unread,
Aug 10, 2012, 4:45:28 PM8/10/12
to rubyonra...@googlegroups.com
Yes. However, this is something currently implemented *in* Rails already (e.g., `SomeModel#find_by_foo_and_bar_and_baz`). Rails itself could benefit from the abstraction being put into ActiveSupport.
Reply all
Reply to author
Forward
0 new messages