开发者

How to store Ruby method references in a database?

I am writing my first rails app. It needs to aggregate some data from multiple sites and for each site I have a unique way of getting the data (some provide RSS, some JSON, for some I scrape the HTML etc.). These will run on schedule, probably as a rake task from cron. It seems logical to store the sites and relevant information in a model, but I am not sure where to put unique data retrieval methods. Do I store method names in开发者_开发技巧 the model? Do I just name the methods the same as site name and call them that way? Basically, I need a way to read a list of sites and call appropriate method for each site. What is the Ruby on Rails way to do it?


I'd avoid storing method names in the database; that makes refactoring difficult and could lead to maddening behavior if you ever get invalid values in that column.

Instead, just store a format string column that's readable ("rss", "json", etc.). Then you can have a single method in your model like:

def pull_data
  case format
  when 'json'
    ...
  when 'rss'
    ...
  else
    raise 'Invalid format'
  end
end

If you want to break your data-getting logic into separate methods, you can call them from this pull_data method.


Assuming you have a Site model, why not just add a new attribute to track the access method? You can do this by generating a new migration for the db alterations:

ruby script/generate migration add_access_method_to_sites # rails <= 2.3
ruby script/rails generate migration add_access_method_to_sites # rails >= 3.0
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜