0

I am creating a Stripe payment engine for the Catarse project. I have three records I need to copy from my User, who is a project owner to my User's project. But because I'm a beginner, the code looks like S&%#te!

#project_controller.rb

def create
  ...
  check_for_stripe_keys
  ....
end

def show
  ...
  check_for_stripe_keys
  ....
end

....

def check_for_stripe_keys
  if @project.stripe_userid.nil?
    @project.reload
    @project.stripe_access_token = @project.user.stripe_access_token.dup
    @project.stripe_key = @project.user.stripe_key.dup
    @project.stripe_userid = @project.user.stripe_userid.dup
  elsif @project.stripe_userid != @project.user.userid
    @project.stripe_access_token = @project.user.stripe_access_token.dup
    @project.stripe_key = @project.user.stripe_key.dup
    @project.stripe_userid = @project.user.stripe_userid.dup
  end
  @project.save
end

....

I only need those three records because my stripe code is an engine. Three things:

1) Initially I thought to user update_attributes but I don't know if its possible to use .dup in that method.

2) Is it possible to put this in a helper located in the engine thats accessible to the main_app so users don't have to edit the main_app project_controller code?

3) Is there a cleaner way to show the above .dup code? 'Cause it's fugly!

Thanks for your help!

lux
  • 37
  • 7

2 Answers2

0

Maybe something like this:

Gemfile:

  gem 'deep_cloneable'

Code:

  @user.dup :include => [:stripe_userid, :stripe_access_token, :stripe_key]

I didn't quite follow your relationships. But take a look at this answer: What is the easiest way to duplicate an activerecord record?

Here is deep_cloneable: https://github.com/moiristo/deep_cloneable

Community
  • 1
  • 1
John Naegle
  • 8,077
  • 3
  • 38
  • 47
  • Thx..my code above works for me, but I wanted to see if I could do the same in less lines for cleanliness. I'll take a look at deep_cloneable...From looking at it, I don't need to declare where @user.dup is being cloned TO (project) - just need to drop it into my project_controller or model and it will match the records? – lux Feb 19 '13 at 22:08
  • Right, it returns a new record that isn't yet committed to the database. It does return a record of the same type, so I'm not sure its exactly what you want since it looks like you are trying to copy attributes from the user to the project – John Naegle Feb 19 '13 at 22:38
0

This is a more compact way to write what you already have:

[:stripe_access_token, :stripe_key, :stripe_userid].each do |field|
  @project.send("#{field.to_s}=", @project.user.send(field).dup)
end
John Naegle
  • 8,077
  • 3
  • 38
  • 47