Rails gem api method chaining dynamic

泪湿孤枕 提交于 2019-12-23 05:20:06

问题


I am a fan of Grackle and Gibbon as they make api queries very simple. I like for example that with grackle, you can chain the methods which will interpolate to the url request. For example:

client.users.show? :screen_name=>'some_user' 
#http://twitter.com/users/show.json?screen_name=some_user

Notice the .users and .show results to /users/show

How can I write code to do so? Such that I can have

Some_class.method1.method2

回答1:


Method chaining usually works by implementing instance methods that serve two purposes:

  1. change some internal state of the class
  2. return the instance itself

Here's an example from A Guide to Method Chaining:

class Person

  def name(value)
    @name = value
    self
  end

  def age(value)
    @age = value
    self
  end

end

That way, you can change the internal state while chaining methods:

> person = Person.new
# => #<Person:0x007ff202829e38>
> person.name('Baz')
# => #<Person:0x007ff202829e38 @name="Baz">
> person.name('Baz').age(21)
# => #<Person:0x007ff202829e38 @name="Baz", @age=21>

You can find more details in the post Method chaining and lazy evaluation in Ruby.

In your case, I'd suggest @resource and @action instance vars that are set by the methods users and show, respectively.



来源:https://stackoverflow.com/questions/24796143/rails-gem-api-method-chaining-dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!