Rails clone or hash?
Hey, i need to use current_user model in order to perform some calculations inside a function. Inside the function i need to do something like current_user.name = 'whatever', thus changing the current value of name.
However, i want that change to be local, only done inside that function. Since Rails uses objects though, it's a problem. So i'm thinking, what is the best thing to do ?
Maybe clone current_user to a new object and use that inside the function ? This seems expensive. Or maybe creating a hash out of a model ? And if i do that, the actual model will not be changed ?
EDIT: It seems that hash works, but there is no type associated with it, so if i do something like :
@attacker = current_user.attributes
then, to use it, i have to specify to_s like (else i get a nil error for some reason):
@attacker[:name].to_s 开发者_高级运维= 'whatever'
Parameters?
def my_f(name)
new_name = "lorem" + name
return new_name
end
Somewhere in your controller:
loremized_name = my_f(current_user.name)
If you need all of the logic in your model, the easiest way would be to simply clone it:
def local_function
user = current_user.clone
# Perform some calculations on user here
end
精彩评论