| 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:
174: # Initialize some check varibles
175: last_class = Object
176: current_class = nil
177: name = nil
178:
179: class_names.flatten.each do |class_name|
180: # Convert to string to allow symbol arguments.
181: class_name = class_name.to_s
182:
183: # Skip empty strings.
184: class_name.strip.empty? ? next : current_class = class_name
185:
186: # Split the class from its module nesting.
187: nesting = class_name.split('::')
188: name = nesting.pop
189:
190: # Extract the last Module in the nesting.
191: last = nesting.inject(last_class) { |last, nest|
192: break unless last_class.const_defined?(nest)
193: last_class = last_class.const_get(nest)
194: }
195:
196: end
197: # If the last Module exists, check whether the given
198: # class exists and raise a collision if so.
199:
200: if last_class and last_class.const_defined?(name.camelize)
201: raise_class_collision(current_class)
202: end
203: end
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 311
311: def complex_template(relative_source, relative_destination, template_options = {})
312: options = template_options.dup
313: options[:assigns] ||= {}
314: options[:assigns]['template_for_inclusion'] = render_template_part(template_options)
315: template(relative_source, relative_destination, options)
316: end
Create a directory including any missing parent directories. Always skips directories which exist.
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 320
320: def directory(relative_path)
321: path = destination_path(relative_path)
322: if File.exist?(path)
323: logger.exists relative_path
324: else
325: logger.create relative_path
326: unless options[:pretend]
327: FileUtils.mkdir_p(path)
328: # git doesn't require adding the paths, adding the files later will
329: # automatically do a path add.
330:
331: # Subversion doesn't do path adds, so we need to add
332: # each directory individually.
333: # So stack up the directory tree and add the paths to
334: # subversion in order without recursion.
335: if options[:svn]
336: stack = [relative_path]
337: until File.dirname(stack.last) == stack.last # dirname('.') == '.'
338: stack.push File.dirname(stack.last)
339: end
340: stack.reverse_each do |rel_path|
341: svn_path = destination_path(rel_path)
342: system("svn add -N #{svn_path}") unless File.directory?(File.join(svn_path, '.svn'))
343: end
344: end
345: end
346: end
347: 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 218
218: def file(relative_source, relative_destination, file_options = {}, &block)
219: # Determine full paths for source and destination files.
220: source = source_path(relative_source)
221: destination = destination_path(relative_destination)
222: destination_exists = File.exist?(destination)
223:
224: # If source and destination are identical then we're done.
225: if destination_exists and identical?(source, destination, &block)
226: return logger.identical(relative_destination)
227: end
228:
229: # Check for and resolve file collisions.
230: if destination_exists
231:
232: # Make a choice whether to overwrite the file. :force and
233: # :skip already have their mind made up, but give :ask a shot.
234: choice = case (file_options[:collision] || options[:collision]).to_sym #|| :ask
235: when :ask then force_file_collision?(relative_destination, source, destination, file_options, &block)
236: when :force then :force
237: when :skip then :skip
238: else raise "Invalid collision option: #{options[:collision].inspect}"
239: end
240:
241: # Take action based on our choice. Bail out if we chose to
242: # skip the file; otherwise, log our transgression and continue.
243: case choice
244: when :force then logger.force(relative_destination)
245: when :skip then return(logger.skip(relative_destination))
246: else raise "Invalid collision choice: #{choice}.inspect"
247: end
248:
249: # File doesn't exist so log its unbesmirched creation.
250: else
251: logger.create relative_destination
252: end
253:
254: # If we're pretending, back off now.
255: return if options[:pretend]
256:
257: # Write destination file with optional shebang. Yield for content
258: # if block given so templaters may render the source file. If a
259: # shebang is requested, replace the existing shebang or insert a
260: # new one.
261: File.open(destination, 'wb') do |dest|
262: dest.write render_file(source, file_options, &block)
263: end
264:
265: # Optionally change permissions.
266: if file_options[:chmod]
267: FileUtils.chmod(file_options[:chmod], destination)
268: end
269:
270: # Optionally add file to subversion or git
271: system("svn add #{destination}") if options[:svn]
272: system("git add -v #{relative_destination}") if options[:git]
273: 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 278
278: def identical?(source, destination, &block)
279: return false if File.directory? destination
280: source = block_given? ? File.open(source) {|sf| yield(sf)} : IO.read(source)
281: destination = IO.read(destination)
282: source == destination
283: 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 358
358: def migration_template(relative_source, relative_destination, template_options = {})
359: migration_directory relative_destination
360: migration_file_name = template_options[:migration_file_name] || file_name
361: raise "Another migration is already named #{migration_file_name}: #{existing_migrations(migration_file_name).first}" if migration_exists?(migration_file_name)
362: template(relative_source, "#{relative_destination}/#{next_migration_string}_#{migration_file_name}.rb", template_options)
363: end
Display a README.
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 350
350: def readme(*relative_sources)
351: relative_sources.flatten.each do |relative_source|
352: logger.readme relative_source
353: puts File.read(source_path(relative_source)) unless options[:pretend]
354: end
355: end
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 365
365: def route_resources(*resources)
366: resource_list = resources.map { |r| r.to_sym.inspect }.join(', ')
367: sentinel = 'ActionController::Routing::Routes.draw do |map|'
368:
369: logger.route "map.resources #{resource_list}"
370: unless options[:pretend]
371: gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match|
372: "#{match}\n map.resources #{resource_list}\n"
373: end
374: end
375: 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 299
299: def template(relative_source, relative_destination, template_options = {})
300: file(relative_source, relative_destination, template_options) do |file|
301: # Evaluate any assignments in a temporary, throwaway binding.
302: vars = template_options[:assigns] || {}
303: b = binding
304: vars.each { |k,v| eval "#{k} = vars[:#{k}] || vars['#{k}']", b }
305:
306: # Render the source file with the temporary binding.
307: ERB.new(file.read, nil, '-').result(b)
308: end
309: end