Class | Rails::Generator::Commands::Create |
In: |
vendor/rails/railties/lib/rails_generator/commands.rb
|
Parent: | Base |
Create is the premier generator command. It copies files, creates directories, renders templates, and more.
SYNONYM_LOOKUP_URI | = | "http://wordnet.princeton.edu/perl/webwn?s=%s" |
Check whether the given class names are already taken by Ruby or Rails. In the future, expand to check other namespaces such as the rest of the user‘s app.
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 172 172: def class_collisions(*class_names) 173: path = class_names.shift 174: class_names.flatten.each do |class_name| 175: # Convert to string to allow symbol arguments. 176: class_name = class_name.to_s 177: 178: # Skip empty strings. 179: next if class_name.strip.empty? 180: 181: # Split the class from its module nesting. 182: nesting = class_name.split('::') 183: name = nesting.pop 184: 185: # Extract the last Module in the nesting. 186: last = nesting.inject(Object) { |last, nest| 187: break unless last.const_defined?(nest) 188: last.const_get(nest) 189: } 190: 191: # If the last Module exists, check whether the given 192: # class exists and raise a collision if so. 193: if last and last.const_defined?(name.camelize) 194: raise_class_collision(class_name) 195: end 196: end 197: end
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 305 305: def complex_template(relative_source, relative_destination, template_options = {}) 306: options = template_options.dup 307: options[:assigns] ||= {} 308: options[:assigns]['template_for_inclusion'] = render_template_part(template_options) 309: template(relative_source, relative_destination, options) 310: end
Create a directory including any missing parent directories. Always skips directories which exist.
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 314 314: def directory(relative_path) 315: path = destination_path(relative_path) 316: if File.exist?(path) 317: logger.exists relative_path 318: else 319: logger.create relative_path 320: unless options[:pretend] 321: FileUtils.mkdir_p(path) 322: # git doesn't require adding the paths, adding the files later will 323: # automatically do a path add. 324: 325: # Subversion doesn't do path adds, so we need to add 326: # each directory individually. 327: # So stack up the directory tree and add the paths to 328: # subversion in order without recursion. 329: if options[:svn] 330: stack = [relative_path] 331: until File.dirname(stack.last) == stack.last # dirname('.') == '.' 332: stack.push File.dirname(stack.last) 333: end 334: stack.reverse_each do |rel_path| 335: svn_path = destination_path(rel_path) 336: system("svn add -N #{svn_path}") unless File.directory?(File.join(svn_path, '.svn')) 337: end 338: end 339: end 340: end 341: end
Copy a file from source to destination with collision checking.
The file_options hash accepts :chmod and :shebang and :collision options. :chmod sets the permissions of the destination file:
file 'config/empty.log', 'log/test.log', :chmod => 0664
:shebang sets the #!/usr/bin/ruby line for scripts
file 'bin/generate.rb', 'script/generate', :chmod => 0755, :shebang => '/usr/bin/env ruby'
:collision sets the collision option only for the destination file:
file 'settings/server.yml', 'config/server.yml', :collision => :skip
Collisions are handled by checking whether the destination file exists and either skipping the file, forcing overwrite, or asking the user what to do.
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 212 212: def file(relative_source, relative_destination, file_options = {}, &block) 213: # Determine full paths for source and destination files. 214: source = source_path(relative_source) 215: destination = destination_path(relative_destination) 216: destination_exists = File.exist?(destination) 217: 218: # If source and destination are identical then we're done. 219: if destination_exists and identical?(source, destination, &block) 220: return logger.identical(relative_destination) 221: end 222: 223: # Check for and resolve file collisions. 224: if destination_exists 225: 226: # Make a choice whether to overwrite the file. :force and 227: # :skip already have their mind made up, but give :ask a shot. 228: choice = case (file_options[:collision] || options[:collision]).to_sym #|| :ask 229: when :ask then force_file_collision?(relative_destination, source, destination, file_options, &block) 230: when :force then :force 231: when :skip then :skip 232: else raise "Invalid collision option: #{options[:collision].inspect}" 233: end 234: 235: # Take action based on our choice. Bail out if we chose to 236: # skip the file; otherwise, log our transgression and continue. 237: case choice 238: when :force then logger.force(relative_destination) 239: when :skip then return(logger.skip(relative_destination)) 240: else raise "Invalid collision choice: #{choice}.inspect" 241: end 242: 243: # File doesn't exist so log its unbesmirched creation. 244: else 245: logger.create relative_destination 246: end 247: 248: # If we're pretending, back off now. 249: return if options[:pretend] 250: 251: # Write destination file with optional shebang. Yield for content 252: # if block given so templaters may render the source file. If a 253: # shebang is requested, replace the existing shebang or insert a 254: # new one. 255: File.open(destination, 'wb') do |dest| 256: dest.write render_file(source, file_options, &block) 257: end 258: 259: # Optionally change permissions. 260: if file_options[:chmod] 261: FileUtils.chmod(file_options[:chmod], destination) 262: end 263: 264: # Optionally add file to subversion or git 265: system("svn add #{destination}") if options[:svn] 266: system("git add -v #{relative_destination}") if options[:git] 267: end
Checks if the source and the destination file are identical. If passed a block then the source file is a template that needs to first be evaluated before being compared to the destination.
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 272 272: def identical?(source, destination, &block) 273: return false if File.directory? destination 274: source = block_given? ? File.open(source) {|sf| yield(sf)} : IO.read(source) 275: destination = IO.read(destination) 276: source == destination 277: end
When creating a migration, it knows to find the first available file in db/migrate and use the migration.rb template.
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 352 352: def migration_template(relative_source, relative_destination, template_options = {}) 353: migration_directory relative_destination 354: migration_file_name = template_options[:migration_file_name] || file_name 355: raise "Another migration is already named #{migration_file_name}: #{existing_migrations(migration_file_name).first}" if migration_exists?(migration_file_name) 356: template(relative_source, "#{relative_destination}/#{next_migration_string}_#{migration_file_name}.rb", template_options) 357: end
Display a README.
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 344 344: def readme(*relative_sources) 345: relative_sources.flatten.each do |relative_source| 346: logger.readme relative_source 347: puts File.read(source_path(relative_source)) unless options[:pretend] 348: end 349: end
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 359 359: def route_resources(*resources) 360: resource_list = resources.map { |r| r.to_sym.inspect }.join(', ') 361: sentinel = 'ActionController::Routing::Routes.draw do |map|' 362: 363: logger.route "map.resources #{resource_list}" 364: unless options[:pretend] 365: gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match| 366: "#{match}\n map.resources #{resource_list}\n" 367: end 368: end 369: end
Generate a file for a Rails application using an ERuby template. Looks up and evaluates a template by name and writes the result.
The ERB template uses explicit trim mode to best control the proliferation of whitespace in generated code. <%- trims leading whitespace; -%> trims trailing whitespace including one newline.
A hash of template options may be passed as the last argument. The options accepted by the file are accepted as well as :assigns, a hash of variable bindings. Example:
template 'foo', 'bar', :assigns => { :action => 'view' }
Template is implemented in terms of file. It calls file with a block which takes a file handle and returns its rendered contents.
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 293 293: def template(relative_source, relative_destination, template_options = {}) 294: file(relative_source, relative_destination, template_options) do |file| 295: # Evaluate any assignments in a temporary, throwaway binding. 296: vars = template_options[:assigns] || {} 297: b = binding 298: vars.each { |k,v| eval "#{k} = vars[:#{k}] || vars['#{k}']", b } 299: 300: # Render the source file with the temporary binding. 301: ERB.new(file.read, nil, '-').result(b) 302: end 303: end