Module: Bento::Controllers::AccountScopable

Included in:
ActionController::Base
Defined in:
lib/bento/controllers/account_scopable.rb

Constant Summary collapse

@@resource_names =
[]

Class Method Summary collapse

Class Method Details

.define_methods(resource_name) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/bento/controllers/account_scopable.rb', line 7

def self.define_methods(resource_name)
  @@resource_names << resource_name.to_s.singularize
  @@name = @@resource_names.first

  ActiveSupport.on_load(:action_controller) do
    class_eval do
      def admin?
        respond_to_admin? and current_user.admin?
      end

      def not_responding_to_admin?
        (not respond_to_admin?)
      end

      def respond_to_admin?
        current_user.respond_to?(:admin?)
      end
    end

    @@resource_names.uniq.each do |name|
      (class << self; self; end).send(:define_method, "scoped_to_#{name}") do
        inherit_resources

        class_eval do
          private

          # This is where things get scoped.
          # If you're using inherit_resources it will automaticly
          # call your associations on this method.
          # In your own code you would just use current_<my account like model>-method.
          def begin_of_association_chain
            begining = instance_variable_get("@#{@@name}".to_sym)
            return begining if begining

            begining = send("current_#{@@name}")
            instance_variable_set("@#{@@name}".to_sym, begining)
            begining
          end

          def bento_resource_by_param_or_session
            if bento_resource_id
              @@name.camelcase.constantize.find(bento_resource_id)
            else
              current_user.send(@@name)
            end
          end

          def bento_resource_id
            key, value = params.find { |key, value| key.to_s.ends_with?("#{@@name}_id") }
            value
          end
        end

        class_eval <<-RUBY, __FILE__, __LINE__+1
          private

          def current_#{name}
            if current_user
              if current_user.#{name}
                current_user.#{name}
              elsif not_responding_to_admin? or admin?
                bento_resource_by_param_or_session
              end
            end
          end
        RUBY
      end # define_method
    end # @@resource_names.uniq.each
  end # ActiveSupport.on_load
end