cropped_paperclip 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (77) hide show
  1. data/.gitignore +8 -0
  2. data/.rspec +2 -0
  3. data/.rvmrc +48 -0
  4. data/Gemfile +7 -0
  5. data/README.md +17 -0
  6. data/Rakefile +31 -0
  7. data/app/.DS_Store +0 -0
  8. data/app/assets/.DS_Store +0 -0
  9. data/app/assets/javascripts/.DS_Store +0 -0
  10. data/app/assets/javascripts/cropped_paperclip/filedrop.js.coffee +254 -0
  11. data/app/assets/javascripts/cropped_paperclip/upload_crop_scale.js.coffee +319 -0
  12. data/app/assets/javascripts/es5-shim.js +1105 -0
  13. data/app/assets/javascripts/uploader.js.coffee +3 -0
  14. data/app/controllers/cropped_paperclip/application_controller.rb +4 -0
  15. data/app/controllers/cropped_paperclip/uploads_controller.rb +40 -0
  16. data/app/helpers/cropped_paperclip/application_helper.rb +4 -0
  17. data/app/models/upload.rb +119 -0
  18. data/config/routes.rb +3 -0
  19. data/cropped_paperclip.gemspec +32 -0
  20. data/db/migrate/20120510103921_uploads.rb +11 -0
  21. data/init.rb +4 -0
  22. data/lib/cropped_paperclip.rb +170 -0
  23. data/lib/cropped_paperclip/engine.rb +7 -0
  24. data/lib/cropped_paperclip/glue.rb +20 -0
  25. data/lib/cropped_paperclip/schema.rb +35 -0
  26. data/lib/cropped_paperclip/version.rb +3 -0
  27. data/lib/paperclip/geometry_transformation.rb +80 -0
  28. data/lib/paperclip/validators/attachment_height_validator.rb +89 -0
  29. data/lib/paperclip/validators/attachment_width_validator.rb +89 -0
  30. data/lib/paperclip_processors/offset_thumbnail.rb +86 -0
  31. data/lib/tasks/cropped_paperclip_tasks.rake +4 -0
  32. data/script/rails +8 -0
  33. data/spec/.DS_Store +0 -0
  34. data/spec/acceptance/acceptance_helper.rb +2 -0
  35. data/spec/controllers/uploads_controller_spec.rb +5 -0
  36. data/spec/dummy/README.rdoc +261 -0
  37. data/spec/dummy/Rakefile +7 -0
  38. data/spec/dummy/app/assets/javascripts/application.js +15 -0
  39. data/spec/dummy/app/assets/stylesheets/application.css +13 -0
  40. data/spec/dummy/app/controllers/application_controller.rb +3 -0
  41. data/spec/dummy/app/helpers/application_helper.rb +2 -0
  42. data/spec/dummy/app/mailers/.gitkeep +0 -0
  43. data/spec/dummy/app/models/.gitkeep +0 -0
  44. data/spec/dummy/app/models/thing.rb +15 -0
  45. data/spec/dummy/app/views/layouts/application.html.erb +14 -0
  46. data/spec/dummy/config.ru +4 -0
  47. data/spec/dummy/config/application.rb +56 -0
  48. data/spec/dummy/config/boot.rb +10 -0
  49. data/spec/dummy/config/database.yml +25 -0
  50. data/spec/dummy/config/environment.rb +5 -0
  51. data/spec/dummy/config/environments/development.rb +37 -0
  52. data/spec/dummy/config/environments/production.rb +67 -0
  53. data/spec/dummy/config/environments/test.rb +37 -0
  54. data/spec/dummy/config/initializers/backtrace_silencers.rb +7 -0
  55. data/spec/dummy/config/initializers/inflections.rb +15 -0
  56. data/spec/dummy/config/initializers/mime_types.rb +5 -0
  57. data/spec/dummy/config/initializers/secret_token.rb +7 -0
  58. data/spec/dummy/config/initializers/session_store.rb +8 -0
  59. data/spec/dummy/config/initializers/wrap_parameters.rb +14 -0
  60. data/spec/dummy/config/locales/en.yml +5 -0
  61. data/spec/dummy/config/routes.rb +3 -0
  62. data/spec/dummy/db/migrate/20120510104910_things.rb +8 -0
  63. data/spec/dummy/db/schema.rb +51 -0
  64. data/spec/dummy/lib/assets/.gitkeep +0 -0
  65. data/spec/dummy/log/.gitkeep +0 -0
  66. data/spec/dummy/public/404.html +26 -0
  67. data/spec/dummy/public/422.html +26 -0
  68. data/spec/dummy/public/500.html +25 -0
  69. data/spec/dummy/public/favicon.ico +0 -0
  70. data/spec/dummy/script/rails +6 -0
  71. data/spec/fixtures/images/.DS_Store +0 -0
  72. data/spec/fixtures/images/icon.png +0 -0
  73. data/spec/fixtures/images/test.jpg +0 -0
  74. data/spec/models/thing_spec.rb +6 -0
  75. data/spec/models/upload_spec.rb +13 -0
  76. data/spec/spec_helper.rb +18 -0
  77. metadata +309 -0
@@ -0,0 +1,3 @@
1
+ module CroppedPaperclip
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,80 @@
1
+ module Paperclip
2
+
3
+ class TransformationError < RuntimeError; end
4
+ class StyleError < RuntimeError; end
5
+
6
+ class Geometry
7
+
8
+ # Returns a new Geometry object with the the same dimensions as this but with no modifier.
9
+ def without_modifier
10
+ Geometry.new(self.width, self.height)
11
+ end
12
+
13
+ # Returns the dimensions that would result if a thumbnail was created by transforming this geometry into that geometry.
14
+ # Its purpose is to mimic imagemagick conversions. Used like so:
15
+ # file_geometry.transformed_by(style_geometry)
16
+ # it returns the size of the thumbnail image you would get by applying that rule.
17
+ # This saves us having to go back to the file, which is expensive with S3.
18
+ # We understand all the Imagemagick geometry arguments described at http://www.imagemagick.org/script/command-line-processing.php#geometry
19
+ # including both '^' and paperclip's own '#' modifier.
20
+ #
21
+ def transformed_by (other)
22
+ other = Geometry.parse(other) unless other.is_a? Geometry
23
+ # if the two geometries are similar, or the destination geometry is a fixed size, the resulting dimensions are fixed
24
+ return other.without_modifier if self =~ other || ['#', '!', '^'].include?(other.modifier)
25
+ # otherwise, we apply the transformation
26
+ raise TransformationError, "geometry is not transformable without both width and height" if self.height == 0 or self.width == 0
27
+ case other.modifier
28
+ when '>'
29
+ (other.width < self.width || other.height < self.height) ? scaled_to_fit(other) : self
30
+ when '<'
31
+ (other.width > self.width && other.height > self.height) ? scaled_to_fit(other) : self
32
+ when '%'
33
+ scaled_by(other)
34
+ when '@'
35
+ scaled_by(other.width * 100 / (self.width * self.height))
36
+ else
37
+ scaled_to_fit(other)
38
+ end
39
+ end
40
+ alias :* :transformed_by
41
+
42
+ # Tests whether two geometries are identical in dimensions and modifier.
43
+ def == (other)
44
+ self.to_s == other.to_s
45
+ end
46
+
47
+ # Tests whether two geometries have the same dimensions, ignoring modifier.
48
+ def =~ (other)
49
+ self.height.to_i == other.height.to_i && self.width.to_i == other.width.to_i
50
+ end
51
+
52
+ # Scales this geometry to fit within that geometry.
53
+ def scaled_to_fit(other)
54
+ if (other.width > 0 && other.height == 0)
55
+ Geometry.new(other.width, self.height * other.width / self.width)
56
+ elsif (other.width == 0 && other.height > 0)
57
+ Geometry.new(self.width * other.height / self.height, other.height)
58
+ else
59
+ ratio = Geometry.new( other.width / self.width, other.height / self.height )
60
+ if ratio.square?
61
+ other.without_modifier
62
+ elsif ratio.horizontal?
63
+ Geometry.new(ratio.height * self.width, other.height)
64
+ else
65
+ Geometry.new(other.width, ratio.width * self.height)
66
+ end
67
+ end
68
+ end
69
+
70
+ # Scales this geometry by the percentage(s) specified in that geometry.
71
+ def scaled_by(other)
72
+ other = Geometry.new("#{other}%") unless other.is_a? Geometry
73
+ if other.height > 0
74
+ Geometry.new(self.width * other.width / 100, self.height * other.height / 100)
75
+ else
76
+ Geometry.new(self.width * other.width / 100, self.height * other.width / 100)
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,89 @@
1
+ require 'active_model/validations/numericality'
2
+
3
+ module Paperclip
4
+ module Validators
5
+ class AttachmentHeightValidator < ActiveModel::Validations::NumericalityValidator
6
+ AVAILABLE_CHECKS = [:less_than, :less_than_or_equal_to, :greater_than, :greater_than_or_equal_to]
7
+
8
+ def initialize(options)
9
+ extract_options(options)
10
+ super
11
+ end
12
+
13
+ def validate_each(record, attr_name, value)
14
+ attachment = record.send(attr_name)
15
+ dimensions = Paperclip::Geometry.from_file(attachment.queued_for_write[:original])
16
+ value = dimensions.height.to_i
17
+ options.slice(*AVAILABLE_CHECKS).each do |option, option_value|
18
+ option_value = extract_option_value(option, option_value)
19
+ unless value.send(CHECKS[option], option_value)
20
+ error_message_key = options[:in] ? :in_between : option
21
+ record.errors.add(attr_name, error_message_key, filtered_options(value).merge(
22
+ :min => min_value,
23
+ :max => max_value
24
+ ))
25
+ end
26
+ end
27
+ end
28
+
29
+ def check_validity!
30
+ unless (AVAILABLE_CHECKS + [:in]).any? { |argument| options.has_key?(argument) }
31
+ raise ArgumentError, "You must pass either :less_than, :greater_than, or :in to the validator"
32
+ end
33
+ end
34
+
35
+ private
36
+
37
+ def extract_options(options)
38
+ if range = options[:in]
39
+ if !options[:in].respond_to?(:call)
40
+ options[:less_than_or_equal_to] = range.max
41
+ options[:greater_than_or_equal_to] = range.min
42
+ else
43
+ options[:less_than_or_equal_to] = range
44
+ options[:greater_than_or_equal_to] = range
45
+ end
46
+ end
47
+ end
48
+
49
+ def extract_option_value(option, option_value)
50
+ if option_value.is_a?(Range)
51
+ if [:less_than, :less_than_or_equal_to].include?(option)
52
+ option_value.max
53
+ else
54
+ option_value.min
55
+ end
56
+ else
57
+ option_value
58
+ end
59
+ end
60
+
61
+ def min_value
62
+ value = options[:greater_than_or_equal_to] || options[:greater_than]
63
+ value = value.min if value.respond_to?(:min)
64
+ value
65
+ end
66
+
67
+ def max_value
68
+ value = options[:less_than_or_equal_to] || options[:less_than]
69
+ value = value.max if value.respond_to?(:max)
70
+ value
71
+ end
72
+ end
73
+
74
+ module HelperMethods
75
+ # Places ActiveRecord-style validations on the pixel height of the file assigned.
76
+ # The possible options are:
77
+ # * +in+: a Range of bytes (i.e. +1..1.megabyte+),
78
+ # * +less_than+: equivalent to :in => 0..options[:less_than]
79
+ # * +greater_than+: equivalent to :in => options[:greater_than]..Infinity
80
+ # * +message+: error message to display, use :min and :max as replacements
81
+ # * +if+: A lambda or name of an instance method. Validation will only
82
+ # be run if this lambda or method returns true.
83
+ # * +unless+: Same as +if+ but validates if lambda or method returns false.
84
+ def validates_attachment_height(*attr_names)
85
+ validates_with AttachmentHeightValidator, _merge_attributes(attr_names)
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,89 @@
1
+ require 'active_model/validations/numericality'
2
+
3
+ module Paperclip
4
+ module Validators
5
+ class AttachmentWidthValidator < ActiveModel::Validations::NumericalityValidator
6
+ AVAILABLE_CHECKS = [:less_than, :less_than_or_equal_to, :greater_than, :greater_than_or_equal_to]
7
+
8
+ def initialize(options)
9
+ extract_options(options)
10
+ super
11
+ end
12
+
13
+ def validate_each(record, attr_name, value)
14
+ attachment = record.send(attr_name)
15
+ dimensions = Paperclip::Geometry.from_file(attachment.queued_for_write[:original])
16
+ value = dimensions.width.to_i
17
+ options.slice(*AVAILABLE_CHECKS).each do |option, option_value|
18
+ option_value = extract_option_value(option, option_value)
19
+ unless value.send(CHECKS[option], option_value)
20
+ error_message_key = options[:in] ? :in_between : option
21
+ record.errors.add(attr_name, error_message_key, filtered_options(value).merge(
22
+ :min => min_value,
23
+ :max => max_value
24
+ ))
25
+ end
26
+ end
27
+ end
28
+
29
+ def check_validity!
30
+ unless (AVAILABLE_CHECKS + [:in]).any? { |argument| options.has_key?(argument) }
31
+ raise ArgumentError, "You must pass either :less_than, :greater_than, or :in to the validator"
32
+ end
33
+ end
34
+
35
+ private
36
+
37
+ def extract_options(options)
38
+ if range = options[:in]
39
+ if !options[:in].respond_to?(:call)
40
+ options[:less_than_or_equal_to] = range.max
41
+ options[:greater_than_or_equal_to] = range.min
42
+ else
43
+ options[:less_than_or_equal_to] = range
44
+ options[:greater_than_or_equal_to] = range
45
+ end
46
+ end
47
+ end
48
+
49
+ def extract_option_value(option, option_value)
50
+ if option_value.is_a?(Range)
51
+ if [:less_than, :less_than_or_equal_to].include?(option)
52
+ option_value.max
53
+ else
54
+ option_value.min
55
+ end
56
+ else
57
+ option_value
58
+ end
59
+ end
60
+
61
+ def min_value
62
+ value = options[:greater_than_or_equal_to] || options[:greater_than]
63
+ value = value.min if value.respond_to?(:min)
64
+ value
65
+ end
66
+
67
+ def max_value
68
+ value = options[:less_than_or_equal_to] || options[:less_than]
69
+ value = value.max if value.respond_to?(:max)
70
+ value
71
+ end
72
+ end
73
+
74
+ module HelperMethods
75
+ # Places ActiveRecord-style validations on the pixel width of the file assigned.
76
+ # The possible options are:
77
+ # * +in+: a Range of bytes (i.e. +1..1.megabyte+),
78
+ # * +less_than+: equivalent to :in => 0..options[:less_than]
79
+ # * +greater_than+: equivalent to :in => options[:greater_than]..Infinity
80
+ # * +message+: error message to display, use :min and :max as replacements
81
+ # * +if+: A lambda or name of an instance method. Validation will only
82
+ # be run if this lambda or method returns true.
83
+ # * +unless+: Same as +if+ but validates if lambda or method returns false.
84
+ def validates_attachment_width(*attr_names)
85
+ validates_with AttachmentWidthValidator, _merge_attributes(attr_names)
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,86 @@
1
+ module Paperclip
2
+ # Handles thumbnailing images that are uploaded.
3
+ class OffsetThumbnail < Processor
4
+
5
+ attr_accessor :current_geometry, :target_geometry, :format, :whiny, :animated, :scale, :crop_and_offset
6
+
7
+ # List of formats that we need to preserve animation
8
+ ANIMATED_FORMATS = %w(gif)
9
+
10
+ # Creates a Thumbnail object set to work on the +file+ given. It
11
+ # will attempt to transform the image into one defined by +target_geometry+
12
+ # which is a "WxH"-style string. +format+ will be inferred from the +file+
13
+ # unless specified. Thumbnail creation will raise no errors unless
14
+ # +whiny+ is true (which it is, by default. If +convert_options+ is
15
+ # set, the options will be appended to the convert command upon image conversion
16
+ #
17
+ # Options include:
18
+ #
19
+ # +geometry+ - the desired width and height of the thumbnail (required)
20
+ # +file_geometry_parser+ - an object with a method named +from_file+ that takes an image file and produces its geometry and a +transformation_to+. Defaults to Paperclip::Geometry
21
+ # +string_geometry_parser+ - an object with a method named +parse+ that takes a string and produces an object with +width+, +height+, and +to_s+ accessors. Defaults to Paperclip::Geometry
22
+ # +source_file_options+ - flags passed to the +convert+ command that influence how the source file is read
23
+ # +convert_options+ - flags passed to the +convert+ command that influence how the image is processed
24
+ # +whiny+ - whether to raise an error when processing fails. Defaults to true
25
+ # +format+ - the desired filename extension
26
+ # +animated+ - whether to merge all the layers in the image. Defaults to true
27
+ def initialize(file, options = {}, attachment = nil)
28
+ super
29
+
30
+ geometry = options[:geometry] # this is not an option
31
+ @file = file
32
+ @crop = geometry[-1,1] == '#'
33
+ @target_geometry = (options[:string_geometry_parser] || Geometry).parse(geometry)
34
+ @current_geometry = (options[:file_geometry_parser] || Geometry).from_file(@file)
35
+ @whiny = options[:whiny].nil? ? true : options[:whiny]
36
+ @format = options[:format]
37
+ @animated = options[:animated].nil? ? true : options[:animated]
38
+ @scale = options[:scale]
39
+ @crop_and_offset = options[:crop_and_offset]
40
+ @current_format = File.extname(@file.path)
41
+ @basename = File.basename(@file.path, @current_format)
42
+ end
43
+
44
+ # Performs the conversion of the +file+ into a thumbnail. Returns the Tempfile
45
+ # that contains the new image.
46
+ def make
47
+ src = @file
48
+ dst = Tempfile.new([@basename, @format ? ".#{@format}" : ''])
49
+ dst.binmode
50
+
51
+ begin
52
+ parameters = []
53
+ parameters << ":source"
54
+ parameters << transformation_command
55
+ parameters << ":dest"
56
+
57
+ parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ")
58
+
59
+ success = Paperclip.run("convert", parameters, :source => "#{File.expand_path(src.path)}#{'[0]' unless animated?}", :dest => File.expand_path(dst.path))
60
+ rescue Cocaine::ExitStatusError => e
61
+ raise Paperclip::Error, "There was an error processing the thumbnail for #{@basename}: #{e}" if @whiny
62
+ rescue Cocaine::CommandNotFoundError => e
63
+ raise Paperclip::CommandNotFoundError.new("Could not run the `convert` command. Please install ImageMagick.")
64
+ end
65
+
66
+ dst
67
+ end
68
+
69
+ # Returns the command ImageMagick's +convert+ needs to transform the image
70
+ # into the thumbnail.
71
+ def transformation_command
72
+ trans = []
73
+ trans << "-coalesce" if animated?
74
+ trans << "-resize" << %["#{scale}"] unless scale.nil? || scale.empty?
75
+ trans << "-crop" << %["#{crop_and_offset}"] << "+repage"
76
+ trans
77
+ end
78
+
79
+ protected
80
+
81
+ # Return true if the format is animated
82
+ def animated?
83
+ @animated && ANIMATED_FORMATS.include?(@current_format[1..-1]) && (ANIMATED_FORMATS.include?(@format.to_s) || @format.blank?)
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :cropped_paperclip do
3
+ # # Task goes here
4
+ # end
data/script/rails ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env ruby
2
+ # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
3
+
4
+ ENGINE_ROOT = File.expand_path('../..', __FILE__)
5
+ ENGINE_PATH = File.expand_path('../../lib/cropped_paperclip/engine', __FILE__)
6
+
7
+ require 'rails/all'
8
+ require 'rails/engine/commands'
data/spec/.DS_Store ADDED
Binary file
@@ -0,0 +1,2 @@
1
+ require 'spec_helper.rb'
2
+ require 'capybara/rspec'
@@ -0,0 +1,5 @@
1
+ require 'spec_helper'
2
+
3
+ describe CroppedPaperclip::UploadsController do
4
+
5
+ end
@@ -0,0 +1,261 @@
1
+ == Welcome to Rails
2
+
3
+ Rails is a web-application framework that includes everything needed to create
4
+ database-backed web applications according to the Model-View-Control pattern.
5
+
6
+ This pattern splits the view (also called the presentation) into "dumb"
7
+ templates that are primarily responsible for inserting pre-built data in between
8
+ HTML tags. The model contains the "smart" domain objects (such as Account,
9
+ Product, Person, Post) that holds all the business logic and knows how to
10
+ persist themselves to a database. The controller handles the incoming requests
11
+ (such as Save New Account, Update Product, Show Post) by manipulating the model
12
+ and directing data to the view.
13
+
14
+ In Rails, the model is handled by what's called an object-relational mapping
15
+ layer entitled Active Record. This layer allows you to present the data from
16
+ database rows as objects and embellish these data objects with business logic
17
+ methods. You can read more about Active Record in
18
+ link:files/vendor/rails/activerecord/README.html.
19
+
20
+ The controller and view are handled by the Action Pack, which handles both
21
+ layers by its two parts: Action View and Action Controller. These two layers
22
+ are bundled in a single package due to their heavy interdependence. This is
23
+ unlike the relationship between the Active Record and Action Pack that is much
24
+ more separate. Each of these packages can be used independently outside of
25
+ Rails. You can read more about Action Pack in
26
+ link:files/vendor/rails/actionpack/README.html.
27
+
28
+
29
+ == Getting Started
30
+
31
+ 1. At the command prompt, create a new Rails application:
32
+ <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name)
33
+
34
+ 2. Change directory to <tt>myapp</tt> and start the web server:
35
+ <tt>cd myapp; rails server</tt> (run with --help for options)
36
+
37
+ 3. Go to http://localhost:3000/ and you'll see:
38
+ "Welcome aboard: You're riding Ruby on Rails!"
39
+
40
+ 4. Follow the guidelines to start developing your application. You can find
41
+ the following resources handy:
42
+
43
+ * The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
44
+ * Ruby on Rails Tutorial Book: http://www.railstutorial.org/
45
+
46
+
47
+ == Debugging Rails
48
+
49
+ Sometimes your application goes wrong. Fortunately there are a lot of tools that
50
+ will help you debug it and get it back on the rails.
51
+
52
+ First area to check is the application log files. Have "tail -f" commands
53
+ running on the server.log and development.log. Rails will automatically display
54
+ debugging and runtime information to these files. Debugging info will also be
55
+ shown in the browser on requests from 127.0.0.1.
56
+
57
+ You can also log your own messages directly into the log file from your code
58
+ using the Ruby logger class from inside your controllers. Example:
59
+
60
+ class WeblogController < ActionController::Base
61
+ def destroy
62
+ @weblog = Weblog.find(params[:id])
63
+ @weblog.destroy
64
+ logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
65
+ end
66
+ end
67
+
68
+ The result will be a message in your log file along the lines of:
69
+
70
+ Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
71
+
72
+ More information on how to use the logger is at http://www.ruby-doc.org/core/
73
+
74
+ Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
75
+ several books available online as well:
76
+
77
+ * Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
78
+ * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
79
+
80
+ These two books will bring you up to speed on the Ruby language and also on
81
+ programming in general.
82
+
83
+
84
+ == Debugger
85
+
86
+ Debugger support is available through the debugger command when you start your
87
+ Mongrel or WEBrick server with --debugger. This means that you can break out of
88
+ execution at any point in the code, investigate and change the model, and then,
89
+ resume execution! You need to install ruby-debug to run the server in debugging
90
+ mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
91
+
92
+ class WeblogController < ActionController::Base
93
+ def index
94
+ @posts = Post.all
95
+ debugger
96
+ end
97
+ end
98
+
99
+ So the controller will accept the action, run the first line, then present you
100
+ with a IRB prompt in the server window. Here you can do things like:
101
+
102
+ >> @posts.inspect
103
+ => "[#<Post:0x14a6be8
104
+ @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
105
+ #<Post:0x14a6620
106
+ @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
107
+ >> @posts.first.title = "hello from a debugger"
108
+ => "hello from a debugger"
109
+
110
+ ...and even better, you can examine how your runtime objects actually work:
111
+
112
+ >> f = @posts.first
113
+ => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
114
+ >> f.
115
+ Display all 152 possibilities? (y or n)
116
+
117
+ Finally, when you're ready to resume execution, you can enter "cont".
118
+
119
+
120
+ == Console
121
+
122
+ The console is a Ruby shell, which allows you to interact with your
123
+ application's domain model. Here you'll have all parts of the application
124
+ configured, just like it is when the application is running. You can inspect
125
+ domain models, change values, and save to the database. Starting the script
126
+ without arguments will launch it in the development environment.
127
+
128
+ To start the console, run <tt>rails console</tt> from the application
129
+ directory.
130
+
131
+ Options:
132
+
133
+ * Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
134
+ made to the database.
135
+ * Passing an environment name as an argument will load the corresponding
136
+ environment. Example: <tt>rails console production</tt>.
137
+
138
+ To reload your controllers and models after launching the console run
139
+ <tt>reload!</tt>
140
+
141
+ More information about irb can be found at:
142
+ link:http://www.rubycentral.org/pickaxe/irb.html
143
+
144
+
145
+ == dbconsole
146
+
147
+ You can go to the command line of your database directly through <tt>rails
148
+ dbconsole</tt>. You would be connected to the database with the credentials
149
+ defined in database.yml. Starting the script without arguments will connect you
150
+ to the development database. Passing an argument will connect you to a different
151
+ database, like <tt>rails dbconsole production</tt>. Currently works for MySQL,
152
+ PostgreSQL and SQLite 3.
153
+
154
+ == Description of Contents
155
+
156
+ The default directory structure of a generated Ruby on Rails application:
157
+
158
+ |-- app
159
+ | |-- assets
160
+ | |-- images
161
+ | |-- javascripts
162
+ | `-- stylesheets
163
+ | |-- controllers
164
+ | |-- helpers
165
+ | |-- mailers
166
+ | |-- models
167
+ | `-- views
168
+ | `-- layouts
169
+ |-- config
170
+ | |-- environments
171
+ | |-- initializers
172
+ | `-- locales
173
+ |-- db
174
+ |-- doc
175
+ |-- lib
176
+ | `-- tasks
177
+ |-- log
178
+ |-- public
179
+ |-- script
180
+ |-- test
181
+ | |-- fixtures
182
+ | |-- functional
183
+ | |-- integration
184
+ | |-- performance
185
+ | `-- unit
186
+ |-- tmp
187
+ | |-- cache
188
+ | |-- pids
189
+ | |-- sessions
190
+ | `-- sockets
191
+ `-- vendor
192
+ |-- assets
193
+ `-- stylesheets
194
+ `-- plugins
195
+
196
+ app
197
+ Holds all the code that's specific to this particular application.
198
+
199
+ app/assets
200
+ Contains subdirectories for images, stylesheets, and JavaScript files.
201
+
202
+ app/controllers
203
+ Holds controllers that should be named like weblogs_controller.rb for
204
+ automated URL mapping. All controllers should descend from
205
+ ApplicationController which itself descends from ActionController::Base.
206
+
207
+ app/models
208
+ Holds models that should be named like post.rb. Models descend from
209
+ ActiveRecord::Base by default.
210
+
211
+ app/views
212
+ Holds the template files for the view that should be named like
213
+ weblogs/index.html.erb for the WeblogsController#index action. All views use
214
+ eRuby syntax by default.
215
+
216
+ app/views/layouts
217
+ Holds the template files for layouts to be used with views. This models the
218
+ common header/footer method of wrapping views. In your views, define a layout
219
+ using the <tt>layout :default</tt> and create a file named default.html.erb.
220
+ Inside default.html.erb, call <% yield %> to render the view using this
221
+ layout.
222
+
223
+ app/helpers
224
+ Holds view helpers that should be named like weblogs_helper.rb. These are
225
+ generated for you automatically when using generators for controllers.
226
+ Helpers can be used to wrap functionality for your views into methods.
227
+
228
+ config
229
+ Configuration files for the Rails environment, the routing map, the database,
230
+ and other dependencies.
231
+
232
+ db
233
+ Contains the database schema in schema.rb. db/migrate contains all the
234
+ sequence of Migrations for your schema.
235
+
236
+ doc
237
+ This directory is where your application documentation will be stored when
238
+ generated using <tt>rake doc:app</tt>
239
+
240
+ lib
241
+ Application specific libraries. Basically, any kind of custom code that
242
+ doesn't belong under controllers, models, or helpers. This directory is in
243
+ the load path.
244
+
245
+ public
246
+ The directory available for the web server. Also contains the dispatchers and the
247
+ default HTML files. This should be set as the DOCUMENT_ROOT of your web
248
+ server.
249
+
250
+ script
251
+ Helper scripts for automation and generation.
252
+
253
+ test
254
+ Unit and functional tests along with fixtures. When using the rails generate
255
+ command, template test files will be generated for you and placed in this
256
+ directory.
257
+
258
+ vendor
259
+ External libraries that the application depends on. Also includes the plugins
260
+ subdirectory. If the app has frozen rails, those gems also go here, under
261
+ vendor/rails/. This directory is in the load path.