| 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/cgi-bin/webwn2.0?stage=2&word=%s&posnumber=1&searchtypenumber=2&senses=&showglosses=1" |
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 168
168: def class_collisions(*class_names)
169: class_names.flatten.each do |class_name|
170: # Convert to string to allow symbol arguments.
171: class_name = class_name.to_s
172:
173: # Skip empty strings.
174: next if class_name.strip.empty?
175:
176: # Split the class from its module nesting.
177: nesting = class_name.split('::')
178: name = nesting.pop
179:
180: # Extract the last Module in the nesting.
181: last = nesting.inject(Object) { |last, nest|
182: break unless last.const_defined?(nest)
183: last.const_get(nest)
184: }
185:
186: # If the last Module exists, check whether the given
187: # class exists and raise a collision if so.
188: if last and last.const_defined?(name.camelize)
189: raise_class_collision(class_name)
190: end
191: end
192: end
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 299
299: def complex_template(relative_source, relative_destination, template_options = {})
300: options = template_options.dup
301: options[:assigns] ||= {}
302: options[:assigns]['template_for_inclusion'] = render_template_part(template_options)
303: template(relative_source, relative_destination, options)
304: end
Create a directory including any missing parent directories. Always directories which exist.
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 308
308: def directory(relative_path)
309: path = destination_path(relative_path)
310: if File.exist?(path)
311: logger.exists relative_path
312: else
313: logger.create relative_path
314: unless options[:pretend]
315: FileUtils.mkdir_p(path)
316:
317: # Subversion doesn't do path adds, so we need to add
318: # each directory individually.
319: # So stack up the directory tree and add the paths to
320: # subversion in order without recursion.
321: if options[:svn]
322: stack=[relative_path]
323: until File.dirname(stack.last) == stack.last # dirname('.') == '.'
324: stack.push File.dirname(stack.last)
325: end
326: stack.reverse_each do |rel_path|
327: svn_path = destination_path(rel_path)
328: system("svn add -N #{svn_path}") unless File.directory?(File.join(svn_path, '.svn'))
329: end
330: end
331: end
332: end
333: 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 207
207: def file(relative_source, relative_destination, file_options = {}, &block)
208: # Determine full paths for source and destination files.
209: source = source_path(relative_source)
210: destination = destination_path(relative_destination)
211: destination_exists = File.exist?(destination)
212:
213: # If source and destination are identical then we're done.
214: if destination_exists and identical?(source, destination, &block)
215: return logger.identical(relative_destination)
216: end
217:
218: # Check for and resolve file collisions.
219: if destination_exists
220:
221: # Make a choice whether to overwrite the file. :force and
222: # :skip already have their mind made up, but give :ask a shot.
223: choice = case (file_options[:collision] || options[:collision]).to_sym #|| :ask
224: when :ask then force_file_collision?(relative_destination, source, destination, file_options, &block)
225: when :force then :force
226: when :skip then :skip
227: else raise "Invalid collision option: #{options[:collision].inspect}"
228: end
229:
230: # Take action based on our choice. Bail out if we chose to
231: # skip the file; otherwise, log our transgression and continue.
232: case choice
233: when :force then logger.force(relative_destination)
234: when :skip then return(logger.skip(relative_destination))
235: else raise "Invalid collision choice: #{choice}.inspect"
236: end
237:
238: # File doesn't exist so log its unbesmirched creation.
239: else
240: logger.create relative_destination
241: end
242:
243: # If we're pretending, back off now.
244: return if options[:pretend]
245:
246: # Write destination file with optional shebang. Yield for content
247: # if block given so templaters may render the source file. If a
248: # shebang is requested, replace the existing shebang or insert a
249: # new one.
250: File.open(destination, 'wb') do |dest|
251: dest.write render_file(source, file_options, &block)
252: end
253:
254: # Optionally change permissions.
255: if file_options[:chmod]
256: FileUtils.chmod(file_options[:chmod], destination)
257: end
258:
259: # Optionally add file to subversion
260: system("svn add #{destination}") if options[:svn]
261: 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 266
266: def identical?(source, destination, &block)
267: return false if File.directory? destination
268: source = block_given? ? File.open(source) {|sf| yield(sf)} : IO.read(source)
269: destination = IO.read(destination)
270: source == destination
271: 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 344
344: def migration_template(relative_source, relative_destination, template_options = {})
345: migration_directory relative_destination
346: migration_file_name = template_options[:migration_file_name] || file_name
347: raise "Another migration is already named #{migration_file_name}: #{existing_migrations(migration_file_name).first}" if migration_exists?(migration_file_name)
348: template(relative_source, "#{relative_destination}/#{next_migration_string}_#{migration_file_name}.rb", template_options)
349: end
Display a README.
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 336
336: def readme(*relative_sources)
337: relative_sources.flatten.each do |relative_source|
338: logger.readme relative_source
339: puts File.read(source_path(relative_source)) unless options[:pretend]
340: end
341: end
# File vendor/rails/railties/lib/rails_generator/commands.rb, line 351
351: def route_resources(*resources)
352: resource_list = resources.map { |r| r.to_sym.inspect }.join(', ')
353: sentinel = 'ActionController::Routing::Routes.draw do |map|'
354:
355: logger.route "map.resources #{resource_list}"
356: unless options[:pretend]
357: gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match|
358: "#{match}\n map.resources #{resource_list}\n"
359: end
360: end
361: 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 287
287: def template(relative_source, relative_destination, template_options = {})
288: file(relative_source, relative_destination, template_options) do |file|
289: # Evaluate any assignments in a temporary, throwaway binding.
290: vars = template_options[:assigns] || {}
291: b = binding
292: vars.each { |k,v| eval "#{k} = vars[:#{k}] || vars['#{k}']", b }
293:
294: # Render the source file with the temporary binding.
295: ERB.new(file.read, nil, '-').result(b)
296: end
297: end