How to reorganize the "general" methods?

I am using Ruby on Rails 3.2.2, and I would like to “extract” some methods from my models / classes. That is, in more than one class / model, I have some methods (note: the methods are associated with user permissions and are called the “ CRUD way”), which are and work almost the same way; so I thought the DRY approach is to put these methods in a “general” module or something like that.

What is the general and proper way to achieve this? For example, where (in which directories and files) should I put the "general" code? How can I include the mentioned methods in my classes / models? what are you advising?

Note. I'm looking for a "Ruby on Rails Way to create things."

+5
source share
2 answers

One popular approach is to use ActiveSupport issues. Then you usually place the general logic in a directory app/concerns/or app/models/concerns/(depending on your preference). Illustrative example:

# app/concerns/mooable.rb
module Mooable
  extend ActiveSupport::Concern

  included do
    before_create :say_moo

    self.mooables
      where(can_moo: true)
    end
  end

  private

  def say_moo
    puts "Moo!"
  end
end

And in the model:

# app/models/cow.rb
class Cow < ActiveRecord::Base
  include Mooable
end

To make it work this way, you should add the following line to config/application.rb

config.autoload_paths += %W(#{config.root}/app/concerns)

Additional Information:

+8
source

My answer has nothing to do with RoR, but more with Ruby.

Shraing Ruby. , Ruby-, , /. lib . :

# lib/authorizable.rb

module Authorizable
  def method1
     #some logic here
  end

  def method2
     #some more logic here
  end
end

# app/models/user.rb

 class User < ActiveRecord::Base
    include Authorizable
 end

1 2, Authorizable. Ruby, , DRY .

+1

All Articles