2

In my application I've setup an Event system to display a log of everything that happens to a user. It uses dirty objects.

Here is what I did so far

def log_details_change(owner)
  Event.log(owner.condo, :updated_owner_details, [owner.changes.slice('first_name', 'last_name', 'email', 'start_date', 'phone_number')])
end

Now I know that the owner.changes method provides a hash that looks like that

{ 'title' => ["Title", "New Title"] }

If, for instance, I delete the phone number for the user, the hash returned by owner.changes becomes

{ 'phone_number' => ["514554541", ""] }

Basically, the changed value is empty (or blank, or nil - I don't really know).

How can I access the values in order to check if the changed value is empty? I'd like to display a string instead of a '' string.

I've tried a lot of different things, including that one below

owner.changes.slice('first_name', 'last_name', 'email', 'start_date', 'phone_number').each_value { |v,k| v.blank? or v.nil? or v.empty? ? 'nope' : v }

but it gets me nothing. Thanks for any help you could give me!

2 Answers 2

2

Can you try the following?

owner.changes.map{ |attr, changes| changes[1].blank? ? owner[attribute] = 'nope' : nil }

The longer version:

owner.changes.map do |attribute, changes|
  changes.map do |old_val, new_val| 
    owner[attribute] = 'was empty' if new_val.blank?
  end
end

Tested on my Intervention model (attribute :name):

irb(main):083:0> i = Intervention.first
irb(main):084:0> i.name
=> "création FAV poignet gauche"
irb(main):085:0> i.name = ''
irb(main):086:0> i.changes.map{ |attr, changes| changes.last.blank? ? i[attr] = 'nope' : nil }
=> ["nope"]
irb(main):087:0> i.changes
=> {"name"=>["création FAV poignet gauche", "nope"]}
irb(main):088:0> 
1
  • The only thing I had to add to make this work was this owner[attribute][1] = 'was empty' if new_val.blank?. If I didn't have [1], the code was overriding the table |old_val,new_val| with only one val - and I needed the two values (the previous one and the changed one). Thanks so much for your help in this! May 23, 2013 at 0:55
0

There are many ways to do that, there some dirty one:

Will return values as an array:

owner.changes.map{|column_name,column_change| column_change.last.blank? }
=> [true, false]

Will return hash with key as changed column and value as true/false for blank:

owner.changes.inject({}){|result,col| result[col.first] = col.last.last.blank?; result}
=> {name: true, surname: false}
1
  • Thanks so much for your help. I took the solution from @MrYoshiji but thanks a lot anyway! May 23, 2013 at 0:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.