Sha256: adca1e34523f62f2f202549461fc01382d126d27a038a00298ff95090139a771

Contents?: true

Size: 1.6 KB

Versions: 2

Compression:

Stored size: 1.6 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)
        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
        # 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

        protected
        # 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)
          return if method_defined? column_name
          define_method(column_name) { source_model.public_send(column_name) }
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
csv_row_model-0.4.1 lib/csv_row_model/export/attributes.rb
csv_row_model-0.4.0 lib/csv_row_model/export/attributes.rb