问题
I'm developing a ruby gem for use in rails app. The gem need to "initialize" using live data from a webservice.
But this initialization is a long process, and i want to save the initialization data somewhere. Where should i save it?
I could save it in the parent rails app database, but i would need to create tables and migrations, and this isn't ideal.
I'm thinking of using a text file or redis database inside the gem folder... Is this a good practice?
Thanks.
回答1:
ActiveSupport has several Cache classes. You could for example use the default Rails.cache:
Rails.cache.write('my-gem-initialization-data', 'foo bar baz')
If you need more flexibility, you could provide an initializer, something like:
# config/initializers/my_gem.rb
MyGem.configure do |config|
config.cache = Rails.cache
config.cache_key = 'my-gem-initialization-data'
end
回答2:
I would argue that it is perfectly fine to expect the user to generate and run a migration as part of the setup of your gem.
In fact this is quite common: Look at well known gems like devise (that needs certain columns on the users table) or paper_trail (that needs a table in the database to store versions)
On the other hand your alternatives are not always feasible. You cannot expect the user to have a redis database configured (most of my apps don't use redis at all) and some environments (like Heroku for example) do not allow to write files persistently.
来源:https://stackoverflow.com/questions/40419913/how-to-persist-data-in-a-ruby-gem