Skip to content

Instantly share code, notes, and snippets.

@ryanb
Created May 6, 2011 01:10
Show Gist options
  • Save ryanb/958283 to your computer and use it in GitHub Desktop.
Save ryanb/958283 to your computer and use it in GitHub Desktop.
The Changelogs for Rails 3.1 Beta 1

Railties 3.1 RC4

  • The new rake task assets:clean removes precompiled assets. [fxn]

  • Application and plugin generation run bundle install unless --skip-gemfile or --skip-bundle. [fxn]

  • Fixed database tasks for jdbc* adapters #jruby [Rashmi Yadav]

  • Template generation for jdbcpostgresql #jruby [Vishnu Atrai]

  • Template generation for jdbcmysql and jdbcsqlite3 #jruby [Arun Agrawal]

  • The -j option of the application generator accepts an arbitrary string. If passed "foo", the gem "foo-rails" is added to the Gemfile, and the application JavaScript manifest requires "foo" and "foo_ujs". As of this writing "prototype-rails" and "jquery-rails" exist and provide those files via the asset pipeline. Default is "jquery". [fxn]

  • jQuery is no longer vendored, it is provided from now on by the jquery-rails gem. [fxn]

  • Prototype and Scriptaculous are no longer vendored, they are provided from now on by the prototype-rails gem. [fxn]

  • The scaffold controller will now produce SCSS file if Sass is available [Prem Sichanugrist]

  • The controller and resource generators will now automatically produce asset stubs (this can be turned off with --skip-assets). These stubs will use Coffee and Sass, if those libraries are available. [DHH]

  • jQuery is the new default JavaScript library. [fxn]

  • Changed scaffold and app generator to create Ruby 1.9 style hash when running on Ruby 1.9 [Prem Sichanugrist]

So instead of creating something like:

redirect_to users_path, :notice => "User has been created"

it will now be like this:

redirect_to users_path, notice: "User has been created"

You can also passing --old-style-hash to make Rails generate old style hash even you're on Ruby 1.9

  • Changed scaffold_controller generator to create format block for JSON instead of XML [Prem Sichanugrist]

  • Add using Turn with natural language test case names for test_help.rb when running with minitest (Ruby 1.9.2+) [DHH]

  • Direct logging of Active Record to STDOUT so it's shown inline with the results in the console [DHH]

  • Added config.force_ssl configuration which loads Rack::SSL middleware and force all requests to be under HTTPS protocol [DHH, Prem Sichanugrist, and Josh Peek]

  • Added rails plugin new command which generates rails plugin with gemspec, tests and dummy application for testing [Piotr Sarnacki]

  • Added -j parameter with jquery/prototype as options. Now you can create your apps with jQuery using rails new myapp -j jquery. The default is still Prototype. [siong1987]

  • Added Rack::Etag and Rack::ConditionalGet to the default middleware stack [José Valim]

  • Added Rack::Cache to the default middleware stack [Yehuda Katz and Carl Lerche]

  • Engine is now rack application [Piotr Sarnacki]

  • Added middleware stack to Engine [Piotr Sarnacki]

  • Engine can now load plugins [Piotr Sarnacki]

  • Engine can load its own environment file [Piotr Sarnacki]

  • Added helpers to call engines' route helpers from application and vice versa [Piotr Sarnacki]

  • Task for copying plugins' and engines' migrations to application's db/migrate directory [Piotr Sarnacki]

  • Changed ActionDispatch::Static to allow handling multiple directories [Piotr Sarnacki]

  • Added isolate_namespace() method to Engine, which sets Engine as isolated [Piotr Sarnacki]

  • Include all helpers from plugins and shared engines in application [Piotr Sarnacki]

Action Pack 3.1 RC4

  • Make sure escape_js returns SafeBuffer string if it receives SafeBuffer string [Prem Sichanugrist]

  • Fix escape_js to work correctly with the new SafeBuffer restriction [Paul Gallagher]

  • Brought back alternative convention for namespaced models in i18n [thoefer]

Now the key can be either "namespace.model" or "namespace/model" until further deprecation.

  • It is prohibited to perform a in-place SafeBuffer mutation [tenderlove]

The old behavior of SafeBuffer allowed you to mutate string in place via method like sub!. These methods can add unsafe strings to a safe buffer, and the safe buffer will continue to be marked as safe.

An example problem would be something like this:

<%= link_to('hello world', @user).sub!(/hello/, params[:xss])  %>

In the above example, an untrusted string (params[:xss]) is added to the safe buffer returned by link_to, and the untrusted content is successfully sent to the client without being escaped. To prevent this from happening sub! and other similar methods will now raise an exception when they are called on a safe buffer.

In addition to the in-place versions, some of the versions of these methods which return a copy of the string will incorrectly mark strings as safe. For example:

<%= link_to('hello world', @user).sub(/hello/, params[:xss]) %>

The new versions will now ensure that all strings returned by these methods on safe buffers are marked unsafe.

You can read more about this change in http://groups.google.com/group/rubyonrails-security/browse_thread/thread/2e516e7acc96c4fb

  • Warn if we cannot verify CSRF token authenticity [José Valim]

  • Allow AM/PM format in datetime selectors [Aditya Sanghi]

  • Only show dump of regular env methods on exception screen (not all the rack crap) [DHH]

  • auto_link has been removed with no replacement. If you still use auto_link please install the rails_autolink gem: http://github.com/tenderlove/rails_autolink [tenderlove]

  • Added streaming support, you can enable it with: [José Valim]

class PostsController < ActionController::Base
  stream :only => :index
end

Please read the docs at ActionController::Streaming for more information.

  • Added ActionDispatch::Request.ignore_accept_header to ignore accept headers and only consider the format given as parameter [José Valim]

  • Created ActionView::Renderer and specified an API for ActionView::Context, check those objects for more information [José Valim]

  • Added ActionController::ParamsWrapper to wrap parameters into a nested hash, and will be turned on for JSON request in new applications by default [Prem Sichanugrist]

This can be customized by setting ActionController::Base.wrap_parameters in config/initializer/wrap_parameters.rb

  • RJS has been extracted out to a gem. [fxn]

  • Implicit actions named not_implemented can be rendered. [Santiago Pastorino]

  • Wildcard route will always match the optional format segment by default. [Prem Sichanugrist]

For example if you have this route:

map '*pages' => 'pages#show'

by requesting '/foo/bar.json', your params[:pages] will be equals to "foo/bar" with the request format of JSON. If you want the old 3.0.x behavior back, you could supply :format => false like this:

map '*pages' => 'pages#show', :format => false
  • Added Base.http_basic_authenticate_with to do simple http basic authentication with a single class method call [DHH]
class PostsController < ApplicationController
  USER_NAME, PASSWORD = "dhh", "secret"

  before_filter :authenticate, :except => [ :index ]

  def index
    render :text => "Everyone can see me!"
  end

  def edit
    render :text => "I'm only accessible if you know the password"
  end

  private
    def authenticate
      authenticate_or_request_with_http_basic do |user_name, password|
        user_name == USER_NAME && password == PASSWORD
      end
    end
end

..can now be written as

class PostsController < ApplicationController
  http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index

  def index
    render :text => "Everyone can see me!"
  end

  def edit
    render :text => "I'm only accessible if you know the password"
  end
end
  • Allow you to add force_ssl into controller to force browser to transfer data via HTTPS protocol on that particular controller. You can also specify :only or :except to specific it to particular action. [DHH and Prem Sichanugrist]

  • Allow FormHelper#form_for to specify the :method as a direct option instead of through the :html hash [DHH]

form_for(@post, remote: true, method: :delete) instead of form_for(@post, remote: true, html: { method: :delete })
  • Make JavaScriptHelper#j() an alias for JavaScriptHelper#escape_javascript() -- note this then supersedes the Object#j() method that the JSON gem adds within templates using the JavaScriptHelper [DHH]

  • Sensitive query string parameters (specified in config.filter_parameters) will now be filtered out from the request paths in the log file. [Prem Sichanugrist, fxn]

  • URL parameters which return false for to_param now appear in the query string (previously they were removed) [Andrew White]

  • URL parameters which return nil for to_param are now removed from the query string [Andrew White]

  • ActionDispatch::MiddlewareStack now uses composition over inheritance. It is no longer an array which means there may be methods missing that were not tested.

  • Add an :authenticity_token option to form_tag for custom handling or to omit the token (pass :authenticity_token => false). [Jakub Kuźma, Igor Wiedler]

  • HTML5 button_tag helper. [Rizwan Reza]

  • Template lookup now searches further up in the inheritance chain. [Artemave]

  • Brought back config.action_view.cache_template_loading, which allows to decide whether templates should be cached or not. [Piotr Sarnacki]

  • url_for and named url helpers now accept :subdomain and :domain as options, [Josh Kalderimis]

  • The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused (check the documentation for examples). [Josh Kalderimis]

  • Added config.action_controller.include_all_helpers. By default helper :all is done in ActionController::Base, which includes all the helpers by default. Setting include_all_helpers to false will result in including only application_helper and helper corresponding to controller (like foo_helper for foo_controller). [Piotr Sarnacki]

  • Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a :data hash of options:

tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
# => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />

Keys are dasherized. Values are JSON-encoded, except for strings and symbols. [Stephen Celis]

  • Deprecate old template handler API. The new API simply requires a template handler to respond to call. [José Valim]

  • :rhtml and :rxml were finally removed as template handlers. [José Valim]

  • Moved etag responsibility from ActionDispatch::Response to the middleware stack. [José Valim]

  • Rely on Rack::Session stores API for more compatibility across the Ruby world. This is backwards incompatible since Rack::Session expects #get_session to accept 4 arguments and requires #destroy_session instead of simply #destroy. [José Valim]

  • file_field automatically adds :multipart => true to the enclosing form. [Santiago Pastorino]

  • Renames csrf_meta_tag -> csrf_meta_tags, and aliases csrf_meta_tag for backwards compatibility. [fxn]

  • Add Rack::Cache to the default stack. Create a Rails store that delegates to the Rails cache, so by default, whatever caching layer you are using will be used for HTTP caching. Note that Rack::Cache will be used if you use #expires_in, #fresh_when or #stale with :public => true. Otherwise, the caching rules will apply to the browser only. [Yehuda Katz, Carl Lerche]

Active Record 3.1 RC4

  • AR#pluralize_table_names can be used to singularize/pluralize table name of an individual model:
class User < ActiveRecord::Base
  self.pluralize_table_names = false
end

Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names. [Guillermo Iguaran]

  • Add block setting of attributes to singular associations:
class User < ActiveRecord::Base
  has_one :account
end

user.build_account{ |a| a.credit_limit => 100.0 }

The block is called after the instance has been initialized. [Andrew White]

  • Add ActiveRecord::Base.attribute_names to return a list of attribute names. This will return an empty array if the model is abstract or table does not exists. [Prem Sichanugrist]

  • CSV Fixtures are deprecated and support will be removed in Rails 3.2.0

  • AR#new, AR#create and AR#update_attributes all accept a second hash as option that allows you to specify which role to consider when assigning attributes. This is built on top of ActiveModel's new mass assignment capabilities:

class Post < ActiveRecord::Base
  attr_accessible :title
  attr_accessible :title, :published_at, :as => :admin
end

Post.new(params[:post], :as => :admin)

assign_attributes() with similar API was also added and attributes=(params, guard) was deprecated.

[Josh Kalderimis]

  • default_scope can take a block, lambda, or any other object which responds to call for lazy evaluation:
default_scope { ... }
default_scope lambda { ... }
default_scope method(:foo)

This feature was originally implemented by Tim Morgan, but was then removed in favour of defining a default_scope class method, but has now been added back in by Jon Leighton. The relevant lighthouse ticket is #1812.

  • Default scopes are now evaluated at the latest possible moment, to avoid problems where scopes would be created which would implicitly contain the default scope, which would then be impossible to get rid of via Model.unscoped.

Note that this means that if you are inspecting the internal structure of an ActiveRecord::Relation, it will not contain the default scope, though the resulting query will do. You can get a relation containing the default scope by calling ActiveRecord#with_default_scope, though this is not part of the public API.

[Jon Leighton]

  • If you wish to merge default scopes in special ways, it is recommended to define your default scope as a class method and use the standard techniques for sharing code (inheritance, mixins, etc.):
class Post < ActiveRecord::Base
  def self.default_scope
    where(:published => true).where(:hidden => false)
  end
end

[Jon Leighton]

  • PostgreSQL adapter only supports PostgreSQL version 8.2 and higher.

  • ConnectionManagement middleware is changed to clean up the connection pool after the rack body has been flushed.

  • Added an update_column method on ActiveRecord. This new method updates a given attribute on an object, skipping validations and callbacks. It is recommended to use #update_attribute unless you are sure you do not want to execute any callback, including the modification of the updated_at column. It should not be called on new records.

Example:

User.first.update_column(:name, "sebastian")         # => true

[Sebastian Martinez]

  • Associations with a :through option can now use any association as the through or source association, including other associations which have a :through option and has_and_belongs_to_many associations [Jon Leighton]

  • The configuration for the current database connection is now accessible via ActiveRecord::Base.connection_config. [fxn]

  • limits and offsets are removed from COUNT queries unless both are supplied. For example:

People.limit(1).count           # => 'SELECT COUNT(*) FROM people'
People.offset(1).count          # => 'SELECT COUNT(*) FROM people'
People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1'

[lighthouse #6262]

  • ActiveRecord::Associations::AssociationProxy has been split. There is now an Association class (and subclasses) which are responsible for operating on associations, and then a separate, thin wrapper called CollectionProxy, which proxies collection associations.

This prevents namespace pollution, separates concerns, and will allow further refactorings.

Singular associations (has_one, belongs_to) no longer have a proxy at all. They simply return the associated record or nil. This means that you should not use undocumented methods such as bob.mother.create - use bob.create_mother instead.

[Jon Leighton]

  • Make has_many :through associations work correctly when you build a record and then save it. This requires you to set the :inverse_of option on the source reflection on the join model, like so:
class Post < ActiveRecord::Base
  has_many :taggings
  has_many :tags, :through => :taggings
end

class Tagging < ActiveRecord::Base
  belongs_to :post
  belongs_to :tag, :inverse_of => :tagging # :inverse_of must be set!
end

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :posts, :through => :taggings
end

post = Post.first
tag = post.tags.build :name => "ruby"
tag.save # will save a Taggable linking to the post

[Jon Leighton]

  • Support the :dependent option on has_many :through associations. For historical and practical reasons, :delete_all is the default deletion strategy employed by association.delete(*records), despite the fact that the default strategy is :nullify for regular has_many. Also, this only works at all if the source reflection is a belongs_to. For other situations, you should directly modify the through association. [Jon Leighton]

  • Changed the behavior of association.destroy for has_and_belongs_to_many and has_many :through. From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link', not (necessarily) 'get rid of the associated records'.

Previously, has_and_belongs_to_many.destroy(*records) would destroy the records themselves. It would not delete any records in the join table. Now, it deletes the records in the join table.

Previously, has_many_through.destroy(*records) would destroy the records themselves, and the records in the join table. [Note: This has not always been the case; previous version of Rails only deleted the records themselves.] Now, it destroys only the records in the join table.

Note that this change is backwards-incompatible to an extent, but there is unfortunately no way to 'deprecate' it before changing it. The change is being made in order to have consistency as to the meaning of 'destroy' or 'delete' across the different types of associations.

If you wish to destroy the records themselves, you can do records.association.each(&:destroy)

[Jon Leighton]

  • Add :bulk => true option to change_table to make all the schema changes defined in change_table block using a single ALTER statement. [Pratik Naik]

Example:

change_table(:users, :bulk => true) do |t|
  t.string :company_name
  t.change :birthdate, :datetime
end

This will now result in:

ALTER TABLE `users` ADD COLUMN `company_name` varchar(255), CHANGE `updated_at` `updated_at` datetime DEFAULT NULL
  • Removed support for accessing attributes on a has_and_belongs_to_many join table. This has been documented as deprecated behavior since April 2006. Please use has_many :through instead. [Jon Leighton]

  • Added a create_association! method for has_one and belongs_to associations. [Jon Leighton]

  • Migration files generated from model and constructive migration generators (for example, add_name_to_users) use the reversible migration's change method instead of the ordinary up and down methods. [Prem Sichanugrist]

  • Removed support for interpolating string SQL conditions on associations. Instead, you should use a proc, like so:

Before:

has_many :things, :conditions => 'foo = #{bar}'

After:

has_many :things, :conditions => proc { "foo = #{bar}" }

Inside the proc, 'self' is the object which is the owner of the association, unless you are eager loading the association, in which case 'self' is the class which the association is within.

You can have any "normal" conditions inside the proc, so the following will work too:

has_many :things, :conditions => proc { ["foo = ?", bar] }

Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call 'record' to get the record being inserted or deleted. This is now passed as an argument to the proc.

  • Added ActiveRecord::Base#has_secure_password (via ActiveModel::SecurePassword) to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]. Example:
# Schema: User(name:string, password_digest:string, password_salt:string)
class User < ActiveRecord::Base
  has_secure_password
end

user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch")
user.save                                                      # => false, password required
user.password = "mUc3m00RsqyRe"
user.save                                                      # => false, confirmation doesn't match
user.password_confirmation = "mUc3m00RsqyRe"
user.save                                                      # => true
user.authenticate("notright")                                  # => false
user.authenticate("mUc3m00RsqyRe")                             # => user
User.find_by_name("david").try(:authenticate, "notright")      # => nil
User.find_by_name("david").try(:authenticate, "mUc3m00RsqyRe") # => user
  • When a model is generated add_index is added by default for belongs_to or references columns
rails g model post user:belongs_to will generate the following:
class CreatePosts < ActiveRecord::Migration
  def up
    create_table :posts do |t|
      t.belongs_to :user

      t.timestamps
    end

    add_index :posts, :user_id
  end

  def down
    drop_table :posts
  end
end

[Santiago Pastorino]

  • Setting the id of a belongs_to object will update the reference to the object. [#2989 state:resolved]

  • ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed to closer match normal Ruby dup and clone semantics.

  • Calling ActiveRecord::Base#clone will result in a shallow copy of the record, including copying the frozen state. No callbacks will be called.

  • Calling ActiveRecord::Base#dup will duplicate the record, including calling after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return true for new_record?, have a nil id field, and is saveable.

  • Migrations can be defined as reversible, meaning that the migration system will figure out how to reverse your migration. To use reversible migrations, mjust define the "change" method. For example:

class MyMigration < ActiveRecord::Migration
  def change
    create_table(:horses) do
      t.column :content, :text
      t.column :remind_at, :datetime
    end
  end
end

Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define 'up' and 'down' in your migration. If you define something in change that cannot be reversed, an IrreversibleMigration exception will be raised when going down.

  • Migrations should use instance methods rather than class methods:
class FooMigration < ActiveRecord::Migration
  def up
    ...
  end
end

[Aaron Patterson]

  • has_one maintains the association with separate after_create / after_update instead of a single after_save. [fxn]

  • The following code:

Model.limit(10).scoping { Model.count }

now generates the following SQL:

SELECT COUNT(*) FROM models LIMIT 10

This may not return what you want. Instead, you may with to do something like this:

Model.limit(10).scoping { Model.all.size }

[Aaron Patterson]

Active Model 3.1 RC4

  • attr_accessible and friends now accepts :as as option to specify a role [Josh Kalderimis]

  • Add support for proc or lambda as an option for InclusionValidator, ExclusionValidator, and FormatValidator [Prem Sichanugrist]

You can now supply Proc, lambda, or anything that respond to #call in those validations, and it will be called with current record as an argument. That given proc or lambda must returns an object which respond to #include? for InclusionValidator and ExclusionValidator, and returns a regular expression object for FormatValidator.

  • Added ActiveModel::SecurePassword to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]

  • ActiveModel::AttributeMethods allows attributes to be defined on demand [Alexander Uvarov]

Active Support 3.1 RC4

  • ActiveSupport::Dependencies now raises NameError if it finds an existing constant in load_missing_constant. This better reflects the nature of the error which is usually caused by calling constantize on a nested constant. [Andrew White]

  • Deprecated ActiveSupport::SecureRandom in favor of SecureRandom from the standard library [Jon Leighton]

  • New reporting method Kernel#quietly. [fxn]

  • Add String#inquiry as a convenience method for turning a string into a StringInquirer object [DHH]

  • Add Object#in? to test if an object is included in another object [Prem Sichanugrist, Brian Morearty, John Reitano]

  • LocalCache strategy is now a real middleware class, not an anonymous class posing for pictures.

  • ActiveSupport::Dependencies::ClassCache class has been introduced for holding references to reloadable classes.

  • ActiveSupport::Dependencies::Reference has been refactored to take direct advantage of the new ClassCache.

  • Backports Range#cover? as an alias for Range#include? in Ruby 1.8 [Diego Carrion, fxn]

  • Added weeks_ago and prev_week to Date/DateTime/Time. [Rob Zolkos, fxn]

  • Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! [Andrew White]

Active Resource 3.1 RC4

  • The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set self.format = :xml in the class. eg.
class User < ActiveResource::Base
  self.format = :xml
end

Action Mailer 3.1 RC4

  • No changes
@rhossi
Copy link

rhossi commented May 11, 2011

Awesome. Nice work guys.

@andersondias
Copy link

Thank you Ryan! Great job!

@brownman
Copy link

ryanb rocks !

@saimonmoore
Copy link

Very handy. Can we make this a tradition? ;) Thanks Ryan.

@gamafranco
Copy link

w00t!

@stjhimy
Copy link

stjhimy commented May 12, 2011

wowwww sounds great, ryanb you rock hard man!

@victusfate
Copy link

:D

@assimovt
Copy link

Great! So much easier than comparison in Github. Thanks!

@talbright
Copy link

Thanks Ryan!

@krokhale
Copy link

Thanks ryan!

@ChuckJHardy
Copy link

Some great changes and additions. Thanks!

@lukashoffmann
Copy link

this rocks, thx ryan!

@antoniorosado
Copy link

Great list! Thanks Ryan.

@brownman
Copy link

i get all comments to my github inbox - strange !
does someone know the reason ?

@dolzenko
Copy link

This must be the most commented on Gist ever. And yeah it is annoying.
On commits we have an option to unsubscribe from notifications, but can't find that for Gists, time for feature request?

@rodrei
Copy link

rodrei commented May 18, 2011 via email

@csph8
Copy link

csph8 commented May 18, 2011

Its good one.
Tx

@victusfate
Copy link

victusfate commented May 18, 2011 via email

@tadast
Copy link

tadast commented May 18, 2011

@victusfate you can edit notification settings in your profile to not receive emails. You will still get github notifications though

@victusfate
Copy link

victusfate commented May 18, 2011 via email

@foeken
Copy link

foeken commented May 23, 2011

Some stuff that might cause issues when migrating to Rails 3.1:

  • By adding the new :as => :admin option to ActiveRecord updates, all AR initializers now require two arguments. If you override any initializers, this must be fixed in your overrides.
  • The Flash hash no longer supports .values, though .keys is still available....
  • ActionDispatch::Request no longer has a request_uri method. The fullpath method might be a suitable replacement.
  • I had some issues with custom columns in an sql query (SELECT foo AS bar). Previously the 'bar' column would always yield a string value, it now seems to be typecasted properly. (maybe this is the mysql2 gem)
  • Caveat with using asset/images You are required to fix all your css files to use asset_paths. Otherwise production mode won't render the images. (logical, but still might require a bigger warning)

UPDATE: Use this script to handle all this stuff...

#!/usr/bin/ruby
require "rubygems"

Dir["**/*.css.scss"].entries.each do |old_filename|

  lines = []
  File.open(old_filename, "r"){|f| lines = f.readlines }
  new_filename = old_filename.gsub(/.css.scss/,".css.erb.scss")

  # Asset paths
  s1 = /url\(\/assets\/(.*)\)/
  r1 = "url('<%= asset_path(\"\\1\") %>')"
  lines = lines.inject([]){|l, line| l << line.gsub(s1, r1)}

  # Import statements
  s2 = ".css.scss"
  r2 = ".css.erb.scss"    
  lines = lines.inject([]){|l, line| l << line.gsub(s2, r2)}

  File.open(old_filename, "w"){|f| f.write(lines) }
  File.rename old_filename, new_filename

end
  • Note we need to have .erb.scss and NOT .scss.erb (else scss won't be able to import them), All of this feels quite...wonky
  • When storing a custom class in an ActiveRecord object previously (old rails versions) used .to_sql , more recently (3.06/7) to_yaml was used. Now to_s is used and the value is not quoted (bug?)
  • I had some strange behavior using create! with it being run twice, still figuring out what is happing there. For now it's easy to fix by using .new and .save!. Will try to figure out what is actually wrong there...
  • If you are using rspec, you should use rspec-rails 2.6.1.beta1, this --semi-- works. Though I can't get single specs to run. (UPDATE: use rspec instead of ruby)
  • If you are using the asset pipeline and running a single worker server it might be quite slow since everything now goes through rails, I recommend unicorn or pow using multiple workers to keep things snappy.
  • When using the asset pipeline, don;t forget to copy over the compressor settings for your production mode
  • If you are getting freaky error messages on ActiveRecord Mysql log, try disabling the newrelic gem, it is broken for 3.1
  • Use native @import for scss not the sprockets requires, else you won't be able top use variables and mixins defined in other files.
  • If you are having issues with to_xml / to_xs, check Hpricot. It seems to break this on 3.1
  • If you use scss's native @import statements the imported files will not generate a refresh of the compiled files when changed. Using the native sprockets include works, but then you can't use shared variables since each file is compiled separately...

@aurels
Copy link

aurels commented Jun 6, 2011

I can't get rid of those warnings :

DEPRECATION WARNING: ref is deprecated and will be removed from Rails 3.2. (called from <top (required)> at /myapppath/config/application.rb:7)

and

DEPRECATION WARNING: new is deprecated and will be removed from Rails 3.2. (called from <top (required)> at /myapppath/config/application.rb:7)

and

DEPRECATION WARNING: get is deprecated and will be removed from Rails 3.2. (called from follow_redirect! at /Users/aurels/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/forwardable.rb:182)

Any ideas ?

@Backoo
Copy link

Backoo commented Jun 10, 2011

Wonderful! I have no more words.

@sohara
Copy link

sohara commented Jun 13, 2011

@aurels Are you using devise? I got rid of the same deprecation warnings by upgrading my devise version from 1.2.x to 1.3.4.

@aurels
Copy link

aurels commented Jun 14, 2011

@sohara : yes that was devise. Thanks !

@gentletrader
Copy link

In "Railties 3.1 RC4" it's said, when talking about the -j option, that the default javascript library is still prototype. I'm afraid there is a mistake there since it's changed into jquery.

@jtomasrl
Copy link

I think is a bad idea to lead every css or js that's not n use in the current view, for example when in user controller you dont need the admin css or js to load, its a waste of bandwidth. and slow loading times, and for example what happend if a have a Jquery for $('#content') in user that has an action and in admin I have another action for $('#content') that makes another thing

@ryanb
Copy link
Author

ryanb commented Jul 23, 2011

@jtomasrl Rails 3.1 does not require you to load all js/css files at once, it is just the default behavior. You can easily change the require_tree line in application.js to include whatever files you want. You can make an admin.js file which includes all of the admin related JavaScript too. The asset pipeline is very powerful in this way.

@jtomasrl
Copy link

@ryanb so can you omit files from require_tree, and except => file for example, or an alt folder to place files i dont want to load

@ryanb
Copy link
Author

ryanb commented Jul 24, 2011

@jtomasri, I'm not certain how to omit files from require_tree, but you can place files in a directory and require_tree on that. This way you can organize the public javascript files from admin side, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment