ruby 文件上传/下载

文件上传/下载

file_upload.rb
within "#employee_file_type_#{@file_type_1.id}" do
  attach_file "employee_files[#{@file_type_1.id}][]", "#{Rails.root}/spec/fixtures/files/amberbit.png"
end

#download
click_link 'Download'
page.response_headers['Content-Type'].should eq "application/pdf"

ruby 检测本地已定义

检测本地已定义

local_defined.rb
if local_assigns[:some_local].nil?
  #not defined
end

ruby gistfile1.rb

gistfile1.rb
class BasicObject
  def !=(other)
    return self.equal?(other)
  end  
end

a = "a" #=> "a"

a != a #=> true

ruby text_file_to_array.rb

text_file_to_array.rb
  def text_file_to_array
    File.open './search_phrases.txt' do |f|
      @search_phrases = Array.new
      f.each_line { |line|
        @search_phrases.push line
      }
    end
  end

ruby 初始化所有参数

初始化所有参数

initialize.rb
def initialize(attrs = {})
  attrs.each do |k, v|
    send("#{k}=", v)
  end
end

ruby 这是Rakefile的示例内容,您可以使用它来运行活动记录任务而不使用Rails。它假定使用相同的

这是Rakefile的示例内容,您可以使用它来运行活动记录任务而不使用Rails。它假设使用与rails使用相同的目录:`db / migrate`,`config / database.yml`。

Rakefile.rb
require 'bundler/setup'

require 'active_record'

include ActiveRecord::Tasks

db_dir = File.expand_path('../db', __FILE__)
config_dir = File.expand_path('../config', __FILE__)

DatabaseTasks.env = ENV['ENV'] || 'development'
DatabaseTasks.db_dir = db_dir
DatabaseTasks.database_configuration = YAML.load(File.read(File.join(config_dir, 'database.yml')))
DatabaseTasks.migrations_paths = File.join(db_dir, 'migrate')

task :environment do
  ActiveRecord::Base.configurations = DatabaseTasks.database_configuration
  ActiveRecord::Base.establish_connection DatabaseTasks.env
end

load 'active_record/railties/databases.rake'

ruby staging.rb

staging.rb
require File.expand_path("../production.rb", __FILE__)

RailsAppName::Application.configure do
  config.middleware.insert_after(::Rack::Lock, "::Rack::Auth::Basic", "Staging") do |u, p|
    [u, p] == [ENV['STAGING_USERNAME'], ENV['STAGING_PASSWORD']]
  end

  config.action_mailer.default_url_options = { :host => 'some-app.herokuapp.com' }
  config.action_mailer.asset_host = ""
end

ruby Amazon S3请求生成器类

Amazon S3请求生成器类

aws_S3.rb
class AwsS3
  AWS_ACCESS_KEY = ENV['AWS_ACCESS_KEY_ID']
  AWS_SECRET_KEY = ENV['AWS_SECRET_ACCESS_KEY']
  S3_BUCKET      = ENV['S3_BUCKET'] || "#{Rails.application.class.parent_name}_#{Rails.env}".downcase

  attr_accessor :file_name, :mime_type, :path, :acl, :expires_in
  attr_writer :as_attachment

  def initialize(file_name, mime_type, acl: 'private', path: '/')
    @file_name = esc file_name # escape for spaces and the like
    @mime_type = mime_type
    @acl       = acl
    @path      = path
  end


  # NOTE why we use non subdomain uris http://stackoverflow.com/questions/5208851/is-there-a-workaround-to-open-urls-containing-underscores-in-ruby
  def self.base_url
    "https://s3.amazonaws.com/#{S3_BUCKET}"
  end

  def base_url
    self.class.base_url
  end

  def file_path
    fp = File.join(path, file_name).gsub /^\//, '' # remove leading /

    return fp+"?response-content-disposition=attachment" if as_attachment?
    fp
  end

  def url
    File.join(base_url, file_path)
  end

  def expires_in
    @expires_in ||= 60.minutes.from_now.to_i
  end

  def as_attachment?
    @as_attachment == true
  end


  def method_missing(method, *args, &block)
    if method.to_s =~ /^(get|put|delete)_signature$/
      esc Base64.encode64(OpenSSL::HMAC
                          .digest(sha1, AWS_SECRET_KEY, __send__("#{$1}_request"))).gsub("\n","")

    elsif method.to_s =~ /^(get|put|delete)_signed_request(!)?$/
      _url = [
        url, 
        %{#{key_and_expires_params}&Signature=#{__send__("#{$1}_signature")}}
      ].join(as_attachment? ? '&' : '?')

      $2 == '!' ? esc(_url) : _url

    else
      super
    end
  end

  def respond_to?(meth, include_private: false)
    return true if meth =~ /^(get|put|delete)_signature$/
    return true if meth =~ /^(get|put|delete)_signed_request(!)?$/
    super
  end


  private

  def key_and_expires_params
    "AWSAccessKeyId=#{AWS_ACCESS_KEY}&Expires=#{expires_in}"
  end

  def amz_acl_header
    "x-amz-acl:#{acl}"
  end

  def amz_date_header
    "x-amz-date:#{expires_in}"
  end

  def bucket_file_path
    "/#{S3_BUCKET}/#{file_path}"
  end

  def put_request
    ['PUT', '', mime_type, expires_in, amz_acl_header, bucket_file_path].join("\n").encode('UTF-8')
  end

  def get_request
    ['GET', '', '', expires_in, bucket_file_path].join("\n").encode('UTF-8')
  end

  def delete_request
    ['DELETE', '', '', expires_in, bucket_file_path].join("\n").encode('UTF-8')
  end

  def sha1
    OpenSSL::Digest::Digest.new('sha1')
  end

  def esc(val)
    CGI.escape val
  end
end

ruby urbanspoon_reservations.rb

urbanspoon_reservations.rb
require 'rubygems'
require 'mechanize'

FIRST_NAME = 'FIRST_NAME'
LAST_NAME = 'LAST_NAME'
PHONE = 'PHONE'
EMAIL = 'EMAIL@provider.com'

PARTY_SIZE = 2
SCHEDULE_RANGE = { :start_time => '19:00', :end_time => '20:30' }

def start_url(restaurant=2086)
  return "http://rez.urbanspoon.com/reservation/start/#{restaurant}"
end

def to_minutes(time)
	hour, minutes = time.split(':')
	raise "Malformed time: #{time}. Should be in the HH:MM format." if hour.nil? || minutes.nil?
	return (hour.to_i * 60) + minutes.to_i
end

url = start_url()
agent = Mechanize.new { |agent|
  agent.user_agent_alias = 'Mac Safari'
}

# Get the start page
start_page = agent.get(url)

# Bail if there are no reservations
exit if start_page.forms.count != 1

# Fill in the details for the reservation
start_form = start_page.forms.first
start_form.size = PARTY_SIZE

# Verify if the available times are in the allowed range
available_times = start_form.field_with(:name => 'seating_time').options

possible_times = available_times.select do |time|
	(to_minutes(SCHEDULE_RANGE[:start_time])..to_minutes(SCHEDULE_RANGE[:end_time])).member?(time.value.to_i)
end

# Select the first of the possible times for the reservation
start_form.seating_time = possible_times.first

# Submit the details and get back the contact form
contact_info_page = start_form.submit

# Check for the existence and get the contact form
exit if contact_info_page.forms.count != 1
contact_form = contact_info_page.forms.first

# Fill in the contact details
contact_form["user[first_name]"] = FIRST_NAME
contact_form["user[last_name]"] = LAST_NAME
contact_form["user[phone]"] = PHONE
contact_form["user[email]"] = EMAIL

# Submit the contact details and get confirmation page
confirmation_page = contact_form.submit

# Confirm the reservation
exit if confirmation_page.forms.count != 1
confirmation_form = confirmation_page.forms.first
final_page = confirmation_form.submit
puts "Got reservation for: #{start_form.seating_time}"

ruby sass_retinize.rb

sass_retinize_example.scss
// DRY retina media queries
@mixin media-retina {
  @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
    @content;
  }
}

@mixin retina-bg-image($image, $size) {
  background-image: src($image);
  background-size: $size;
  
  @include media-retina {
    background-image: src(retinize($image));
  }
}
sass_retinize.rb
module Sass::Script::Functions

  # Appends "_2x" to the end of a filename before the extension
  # e.g. foobar.jpg => foobar_2x.jpg
  def retinize(string)
    assert_type string, :String
    Sass::Script::String.new string.value.gsub(/\.(\w+)$/, '_2x.\\1')
  end

  declare :retinize, :args => [:string]
end