Class: Rails::Generator::Commands::Create
- Defined in:
- lib/rails_generator/commands.rb
Overview
Create is the premier generator command. It copies files, creates directories, renders templates, and more.
Direct Known Subclasses
Instance Attribute Summary
Attributes inherited from Base
#args, #destination_root, #source_root
Attributes included from Options
Instance Method Summary collapse
-
#class_collisions(*class_names) ⇒ Object
Check whether the given class names are already taken by Ruby or Rails.
- #complex_template(relative_source, relative_destination, template_options = {}) ⇒ Object
-
#directory(relative_path) ⇒ Object
Create a directory including any missing parent directories.
-
#file(relative_source, relative_destination, file_options = {}, &block) ⇒ Object
Copy a file from source to destination with collision checking.
-
#identical?(source, destination, &block) ⇒ Boolean
Checks if the source and the destination file are identical.
-
#migration_template(relative_source, relative_destination, template_options = {}) ⇒ Object
When creating a migration, it knows to find the first available file in db/migrate and use the migration.rb template.
-
#readme(*relative_sources) ⇒ Object
Display a README.
-
#template(relative_source, relative_destination, template_options = {}) ⇒ Object
Generate a file for a Rails application using an ERuby template.
Methods inherited from Base
Methods inherited from Base
#destination_path, #initialize, #manifest, #source_path
Methods included from Options
Constructor Details
This class inherits a constructor from Rails::Generator::Base
Instance Method Details
#class_collisions(*class_names) ⇒ Object
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.
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
# File 'lib/rails_generator/commands.rb', line 138 def class_collisions(*class_names) class_names.flatten.each do |class_name| # Convert to string to allow symbol arguments. class_name = class_name.to_s # Skip empty strings. next if class_name.strip.empty? # Split the class from its module nesting. nesting = class_name.split('::') name = nesting.pop # Extract the last Module in the nesting. last = nesting.inject(Object) { |last, nest| break unless last.const_defined?(nest) last.const_get(nest) } # If the last Module exists, check whether the given # class exists and raise a collision if so. if last and last.const_defined?(name.camelize) raise_class_collision(class_name) end end end |
#complex_template(relative_source, relative_destination, template_options = {}) ⇒ Object
281 282 283 284 285 286 |
# File 'lib/rails_generator/commands.rb', line 281 def complex_template(relative_source, relative_destination, = {}) = .dup [:assigns] ||= {} [:assigns]['template_for_inclusion'] = render_template_part() template(relative_source, relative_destination, ) end |
#directory(relative_path) ⇒ Object
Create a directory including any missing parent directories. Always directories which exist.
290 291 292 293 294 295 296 297 298 299 300 301 |
# File 'lib/rails_generator/commands.rb', line 290 def directory(relative_path) path = destination_path(relative_path) if File.exists?(path) logger.exists relative_path else logger.create relative_path FileUtils.mkdir_p(path) unless [:pretend] # Optionally add file to subversion system("svn add #{path}") if [:svn] end end |
#file(relative_source, relative_destination, file_options = {}, &block) ⇒ Object
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.
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
# File 'lib/rails_generator/commands.rb', line 177 def file(relative_source, relative_destination, = {}, &block) # Determine full paths for source and destination files. source = source_path(relative_source) destination = destination_path(relative_destination) destination_exists = File.exists?(destination) # If source and destination are identical then we're done. if destination_exists and identical?(source, destination, &block) return logger.identical(relative_destination) end # Check for and resolve file collisions. if destination_exists # Make a choice whether to overwrite the file. :force and # :skip already have their mind made up, but give :ask a shot. choice = case ([:collision] || [:collision]).to_sym #|| :ask when :ask then force_file_collision?(relative_destination) when :force then :force when :skip then :skip else raise "Invalid collision option: #{[:collision].inspect}" end # Take action based on our choice. Bail out if we chose to # skip the file; otherwise, log our transgression and continue. case choice when :force then logger.force(relative_destination) when :skip then return(logger.skip(relative_destination)) else raise "Invalid collision choice: #{choice}.inspect" end # File doesn't exist so log its unbesmirched creation. else logger.create relative_destination end # If we're pretending, back off now. return if [:pretend] # Write destination file with optional shebang. Yield for content # if block given so templaters may render the source file. If a # shebang is requested, replace the existing shebang or insert a # new one. File.open(destination, 'wb') do |df| File.open(source, 'rb') do |sf| if block_given? df.write(yield(sf)) else if [:shebang] df.puts("#!#{[:shebang]}") if line = sf.gets df.puts(line) if line !~ /^#!/ end end df.write(sf.read) end end end # Optionally change permissions. if [:chmod] FileUtils.chmod([:chmod], destination) end # Optionally add file to subversion system("svn add #{destination}") if [:svn] end |
#identical?(source, destination, &block) ⇒ Boolean
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.
248 249 250 251 252 253 |
# File 'lib/rails_generator/commands.rb', line 248 def identical?(source, destination, &block) return false if File.directory? destination source = block_given? ? File.open(source) {|sf| yield(sf)} : IO.read(source) destination = IO.read(destination) source == destination end |
#migration_template(relative_source, relative_destination, template_options = {}) ⇒ Object
When creating a migration, it knows to find the first available file in db/migrate and use the migration.rb template.
312 313 314 315 316 317 |
# File 'lib/rails_generator/commands.rb', line 312 def migration_template(relative_source, relative_destination, = {}) migration_directory relative_destination migration_file_name = [:migration_file_name] || file_name raise "Another migration is already named #{migration_file_name}: #{existing_migrations(migration_file_name).first}" if migration_exists?(migration_file_name) template(relative_source, "#{relative_destination}/#{next_migration_string}_#{migration_file_name}.rb", ) end |
#readme(*relative_sources) ⇒ Object
Display a README.
304 305 306 307 308 309 |
# File 'lib/rails_generator/commands.rb', line 304 def readme(*relative_sources) relative_sources.flatten.each do |relative_source| logger.readme relative_source puts File.read(source_path(relative_source)) unless [:pretend] end end |
#template(relative_source, relative_destination, template_options = {}) ⇒ Object
Generate a file for a Rails application using an ERuby template. Looks up and evalutes 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.
269 270 271 272 273 274 275 276 277 278 279 |
# File 'lib/rails_generator/commands.rb', line 269 def template(relative_source, relative_destination, = {}) file(relative_source, relative_destination, ) do |file| # Evaluate any assignments in a temporary, throwaway binding. vars = [:assigns] || {} b = binding vars.each { |k,v| eval "#{k} = vars[:#{k}] || vars['#{k}']", b } # Render the source file with the temporary binding. ERB.new(file.read, nil, '-').result(b) end end |