Sha256: 8806dce62fe6e268f059cbc3c5a0edd7211a15477fcdf5b981c4138f9879fc3a

Contents?: true

Size: 1.47 KB

Versions: 2

Compression:

Stored size: 1.47 KB

Contents

module CsvRowModel
  module Export
    module Attributes
      extend ActiveSupport::Concern

      included do
        self.column_names.each { |*args| define_attribute_method(*args) }
      end

      # @return [Hash] a map of `column_name => self.class.format_cell(public_send(column_name))`
      def formatted_attributes
        formatted_attributes_from_column_names self.class.column_names
      end

      def formatted_attribute(column_name)
        self.class.format_cell(
          public_send(column_name),
          column_name,
          self.class.index(column_name),
          context
        )
      end

      protected
      def formatted_attributes_from_column_names(column_names)
        array_to_block_hash(column_names) { |column_name| formatted_attribute(column_name) }
      end

      class_methods do
        # See {Model#column}
        def column(column_name, options={})
          super
          define_attribute_method(column_name)
        end

        # Define default attribute method for a column
        # @param column_name [Symbol] the cell's column_name
        def define_attribute_method(column_name)
          define_method(column_name) do
            source_model.public_send(column_name)
          end
        end

        # Safe to override. Method applied to each cell by default
        #
        # @param cell [Object] the cell's value
        def format_cell(cell, column_name, column_index, context={})
          cell
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
csv_row_model-0.3.5 lib/csv_row_model/export/attributes.rb
csv_row_model-0.3.4 lib/csv_row_model/export/attributes.rb