Sha256: 929c6ac4a7c924b317d2c11fb25de282f1f09c407d91b2a961d1ce9957227f20

Contents?: true

Size: 1.43 KB

Versions: 36

Compression:

Stored size: 1.43 KB

Contents

module Lolita
  module Support
    # Containes different kind of formaters.
    # Change output format of different input types.
    # To define, pass block, or String.
    # ====Exmaple
    #     Lolita::Support::Formatter.new do |value|
    #       value.to_i**2
    #     end
    #     # or as String
    #     Lolita::Support::Formatter.new("%U")
    # To format any value with defined formater call #with
    # ====Example
    #     # Previous examples may be called like this
    #     formatter.with(1)
    #     formatter.with(Date.today)
    class Formatter

      def initialize(format=nil,&block)
        @format=format
        @block=block if block_given?
      end

      def format
        @format
      end

      def block
        @block
      end

      def with(value,*optional_values)
        if @block
          @block.call(value,*optional_values)
        elsif @format
          use_format_for(value,*optional_values)
        else
          use_default_format(value,*optional_values)
        end
      end

      private

      def use_default_format(value,*optional_values)
        value
      end

      def use_format_for(value, *optional_values)
        if value.respond_to?(:format)
          call_block(value,*optional_values)
        else
          @format ? (@format % value) : value
        end
      end

      def call_block(value,*optional_values)
        value.send(:format,value,*optional_values)
      end

    end
    
  end
end

Version data entries

36 entries across 36 versions & 1 rubygems

Version Path
lolita-4.0.11 lib/lolita/support/formatter.rb
lolita-4.2.0 lib/lolita/support/formatter.rb
lolita-4.0.10 lib/lolita/support/formatter.rb
lolita-4.0.9 lib/lolita/support/formatter.rb
lolita-4.0.8 lib/lolita/support/formatter.rb
lolita-4.0.6 lib/lolita/support/formatter.rb
lolita-3.4.3 lib/lolita/support/formatter.rb
lolita-3.3.7 lib/lolita/support/formatter.rb
lolita-3.3.5 lib/lolita/support/formatter.rb
lolita-3.2.0.rc.17 lib/lolita/support/formatter.rb
lolita-3.2.0.rc.16 lib/lolita/support/formatter.rb
lolita-3.2.0.rc.14 lib/lolita/support/formatter.rb
lolita-3.2.0.rc.13 lib/lolita/support/formatter.rb
lolita-3.2.0.rc.12 lib/lolita/support/formatter.rb
lolita-3.2.0.rc.11 lib/lolita/support/formatter.rb
lolita-3.2.0.rc.10 lib/lolita/support/formatter.rb
lolita-3.2.0.rc.9 lib/lolita/support/formatter.rb
lolita-3.2.0.rc.7 lib/lolita/support/formatter.rb
lolita-3.1.18 lib/lolita/support/formatter.rb
lolita-3.2.0.rc.6 lib/lolita/support/formatter.rb