低效的 Ruby 方法命名:将名称空间作为参数传递作为调用方法的方式
在 Ruby 中必须有一种更有效的方法来做到这一点。我有一个方法列表,可以在多个网站上抓取相同的内容(标题、价格),但根据每个商店的代码,以稍微不同的方式。例如:
def store1_get_title
def store1_get_price
def store2_get_title
def store2_get_price
def store3_get_title
def store3_get_price
当调用所有这些函数时,我只需要一个带有“命名空间”参数的通用调用来调用这些方法中的任何一个,而不必键入所有这些方法,例如:
for get_all_stores().each do |store|
store::get_title
store::get_price
end
...这将调用 store1_get_title ,store1_get_price,store2_get_title,store2_get_price 就像我想要的那样。有类似的事情或更好的方法吗?
希望这是有道理的。感谢您的任何意见!
编辑:这些任务位于 rake 任务代码中。
There has got to be a more efficient way to do this in Ruby. I have a list of methods that scrape the same things (title, price) across multiple sites but in slightly different ways based on the code in each store. For example:
def store1_get_title
def store1_get_price
def store2_get_title
def store2_get_price
def store3_get_title
def store3_get_price
When calling all of these functions, I would just like a generic call with say a "namespace" parameter to do invoke any of these methods without having to type out all of them, something like:
for get_all_stores().each do |store|
store::get_title
store::get_price
end
...which would invoke store1_get_title, store1_get_price, store2_get_title, store2_get_price like I want. Is there something like this or a better way to do this?
Hope that makes sense. Thanks for any input!
Edit: these tasks are in rake task code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是课程的完美用途。如果您发现两个商店使用相同的软件(可能是雅虎商务或 eBay 商店),您可以使用不同的参数创建类的实例。
您可以通过定义所有商店都实现/继承的基类或接口,以任何其他面向对象的语言来完成此操作。
This is a perfect use for classes. If you find two stores with the same software powering them (maybe Yahoo commerce or EBay stores) you can make instances of the classes with different parameters.
And you can do this in any other object-oriented language by defining a base class or interface that all of the stores implement/inherit.
我不明白你的申请逻辑。也许你应该考虑一个类定义(参见 Ken Blooms 的回答)。
不过,您可以尝试使用
send
进行动态调用:您没有定义
get_all_stores
返回的内容。在我的示例中,我使用了字符串。您可以添加一些语法糖并扩展字符串(我不推荐这样做)最后一点。您
单独编写
each
就足够了。for
与 ruby 不同,与each
结合使用对我来说看起来不合理。I don't understand the logic of your application. Perhaps you should think about a class definition (see Ken Blooms answer).
Nevertheless you could try a dynamic call with
send
:You didn't define what
get_all_stores
returns. In my example I used Strings. You could add some syntactical sugar and extend String (I don't recommend this)One last remark. You wrote
each
alone should be enough.for
is not ruby-like and in combination witheach
it doen't look reasonable to me.