Skip to content

Instantly share code, notes, and snippets.

View liushooter's full-sized avatar

Shooter liushooter

View GitHub Profile
class PostsController < ActionController::Base
def create
Post.create(post_params)
end
def update
Post.find(params[:id]).update_attributes!(post_params)
end
private
@liushooter
liushooter / test.rb
Created November 26, 2013 03:21 — forked from clemens/test.rb
>> require 'bigdecimal'
=> true
>> require 'bigdecimal/util'
=> true
>> BigDecimal('40.30') == 40.3
=> true
>> BigDecimal('40.90') == 40.9
=> true
>> BigDecimal('40.10') == 40.1
#! /usr/bin/env ruby
str = $stdin.read
if RUBY_VERSION < '1.9'
print str
exit
end
str.force_encoding 'utf-8'
str.gsub! /(\p{Han})([a-zA-Z0-9\(\)\[\]\{\}])/u do
"#$1 #$2"
Here is a list of scopes to use in Sublime Text 2 snippets -
ActionScript: source.actionscript.2
AppleScript: source.applescript
ASP: source.asp
Batch FIle: source.dosbatch
C#: source.cs
C++: source.c++
Clojure: source.clojure
CoffeeScript: source.coffee

Routes

小心地使用 Match(Rails 3 已实现)

Rails 3 提供了 match 方法供我们自定义 routes,然而我们要小心使用它以避免“跨站脚本攻击”(XSS Attack)。比如像这样的 routes:

注:(r3 代表 Rails 3,r4 代表 Rails 4)

# routes.rb
class ApiLogger < Grape::Middleware::Base
def before
Rails.logger.info "[api] Requested: #{request_log_data.to_json}\n" +
"[api] #{response_log_data[:description]} #{response_log_data[:source_file]}:#{response_log_data[:source_line]}"
end
private
def request_log_data
module Todo
class API < Grape::API
use Rack::Session::Cookie
version 'v1', :format => :json
helpers do
def current_user
return nil if env['rack.session'][:user_id].nil?
@current_user ||= User.get(env['rack.session'][:user_id])
end
#
# Wide-open CORS config for nginx
#
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
#
types {
# other mime types...
application/json json;
}

善用 define_method

define_method 可以帮助我们动态的,快速的定义多个方法;比如有这样一个类:

class Post
  attr_accessor :title, :content, :state

  def initialize(title, content, state = :draft)
    @title, @content, @state = title, content, state