Skip to content

Commit

Permalink
NamedBase.
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Jun 23, 2009
1 parent 301c48c commit 83f7fe2
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 11 deletions.
3 changes: 1 addition & 2 deletions railties/lib/generator/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ def self.banner
#
def self.generator_name
@generator_name ||= begin
klass_name = self.name
klass_name.gsub!(/^Rails::Generators::/, '')
klass_name = self.name.gsub(/^Rails::Generators::/, '')
klass_name.gsub!(/Generator$/, '')
klass_name.underscore
end
Expand Down
10 changes: 1 addition & 9 deletions railties/lib/generator/generators/metal/metal_generator.rb
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
module Rails::Generators
class MetalGenerator < Base
argument :file_name, :type => :string

class MetalGenerator < NamedBase
def create_file
template "metal.rb", "app/metal/#{file_name}.rb"
end

protected

def class_name
file_name.classify
end
end
end
55 changes: 55 additions & 0 deletions railties/lib/generator/named_base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,61 @@
module Rails
module Generators
class NamedBase < Base
argument :name, :type => :string

attr_reader :class_name, :singular_name, :plural_name, :table_name,
:class_path, :file_path, :class_nesting, :class_nesting_depth
alias :file_name :singular_name

def initialize(*args)
super
assign_names!
end

protected

def assign_names!
base_name, @class_path, @file_path, @class_nesting, @class_nesting_depth = extract_modules(name)
@class_name_without_nesting, @singular_name, @plural_name = inflect_names(base_name)

@table_name = if !defined?(ActiveRecord::Base) || ActiveRecord::Base.pluralize_table_names
plural_name
else
singular_name
end
@table_name.gsub! '/', '_'

if @class_nesting.empty?
@class_name = @class_name_without_nesting
else
@table_name = @class_nesting.underscore << "_" << @table_name
@class_name = "#{@class_nesting}::#{@class_name_without_nesting}"
end
end

# Extract modules from filesystem-style or ruby-style path. Both
# good/fun/stuff and Good::Fun::Stuff produce the same results.
#
def extract_modules(name)
modules = name.include?('/') ? name.split('/') : name.split('::')
name = modules.pop
path = modules.map { |m| m.underscore }

file_path = (path + [name.underscore]).join('/')
nesting = modules.map { |m| m.camelize }.join('::')

[name, path, file_path, nesting, modules.size]
end

# Receives name and return camelized, underscored and pluralized names.
#
def inflect_names(name)
camel = name.camelize
under = camel.underscore
plural = under.pluralize
[camel, under, plural]
end

end
end
end

0 comments on commit 83f7fe2

Please sign in to comment.