aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib/rails/generators/resource_helpers.rb
blob: 3df25219ab5c5c351863ab6f4ffc4045efd81986 (plain) (blame)
1
2
3
4
5
6
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
77
78
require 'rails/generators/active_model'

module Rails
  module Generators
    # Deal with controller names on scaffold and add some helpers to deal with
    # ActiveModel.
    module ResourceHelpers # :nodoc:
      mattr_accessor :skip_warn

      def self.included(base) #:nodoc:
        base.class_option :force_plural, :type => :boolean, :desc => "Forces the use of a plural ModelName"
      end

      # Set controller variables on initialization.
      def initialize(*args) #:nodoc:
        super

        if name == name.pluralize && name.singularize != name.pluralize && !options[:force_plural]
          unless ResourceHelpers.skip_warn
            say "Plural version of the model detected, using singularized version. Override with --force-plural."
            ResourceHelpers.skip_warn = true
          end
          name.replace name.singularize
          assign_names!(name)
        end

        @controller_name = name.pluralize
      end

      protected

        attr_reader :controller_name

        def controller_class_path
          class_path
        end

        def controller_file_name
          @controller_file_name ||= file_name.pluralize
        end

        def controller_file_path
          @controller_file_path ||= (controller_class_path + [controller_file_name]).join('/')
        end

        def controller_class_name
          (controller_class_path + [controller_file_name]).map!{ |m| m.camelize }.join('::')
        end

        def controller_i18n_scope
          @controller_i18n_scope ||= controller_file_path.tr('/', '.')
        end

        # Loads the ORM::Generators::ActiveModel class. This class is responsible
        # to tell scaffold entities how to generate an specific method for the
        # ORM. Check Rails::Generators::ActiveModel for more information.
        def orm_class
          @orm_class ||= begin
            # Raise an error if the class_option :orm was not defined.
            unless self.class.class_options[:orm]
              raise "You need to have :orm as class option to invoke orm_class and orm_instance"
            end

            begin
              "#{options[:orm].to_s.camelize}::Generators::ActiveModel".constantize
            rescue NameError
              Rails::Generators::ActiveModel
            end
          end
        end

        # Initialize ORM::Generators::ActiveModel to access instance methods.
        def orm_instance(name=singular_table_name)
          @orm_instance ||= orm_class.new(name)
        end
    end
  end
end