Mohamed El Mahallawy
Mohamed El Mahallawy

Reputation: 13842

Rails gem api method chaining dynamic

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

Upvotes: 0

Views: 268

Answers (1)

awendt
awendt

Reputation: 13633

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.

Upvotes: 1

Related Questions