Sha256: 198fe528022d3962fd69847eca077bc6a0b17a4bf21822837433a076895e4d49

Contents?: true

Size: 1.63 KB

Versions: 2

Compression:

Stored size: 1.63 KB

Contents

require 'csv_row_model/model/comparison'

module CsvRowModel
  module Export
    module Attributes
      extend ActiveSupport::Concern

      included do
        include Model::Comparison
        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)
        return public_send(column_name) if self.class.is_dynamic_column?(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.10 lib/csv_row_model/export/attributes.rb
csv_row_model-0.3.9 lib/csv_row_model/export/attributes.rb