Sha256: d6d2eb34eb71345037fe7422cf64b529ce48565616d87209b44d6ec71a5e9e05

Contents?: true

Size: 1.45 KB

Versions: 10

Compression:

Stored size: 1.45 KB

Contents

module Clevic

# Format values for display / edit. Essentially a common interface
# for % for Strings and strftime for Dates and Times.
#
# includers must provide meta and display
module GenericFormat
  # Return true if the field is a date, datetime, time or timestamp.
  # If display is nil, the value is calculated, so we need
  # to check the value. Otherwise use the field metadata.
  # Cache the result for the first non-nil value.
  def is_date_time?( value )
    if value.nil?
      false
    else
      @is_date_time ||=
      if display.nil?
        [:time, :date, :datetime, :timestamp].include?( meta.type )
      else
        # it's a virtual field, so we need to use the value
        value.is_a?( Date ) || value.is_a?( Time )
      end
    end
  end

  # apply format to value. Use strftime for date_time types, or % for everything else.
  # If format is a proc, pass value to it.
  def do_generic_format( format, value )
    begin
      unless format.nil?
        if format.is_a? Proc
          format.call( value )
        else
          if is_date_time?( value )
            value.strftime( format )
          else
            format % value
          end
        end
      else
        value
      end
    rescue Exception => e
      puts "self: #{self.inspect}"
      puts "format: #{format.inspect}"
      puts "value.class: #{value.class.inspect}"
      puts "value: #{value.inspect}"
      puts e.message
      puts e.backtrace
      nil
    end
  end

end

end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
clevic-0.14.6 lib/clevic/generic_format.rb
clevic-0.14.5 lib/clevic/generic_format.rb
clevic-0.14.4 lib/clevic/generic_format.rb
clevic-0.14.3 lib/clevic/generic_format.rb
clevic-0.14.2 lib/clevic/generic_format.rb
clevic-0.14.1 lib/clevic/generic_format.rb
clevic-0.14.0 lib/clevic/generic_format.rb
clevic-0.13.0.b12 lib/clevic/generic_format.rb
clevic-0.13.0.b11 lib/clevic/generic_format.rb
clevic-0.13.0.b10 lib/clevic/generic_format.rb