Sha256: 7078494f9b197e677c0e722ccb8114444d039285d8cdd2322a199f1a25000de9

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

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

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

      def rom
        ::Rails.application.config.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

1 entries across 1 versions & 1 rubygems

Version Path
rom-rails-0.2.0 lib/rom/rails/controller_extension.rb