Nic Stelter
Nic Stelter

Reputation: 661

storing a lambda in the value portion of a hash

Can anyone tell me what's going on here:

value: -> f { view_context.fr_user_column(f) }

This is from a larger hash:

def self.columns
 {
   user: {
     title: "Applicant",
     value: -> f { view_context.fr_user_column(f) }
   },
   ch_rep: {
    title: "CH Rep",
    value: -> f { view_context.fr_ch_rep_column(f) }
  }
 }

That gets used in a method to create a table:

def self.render_zable_columns(context, options = {})
 self.columns.each do |key, col|
  next if options[:except] && options[:except].include?(key)
  col_options = {title: col[:title]}
  col_options[:class] = "franchise_#{key}"
  col_options[:sort] = col.key?(:sort) ? col[:sort] : true
  if col[:value].present?
    context.send(:column, key, col_options, &col[:value])
  else
    context.send(:column, key, col_options)
  end
 end
end

The reason I ask is because I also have the CH rep which is just a different name for the User model, and I'm trying to get the table to display the CH rep (User) name but this isn't working:

value: -> f { view_context.fr_ch_rep_column(f) }

Upvotes: 1

Views: 757

Answers (1)

snowe
snowe

Reputation: 1375

This is storing a lambda in the value portion of a hash. f corresponds to the variable that will be available inside of the lambda when the lambda is called.

if col[:value].present? checks for the lambda

context.send(:column, key, col_options, &col[:value]) sends (in order)

  • column as a symbol
  • the key (i.e. ch_rep or `user)
  • column_options which includes the title and other non lambda keys/values
  • the lambda specified as the value key, to context

Upvotes: 2

Related Questions