开发者

ruby dynamic chaining methods

开发者 https://www.devze.com 2023-01-29 08:33 出处:网络
HI I try to build some dynamic defined methods and chain some scope methods something like: define_method \"#{instance_name_method}\" do

HI

I try to build some dynamic defined methods and chain some scope methods something like:

define_method "#{instance_name_method}" do
        Kernel.const_get(model_name).___some_chaining methods basd on开发者_开发问答 condition
end

One idea for that is something like:

method_action = model_name #ex Post

['latest', 'old', 'deleted','latest_deleted','archived'].each do |prefix| 

  method_action << ".deleted"  if prefix.match('deleted') 
  method_action << ".latest"  if prefix.match('latest')
  method_action << ".old"  if prefix.match('old')

  define_method "#{prefix}_#{instance_name_method}" do
           eval( method_action)
    end


end

in post we have defiend scopes latest,old ...

Now we can call methods like:

Post.latest or Post.old_archived etc...

My questions are:

  1. Is there a better approach for doing this? (similar to active record find but without method_missing) this is kind ugly...

  2. How can I chain methods dynamically ?

I already know for send('method',var) but i don't know how to join those methods from strings based on condition...

Thanks


I'm sorry but it's difficult for me to understand exactly what you're asking. And I'm not sure you're using some terms correctly for instance what do you mean by "scope methods?" Do you mean a class method vs. an instance method? That would pertain to scope.

And when you say chain do you mean to call one method after the other? Like so?

f = Foo.new
puts f.method1(some_value).method2(some_other_value)

I will just comment that your not so dynamic part above could be written:

method_action << ".#{prefix}"

I don't see any actual chaining in your question so I'm not sure if you just mean to concatenate stings to build names dynamically. If you do in fact mean to chain methods you need to remember that you need to always return self at the end of a method you want to make chainable back to that class.

For instance:

class Foo

  def method1(value)
    puts "method1 called with #{value}"
    self
  end

  def method2(value)
    puts "method2 called with #{value}"
    self
  end

end

f = Foo.new
puts f.method1("Hello").method2("World").method1("I can").method2("do this").method2("all").method1("day!")

Would output:

method1 called with Hello
method2 called with World
method1 called with I can
method2 called with do this
method2 called with all
method1 called with day!
#<Foo:0x0000010084de50>
0

精彩评论

暂无评论...
验证码 换一张
取 消