Rails gem api 方法链接动态 [英] Rails gem api method chaining dynamic

查看:23
本文介绍了Rails gem api 方法链接动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 GrackleGibbon 因为它们使 api 查询变得非常简单.例如,我喜欢使用 grackle,您可以链接将插入 url 请求的方法.例如:

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

注意 .users.show 结果到 /users/show

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

推荐答案

方法链通常通过实现有两个目的的实例方法来工作:

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

  1. 改变类的一些内部状态
  2. 返回实例本身

以下是方法链指南中的示例:

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>

您可以在 方法链和Ruby 中的惰性求值.

在您的情况下,我建议使用 @resource@action 实例变量,它们由方法 users 设置分别显示.

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

这篇关于Rails gem api 方法链接动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆