6

DHH wrote an article advocating for the use of concerns. It seems like a good practice, and in a lot of cases, they work well with my app. There are several cases, however, where multiple models have similar but slightly different methods, such as:

def find_or_create_membership
  user_membership = User::Membership.where(:group_id => self.group_id,
  :user_id => self.invitee_id).first_or_create(:status => "invited")
end

and:

def find_or_create_membership
  user_membership = User::Membership.where(:group_id => self.group_id,
  :user_id => self.invitee_id).first_or_create(:status => "declined")
end

These methods are identical save that the first sets status to "invited" and the second to "declined". Is there a way I could pass an argument to these methods via a concern?

nullnullnull
  • 8,039
  • 12
  • 55
  • 107
  • One thing I did for that is trying to mimic what devise is doing for instance by defining a class method that takes argument. Here is the devise example (https://github.com/plataformatec/devise/blob/master/lib/devise/models.rb#L83), and here is for instance what I did in one of my projects : https://github.com/pjambet/beech-server/blob/master/app/models/concerns/searchable.rb Please note that my way of doing my be completely wrong and stupid, this was just an attempt to mimic the devise (and others) behavior – pjam Mar 20 '13 at 16:23
  • How do you pass in the parameter? – nullnullnull Mar 20 '13 at 17:13
  • You can call the method in the class and pass arguments as you would usually do : see https://github.com/pjambet/beech-server/blob/master/app/models/user.rb#L40 – pjam Mar 20 '13 at 17:14
  • Beautiful. I'll give that shot. – nullnullnull Mar 20 '13 at 17:26
  • See also http://stackoverflow.com/questions/14300427/how-do-i-add-a-model-specific-configuration-option-to-a-rails-concern – antinome Sep 03 '14 at 17:12
  • Related: http://stackoverflow.com/questions/26900356/how-to-create-a-rails-4-concern-that-takes-an-argument – jesal Nov 13 '14 at 21:52

1 Answers1

0

You might be interested in Paramix.

Never used it myself, though. Dunno, smells like a False-Good-Idea©.

m_x
  • 12,357
  • 7
  • 46
  • 60