Rails 4: how to use $(document).ready() with turbo-links

2014年11月14日 14:20

CoffeeScript:

ready = ->

  ...your coffeescript goes here...

$(document).ready(ready)
$(document).on('page:load', ready)

Javascript

var ready;
ready = function() {

  ...your javascript goes here...

};

$(document).ready(ready);
$(document).on('page:load', ready);

继续阅读 »

A Rails API Pattern for Complex Collections

2013年8月26日 22:15

def index
  @recipe_collection = RecipeCollection.from_params(params)
  render json: @recipe_collection.recipes
end
class RecipeCollection
  attr_accessor :featured, :time_filter

  # Handles the logic of sorting params into a collection
  def self.from_params(params)
    RecipeCollection.new.tap do |recipe_collection|
      recipe_collection.time_filter = params[:time_filter]
      recipe_collection.featured = params[:featured]
    end
  end

  # Should return an ActiveRecord relation
  def recipes
    query = Recipe.scoped
    query.featured if featured.present?
    query.filter_by_time(time_filter)
  end

  def time_filter
  valid_time_filters.include?( @time_filter ) ? @time_filter : default_time_filter
  end

  def default_time_filter
    "today"
  end

  def valid_time_filters
    %w[ today yesterday this-week this-year ]
  end
end

继续阅读 »

Incremental Redesign with Rails

2013年7月31日 17:15

重构前

<%- if current_user.redesign_enabled? %>
  <%# new code %>
<%- else %>
  <%# old code %>
<%- end %>

重构后

class ApplicationController < ActionController::Base
  before_filter :add_view_path_for_redesign

  private

  def add_view_path_for_redesign
    if current_user.redesign_enabled?
      prepend_view_path Rails.root.join('app/views/redesign')
    end
  end
end
# original
app/views/users/edit.html.erb
app/views/users/show.html.erb

# redesign
app/views/redesign/users/edit.html.erb
app/views/redesign/users/show.html.erb

继续阅读 »

Rails Partial

2013年3月06日 22:33

Collection:

<%= render :partial => "common/post", :collection => @posts %>

Partials are very useful in rendering collections. When you pass a collection to a partial via the :collection option, the partial will be inserted once for each member in the collection

Object:

<%= render :partial => "customer", :object => @new_customer %>

继续阅读 »