ruby-on-rails-4merit-gem

Rails 4: Merit Gem: DRYing up the PointRules code?


Is there a way to DRY the PointRules class up a bit? I tried this but it didn't work:

%w(attr1 attr2 attr3).each do |attribute|
  score 10, on: 'comments#create', do |comment|
    comment.attribute.present?
  end
end

It gave me this error:

private method `attribute' called for...

FINAL EDIT:

The answer provided below works plus you can DRY your code even further by doing something like this:

%w(attr1? attr2? attr3?).each do |attr|
  score 5, on: ['comments#update', 'users#update'] do |item|
    item(attr).call
  end
  score 10, on: ['comments#create', 'users#create'] do |item|
    item(attr).call
  end
  score 15, on: ['comments#delete', 'users#delete'] do |item|
    item(attr).call
  end
end

Solution

  • Sorry for the wait :(

    Here is a solution that it might help you

    %w(attr1? attr2? attr3?).each do |attr|
      score 10, on: 'comments#create', do |comment|
        comment.method(attr).call
      end
    end
    

    Active Record adds boolean methods for all your columns, so that is why I used the question mark on the columns.

    Please let me know if you have any questions.