Extending a ruby gem in Rails - ruby-on-rails

Let's say I have a Rails app that gets most of it's functionality from a gem (for instance, a CMS).
If I now need to add some customisation (for instance, add a property to a user) what is the best practice way of doing this? If I customise the gem, then I will have issues with updating the gem in the future.
What is the best approach to take here?

This question is quite old, but I feel it could use a bit more fleshing out. It is true that you can monkeypatch rails (and ruby) at run-time. That means it's easy to reopen a class or module and inject new code. However, this is somewhat trickier in rails due to all the dynamic class loading and unloading that goes on development mode.
I won't go into details, but you really want to put your extensions into an initializer, or a gem, since they get reloaded between requests in dev mode. If you put the code into a plugin it won't get reloaded and you'll get very mysterious errors such as "A copy of XXX has been removed from the module tree but is still active!"
The easiest thing to do is throw the code into an initializer (e.g. config/initializers/user_extensions.rb). You can just use class_eval to inject the code.
User.class_eval do
... new code ...
end
One major drawback of ruby's extensibility is tracking down where code is coming from. You might want to add some kind of log message about the extensions being loaded, so people can track it down.
Rails.logger.info "\n~~~ Loading extensions to the User model from #{ __FILE__ }\n"
User.class_eval do
... new code ...
end
Further reading:
http://airbladesoftware.com/notes/monkey-patching-a-gem-in-rails-2-3

Ruby allows you to extend classes in runtime, so you can often hack in to a library without touching the source code. Otherwise I would suggest that you download the gem, create some hooks in the library and submit that back as a patch.
Update:
Note that these customisations are application specific
Yes. What I meant was to modify the generic api in a way, such that it is possible to customise per application. For example, by allowing the user to pass a block to certain methods etc.

Related

Loading custom classes in Rails 4

I'm rewriting one old app - Rails 1.2.6 :)) - completely in Rails 4... so you can imagine the information overload.
It's going quite well so far but I'm currently struggling with one task that should be pretty obvious but it lacks proper documentation and there are just too many blogs with different solutions to this issue.
I have a custom class with custom text conversion functionality (using Redcloth, autolinker, Sanitize etc.), let's call it Textilize class. It's used in models as well as controllers so I guess the best solution would be to create a gem from it. I want to attack gem creation later though since it's just a simple one-file class.
So for now I just added textilize.rb file to /lib directory and added config.autoload_paths += %W(#{config.root}/lib).
It works fine and I can now use it in the app without requiring it in the models and controllers.
Is this a good practice in Rails 4? Is it thread-safe?
If not, is there a way to refactor it without creating a complete gem for now?
Thanks!
"Is this a good practice?" I think it is.
"Is it thread-safe?" I don't know
Any other way? I will use your solution if the lib is crossing Model and Controller and it is simple. If it get rather complex, I will create a plugin. If it is complex and can be extended to be useful on other apps, I will create a gem.

Where to put completely miscellaneous code in a Rails app

I have a rails app the works with multiple 3rd party APIs. Some of these APIs are rate limited and many have methods that can take hours to complete and you have to continually check to see if your request is ready. As such, I have built a queueing system to manage all the baggage.
Each request that goes into this queue has a JSON string that details which 3rd party API the request pertains to, which method, what arguments and a callback to handle the response. I'm going to need a good many callback methods and they handle wildly different tasks. Some update the service status of the 3rd party, some update customer information, some create another queued request to download a large CSV or parse a CSV, etc.
I'm not sure where to put all these unrelated callback methods. They are so varied and meddle with so many different models that I'm not sure it's right to put them under the QueuedRequest model (although that seems the easiest especially regarding testing). I'd like to consolidate them in a single place (again to make testing easier) so trying to shoehorn them into their related models (though often they may not be related to a model at all) isn't going to work.
A utility class of sorts seems to be the best place but where would I put that file?
Details:
Rails 3.2.6
Update: To elaborate on the answer below, what I ended up doing was putting a module of utility methods in /lib/api. I added /lib/api to my autoload_paths in /config/application.rb and, unmentioned, I created an initializer to load the module into my app for me.
/lib/api/callbacks.rb
module Callbacks
extend self
def some_method
# magic
end
end
/config/application.rb
config.autoload_paths += %W(#{config.root}/lib/api)
/config/initializers/application.rb
require 'callbacks'
Under the lib directory, and don't forget to add it to your autoload paths (or eagerload paths if your app is threadsafe!). Make a folder called api and then stick that stuff in a namespace
For example, lib/api/stack_overflow.rb
module API
class StackOverflow
# schtuff
end
end
You could always just throw it into the lib folder.
I am working on an application which queries an external API and presents the data to the user without actually saving it to the DB. There are various elements involved in this process (passing the API key and user ID to the API, validating the query parameters in the request, parsing the response, etc.) which don't have a lot to do with the actual rails application (which will be mainly focused on presenting this data to the user), so I split off all the API stuff into its own directory under lib.
By doing it this way I can test it separately from the main application, which makes for a clean separation of concerns. Also, since my classes for the library are not based on activemodel, the library can be spun off into its own gem and potentially used in other non-rails projects. I have considered, for example, switching rails for sinatra, which is easy to do given the current setup.

Helpers in rails

I'm just starting out in Rails and there's a lot I still need to learn so I'm likely to be on Stackoverflow more often than normal asking beginner Rails / Ruby questions.
I'm just trying to figure out how Helpers work in Rails. From what I've seen so far, Helpers are intended to be used with Views and not so much with your Controllers.
However I would like to make a simple function that will validate the user input given in params (check if certain params are defined and optionally check if their value is valid).
Can anyone explain to me what would be the best way of implementing this? (Keeping in mind that I will want to use this in many different controllers so it should be globally available.)
I also noticed that by default Rails does not generate a lib folder in the main application folder. Are developers to place their libs outside the app folder in the main folder, or does Rails use libraries differently?
With regards to your validation issue, it depends on what you are validating.
If the data makes up objects from your problem domain, also known as models, then you should use the built in validators from ActiveModel. This is probably what you should do, but its hard to say without knowing the exact problem. See the Rails Guides on Validations. You can tell if this is the case by asking yourself if the data that needs validation will be stored after you get it. If so, its most definitely a model. An example of this kind of data would be the title and text fields of a blog post being sent to Rails from a browser form.
If the data is something tertiary to your models, or specific to presentation, then you should be fine using helpers. You noticed that helpers are used mostly in the views, and although this is true, theres nothing stopping you from using them in the controllers, you just have to declare that you will use them using the ActiveController#helper method. Inside the ApplicationController class, a lot of devs will put helper :all to just include all the helpers in all the controllers. Once the code has been required once, it doesn't really incur that big a performance hit.
Do note that almost all incoming data can be modeled using a model. A big school of thought in the Rails world subscribes to the Fat Model idea. People say that putting as much code as possible in the model and as little in the controller as possible separates concerns properly and leads to more maintainable code. This suggests that even if you don't think the incoming data is modelable (in the sense that you can create a model to represent it), you should try to make it a model and encapsulate the logic around validating it. However, you may find that making a helper function is faster, and either will work.
Your notion of validating user input is a good one. I get the feeling that as you are new to Rails you are used to doing these things yourself, but that doesn't quite apply here. In the Rails world, a lot of the common stuff like validations is handled by the framework. You don't have to check for presence in the params array, instead you call validates_presence_of on the model and let Rails spit the error out to the user. It makes things easier in the long run if you let the framework do what it is designed to.
With regards to your question about the lib folder, it doesn't really matter. You can put miscellaneous support files and libraries in the lib folder in the root directory and they will be available for use in your application (the files in the app folder). You can also choose to abstract your code into a plugin or a gem and include it that way, which a lot of people opt to do. My suggestion for this would be to read up on the notion of gems and plugins before diving in.
Want you want is probably a custom validator (in Rails3):
http://railscasts.com/episodes/211-validations-in-rails-3
You can either add libs in a lib folder you create, or add them to config/initializers in a file you add. Files in the initializers directory are automatically loaded by Rails.

How to break rails models into modules? [duplicate]

I have a model that requires loading external data from an auxiliary source. A number of web services exist that my model can fetch the data from (swappable), but I don't want to create code that will make it difficult to change services (costs significantly differ based on variable and fixed usage and it is likely changing will be required).
I would like to create a driver to perform the interaction (and then create further custom drivers if the service requires switching). Unfortunately, due to the tight coupling of the driver and model, it does not makes sense to extract the code into a plugin or gem. I have extracted all the code into a module (see example), and currently have the code declared above my model.
module Synchronize
def refresh
self.attributes = ...
self.save
end
end
class Data < ActiveRecord::Base
include Synchronize
end
Does Rails (3.0.0) have a convention for storing modules tightly coupled with models? Should I be using a plugin to do this? Is this associated with the 'app/helpers' directory? If not, where is the most appropriate place to store the code? Thanks!
You are correct that if the module is tightly coupled to that specific model then it's not a good candidate for a gem/plugin.
app/helpers/ is for view helper methods and shouldn't contain modules that are solely for mixing into models.
One place you could put the module is within lib/. This is for code that doesn't really fit anywhere within app/ and is often the initial home of loosely coupled code before it is moved to a plugin (but that isn't a hard and fast rule). However, since your module is tightly coupled to your model, lib/ may not be the best place for it.
I know that 37signals (and others) use the concept of 'concerns' as a way of keeping related model code organised in modules. This is implemented by creating app/concerns/ and putting the modules in there. That directory is then added to the app's load path in config/application.rb (config/environment.rb for Rails 2) with:
config.load_paths += %W(#{Rails.root}/app/concerns)
The module can then be mixed into the model as normal.
Here's the original blog post about this by Jamis Buck - http://weblog.jamisbuck.org/2007/1/17/concerns-in-activerecord
Another variation of this which I personally prefer, although it doesn't involve modules, uses this plugin:
http://github.com/jakehow/concerned_with
Hope that helps.
This link has helped me out around this.
http://ander.heroku.com/2010/12/14/concerns-in-rails-3/
I have been sticking it in a model/extensions directory. The concerns directory makes sense but the word 'concerns' doesn't feel obvious to me. Maybe it will grow on me.
I also added the extensions path in the application.rb
config.autoload_paths += %W(#{config.root}/app/models/extensions)

Model Using Modules in Rails Application

I have a model that requires loading external data from an auxiliary source. A number of web services exist that my model can fetch the data from (swappable), but I don't want to create code that will make it difficult to change services (costs significantly differ based on variable and fixed usage and it is likely changing will be required).
I would like to create a driver to perform the interaction (and then create further custom drivers if the service requires switching). Unfortunately, due to the tight coupling of the driver and model, it does not makes sense to extract the code into a plugin or gem. I have extracted all the code into a module (see example), and currently have the code declared above my model.
module Synchronize
def refresh
self.attributes = ...
self.save
end
end
class Data < ActiveRecord::Base
include Synchronize
end
Does Rails (3.0.0) have a convention for storing modules tightly coupled with models? Should I be using a plugin to do this? Is this associated with the 'app/helpers' directory? If not, where is the most appropriate place to store the code? Thanks!
You are correct that if the module is tightly coupled to that specific model then it's not a good candidate for a gem/plugin.
app/helpers/ is for view helper methods and shouldn't contain modules that are solely for mixing into models.
One place you could put the module is within lib/. This is for code that doesn't really fit anywhere within app/ and is often the initial home of loosely coupled code before it is moved to a plugin (but that isn't a hard and fast rule). However, since your module is tightly coupled to your model, lib/ may not be the best place for it.
I know that 37signals (and others) use the concept of 'concerns' as a way of keeping related model code organised in modules. This is implemented by creating app/concerns/ and putting the modules in there. That directory is then added to the app's load path in config/application.rb (config/environment.rb for Rails 2) with:
config.load_paths += %W(#{Rails.root}/app/concerns)
The module can then be mixed into the model as normal.
Here's the original blog post about this by Jamis Buck - http://weblog.jamisbuck.org/2007/1/17/concerns-in-activerecord
Another variation of this which I personally prefer, although it doesn't involve modules, uses this plugin:
http://github.com/jakehow/concerned_with
Hope that helps.
This link has helped me out around this.
http://ander.heroku.com/2010/12/14/concerns-in-rails-3/
I have been sticking it in a model/extensions directory. The concerns directory makes sense but the word 'concerns' doesn't feel obvious to me. Maybe it will grow on me.
I also added the extensions path in the application.rb
config.autoload_paths += %W(#{config.root}/app/models/extensions)

Resources