Sha256: b0e560e51b9663902a8b0f08ff3428e288c3d3f3a5a4b08cb97698175b6fa3e0

Contents?: true

Size: 1.09 KB

Versions: 2

Compression:

Stored size: 1.09 KB

Contents

module ROM
  module Rails
    RelationParamsMissingError = Class.new(StandardError)

    module ControllerExtension
      def self.included(klass)
        klass.extend(ClassExtensions)
      end

      def rom
        ROM.env
      end

      module ClassExtensions
        def relation(path, options)
          root, method = path.split('.').map(&:to_sym)

          name = options.fetch(:as) { root }
          requires = Array(options.fetch(:requires) { [] })

          before_filter(options.except(:as, :requires)) do
            args = params.values_at(*requires)

            if requires.any? && args.none?
              raise RelationParamsMissingError
            else
              relation =
                if args.any?
                  rom.read(root).send(method, *args)
                else
                  rom.read(root).send(method)
                end

              instance_variable_set("@#{name}", relation.to_a)
            end
          end

          unless respond_to?(name)
            attr_reader name
            helper_method name
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rom-rails-0.3.0.beta1 lib/rom/rails/controller_extension.rb
rom-rails-0.2.1 lib/rom/rails/controller_extension.rb