Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Usage of PROC objects
4 Posts
Usage of PROC objects

I'm glad you found this helpful Balaji:)

Thanks for the reply Marcin

Person
Forum Rating: 100
Sign In To Rate Post

\lib\ruby\gems\1.8\gems\activerecord-1.15.3\lib\active_record\validations.rb(from line 260):


      def evaluate_condition(condition, record)
        case condition
          when Symbol: record.send(condition)
          when String: eval(condition, binding)
          else
            if condition_block?(condition)
              condition.call(record) #!!!!!!!!!!!!!!!!!!!!
            else
              raise(
                ActiveRecordError,
                "Validations need to be either a symbol, string (to be eval'ed), proc/method, or " +
                "class implementing a static validation method"
              )
            end
          end
      end


[...]

      def validates_each(*attrs)
        options = attrs.last.is_a?(Hash) ? attrs.pop.symbolize_keys : {}
        attrs   = attrs.flatten

        # Declare the validation.
        send(validation_method(options[:on] || :save)) do |record|
          # Don't validate when there is an :if condition and that condition is false
          unless options[:if] && !evaluate_condition(options[:if], record)  #!!!!!!!!!!!!!!!!!!!!
            attrs.each do |attr|
              value = record.send(attr)
              next if value.nil? && options[:allow_nil]
              yield record, attr, value
            end
          end
        end
      end

In some of the Ruby tutorials PROC are explained as callable objects in ruby and they are not executed unless called explicitly.

Like

pr = Proc.new { puts "Hello World" }

This statement is not executed at this point

But if we do

pr.call

it results in

=> Hello World

I would like to know how this works in our model validations

suppose we have

validates_length_of :user_name, :maximum => 40,:if => Proc.new { |user| !user.user_name.blank? }

so to do this validation we have specified a condition using a Proc block but how is this Proc block called ? is the call to Proc block made internally by rails?

Person
Forum Rating: 100
Sign In To Rate Post
4 Posts
Login to add your message