I am using Ruby on Rails 3.0.9 and I am trying to make it possible to call some methods from all inside helper, controller, models and view files. What I would like to make is to create a library to build\standardize naming conventions internally to my application so that I can use\run something like the following:
standardized_name = standardize_name(Article)
What do you advice about?
P.S.: I have heard of mixin, but how should I use those in my case? Furthermore I would like not to state inclusion of that mixin in each class that need to use that (that is, I would like to have a “unique” statement that includes the mixin in all my application classes).
Depending on your use case, you can take one of these approaches to rather attach the method to the objects it acts on. Then you don’t need to include the
standardize_namemethod everywhere you want to use it; you just centralized it on the objects to which it applies:To use as Article.standardized_name (class method):
If your
standardize_namemethod only takes ActiveRecord models as arguments, consider putting it in a module (inlib/standardizable.rbfor example) and extending it ontoActiveRecord::Base(or some other class that is a parent to all your domain classes):Alternatively, if you don’t want to include it in all models, just include the module into the individual classes where you want
standardized_nameto be available:With both of the following approaches, you will be able to use the method like so:
To use as Article.new.standardized_name (instance method):
If you’d rather use the method on instances of your model classes, just change
extendin the above example toinclude:The usage then looks like this:
Wrapping up with ActiveSupport::Concern:
A nice way to wrap up both these approaches in Rails 3 is with
ActiveSupport::Concern:Then you can use both the class and instance method to get the standardized name: