Foolish Chap
Foolish Chap

Reputation: 765

How can I add a line to a proprietary ruby gem so it will work correctly on Heroku?

I need to add

attr_accessible :user

To the Vote model of the engagecsm gem.

See this question for why I need to do this (skip to the answer): Rails Engage! Error (Can't mass-assign protected attributes: user)

Now, usually I would just fork this on github and add the line, but there's not a github for it, plus I think it may be against the rules to put it out to the public or something. Anyways, so I have just been adding the gem on the gemfile as noted here: https://rubygems.org/gems/engagecsm

I have added that line to my local install of engagecsm by opening the gem on my local computer and typing in that line. However, I want this to work on Heroku.

Upvotes: 0

Views: 112

Answers (2)

yfeldblum
yfeldblum

Reputation: 65435

In config/application.rb:

# run before each request in dev, or during initialization in test & prod
config.to_prepare do
  # re-open the `Vote` class so we can make some changes
  Vote.class_exec do
    # the custom changes
    attr_accessible :user
  end
end

Upvotes: 1

Jim Deville
Jim Deville

Reputation: 10662

In your lib folder, create a file (my recommendation would be lib/ext/engagecms/vote.rb), and put the following:

require 'engagecms' #make this the correct require for the gem, the goal is to force the gem to load before your code

class Vote < ActiveRecord::Base # you'll need to make this declaration equal the engage one
  attr_accessible :user
end

This is monkey patching the code, so it might break in the future due to upgrades.

A better long term strategy would be to create a wrapper that converts Vote.create(params[:vote]) (with params[:vote] having your user attribute) to

user = params[:vote].delete(:user)

Vote.create(params[:vote]) do |v|
  v.user = user
end

This technique allows you to act as if it is accessible, but avoids the monkey patch, which is not a best practice due to the risk of breakage and conflicts.

Upvotes: 1

Related Questions