All Files (50.58% covered at 52.18 hits/line)
1279 files in total.
60068 relevant lines.
30381 lines covered and
29687 lines missed
-
2
class AdvisorsController < ApplicationController
-
2
load_and_authorize_resource
-
# GET /advisors
-
# GET /advisors.json
-
2
def index
-
respond_to do |format|
-
format.html # index.html.erb
-
format.json { render json: @advisors }
-
end
-
end
-
-
# GET /advisors/1
-
# GET /advisors/1.json
-
2
def show
-
respond_to do |format|
-
format.html # show.html.erb
-
format.json { render json: @advisor }
-
end
-
end
-
-
# GET /advisors/new
-
# GET /advisors/new.json
-
2
def new
-
respond_to do |format|
-
format.html # new.html.erb
-
format.json { render json: @advisor }
-
end
-
end
-
-
# GET /advisors/1/edit
-
2
def edit
-
end
-
-
# POST /advisors
-
# POST /advisors.json
-
2
def create
-
respond_to do |format|
-
if @advisor.save
-
format.html { redirect_to @advisor, notice: 'Advisor was successfully created.' }
-
format.json { render json: @advisor, status: :created, location: @advisor }
-
else
-
format.html { render action: "new" }
-
format.json { render json: @advisor.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# PUT /advisors/1
-
# PUT /advisors/1.json
-
2
def update
-
respond_to do |format|
-
if @advisor.update_attributes(params[:advisor])
-
format.html { redirect_to @advisor, notice: 'Advisor was successfully updated.' }
-
format.json { head :no_content }
-
else
-
format.html { render action: "edit" }
-
format.json { render json: @advisor.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# DELETE /advisors/1
-
# DELETE /advisors/1.json
-
2
def destroy
-
@advisor.destroy
-
-
respond_to do |format|
-
format.html { redirect_to advisors_url }
-
format.json { head :no_content }
-
end
-
end
-
end
-
2
class ApplicationController < ActionController::Base
-
2
protect_from_forgery
-
-
2
before_filter :check_login!
-
2
rescue_from CanCan::AccessDenied do |exception|
-
Rails.logger.info "Access denied on #{exception.action} #{exception.subject.inspect}"
-
alert = "You are not authorized to perform that action."
-
redirect_to calendars_path, :alert => alert
-
end
-
-
2
def current_user
-
9
@current_user ||= User.find(session[:user_id]) if session[:user_id]
-
end
-
-
2
helper_method :current_user
-
-
2
def logged_in?
-
9
current_user != nil
-
end
-
-
2
helper_method :logged_in?
-
-
2
private
-
-
2
def check_login!
-
9
err_msg = 'You must log in to perform that action.'
-
9
redirect_to login_url, alert: err_msg if not logged_in?
-
end
-
-
end
-
2
class AppointmentsController < ApplicationController
-
2
load_and_authorize_resource
-
-
# GET /appointments
-
# GET /appointments.json
-
2
def index
-
respond_to do |format|
-
format.html # index.html.erb
-
format.json { render json: @appointments }
-
end
-
end
-
-
# GET /appointments/1
-
# GET /appointments/1.json
-
2
def show
-
respond_to do |format|
-
format.html # show.html.erb
-
format.json { render json: @appointment }
-
end
-
end
-
-
# GET /appointments/new
-
# GET /appointments/new.json
-
2
def new
-
respond_to do |format|
-
format.html # new.html.erb
-
format.json { render json: @appointment }
-
end
-
end
-
-
# GET /appointments/1/edit
-
2
def edit
-
end
-
-
# POST /appointments
-
# POST /appointments.json
-
2
def create
-
@appointment.end = @appointment.start + Integer(params[:duration]).minute
-
this_student = current_user.student
-
-
@appointment.advisor = Advisor.find(params[:advisor])
-
@appointment.student = this_student
-
-
respond_to do |format|
-
if @appointment.save
-
## TODO: run below line in the background
-
ConfirmationMailer.confirm_appointment(@appointment).deliver
-
format.html { render :partial => "partials/close_window_refresh"}
-
format.json { render json: @appointment, status: :created, location: @appointment }
-
else
-
format.html { render action: "new" }
-
format.json { render json: @appointment.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
2
def advisor_cancel
-
##TODO check whether advisor is authorized (is advisor and is their student)
-
respond_to do |format|
-
if @appointment.cancel
-
##CONSIDER: move email delivery to model
-
CancelMailer.advisor_cancel_email(@appointment).deliver
-
format.html { render :partial => "partials/close_window_refresh"}
-
format.json { head :no_content }
-
else
-
format.html { render action: "show" }
-
format.json { render json: @appointment.errors, status: :unprocessable_entity }
-
end
-
end
-
-
end
-
-
2
def student_cancel
-
##TODO check whether student is authorized (is their appointment)
-
respond_to do |format|
-
if @appointment.cancel
-
CancelMailer.student_cancel_email(@appointment).deliver
-
format.html { render :partial => "partials/close_window_refresh"}
-
format.json { head :no_content }
-
else
-
format.html { render action: "show" }
-
format.json { render json: @appointment.errors, status: :unprocessable_entity }
-
end
-
end
-
-
end
-
-
-
# PUT /appointments/1
-
# PUT /appointments/1.json
-
2
def update
-
# TODO this should probably be in a transaction along with update_attributes?
-
@appointment.end = @appointment.start.to_time + Integer(params[:duration]).minute
-
-
respond_to do |format|
-
if @appointment.save
-
format.html { render :partial => "partials/close_window_refresh"}
-
format.json { head :no_content }
-
else
-
format.html { render action: "edit" }
-
format.json { render json: @appointment.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# DELETE /appointments/1
-
# DELETE /appointments/1.json
-
2
def destroy
-
@appointment.destroy
-
-
respond_to do |format|
-
format.html { redirect_to appointments_url }
-
format.json { head :no_content }
-
end
-
end
-
-
end
-
2
class BlackoutsController < ApplicationController
-
# GET /blackouts
-
# GET /blackouts.json
-
-
2
load_and_authorize_resource
-
2
skip_authorize_resource :only => [:index, :new]
-
-
2
def index
-
authorize! :manage, Blackout
-
@blackouts = current_user.advisor
-
.blackouts
-
.paginate(:page => params[:page], :per_page => 300)
-
.order('id DESC')
-
.where("cancelled <> ? OR cancelled IS ?", true, nil)
-
-
respond_to do |format|
-
format.html # index.html.erb
-
format.json { render json: @blackouts }
-
end
-
end
-
-
# GET /blackouts/1
-
# GET /blackouts/1.json
-
2
def show
-
respond_to do |format|
-
format.html # show.html.erb
-
format.json { render json: @blackout }
-
end
-
end
-
-
# GET /blackouts/new
-
# GET /blackouts/new.json
-
2
def new
-
@blackout = Blackout.new_from_params(params)
-
authorize! :manage, @blackout
-
@blackout.build_weekly_repeated_day
-
## date exceptions will be built through the form
-
respond_to do |format|
-
format.html # new.html.erb
-
format.json { render json: @blackout }
-
end
-
end
-
-
# GET /blackouts/1/edit
-
2
def edit
-
end
-
-
# POST /blackouts
-
# POST /blackouts.json
-
2
def create
-
this_advisor = current_user.advisor
-
-
@blackout.advisor = this_advisor
-
respond_to do |format|
-
if @blackout.save
-
format.html { render :partial => "partials/close_window_refresh"}
-
format.json { render json: @blackout, status: :created, location: @blackout }
-
else
-
format.html { render action: "new" }
-
format.json { render json: @blackout.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
2
def cancel
-
##TODO check whether advisor is authorized
-
respond_to do |format|
-
if @blackout.cancel
-
format.html { render :partial => "partials/close_window_refresh"}
-
format.json { head :no_content }
-
else
-
format.html { render action: "show" }
-
format.json { render json: @blackout.errors, status: :unprocessable_entity }
-
end
-
end
-
-
end
-
-
# PUT /blackouts/1
-
# PUT /blackouts/1.json
-
2
def update
-
respond_to do |format|
-
if @blackout.update_attributes(params[:blackout])
-
format.html { render :partial => "partials/close_window_refresh"}
-
format.json { head :no_content }
-
else
-
format.html { render action: "edit" }
-
format.json { render json: @blackout.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# DELETE /blackouts/1
-
# DELETE /blackouts/1.json
-
2
def destroy
-
@blackout.destroy
-
-
respond_to do |format|
-
format.html { redirect_to blackouts_url }
-
format.json { head :no_content }
-
end
-
end
-
end
-
2
class CalendarsController < ApplicationController
-
2
include CalendarsHelper
-
-
# We can control access to :calendar even without a Calendar model
-
2
authorize_resource :class => false
-
-
# GET /calendars
-
2
def index
-
if current_user.role == :advisor
-
redirect_to :action => "advisor"
-
else
-
#redirect_to :action => "student", :id => current_user.student.advisor.id
-
-
@advisors = Advisor.all
-
respond_to do |format|
-
format.html # index.html.erb
-
format.json { render json: @advisors }
-
end
-
end
-
end
-
-
# GET /calendars/advisor
-
2
def advisor
-
#authorize! :manage, :all, :message => "Only advisors can view advisor calendars."
-
@start = nil
-
@end = nil
-
if params[:start] != nil
-
# we use to_date so we can iterate over dates (using (start..end))
-
@start = Time.zone.parse(params[:start]).to_date
-
@end = @start.end_of_week
-
else
-
week_start = Date.current.beginning_of_week
-
week_end = Date.current.end_of_week
-
@start = week_start
-
@end = week_end
-
end
-
-
@advisor = current_user.advisor
-
start_time = Time.zone.local(@start.year, @start.month, @start.day, 0, 0, 0)
-
end_time = Time.zone.local(@end.year, @end.month, @end.day, 24, 0, 0)
-
@upcoming_tb_hash = UpcomingTimeBlock.get_week(start_time, end_time, :advisor_id => @advisor.id)
-
-
end
-
-
# GET /calendars/student/:id
-
# params[:id] is the Advisor id.
-
2
def student
-
@start = nil
-
@end = nil
-
if params[:start] != nil
-
@start = Time.zone.parse(params[:start]).to_date
-
@end = @start.end_of_week
-
else
-
week_start = Date.current.beginning_of_week
-
week_end = Date.current.end_of_week
-
@start = week_start
-
@end = week_end
-
end
-
-
@advisor = Advisor.find(params[:id])
-
-
# Send student elsewhere "temporarily"--maybe to a vacation page, maybe to another calendar service.
-
if !@advisor.student_redirect_url.blank?
-
redirect_to @advisor.student_redirect_url
-
return
-
end
-
-
@student = current_user.student
-
start_time = Time.zone.local(@start.year, @start.month, @start.day, 0, 0, 0)
-
end_time = Time.zone.local(@end.year, @end.month, @end.day, 24, 0, 0)
-
@upcoming_tb_hash = UpcomingTimeBlock.get_week(start_time, end_time, {:student_id => @student.id}, @advisor.id)
-
-
end
-
-
# POST /calendars/time_slot
-
# When a blackout is clicked in the calendar view, this action is
-
# called to show the blackouts that apply to the timeslot.
-
# params[:utbs] contains a comma separated string of the applicable UTBs.
-
2
def time_slot
-
@upcoming_time_blocks = get_time_blocks(params[:utbs])
-
@start_time = Time.zone.local(2000, 1, 31, params[:start_hour], params[:start_minute], 0)
-
@end_time = Time.zone.local(2000, 1, 31, params[:end_hour], params[:end_minute], 0)
-
@time_slot = Time.zone.parse(params[:date])
-
end
-
end
-
2
class DayviewController < ApplicationController
-
2
def index
-
advisor = current_user.advisor.id
-
date_str = params[:date]
-
@date = Date.current.strftime("%A") + ", " + Date.current.strftime("%Y-%m-%d")
-
day_start = Time.current.beginning_of_day
-
day_end = Time.current.end_of_day
-
begin
-
if date_str
-
date = Time.strptime(date_str, "%Y-%m-%d") # will raise ex if invalid date
-
day_start = date.beginning_of_day
-
day_end = date.end_of_day
-
@date = date.strftime("%A") + ", " + date.strftime("%Y-%m-%d")
-
end
-
rescue
-
# treating invalid dates as being today's date
-
end
-
@events = current_user.advisor.events_for day_start, day_end
-
end
-
end
-
2
class DepartmentsController < ApplicationController
-
2
load_and_authorize_resource
-
# GET /departments
-
# GET /departments.json
-
2
def index
-
respond_to do |format|
-
format.html # index.html.erb
-
format.json { render json: @departments }
-
end
-
end
-
-
# GET /departments/1
-
# GET /departments/1.json
-
2
def show
-
respond_to do |format|
-
format.html # show.html.erb
-
format.json { render json: @department }
-
end
-
end
-
-
# GET /departments/new
-
# GET /departments/new.json
-
2
def new
-
respond_to do |format|
-
format.html # new.html.erb
-
format.json { render json: @department }
-
end
-
end
-
-
# GET /departments/1/edit
-
2
def edit
-
end
-
-
# POST /departments
-
# POST /departments.json
-
2
def create
-
respond_to do |format|
-
if @department.save
-
format.html { redirect_to @department, notice: 'Department was successfully created.' }
-
format.json { render json: @department, status: :created, location: @department }
-
else
-
format.html { render action: "new" }
-
format.json { render json: @department.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# PUT /departments/1
-
# PUT /departments/1.json
-
2
def update
-
respond_to do |format|
-
if @department.update_attributes(params[:department])
-
format.html { redirect_to @department, notice: 'Department was successfully updated.' }
-
format.json { head :no_content }
-
else
-
format.html { render action: "edit" }
-
format.json { render json: @department.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# DELETE /departments/1
-
# DELETE /departments/1.json
-
2
def destroy
-
@department.destroy
-
-
respond_to do |format|
-
format.html { redirect_to departments_url }
-
format.json { head :no_content }
-
end
-
end
-
end
-
2
class FeedbackController < ApplicationController
-
2
load_and_authorize_resource
-
-
2
def index
-
@feedback = Feedback.order(:created_at)
-
respond_to do |format|
-
format.html # index.html.erb
-
format.json { render json: @feedback }
-
end
-
end
-
-
2
def show
-
respond_to do |format|
-
format.html # show.html.erb
-
format.json { render json: @feedback }
-
end
-
end
-
-
2
def new
-
respond_to do |format|
-
format.html # new.html.erb
-
format.json { render json: @feedback }
-
end
-
end
-
-
2
def create
-
@feedback.student = current_user.student
-
respond_to do |format|
-
if @feedback.save
-
format.html { redirect_to calendars_path, notice: 'Your feedback has been submitted.' }
-
format.json { render json: @feedback, status: :created, location: @feedback }
-
else
-
format.html { render action: "new" }
-
format.json { render json: @feedback.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
2
def destroy
-
@feedback.destroy
-
respond_to do |format|
-
format.html { redirect_to feedback_index_path }
-
format.json { head :no_content }
-
end
-
end
-
end
-
2
class SessionsController < ApplicationController
-
-
# We can control access to :session even without a Session model
-
2
authorize_resource :class => false
-
2
skip_authorize_resource :except => :update
-
-
2
skip_before_filter :check_login!, only: [:new, :create]
-
-
2
def is_authorized?
-
logger.info "SessionsController#is_authorized?: current_user is #{current_user.email}."
-
logger.info "SessionsController#is_authorized?: current_user.role is #{current_user.role}."
-
if current_user.nil? or current_user.role != :advisor
-
if Rails.env.production?
-
err_msg = 'You need to be an advisor to masquerade.'
-
redirect_to root_url, notice: err_msg
-
end
-
end
-
end
-
-
-
2
def new
-
remote_user = request.env['REMOTE_USER']
-
-
if remote_user.nil?
-
logger.info "SessionsController#new: bailing out to web form in a non-Shibboleth configuration."
-
render "new"
-
return
-
end
-
-
remote_user.encode!("UTF-8") # so we can stick derived substrings in the database later
-
-
logger.info "SessionsController#new: REMOTE_USER is #{remote_user}."
-
logger.info "SessionsController#new: REMOTE_USER encoding is #{remote_user.encoding}."
-
-
@user = User.find_by_email(remote_user)
-
-
if @user.nil?
-
@user = User.create!(:email => remote_user,
-
:name => remote_user.sub(/@.*$/, ''),
-
:type => "Student",
-
:department_id => 1, # XXX
-
:student_advisor_id => 0)
-
logger.info "SessionsController#new: created new user (id #{@user.id})."
-
end
-
-
if @user
-
logger.info "SessionsController#new: We are in, user.id is #{@user.id}."
-
session[:user_id] = @user.id
-
respond_to_logged_in
-
else
-
# XXX We can't actually get here, right?
-
# XXX If we are not using Shibboleth we bounced off to web form then back to #create.
-
# XXX If *are* using Shibboleth User#create! either worked or choked (and "registration" would be wrong).
-
fail("Should not be trying to bounce to registration form (right?)")
-
logger.info "SessionsController#new: off to registration form because no user record."
-
redirect_to register_url
-
end
-
end
-
-
2
def create
-
fail("Should not be manually creating a Session") if request.env['REMOTE_USER']
-
-
@user = User.find_by_email(params[:email])
-
if @user
-
session[:user_id] = @user.id
-
respond_to_logged_in
-
else
-
flash.now.alert = "No account found with email of #{params[:email]}"
-
render "new"
-
end
-
end
-
-
2
def destroy
-
session[:user_id] = nil
-
reset_cancan
-
redirect_to root_url, notice: "Logged out!"
-
end
-
-
2
def admin
-
end
-
-
2
def update
-
##ability.rb## # do not allow students to masquerade.
-
##ability.rb## if not Rails.env.development?
-
##ability.rb## authorize! :manage, :all, :message => "Only advisors can masquerade."
-
##ability.rb## end
-
@user = User.find(params[:masquerade_user]) # else exn
-
session[:user_id] = @user.id
-
-
reset_cancan
-
-
respond_to_logged_in
-
end
-
-
2
private
-
-
2
def reset_cancan
-
# We are changing something, so tell CanCan to start over
-
# https://github.com/ryanb/cancan/wiki/Authorizing-controller-actions#resetting-current-ability
-
@current_ability = nil
-
@current_user = nil
-
end
-
-
2
def respond_to_logged_in
-
if @user.advisor_id != nil
-
redirect_to calendars_advisor_url, notice: "Logged in!"
-
else
-
advisor_id = Student.find(@user.student_id).advisor_id
-
if !advisor_id.nil? and advisor_id > 0
-
redirect_to calendars_student_url(advisor_id), notice: "Logged in!"
-
else
-
redirect_to calendars_url, notice: "Logged in!"
-
end
-
end
-
end
-
end
-
2
class SpecialStudentsController < ApplicationController
-
2
load_and_authorize_resource
-
2
skip_authorize_resource :only => [:create]
-
-
# GET /special_students
-
# GET /special_students.json
-
2
def index
-
@special_students = SpecialStudent.all
-
-
respond_to do |format|
-
format.html # index.html.erb
-
format.json { render json: @special_students }
-
end
-
end
-
-
# GET /special_students/1
-
# GET /special_students/1.json
-
2
def show
-
@special_student = SpecialStudent.find(params[:id])
-
-
respond_to do |format|
-
format.html # show.html.erb
-
format.json { render json: @special_student }
-
end
-
end
-
-
# GET /special_students/new
-
# GET /special_students/new.json
-
2
def new
-
@special_student = SpecialStudent.new
-
-
respond_to do |format|
-
format.html # new.html.erb
-
format.json { render json: @special_student }
-
end
-
end
-
-
# GET /special_students/1/edit
-
2
def edit
-
@special_student = SpecialStudent.find(params[:id])
-
end
-
-
# POST /special_students
-
# POST /special_students.json
-
2
def create
-
##CONSIDER moving below into model
-
authorize! :manage, SpecialStudent
-
@special_student = SpecialStudent.new(params[:special_student])
-
@student = Student.find_all_by_name(params[:student_name])[0]
-
if @student != nil
-
@std_id = @student.id
-
@special_student.student_id = @std_id
-
else
-
@special_student.student_id = nil
-
end
-
-
-
-
respond_to do |format|
-
if @special_student.save
-
format.html { redirect_to @special_student, notice: 'Special student was successfully created.' }
-
format.json { render json: @special_student, status: :created, location: @special_student }
-
else
-
format.html { render action: "new" }
-
format.json { render json: @special_student.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# PUT /special_students/1
-
# PUT /special_students/1.json
-
2
def update
-
@special_student = SpecialStudent.find(params[:id])
-
-
respond_to do |format|
-
if @special_student.update_attributes(params[:special_student])
-
format.html { redirect_to @special_student, notice: 'Special student was successfully updated.' }
-
format.json { head :no_content }
-
else
-
format.html { render action: "edit" }
-
format.json { render json: @special_student.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# DELETE /special_students/1
-
# DELETE /special_students/1.json
-
2
def destroy
-
@special_student = SpecialStudent.find(params[:id])
-
@special_student.destroy
-
-
respond_to do |format|
-
format.html { redirect_to special_students_url }
-
format.json { head :no_content }
-
end
-
end
-
end
-
2
class StaticController < ApplicationController
-
2
def about
-
render :about
-
end
-
end
-
2
class StudentsController < ApplicationController
-
2
load_and_authorize_resource
-
# GET /students
-
# GET /students.json
-
2
def index
-
respond_to do |format|
-
format.html # index.html.erb
-
format.json { render json: @students }
-
end
-
end
-
-
# GET /students/1
-
# GET /students/1.json
-
2
def show
-
respond_to do |format|
-
format.html # show.html.erb
-
format.json { render json: @student }
-
end
-
end
-
-
# GET /students/new
-
# GET /students/new.json
-
2
def new
-
respond_to do |format|
-
format.html # new.html.erb
-
format.json { render json: @student }
-
end
-
end
-
-
# GET /students/1/edit
-
2
def edit
-
end
-
-
# POST /students
-
# POST /students.json
-
2
def create
-
respond_to do |format|
-
if @student.save
-
format.html { redirect_to @student, notice: 'Student was successfully created.' }
-
format.json { render json: @student, status: :created, location: @student }
-
else
-
format.html { render action: "new" }
-
format.json { render json: @student.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# PUT /students/1
-
# PUT /students/1.json
-
2
def update
-
respond_to do |format|
-
if @student.update_attributes(params[:student])
-
format.html { redirect_to @student, notice: 'Student was successfully updated.' }
-
format.json { head :no_content }
-
else
-
format.html { render action: "edit" }
-
format.json { render json: @student.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# DELETE /students/1
-
# DELETE /students/1.json
-
2
def destroy
-
@student.destroy
-
-
respond_to do |format|
-
format.html { redirect_to students_url }
-
format.json { head :no_content }
-
end
-
end
-
end
-
2
class TodayController < ApplicationController
-
2
def index
-
advisor = current_user.advisor.id
-
now = Time.current
-
query = "(cancelled <> ? OR cancelled IS ?) AND start >= ? AND start <= ?"
-
@appointments = Appointment.where(query, true, nil, now.beginning_of_day, now.end_of_day).where(:advisor_id => current_user.advisor.id)
-
end
-
end
-
2
class UsersController < ApplicationController
-
2
skip_before_filter :check_login!, only: [:new, :create]
-
-
2
load_and_authorize_resource
-
2
skip_authorize_resource :only => [:create, :new]
-
-
# GET /users
-
# GET /users.json
-
2
def index
-
@users = User.order :email
-
-
respond_to do |format|
-
format.html # index.html.erb
-
format.json { render json: @users }
-
end
-
end
-
-
2
def advisors
-
@users = User.order(:email).where "advisor_id IS NOT ?", nil
-
-
respond_to do |format|
-
format.html { render :index }
-
end
-
end
-
-
2
def students
-
@users = User.order(:email).where "student_id IS NOT ?", nil
-
-
respond_to do |format|
-
format.html { render :index }
-
end
-
end
-
-
# GET /users/1
-
# GET /users/1.json
-
2
def show
-
@user = User.find(params[:id])
-
-
respond_to do |format|
-
format.html # show.html.erb
-
format.json { render json: @user }
-
end
-
end
-
-
# GET /users/new
-
# GET /users/new.json
-
2
def new
-
@user = User.new
-
-
respond_to do |format|
-
format.html # new.html.erb
-
format.json { render json: @user }
-
end
-
end
-
-
# GET /users/1/edit
-
2
def edit
-
@user = User.find(params[:id])
-
@user.advisor.confirmed_appt_cancellations = false if @user.role == :advisor
-
end
-
-
# POST /users
-
# POST /users.json
-
2
def create
-
@user = User.new
-
@user.email = params[:user][:email]
-
@user.advisor = params[:user][:advisor_id]
-
@user.student = params[:user][:student_id]
-
@user.name = params[:user][:name]
-
@user.department_id = params[:user][:department_id]
-
@user.type = params[:user][:type]
-
@user.student_advisor_id = params[:user][:student_advisor_id]
-
@user.office = params[:user][:office]
-
@user.face_url = params[:user][:face_url]
-
@user.student_redirect_url = params[:user][:student_redirect_url]
-
@user.weeks_in_advance = params[:user][:weeks_in_advance]
-
-
-
respond_to do |format|
-
if @user.save
-
format.html { redirect_to root_url, notice: 'Your account was created.' }
-
# format.json { render json: @user, status: :created, location: @user }
-
else
-
format.html { render action: "new" }
-
# format.json { render json: @user.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# PUT /users/1
-
# PUT /users/1.json
-
2
def update
-
# Note: cannot change type of users
-
@user = User.find(params[:id])
-
@user.email = params[:user][:email]
-
@user.name = params[:user][:name]
-
@user.department_id = params[:user][:department_id]
-
@user.student_advisor_id = params[:user][:student_advisor_id]
-
@user.office = params[:user][:office]
-
@user.face_url = params[:user][:face_url]
-
@user.student_redirect_url = params[:user][:student_redirect_url]
-
@user.announcement = params[:user][:announcement]
-
@user.weeks_in_advance = params[:user][:weeks_in_advance]
-
@user.confirmed_appt_cancellations = params[:user][:confirmed_appt_cancellations]
-
-
respond_to do |format|
-
if @user.save
-
format.html { redirect_to @user, notice: 'User was successfully updated.' }
-
format.json { head :no_content }
-
else
-
if @user.role == :advisor
-
@appts_after_end_of_time = @user.advisor.try(:errors)
-
.get(:appts_after_end_of_time) || []
-
end
-
format.html { render action: "edit" }
-
format.json { render json: @user.errors, status: :unprocessable_entity }
-
end
-
end
-
end
-
-
# DELETE /users/1
-
# DELETE /users/1.json
-
2
def destroy
-
@user = User.find(params[:id])
-
@user.destroy
-
-
respond_to do |format|
-
format.html { redirect_to users_url }
-
format.json { head :no_content }
-
end
-
end
-
end
-
2
module AdvisorsHelper
-
end
-
2
module ApplicationHelper
-
end
-
2
module AppointmentsHelper
-
end
-
2
module BlackoutsHelper
-
end
-
2
module CalendarsHelper
-
-
2
def get_time_blocks(utbs)
-
utb_ids = utbs.split(",")
-
UpcomingTimeBlock.where("id IN (?)", utb_ids)
-
-
end
-
-
# given an Array of UpcomingTimeBlocks,
-
# return a string of comma separated utb_ids
-
2
def utb_ids(utb_array)
-
if utb_array.class != Array ## if no overlaps string just has 1 number
-
return utb_array.id.to_s
-
end
-
utb_string = ""
-
utb_array.each do |utb|
-
utb_string += "#{utb.id},"
-
end
-
-
idx_end = utb_string.length - 2
-
return utb_string[0 .. idx_end]
-
end
-
end
-
2
module DateExceptionsHelper
-
end
-
2
module DayviewHelper
-
end
-
2
module DepartmentsHelper
-
end
-
2
module SessionsHelper
-
end
-
2
module SpecialStudentHelper
-
end
-
2
module SpecialStudentsHelper
-
end
-
2
module StudentsHelper
-
end
-
2
module UpcomingTimeBlocksHelper
-
end
-
2
module UsersHelper
-
end
-
2
module WeeklyRepeatedDaysHelper
-
end
-
2
class CancelMailer < ActionMailer::Base
-
2
default from: 'de0u+sailfish@andrew.cmu.edu'
-
-
2
def advisor_cancel_email(appointment)
-
4
@appointment = appointment
-
4
mail(to: appointment.student.user.email, subject: "Appointment with #{appointment.advisor.name} cancelled")
-
end
-
-
2
def student_cancel_email(appointment)
-
@appointment = appointment
-
mail(to: appointment.advisor.user.email, subject: "Appointment with #{appointment.student.name} cancelled")
-
end
-
-
end
-
2
class ConfirmationMailer < ActionMailer::Base
-
2
default from: 'de0u+sailfish@andrew.cmu.edu'
-
-
2
def confirm_appointment(appointment)
-
@appointment = appointment
-
@date = @appointment.start.strftime "%A, %B %e"
-
mail(to: appointment.student.user.email, subject: "Advising appointment with #{appointment.advisor.name} on #{@date}")
-
end
-
-
end
-
2
class NightlyEmailMailer < ActionMailer::Base
-
2
default from: 'de0u+sailfish@andrew.cmu.edu'
-
-
2
def appointment_reminder(appointment)
-
@appointment = appointment
-
mail(to: appointment.student.user.email, subject: "Advising appointment with #{appointment.advisor.name} tomorrow")
-
end
-
-
end
-
2
class Ability
-
2
include CanCan::Ability
-
-
2
def initialize(user)
-
user ||= User.new # guest user (not logged in)
-
if user.role == :advisor
-
can :manage, :all
-
cannot :create, Feedback
-
else
-
-
can [:show, :update], User do |_user|
-
_user.id == user.id
-
end
-
-
can [:index, :student, :time_slot], :calendar
-
-
can :create, Appointment
-
can :create, Feedback
-
-
can [:student_cancel, :show], Appointment do |appointment|
-
appointment.student_id == user.student_id
-
end
-
-
# in development mode, students can masquerade
-
if Rails.env.development?
-
can :update, :session
-
end
-
end
-
end
-
end
-
2
class Advisor < ActiveRecord::Base
-
2
attr_accessible :department, :name, :department_id, :office,
-
:face_url, :student_redirect_url, :announcement,
-
:end_of_time, :weeks_in_advance, :confirmed_appt_cancellations
-
2
attr_accessor :confirmed_appt_cancellations, :appts_after_end_of_time
-
-
2
MAX_APPT_TIME = 120.minutes
-
2
LOCKDOWN_PERIOD = 1.hours
-
-
2
belongs_to :department
-
2
has_many :appointments
-
2
has_many :blackouts
-
2
has_many :students
-
2
has_one :user
-
-
2
has_many :upcoming_time_blocks
-
-
2
before_create :set_end_of_time
-
2
before_update :handle_weeks_in_advance_change, if: :weeks_in_advance_changed?
-
2
validate :no_appts_after_end_of_time, if: :weeks_in_advance_changed?
-
-
2
validates :weeks_in_advance, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
-
-
2
def no_appts_after_end_of_time
-
8
new_end_of_time = Date.current + weeks_in_advance.weeks
-
8
if end_of_time and new_end_of_time < end_of_time and confirmed_appt_cancellations != "true"
-
3
query = "start >= ? AND appointment_id IS NOT ?"
-
3
utbs = self.upcoming_time_blocks.where(query,
-
new_end_of_time + 1.day,
-
nil)
-
.not_cancelled
-
.order(:start)
-
3
if utbs.count > 0
-
2
self.confirmed_appt_cancellations = "true"
-
# self.errors.add(:appts_after_end_of_time, "The following appointments must be cancelled to decrease your window size. To proceed, click 'Update advisor' again.")
-
2
utbs.each do |utb|
-
4
self.errors.add(:appts_after_end_of_time, "#{utb.name} at #{utb.start}")
-
end
-
2
self.appts_after_end_of_time = utbs
-
end
-
end
-
end
-
-
2
def set_end_of_time
-
self.end_of_time = Date.current + weeks_in_advance.weeks
-
end
-
-
2
def events_for(day_start, day_end)
-
[].tap do |events|
-
utbs = self.upcoming_time_blocks.not_cancelled
-
.after(day_start)
-
.before(day_end)
-
.order(:start)
-
fmt = "%l:%M %P"
-
utbs.each do |utb|
-
event = { start_time: utb.start.strftime(fmt),
-
end_time: utb.end.strftime(fmt) }
-
if utb.appointment
-
description = "Appointment: #{utb.student.name}"
-
else
-
description = "Blackout: #{utb.name}"
-
end
-
events << event.merge(description: description)
-
end
-
end
-
end
-
-
2
def update_utbs
-
11
last_valid_date = self.end_of_time
-
11
new_end_of_time = Date.current + self.weeks_in_advance.weeks
-
# TODO only query the blackouts that are "relevant"
-
# to avoid looping through blackouts that apply to the past, for example.
-
11
self.blackouts.not_cancelled.each do |blackout|
-
4
((last_valid_date + 1)..new_end_of_time).each do |date|
-
12
frequency = blackout.frequency
-
12
start_date = blackout.start_date
-
12
end_date = blackout.end_date
-
-
# CONSIDER using find_or_create in case a UTB has already been made
-
# (this should never happen though since we iterate starting from
-
# last_valid_date + 1)
-
12
if frequency == "never"
-
1
if date == start_date
-
1
UpcomingTimeBlock.create(:appointment_id => nil,
-
:blackout_id => blackout.id,
-
:start => TimeHelper.combine_date_time(date, blackout.start_time),
-
:end => TimeHelper.combine_date_time(date, blackout.end_time),
-
:advisor_id => blackout.advisor_id,
-
:name => blackout.name,
-
:past => false,
-
:cancelled => false)
-
end
-
elsif frequency == "daily"
-
11
if (start_date <= date && date <= end_date && blackout.is_not_exception(date))
-
11
UpcomingTimeBlock.create(:appointment_id => nil,
-
:blackout_id => blackout.id,
-
:start => TimeHelper.combine_date_time(date, blackout.start_time),
-
:end => TimeHelper.combine_date_time(date, blackout.end_time),
-
:advisor_id => blackout.advisor_id,
-
:name => blackout.name,
-
:past => false,
-
:cancelled => false)
-
end
-
-
elsif frequency == "weekly"
-
weekly_repeated_day = blackout.weekly_repeated_day
-
if (weekly_repeated_day.repeats_on?(date) && start_date <= date && date <= end_date && blackout.is_not_exception(date))
-
UpcomingTimeBlock.create(:appointment_id => nil,
-
:blackout_id => blackout.id,
-
:start => TimeHelper.combine_date_time(date, blackout.start_time),
-
:end => TimeHelper.combine_date_time(date, blackout.end_time),
-
:advisor_id => blackout.advisor_id,
-
:name => blackout.name,
-
:past => false,
-
:cancelled => false)
-
end
-
-
elsif frequency == "monthly"
-
if (date.day == start_date.day && start_date <= date && date <= end_date && blackout.is_not_exception(date))
-
UpcomingTimeBlock.create(:appointment_id => nil,
-
:blackout_id => blackout.id,
-
:start => TimeHelper.combine_date_time(date, blackout.start_time),
-
:end => TimeHelper.combine_date_time(date, blackout.end_time),
-
:advisor_id => blackout.advisor_id,
-
:name => blackout.name,
-
:past => false,
-
:cancelled => false)
-
-
end
-
end
-
end
-
end
-
# we only want to set end_of_time for this advisor once all
-
# of this advisor's blackouts have been processed.
-
11
self.end_of_time = new_end_of_time
-
end
-
-
2
def set_weeks_in_advance(weeks=3)
-
2
self.update_attributes(weeks_in_advance: weeks)
-
end
-
-
2
private
-
2
def handle_weeks_in_advance_change
-
6
new_end_of_time = Date.current + weeks_in_advance.weeks
-
6
if end_of_time and new_end_of_time < end_of_time
-
3
query = "start >= ? AND appointment_id IS ?"
-
3
self.upcoming_time_blocks.where(query, new_end_of_time + 1.day, nil).delete_all
-
# cancel appointments beyong the new end of time
-
3
query = "start >= ? AND appointment_id IS NOT ?"
-
3
appt_utbs = UpcomingTimeBlock.where(query, new_end_of_time + 1.day, nil)
-
.not_cancelled
-
3
appt_utbs.each do |utb|
-
4
appt = utb.appointment
-
4
appt.cancel
-
4
CancelMailer.advisor_cancel_email(appt).deliver
-
end
-
3
self.end_of_time = new_end_of_time
-
else
-
3
if end_of_time.nil?
-
# CONSIDER removing this if branch after initial production migration since
-
# end_of_time should never be nil after that point.
-
last_utb = self.upcoming_time_blocks.where("blackout_id IS NOT ?", nil)
-
.order("start DESC")
-
.first
-
if last_utb and not last_utb.start.nil?
-
self.end_of_time = last_utb.start.to_date
-
else
-
self.end_of_time = Date.current
-
end
-
end
-
3
update_utbs
-
end
-
end
-
end
-
2
class Appointment < ActiveRecord::Base
-
2
attr_accessible :end, :start
-
-
2
belongs_to :student
-
2
belongs_to :advisor
-
2
has_one :upcoming_time_block
-
-
2
after_create :create_time_block
-
2
before_update :cancel_time_block
-
2
after_update :maybe_replace_time_block
-
2
validate :valid_appointment_time
-
2
validate :open_for_appointment
-
2
validate :duration_within_limit
-
2
validate :not_last_min_appointment
-
2
validate :not_too_early
-
-
2
scope :not_cancelled, where("cancelled IS ? OR cancelled = ?", nil, false)
-
-
2
def valid_appointment_time
-
38
valid_time = self.start < self.end
-
#valid_time ?
-
# {return true} :
-
# {self.errors.add(:base, "Invalid appointment time.")
-
# return false}
-
-
38
if valid_time
-
37
return true
-
else
-
1
self.errors.add(:base, "Invalid appointment time.")
-
1
return false
-
end
-
end
-
-
2
def open_for_appointment
-
38
is_open = UpcomingTimeBlock.open_for_appointment?(self)
-
-
38
if is_open
-
28
return true
-
else
-
10
self.errors.add(:base, "That appointment time is taken.")
-
10
return false
-
end
-
end
-
-
2
def duration_within_limit
-
38
within_limit = (self.end - self.start <= Advisor::MAX_APPT_TIME)
-
38
special_student = self.student.special_student
-
-
38
if !within_limit
-
5
self.errors.add(:base, "Appointment duration is too long.")
-
5
return false
-
33
elsif (!(!special_student.nil? && special_student.is_extended) && (self.end - self.start > 15.minutes))
-
1
self.errors.add(:base, "Appointment duration is too long. You can only book for appointments not longer than 15 minutes.")
-
1
return false
-
32
elsif ((!special_student.nil? && special_student.is_extended) && (self.end - self.start > special_student.max_time.minutes))
-
self.errors.add(:base, "Appointment duration is too long. You can only book for appointments not longer than #{special_student.max_time} minutes.")
-
return false
-
else
-
32
return true
-
end
-
end
-
-
2
def not_last_min_appointment
-
# bookings made within an hour from start time are "last-minute"
-
38
now = Time.current
-
38
not_last_min = (now <= (self.start - Advisor::LOCKDOWN_PERIOD))
-
-
38
if not_last_min
-
37
return true
-
else
-
1
error_message = "It is too late to book that time slot now."
-
1
self.errors.add(:base, error_message)
-
1
return false
-
end
-
end
-
-
2
def not_last_min_cancel
-
7
return (start - Time.current) > 1.hour
-
end
-
-
2
def not_too_early
-
# TODO wrong -- needs to match not_last_min_appointment code above
-
# bookings made within 3 weeks from current time are recent
-
-
# TODO find out what is "wrong" according to Dave.
-
38
not_too_early = advisor.end_of_time >= self.end.to_date
-
38
return true if not_too_early
-
1
error_message = "It is too early to book for that appointment time now. " +
-
"You cannot book an appointment with #{advisor.name} beyond #{advisor.end_of_time}."
-
1
self.errors.add(:base, error_message)
-
1
return false
-
end
-
-
-
2
def cancel
-
7
if not_last_min_cancel
-
7
self.update_attribute(:cancelled, true)
-
else
-
error_message = "It is too late to cancel that appointment now."
-
self.errors.add(:base, error_message)
-
return false
-
end
-
end
-
-
## Send an email to every student who has an appointment tomorrow.
-
2
def self.nightly_email_reminder
-
tomorrow = Date.current + 1.day
-
query = 'start >= ? AND start <= ?'
-
appointments = Appointment.where(query,
-
tomorrow.beginning_of_day,
-
tomorrow.end_of_day)
-
.not_cancelled
-
appointments.each do |appointment|
-
NightlyEmailMailer.appointment_reminder(appointment).deliver
-
end
-
puts "Nightly email reminders sent on #{Date.today}"
-
# Above will be output in 'log/nightly_email.log'
-
end
-
-
2
private
-
-
2
def create_time_block
-
31
UpcomingTimeBlock.create!(:appointment_id => self.id,
-
:blackout_id => nil,
-
:end => self.end,
-
:start => self.start,
-
:student_id => self.student.id,
-
:advisor_id => self.advisor_id,
-
:name => self.student.name,
-
:short_name => self.student.user.andrewid)
-
end
-
-
# Run before any update: cancel or start/duration-change
-
2
def cancel_time_block
-
7
self.upcoming_time_block.update_attribute(:cancelled, true)
-
end
-
-
# Fancy footwork after an update.
-
#
-
# If the update was a cancel, leave the cancelled UTB for posterity
-
# (this is the old behavior of the system).
-
#
-
# Otherwise, destroy the old UTB and create a new one from scratch
-
# (the UTB-creation code handles collision detection).
-
#
-
# The destroy-then-create-maybe-failing approach depends on us
-
# living in a transaction.
-
#
-
2
def maybe_replace_time_block
-
7
if !self.cancelled?
-
self.upcoming_time_block.destroy if !self.upcoming_time_block.nil?
-
create_time_block
-
end
-
end
-
-
end
-
2
require 'time_helper'
-
-
2
class Blackout < ActiveRecord::Base
-
2
include TimeHelper
-
-
2
attr_accessible :advisor_id, :frequency, :weekly_repeated_day_attributes
-
2
attr_accessible :start_time, :start_date, :end_time, :end_date
-
2
attr_accessible :date_exceptions_attributes, :name, :cancelled
-
-
2
belongs_to :advisor
-
2
has_one :weekly_repeated_day
-
2
accepts_nested_attributes_for :weekly_repeated_day
-
-
2
has_many :date_exceptions
-
2
accepts_nested_attributes_for :date_exceptions, :allow_destroy => true
-
-
-
2
has_many :upcoming_time_blocks
-
-
2
after_create :create_time_blocks
-
2
after_update :update_time_blocks, :unless => :cancelled?
-
-
2
before_validation :adjust_dates
-
-
2
validate :valid_blackout_time
-
2
validate :open_for_blackout
-
-
2
scope :not_cancelled, where("cancelled IS ? OR cancelled = ?", nil, false)
-
-
2
FREQUENCIES = [["never", :never], ["daily", :daily], ["weekly", :weekly], ["monthly", :monthly]]
-
-
## if the frequency of the blackout is "never", then we want
-
## start_date == end_date
-
2
def adjust_dates
-
48
if self.frequency == "never"
-
12
self.end_date = self.start_date
-
end
-
end
-
-
2
def is_not_exception(date)
-
209
exceptions = date_exceptions
-
209
exceptions.each do |exception|
-
40
if (exception.start_date <= date && date <= exception.end_date)
-
8
return false
-
end
-
end
-
201
return true
-
end
-
-
2
def self.is_not_exception(blackout, date)
-
exceptions = blackout.date_exceptions
-
exceptions.each do |exception|
-
if (exception.start_date <= date && date <= exception.end_date)
-
return false
-
end
-
end
-
return true
-
end
-
-
2
def create_never_time_blocks
-
8
if start_date < Date.current
-
return
-
elsif start_date > advisor.end_of_time
-
2
return
-
end
-
6
UpcomingTimeBlock.create(:appointment_id => nil,
-
:blackout_id => self.id,
-
:start => TimeHelper.combine_date_time(start_date, start_time),
-
:end => TimeHelper.combine_date_time(end_date, end_time),
-
:advisor_id => advisor_id,
-
:name => self.name,
-
:past => false,
-
:cancelled => false)
-
end
-
-
2
def self.add_future_utbs
-
# assuming daily script is run every night past midnight
-
# we use this where clause for now since some old advisors have
-
# weeks_in_advance = null.
-
4
Advisor.where("weeks_in_advance IS NOT ?", nil).each do |advisor|
-
8
advisor.transaction do
-
8
advisor.update_utbs
-
# save to adjust end_of_time
-
8
advisor.save
-
end
-
end
-
end
-
-
2
def create_daily_time_blocks
-
15
if end_date < Date.current
-
return
-
elsif start_date > advisor.end_of_time
-
1
return
-
end
-
-
14
upcoming_start_date = start_date <= Date.current ? Date.current : start_date
-
14
upcoming_end_date = end_date > advisor.end_of_time ? advisor.end_of_time : end_date
-
-
14
days_to_create = (upcoming_end_date - upcoming_start_date).to_i + 1
-
14
days_to_create.times do |i|
-
190
date = upcoming_start_date + i.day
-
190
if (is_not_exception(date))
-
183
UpcomingTimeBlock.create(:appointment_id => nil,
-
:blackout_id => self.id,
-
:start => TimeHelper.combine_date_time(date, start_time),
-
:end => TimeHelper.combine_date_time(date, end_time),
-
:advisor_id => advisor_id,
-
:name => self.name,
-
:past => false,
-
:cancelled => false)
-
end
-
end
-
end
-
-
2
def create_weekly_time_blocks(wday)
-
9
if end_date < Date.current
-
return
-
elsif start_date > advisor.end_of_time
-
7
return
-
end
-
-
2
upcoming_start_date = start_date <= Date.current ? Date.current : start_date
-
2
upcoming_end_date = end_date > advisor.end_of_time ? advisor.end_of_time : end_date
-
-
2
date = upcoming_start_date + ((wday - upcoming_start_date.wday) % 7)
-
-
2
while (upcoming_start_date <= date && date <= upcoming_end_date) do
-
4
if (is_not_exception(date))
-
3
UpcomingTimeBlock.create(:appointment_id => nil,
-
:blackout_id => self.id,
-
:start => TimeHelper.combine_date_time(date, start_time),
-
:end => TimeHelper.combine_date_time(date, end_time),
-
:advisor_id => advisor_id,
-
:name => self.name,
-
:past => false,
-
:cancelled => false)
-
end
-
4
date += 7.day
-
end
-
end
-
-
##TODO monthly repeats aren't completely tested (hard since "the window" is currently 3 weeks!)
-
2
def create_monthly_time_blocks
-
3
if end_date < Date.current
-
return
-
elsif start_date > advisor.end_of_time
-
1
return
-
end
-
-
2
upcoming_start_date = start_date <= Date.current ? Date.current : start_date
-
2
upcoming_end_date = end_date > advisor.end_of_time ? advisor.end_of_time : end_date
-
-
2
date = upcoming_start_date
-
-
2
while (upcoming_start_date <= date && date <= upcoming_end_date) do
-
4
if (is_not_exception(date))
-
4
UpcomingTimeBlock.create(:appointment_id => nil,
-
:blackout_id => self.id,
-
:start => TimeHelper.combine_date_time(date, start_time),
-
:end => TimeHelper.combine_date_time(date, end_time),
-
:advisor_id => advisor_id,
-
:name => self.name,
-
:past => false,
-
:cancelled => false)
-
end
-
4
date += 1.month
-
end
-
end
-
-
2
def create_time_blocks
-
29
if frequency == "never"
-
8
create_never_time_blocks
-
21
elsif frequency == "daily"
-
15
create_daily_time_blocks
-
6
elsif frequency == "weekly"
-
3
wday_hash = weekly_repeated_day.wday_hash
-
3
7.times do |i|
-
21
if wday_hash[i]
-
9
create_weekly_time_blocks(i)
-
end
-
end
-
3
elsif frequency == "monthly"
-
3
create_monthly_time_blocks
-
end
-
-
end
-
-
2
def update_time_blocks
-
## CONSIDER: only calling below two lines if is_changed == true
-
## right now, is_changed method is not completely correct.
-
if self.changed
-
changes = self.changes
-
name_changed = changes.has_key?("name")
-
if (!name_changed or (name_changed and changes.keys.size > 2)) # update time also changed
-
self.upcoming_time_blocks.destroy_all
-
create_time_blocks
-
else
-
self.upcoming_time_blocks.update_all(:name => name)
-
end
-
end
-
end
-
-
2
def cancel
-
1
if self.update_attribute(:cancelled, true)
-
1
time_blocks = self.upcoming_time_blocks
-
1
time_blocks.each do |time_block|
-
22
time_block.update_attribute(:cancelled, true)
-
end
-
end
-
end
-
-
2
def valid_blackout_time
-
48
if start_time >= end_time
-
2
self.errors.add(:base, "Blackout start time should be before end time.")
-
2
return false
-
elsif start_date > end_date
-
self.errors.add(:base, "Blackout start datetime should be before end time.")
-
return false
-
elsif end_date < Date.current
-
6
self.errors.add(:base, "Blackout end datetime should not be before today")
-
6
return false
-
end
-
40
return true
-
end
-
-
# if there are no UpcomingTimeBlocks that conflict with self's time ranges,
-
# return true, else return false and add the conflicts to the error message.
-
2
def open_for_blackout
-
48
is_open = UpcomingTimeBlock.open_for_blackout?(self)
-
48
if is_open == true
-
40
return true
-
else
-
8
self.errors.add(:base, "There were conflicts.")
-
8
self.errors.add(:base, "#{is_open.inspect}")
-
8
return false
-
end
-
end
-
-
# a string represention of the blackout
-
2
def to_s
-
str = self.start_date.to_s
-
str += " "
-
-
str += self.start_time.strftime "%H:%M:%S"
-
-
str += " to "
-
-
str += self.end_date.to_s
-
str += " "
-
-
str += self.end_time.strftime "%H:%M:%S"
-
return str
-
end
-
-
# the frequency of the blackout, with the first letter uppercase
-
# i.e. returns "Never", "Weekly", "Monthly", etc
-
2
def frequency_str
-
freq_str = self.frequency
-
freq = freq_str[0].upcase + freq_str[1..freq_str.length]
-
return freq
-
end
-
-
2
def self.new_from_params(params)
-
attrs = {
-
start_time: Time.zone.parse(params[:time]),
-
end_time: Time.zone.parse(params[:time]) + 1.hour,
-
start_date: params[:time],
-
end_date: params[:time]
-
}
-
self.new(attrs)
-
end
-
end
-
2
class DateException < ActiveRecord::Base
-
2
attr_accessible :blackout_id, :end_date, :start_date
-
2
belongs_to :blackout
-
-
2
validate :valid_dates
-
##
-
# TODO make sure date range falls within blackout range!
-
-
2
def stringify
-
str = ""
-
if (start_date == end_date)
-
str = start_date.strftime "%m/%d/%y"
-
else
-
start_str = start_date.strftime "%m/%d/%y"
-
end_str = end_date.strftime "%m/%d/%y"
-
-
str = "#{start_str} to #{end_str}"
-
-
end
-
return str
-
-
end
-
-
2
def valid_dates
-
4
if start_date > end_date
-
1
self.errors.add(:base, "Date exception start dates should be before end dates.")
-
1
return false
-
end
-
end
-
-
end
-
2
class Department < ActiveRecord::Base
-
2
attr_accessible :name
-
2
has_many :students
-
2
has_many :advisors
-
end
-
2
class Feedback < ActiveRecord::Base
-
2
attr_accessible :content, :student_id
-
2
belongs_to :student
-
end
-
2
class SpecialStudent < ActiveRecord::Base
-
2
belongs_to :student
-
-
2
attr_accessible :max_time, :student_id, :is_extended, :is_urgent
-
2
validate :valid_student_id
-
#Validate student with the given name exist
-
2
def valid_student_id
-
-
if self.student_id != nil
-
return true
-
else
-
-
self.errors.add(:base, "Student does not exist.")
-
return false
-
end
-
end
-
-
end
-
2
class Student < ActiveRecord::Base
-
2
attr_accessible :advisor_id, :department_id, :name, :department, :advisor
-
2
belongs_to :department
-
2
belongs_to :advisor
-
2
has_one :user
-
2
has_one :special_student
-
-
2
has_many :appointments
-
2
has_many :upcoming_time_blocks
-
2
has_many :feedback
-
-
#Return an array of time slots up to the maximum time set for the special student
-
#Maximum time for normal student is 15 minutes
-
#i.e. if max_time == 30, return [15, 30]
-
2
def get_time_slots
-
special_student = self.special_student
-
if special_student == nil
-
max_slot = 15
-
else
-
max_slot = special_student.max_time
-
end
-
-
slot_num = max_slot/15
-
arr = Array.new
-
for i in 1..slot_num do
-
arr.push(15*i)
-
end
-
return arr
-
end
-
-
end
-
-
-
2
require 'time_helper'
-
-
2
class UpcomingTimeBlock < ActiveRecord::Base
-
2
include TimeHelper
-
-
2
attr_accessible :advisor_id, :appointment_id, :blackout_id, :end, :start
-
2
attr_accessible :student_id, :name, :past, :cancelled, :short_name
-
-
2
belongs_to :advisor
-
2
belongs_to :appointment
-
2
belongs_to :blackout
-
2
belongs_to :student
-
-
2
day_start_hour = 9.hour # 9am
-
2
slot_duration = 15.minute
-
2
unlock_urgent_slot_duration = 30.minute
-
2
num_day_slots = 28
-
2
num_week_days = 7
-
-
11
scope :after, lambda { |time| where("start >= ?", time) }
-
11
scope :before, lambda { |time| where("end <= ?", time) }
-
2
scope :not_cancelled, where("cancelled <> ? OR cancelled IS ?", true, nil)
-
-
# An appointment cannot be saved if it conflicts with existing appointments
-
# or blackouts. If the advisor of the appointment passed in has no conflicts
-
# (they are open), return true. Otherwise, return false.
-
2
def self.open_for_appointment?(appointment)
-
38
student_id = appointment.student_id
-
38
advisor_id = appointment.advisor_id
-
38
start_dt = appointment.start
-
38
end_dt = appointment.end
-
-
38
query = "start < ? AND end > ? AND advisor_id = ? AND (cancelled <> ? OR cancelled IS ?) AND (past <> ? OR past IS ?)"
-
38
results = UpcomingTimeBlock.where(query, end_dt, start_dt, advisor_id, true, nil, true, nil)
-
-
# if we are trying to grow/shrink an appointment
-
38
results.reject! { |u| u.appointment_id == appointment.id } unless appointment.id.nil?
-
-
38
if results != []
-
# TODO This should happen only if two students have raced for the same block (it actually happened once because of a bug). How best to handle it? Failing would be wrong, but maybe send mail to maintainer? I guess not if we are in test mode?
-
10
logger.info "UpcomingTimeBlock.open_for_appointment?: appointment #{appointment.to_yaml}."
-
10
logger.info "UpcomingTimeBlock.open_for_appointment?: results #{results == [] ? '[none]' : results.to_yaml}."
-
end
-
-
38
return_val = results == [] ? true : false
-
end
-
-
# Build a query string that excludes looking at the dates in date_exceptions
-
# in order to avoid finding at appointments falling on those dates.
-
# CONSIDER making this a class method on DateException.
-
2
def self.build_date_exclusions_query(date_exceptions)
-
# sample = "start < ? AND end > ? AND advisor_id = ? AND blackout_id is NULL"
-
59
date_exceptions = date_exceptions.reject {|de| de.marked_for_destruction? }
-
52
query = "("
-
52
if date_exceptions.size == 0
-
48
return nil
-
end
-
4
date_exceptions.each do |date_exception|
-
4
start_date = date_exception.start_date
-
4
end_date = date_exception.end_date
-
## since date of UTB.start == date of UTB.end
-
## we only check start
-
4
part = "(start < '#{date_exception.start_date} 00:00:00' OR start > '#{date_exception.end_date} 23:59:59') AND "
-
4
query += part
-
end
-
-
# remove last ' AND '
-
4
query = query[0 .. query.length - 6] + ")"
-
-
4
return query
-
end
-
-
# A blackout cannot be saved if it conflicts with existing appointments.
-
# If the advisor of the blackout passed in has no conflicts (they are open),
-
# return true. Otherwise, return an array of the conflicting UTBs.
-
####
-
## TODO
-
# Improve efficiency
-
####
-
2
def self.open_for_blackout?(blackout)
-
52
start_dt = Time.zone.local(blackout.start_date.year,
-
blackout.start_date.month,
-
blackout.start_date.day,
-
blackout.start_time.hour,
-
blackout.start_time.min,
-
0,
-
0)
-
52
end_dt = Time.zone.local(blackout.end_date.year,
-
blackout.end_date.month,
-
blackout.end_date.day,
-
blackout.end_time.hour,
-
blackout.end_time.min,
-
0,
-
0)
-
52
query = "start < ? AND end > ? AND advisor_id = ? AND appointment_id IS NOT NULL AND (cancelled IS NULL OR cancelled = ?) AND (past IS NULL OR past = ?)"
-
# never, daily, weekly, monthly
-
52
freq = blackout.frequency
-
52
results = []
-
52
date_exceptions_query = build_date_exclusions_query(blackout.date_exceptions)
-
52
if not date_exceptions_query.nil?
-
4
query += " AND #{date_exceptions_query}"
-
end
-
52
duration = TimeHelper.difference(end_dt, start_dt)
-
52
time_delta = 1.day
-
52
if freq == "weekly"
-
9
weekly_repeated_day = blackout.weekly_repeated_day
-
9
wday_hash = weekly_repeated_day.wday_hash
-
elsif freq == "monthly"
-
7
time_delta = 1.month
-
end
-
52
while start_dt <= end_dt
-
436
if freq == "weekly" and not wday_hash[start_dt.wday] # ignore looking at days not repeated
-
93
start_dt += time_delta
-
93
next
-
end
-
343
result_part = UpcomingTimeBlock.where(query, start_dt + duration, start_dt, blackout.advisor_id, false, false)
-
343
start_dt += time_delta
-
343
results.concat result_part
-
# there can be no appointments beyong end_of_time so we can stop looking
-
343
break if start_dt > blackout.advisor.end_of_time
-
end
-
52
if results == []
-
40
return true
-
end
-
12
return results ## return these so client knows the conflicting appts/
-
end
-
-
2
def insert(week_info, time, time_slot)
-
fail("Code believed to be dead is running") # 2015-05-28
-
if (week_info[time] == nil)
-
week_info[time] = [time_slot]
-
else
-
slots_array = week_info[time]
-
slots_array.append(time_slot)
-
week_info[time] = slots_array
-
end
-
end
-
-
# call this method on the result of get_week for normal students, this method
-
# will create 'temporary' blackout slots on the slot reserved for urgent students,
-
# which is at least one slot everyday
-
2
def self.get_filtered_week (week_start, week_end, person, week_info)
-
9
now = Time.current
-
# if person is not student, do nothing
-
9
if person[:student_id].nil?
-
9
return week_info
-
end
-
-
special_student = SpecialStudent.where("student_id = ?", person)[0]
-
-
# this method is only required for urgent students
-
if (special_student.nil? || !special_student.is_urgent)
-
return week_info
-
end
-
-
filtered_week_info = week_info
-
-
for day in 0..(num_week_days-1) do
-
num_free_slot = 0
-
last_free_slot = nil
-
day_start = week_start + (day.day) # week_start is the midnight
-
slot_time = day_start + day_start_hour
-
for slot in 0..(num_day_slots-1) do
-
slot_time += (slot * slot_duration)
-
if (week_info[slot_time].nil?)
-
num_free_slot += 1
-
last_free_slot = slot_time
-
end
-
end
-
if (num_free_slot == 1 && !last_free_slot.nil? &&
-
now < (last_free_slot - unlock_urgent_slot_duration))
-
blackout = UpcomingTimeBlock.new(:appointment_id => nil,
-
:blackout_id => nil,
-
:start => last_free_slot,
-
:end => last_free_slot + slot_duration,
-
:advisor_id => nil,
-
:name => nil,
-
:past => false)
-
filtered_week_info[last_free_slot] = blackout
-
end
-
end
-
return filtered_week_info
-
end
-
-
-
# person is a Hash. It will contain one key, either :student_id or :advisor_id,
-
# depending if the currently logged in user is an advisor or a student. The
-
# value of the key corresponds to the primary key of the currently logged
-
# in Student or Advisor in the database.
-
#
-
# The advisor_id is an optional argument that is required when the currently
-
# logged in user is a student (i.e. when person[:student_id] is not nil.).
-
# This advisor_id corresponds to the id of the advisor whose calendar is being
-
# viewed.
-
#
-
# Returns a hash table with keys as the start times and values as the appointment
-
# or blackout(s) at associated start time.
-
#
-
# Invocation is odd. We ALWAYS are scanning an advisor's calendar, and
-
# SOMETIMES are doing so on behalf of a student, but advisor_id is an
-
# optional parameter!?
-
#
-
2
def self.get_week(week_start, week_end, person, *advisor_id)
-
9
week_info = Hash.new
-
-
9
if !person[:student_id].nil?
-
advisor_id = advisor_id.first ## dubious style
-
student_id = person[:student_id]
-
week_slots = UpcomingTimeBlock.not_cancelled.after(week_start).before(week_end).where("advisor_id = ? OR student_id = ?", advisor_id, student_id)
-
elsif !person[:advisor_id].nil?
-
9
advisor_id = person[:advisor_id]
-
9
week_slots = UpcomingTimeBlock.not_cancelled.after(week_start).before(week_end).where("advisor_id = ?", advisor_id)
-
else
-
raise "get_week called incorrectly!"
-
end
-
-
59
advisor_slots, student_slots = week_slots.partition { |time_slot| time_slot.advisor_id == advisor_id }
-
-
# Collect all appointments with this advisor -- including this student, if we are a student.
-
9
advisor_slots.each do |time_slot|
-
50
start_time = time_slot.start
-
50
num_slots = (time_slot.end - time_slot.start)/15.minutes
-
50
for i in 0..(num_slots-1)
-
102
time = start_time + (i*15).minutes
-
102
if (time_slot.appointment_id != nil)
-
1
fail("Collision") unless week_info[time].nil?
-
1
week_info[time] = time_slot
-
else
-
101
if week_info[time].nil?
-
101
week_info[time] = [time_slot]
-
else
-
week_info[time].push(time_slot)
-
end
-
end
-
end
-
end
-
-
# Fold in this-student appointments with *other* advisors -- if we are a student.
-
9
student_slots.each do |time_slot|
-
fail ("Intruder alert") if time_slot.appointment_id.nil?
-
start_time = time_slot.start
-
num_slots = (time_slot.end - time_slot.start)/15.minutes
-
for i in 0..(num_slots-1)
-
time = start_time + (i*15).minutes
-
week_info[time] = time_slot
-
end
-
end
-
-
9
return get_filtered_week(week_start, week_end, person, week_info)
-
end
-
-
end
-
# NOTE
-
# User, Advisor, and Student have no hierarchy relationship --
-
# not as far as Rails knows. This is *not* an STI situation.
-
#
-
# User "fronts for" Advisor and Student: any field of them
-
# that should be presented turns into a virtual field of User.
-
#
-
2
class User < ActiveRecord::Base
-
# has_secure_password
-
2
belongs_to :advisor, dependent: :destroy
-
2
belongs_to :student, dependent: :destroy
-
-
2
attr_accessor :name, :department_id, :type, :student_advisor_id, :announcement
-
2
attr_accessor :office, :face_url, :student_redirect_url, :weeks_in_advance, :confirmed_appt_cancellations
-
2
attr_accessible :email, :name, :student_advisor_id, :type, :department_id, :announcement
-
2
attr_accessible :office, :face_url, :student_redirect_url, :weeks_in_advance
-
-
# allowable for these to be blank: office, face_url, student_redirect_url, announcement
-
2
validates :email, :presence => true, :uniqueness => true
-
2
validates :type, :presence => true, :on => :create
-
2
validates :weeks_in_advance, :presence => true, :on => :update, :if => lambda { |user| user.role == :advisor }
-
2
validates :weeks_in_advance, numericality: { only_integer: true, greater_than_or_equal_to: 0 }, :if => lambda { |user| user.role == :advisor }
-
2
validates :weeks_in_advance, :presence => true, :on => :create, :if => lambda { |user| user.type == "Advisor" }
-
2
validates :name, :presence => true
-
2
validates :department_id, :presence => true
-
-
2
before_create :create_student_or_advisor
-
2
before_update :update_student_or_advisor
-
-
3
after_create :safety_net_blackout, :if => lambda { |user| user.role == :advisor }
-
-
2
def role
-
1
if self.advisor_id != nil
-
return :advisor
-
elsif self.student_id != nil
-
1
return :student
-
end
-
return nil
-
end
-
-
2
def create_student_or_advisor
-
1
if type == "Advisor"
-
new_advisor = Advisor.create(:department_id => department_id,
-
:name => name,
-
:office => office,
-
:face_url => face_url,
-
:student_redirect_url => student_redirect_url,
-
:weeks_in_advance => weeks_in_advance)
-
self.advisor = new_advisor
-
else
-
1
new_student = Student.create(:department_id => department_id,
-
:name => name,
-
:advisor_id => student_advisor_id)
-
1
self.student = new_student
-
end
-
end
-
-
2
def update_student_or_advisor
-
if self.role == :advisor
-
self.advisor.update_attributes(name: name,
-
department_id: department_id,
-
office: office,
-
face_url: face_url,
-
student_redirect_url: student_redirect_url,
-
announcement: announcement,
-
weeks_in_advance: weeks_in_advance,
-
confirmed_appt_cancellations: confirmed_appt_cancellations)
-
else
-
self.student.update_attributes(name: name,
-
department_id: department_id,
-
advisor_id: student_advisor_id)
-
end
-
end
-
-
2
def full_name
-
if !self.advisor.nil?
-
return self.advisor.name
-
elsif !self.student.nil?
-
return self.student.name
-
end
-
return nil
-
end
-
-
2
def department
-
if !self.advisor.nil?
-
return self.advisor.department_id
-
elsif !self.student.nil?
-
return self.student.department_id
-
end
-
return nil
-
end
-
-
2
def andrewid
-
31
email.gsub /@.+/, ""
-
end
-
-
2
private
-
-
2
def safety_net_blackout
-
start_dt = Date.today
-
end_dt = Date.parse("2030-12-31 00:00:00")
-
-
# use utc to match db
-
start_time = Time.utc(2000, 1, 31, 0, 0, 0)
-
end_time = Time.utc(2000, 1, 31, 23, 59, 59)
-
-
blackout = Blackout.create!(:advisor_id => self.advisor.id,
-
:frequency => "daily",
-
:name => "Safety-net blackout",
-
:start_date => start_dt,
-
:start_time => start_time,
-
:end_date => end_dt,
-
:end_time => end_time)
-
end
-
-
end
-
2
class WeeklyRepeatedDay < ActiveRecord::Base
-
2
attr_accessible :blackout_id, :friday, :monday, :saturday, :sunday, :thursday, :tuesday, :wednesday
-
2
belongs_to :blackout
-
-
-
2
def to_s
-
arr = []
-
-
monday ? arr.push("Monday") : nil
-
tuesday ? arr.push("Tuesday") : nil
-
wednesday ? arr.push("Wednesday") : nil
-
thursday ? arr.push("Thursday") : nil
-
friday ? arr.push("Friday") : nil
-
saturday ? arr.push("Saturday") : nil
-
sunday ? arr.push("Sunday") : nil
-
-
return arr.join(", ")
-
-
end
-
-
# Return true if the blackout does repeat on the passed in date.
-
2
def repeats_on?(date)
-
wday_hash[date.wday]
-
end
-
-
2
def wday_hash
-
{ 1 => monday,
-
2 => tuesday,
-
3 => wednesday,
-
4 => thursday,
-
5 => friday,
-
6 => saturday,
-
12
0 => sunday }
-
end
-
-
end
-
2
require File.expand_path('../boot', __FILE__)
-
-
2
require 'rails/all'
-
-
2
if defined?(Bundler)
-
# If you precompile assets before deploying to production, use this line
-
##### Bundler.require(*Rails.groups(:assets => %w(development test)))
-
# If you want your assets lazily compiled in production, use this line
-
2
Bundler.require(:default, :assets, Rails.env)
-
end
-
-
2
module Sailfish
-
2
class Application < Rails::Application
-
# Settings in config/environments/* take precedence over those specified here.
-
# Application configuration should go into files in config/initializers
-
# -- all .rb files in that directory are automatically loaded.
-
-
# Custom directories with classes and modules you want to be autoloadable.
-
# config.autoload_paths += %W(#{config.root}/extras)
-
-
# Only load the plugins named here, in the order given (default is alphabetical).
-
# :all can be used as a placeholder for all plugins not explicitly named.
-
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
-
-
# Activate observers that should always be running.
-
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
-
-
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
-
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
-
2
config.time_zone = 'Eastern Time (US & Canada)'
-
-
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
-
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
-
# config.i18n.default_locale = :de
-
-
# Configure the default encoding used in templates for Ruby 1.9.
-
2
config.encoding = "utf-8"
-
-
# Configure sensitive parameters which will be filtered from the log file.
-
2
config.filter_parameters += [:password]
-
-
# Enable escaping HTML in JSON.
-
2
config.active_support.escape_html_entities_in_json = true
-
-
# Use SQL instead of Active Record's schema dumper when creating the database.
-
# This is necessary if your schema can't be completely dumped by the schema dumper,
-
# like if you have constraints or database-specific column types
-
# config.active_record.schema_format = :sql
-
-
# Enforce whitelist mode for mass assignment.
-
# This will create an empty whitelist of attributes available for mass-assignment for all models
-
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
-
# parameters by using an attr_accessible or attr_protected declaration.
-
2
config.active_record.whitelist_attributes = true
-
-
# Enable the asset pipeline
-
2
config.assets.enabled = true
-
-
# Version of your assets, change this if you want to expire all your assets
-
2
config.assets.version = '1.0'
-
-
# Colorization is enabled by default in various circumstances
-
# config.colorize_logging = false
-
end
-
end
-
2
require 'rubygems'
-
-
# Set up gems listed in the Gemfile.
-
2
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
-
-
2
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
-
# Load the rails application
-
2
require File.expand_path('../application', __FILE__)
-
-
# Initialize the rails application
-
2
Sailfish::Application.initialize!
-
2
Sailfish::Application.configure do
-
# Settings specified here will take precedence over those in config/application.rb
-
-
# The test environment is used exclusively to run your application's
-
# test suite. You never need to work with it otherwise. Remember that
-
# your test database is "scratch space" for the test suite and is wiped
-
# and recreated between test runs. Don't rely on the data there!
-
2
config.cache_classes = true
-
-
# Configure static asset server for tests with Cache-Control for performance
-
2
config.serve_static_assets = true
-
2
config.static_cache_control = "public, max-age=3600"
-
-
# Log error messages when you accidentally call methods on nil
-
2
config.whiny_nils = true
-
-
# Show full error reports and disable caching
-
2
config.consider_all_requests_local = true
-
2
config.action_controller.perform_caching = false
-
-
# Raise exceptions instead of rendering exception templates
-
2
config.action_dispatch.show_exceptions = false
-
-
# Disable request forgery protection in test environment
-
2
config.action_controller.allow_forgery_protection = false
-
-
# Tell Action Mailer not to deliver emails to the real world.
-
# The :test delivery method accumulates sent emails in the
-
# ActionMailer::Base.deliveries array.
-
2
config.action_mailer.delivery_method = :test
-
-
# Raise exception on mass assignment protection for Active Record models
-
2
config.active_record.mass_assignment_sanitizer = :strict
-
-
# Print deprecation notices to the stderr
-
2
config.active_support.deprecation = :stderr
-
end
-
# Be sure to restart your server when you modify this file.
-
-
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
-
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
-
-
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
-
# Rails.backtrace_cleaner.remove_silencers!
-
2
ActiveSupport::Inflector.inflections do |inflect|
-
2
inflect.irregular 'feedback', 'feedback'
-
end
-
# Be sure to restart your server when you modify this file.
-
-
# Add new mime types for use in respond_to blocks:
-
# Mime::Type.register "text/richtext", :rtf
-
# Mime::Type.register_alias "text/html", :iphone
-
# Enable below to see where active record queries are made in our code
-
# (useful to increase perf)
-
# ActiveRecordQueryTrace.enabled = true
-
2
module ActionView
-
2
class LogSubscriber
-
2
def render_partial(event)
-
# Consider calling debug for partials not rendered as frequently
-
# (which would probably be the partials outside of app/views/calendars)
-
end
-
end
-
end
-
# Be sure to restart your server when you modify this file.
-
-
# Your secret key for verifying the integrity of signed cookies.
-
# If you change this key, all old signed cookies will become invalid!
-
# Make sure the secret is at least 30 characters and all random,
-
# no regular words or you'll be exposed to dictionary attacks.
-
-
2
if Rails.env.production?
-
Sailfish::Application.config.secret_token = 'ca2f2ad0ea887d57d874eea1520dcf929ee4084062046982f006be2a2aade1af1d479fc87e5a1e88ead18f71c67542e4dbde4aa648ba7194d9b76edf7c534163'
-
else
-
2
Sailfish::Application.config.secret_token = 'ca2f2ad0ea887d573045972352deaf929ee40840620469feed00be2a2aade1af1d479fc87e5a1e88ead18f71c67542e4dbde4aa648ba7194d9b76edf7c534163'
-
end
-
# Be sure to restart your server when you modify this file.
-
-
2
Sailfish::Application.config.session_store :cookie_store, key: '_sailfish_session'
-
-
# Use the database for sessions instead of the cookie-based default,
-
# which shouldn't be used to store highly confidential information
-
# (create the session table with "rails generate session_migration")
-
# Sailfish::Application.config.session_store :active_record_store
-
# Be sure to restart your server when you modify this file.
-
#
-
# This file contains settings for ActionController::ParamsWrapper which
-
# is enabled by default.
-
-
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
-
2
ActiveSupport.on_load(:action_controller) do
-
2
wrap_parameters format: [:json]
-
end
-
-
# Disable root element in JSON by default.
-
2
ActiveSupport.on_load(:active_record) do
-
2
self.include_root_in_json = false
-
end
-
2
Sailfish::Application.routes.draw do
-
-
2
get "dayview/index"
-
-
2
get 'about' => 'static#about', :as => :about
-
-
2
resources :feedback
-
-
2
resources :special_students
-
-
2
resources :calendars, :only => [:index]
-
-
-
2
get '/calendars/student/:id', to: 'calendars#student', as: 'calendars_student'
-
2
get "calendars/advisor"
-
2
post "calendars/time_slot"
-
-
2
resources :users do
-
2
collection do
-
# index routes to show only either advisors or students
-
2
get :advisors
-
2
get :students
-
end
-
end
-
-
2
resources :students
-
-
2
resources :blackouts do
-
2
member do
-
2
get :cancel
-
end
-
end
-
-
-
2
resources :appointments do
-
2
member do
-
2
post :advisor_cancel
-
2
post :student_cancel
-
end
-
2
collection do
-
2
get :today
-
end
-
end
-
-
-
2
resources :departments
-
-
-
2
resources :advisors
-
-
-
2
match 'register' => 'users#new', :as => :register
-
2
match 'logout' => 'sessions#destroy', :as => :logout
-
2
match 'login' => 'sessions#new', :as => :login
-
2
match 'masquerade' => 'sessions#edit'
-
2
put 'sessions', to: "sessions#update"
-
2
resources :sessions
-
-
2
root :to => "sessions#new"
-
-
# The priority is based upon order of creation:
-
# first created -> highest priority.
-
-
# Sample of regular route:
-
# match 'products/:id' => 'catalog#view'
-
# Keep in mind you can assign values other than :controller and :action
-
-
# Sample of named route:
-
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
-
# This route can be invoked with purchase_url(:id => product.id)
-
-
# Sample resource route (maps HTTP verbs to controller actions automatically):
-
# resources :products
-
-
# Sample resource route with options:
-
# resources :products do
-
# member do
-
# get 'short'
-
# post 'toggle'
-
# end
-
#
-
# collection do
-
# get 'sold'
-
# end
-
# end
-
-
# Sample resource route with sub-resources:
-
# resources :products do
-
# resources :comments, :sales
-
# resource :seller
-
# end
-
-
# Sample resource route with more complex sub-resources
-
# resources :products do
-
# resources :comments
-
# resources :sales do
-
# get 'recent', :on => :collection
-
# end
-
# end
-
-
# Sample resource route within a namespace:
-
# namespace :admin do
-
# # Directs /admin/products/* to Admin::ProductsController
-
# # (app/controllers/admin/products_controller.rb)
-
# resources :products
-
# end
-
-
# You can have the root of your site routed with "root"
-
# just remember to delete public/index.html.
-
# root :to => 'welcome#index'
-
-
# See how all your routes lay out with "rake routes"
-
-
# This is a legacy wild controller route that's not recommended for RESTful applications.
-
# Note: This route will make all actions in every controller accessible via GET requests.
-
# match ':controller(/:action(/:id))(.:format)'
-
end
-
2
module TimeHelper
-
# return difference in seconds
-
2
def difference(end_time, start_time)
-
(Time.zone.at(end_time.hour * 60 * 60 + end_time.min * 60 + end_time.sec) -
-
64
Time.zone.at(start_time.hour * 60 * 60 + start_time.min * 60 + start_time.sec))
-
.seconds
-
end
-
-
2
def combine_date_time(date, time)
-
428
return Time.zone.local(date.year, date.month, date.day,
-
time.hour, time.min, time.sec)
-
end
-
-
2
module_function :difference
-
2
module_function :combine_date_time
-
end
-
1
module TimeShifter
-
1
extend self
-
1
def shift_appointment(a, shift_meth)
-
6
new_start = shift_meth.call a.start
-
6
new_end = shift_meth.call a.end
-
6
a.update_column :start, new_start
-
6
a.update_column :end, new_end
-
6
a.upcoming_time_block.update_column :start, new_start
-
6
a.upcoming_time_block.update_column :end, new_end
-
end
-
-
1
def shift_blackout(b, shift_meth)
-
6
b.upcoming_time_blocks.each do |utb|
-
8
new_start = shift_meth.call utb.start
-
8
new_end = shift_meth.call utb.end
-
8
utb.update_column :start, new_start
-
8
utb.update_column :end, new_end
-
end
-
end
-
-
1
def shift_times(shift_meth)
-
4
if shift_meth == :forward # utc_to_et
-
16
shift_meth = Proc.new {|time| time - (time.utc_offset / 60 / 60).hours}
-
elsif shift_meth == :backward
-
16
shift_meth = Proc.new {|time| time + (time.utc_offset / 60 / 60).hours}
-
else
-
raise ArgumentError, "direction must be :forward or :backward"
-
end
-
4
Appointment.transaction do
-
4
Appointment.all.each do |a|
-
6
TimeShifter.shift_appointment a, shift_meth
-
end
-
4
Blackout.all.each do |b|
-
6
TimeShifter.shift_blackout b, shift_meth
-
end
-
end
-
end
-
end
-
1
require 'test_helper'
-
-
1
class AppointmentsControllerTest < ActionController::TestCase
-
1
setup do
-
7
@appointment = appointments(:one)
-
end
-
-
1
test "should get index" do
-
get :index
-
assert_response :success
-
assert_not_nil assigns(:appointments)
-
end
-
-
1
test "should get new" do
-
get :new
-
assert_response :success
-
end
-
-
1
test "should create appointment" do
-
assert_difference('Appointment.count') do
-
post :create, appointment: { advisor_id: @appointment.advisor_id, end: @appointment.end, start: @appointment.start, student_id: @appointment.student_id }
-
end
-
-
assert_redirected_to appointment_path(assigns(:appointment))
-
end
-
-
1
test "should show appointment" do
-
get :show, id: @appointment
-
assert_response :success
-
end
-
-
1
test "should get edit" do
-
get :edit, id: @appointment
-
assert_response :success
-
end
-
-
1
test "should update appointment" do
-
put :update, id: @appointment, appointment: { advisor_id: @appointment.advisor_id, end: @appointment.end, start: @appointment.start, student_id: @appointment.student_id }
-
assert_redirected_to appointment_path(assigns(:appointment))
-
end
-
-
1
test "should destroy appointment" do
-
assert_difference('Appointment.count', -1) do
-
delete :destroy, id: @appointment
-
end
-
-
assert_redirected_to appointments_path
-
end
-
end
-
1
require 'test_helper'
-
-
1
class BlackoutsControllerTest < ActionController::TestCase
-
1
setup do
-
7
@blackout = blackouts(:one)
-
end
-
-
1
test "should get index" do
-
get :index
-
assert_response :success
-
assert_not_nil assigns(:blackouts)
-
end
-
-
1
test "should get new" do
-
get :new
-
assert_response :success
-
end
-
-
1
test "should create blackout" do
-
assert_difference('Blackout.count') do
-
post :create, blackout: { advisor_id: @blackout.advisor_id, end: @blackout.end, frequency: @blackout.frequency, start: @blackout.start }
-
end
-
-
assert_redirected_to blackout_path(assigns(:blackout))
-
end
-
-
1
test "should show blackout" do
-
get :show, id: @blackout
-
assert_response :success
-
end
-
-
1
test "should get edit" do
-
get :edit, id: @blackout
-
assert_response :success
-
end
-
-
1
test "should update blackout" do
-
put :update, id: @blackout, blackout: { advisor_id: @blackout.advisor_id, end: @blackout.end, frequency: @blackout.frequency, start: @blackout.start }
-
assert_redirected_to blackout_path(assigns(:blackout))
-
end
-
-
1
test "should destroy blackout" do
-
assert_difference('Blackout.count', -1) do
-
delete :destroy, id: @blackout
-
end
-
-
assert_redirected_to blackouts_path
-
end
-
end
-
1
require 'test_helper'
-
-
1
class CalendarsControllerTest < ActionController::TestCase
-
1
test "should get advisor" do
-
1
get :advisor
-
1
assert_response :success
-
end
-
-
1
test "should get student" do
-
1
get :student
-
assert_response :success
-
end
-
-
end
-
1
require 'test_helper'
-
-
1
class CalendersControllerTest < ActionController::TestCase
-
1
test "should get advisor" do
-
1
get :advisor
-
assert_response :success
-
end
-
-
1
test "should get student" do
-
1
get :student
-
assert_response :success
-
end
-
-
end
-
1
require 'test_helper'
-
-
1
class CancelMailerTest < ActionMailer::TestCase
-
# test "the truth" do
-
# assert true
-
# end
-
end
-
1
require 'test_helper'
-
-
1
class ConfirmationMailerTest < ActionMailer::TestCase
-
# test "the truth" do
-
# assert true
-
# end
-
end
-
1
require 'test_helper'
-
-
1
class DateExceptionsControllerTest < ActionController::TestCase
-
1
setup do
-
7
@date_exception = date_exceptions(:one)
-
end
-
-
1
test "should get index" do
-
1
get :index
-
assert_response :success
-
assert_not_nil assigns(:date_exceptions)
-
end
-
-
1
test "should get new" do
-
1
get :new
-
assert_response :success
-
end
-
-
1
test "should create date_exception" do
-
1
assert_difference('DateException.count') do
-
1
post :create, date_exception: { blackout_id: @date_exception.blackout_id, end_date: @date_exception.end_date, start_date: @date_exception.start_date }
-
end
-
-
assert_redirected_to date_exception_path(assigns(:date_exception))
-
end
-
-
1
test "should show date_exception" do
-
1
get :show, id: @date_exception
-
assert_response :success
-
end
-
-
1
test "should get edit" do
-
1
get :edit, id: @date_exception
-
assert_response :success
-
end
-
-
1
test "should update date_exception" do
-
1
put :update, id: @date_exception, date_exception: { blackout_id: @date_exception.blackout_id, end_date: @date_exception.end_date, start_date: @date_exception.start_date }
-
assert_redirected_to date_exception_path(assigns(:date_exception))
-
end
-
-
1
test "should destroy date_exception" do
-
1
assert_difference('DateException.count', -1) do
-
1
delete :destroy, id: @date_exception
-
end
-
-
assert_redirected_to date_exceptions_path
-
end
-
end
-
1
require 'test_helper'
-
-
1
class DayviewControllerTest < ActionController::TestCase
-
1
test "should get index" do
-
1
get :index
-
1
assert_response :success
-
end
-
-
end
-
1
require 'test_helper'
-
-
1
class DepartmentsControllerTest < ActionController::TestCase
-
1
setup do
-
7
@department = departments(:one)
-
end
-
-
1
test "should get index" do
-
get :index
-
assert_response :success
-
assert_not_nil assigns(:departments)
-
end
-
-
1
test "should get new" do
-
get :new
-
assert_response :success
-
end
-
-
1
test "should create department" do
-
assert_difference('Department.count') do
-
post :create, department: { name: @department.name }
-
end
-
-
assert_redirected_to department_path(assigns(:department))
-
end
-
-
1
test "should show department" do
-
get :show, id: @department
-
assert_response :success
-
end
-
-
1
test "should get edit" do
-
get :edit, id: @department
-
assert_response :success
-
end
-
-
1
test "should update department" do
-
put :update, id: @department, department: { name: @department.name }
-
assert_redirected_to department_path(assigns(:department))
-
end
-
-
1
test "should destroy department" do
-
assert_difference('Department.count', -1) do
-
delete :destroy, id: @department
-
end
-
-
assert_redirected_to departments_path
-
end
-
end
-
1
require 'test_helper'
-
-
1
class NightlyEmailMailerTest < ActionMailer::TestCase
-
# test "the truth" do
-
# assert true
-
# end
-
end
-
1
require 'test_helper'
-
-
1
class SessionsControllerTest < ActionController::TestCase
-
# test "the truth" do
-
# assert true
-
# end
-
end
-
1
require 'test_helper'
-
-
1
class SpecialStudentControllerTest < ActionController::TestCase
-
# test "the truth" do
-
# assert true
-
# end
-
end
-
1
require 'test_helper'
-
-
1
class SpecialStudentsControllerTest < ActionController::TestCase
-
1
setup do
-
7
@special_student = special_students(:one)
-
end
-
-
1
test "should get index" do
-
1
get :index
-
1
assert_response :success
-
assert_not_nil assigns(:special_students)
-
end
-
-
1
test "should get new" do
-
1
get :new
-
1
assert_response :success
-
end
-
-
1
test "should create special_student" do
-
1
assert_difference('SpecialStudent.count') do
-
1
post :create, special_student: { }
-
end
-
-
assert_redirected_to special_student_path(assigns(:special_student))
-
end
-
-
1
test "should show special_student" do
-
1
get :show, id: @special_student
-
1
assert_response :success
-
end
-
-
1
test "should get edit" do
-
1
get :edit, id: @special_student
-
1
assert_response :success
-
end
-
-
1
test "should update special_student" do
-
1
put :update, id: @special_student, special_student: { }
-
1
assert_redirected_to special_student_path(assigns(:special_student))
-
end
-
-
1
test "should destroy special_student" do
-
1
assert_difference('SpecialStudent.count', -1) do
-
1
delete :destroy, id: @special_student
-
end
-
-
assert_redirected_to special_students_path
-
end
-
end
-
1
require 'test_helper'
-
-
1
class StudentsControllerTest < ActionController::TestCase
-
1
setup do
-
7
@student = students(:one)
-
end
-
-
1
test "should get index" do
-
get :index
-
assert_response :success
-
assert_not_nil assigns(:students)
-
end
-
-
1
test "should get new" do
-
get :new
-
assert_response :success
-
end
-
-
1
test "should create student" do
-
assert_difference('Student.count') do
-
post :create, student: { advisor_id: @student.advisor_id, department_id: @student.department_id, name: @student.name }
-
end
-
-
assert_redirected_to student_path(assigns(:student))
-
end
-
-
1
test "should show student" do
-
get :show, id: @student
-
assert_response :success
-
end
-
-
1
test "should get edit" do
-
get :edit, id: @student
-
assert_response :success
-
end
-
-
1
test "should update student" do
-
put :update, id: @student, student: { advisor_id: @student.advisor_id, department_id: @student.department_id, name: @student.name }
-
assert_redirected_to student_path(assigns(:student))
-
end
-
-
1
test "should destroy student" do
-
assert_difference('Student.count', -1) do
-
delete :destroy, id: @student
-
end
-
-
assert_redirected_to students_path
-
end
-
end
-
1
require 'test_helper'
-
-
1
class UpcomingTimeBlocksControllerTest < ActionController::TestCase
-
1
setup do
-
7
@upcoming_time_block = upcoming_time_blocks(:one)
-
end
-
-
1
test "should get index" do
-
get :index
-
assert_response :success
-
assert_not_nil assigns(:upcoming_time_blocks)
-
end
-
-
1
test "should get new" do
-
get :new
-
assert_response :success
-
end
-
-
1
test "should create upcoming_time_block" do
-
assert_difference('UpcomingTimeBlock.count') do
-
post :create, upcoming_time_block: { apt_id: @upcoming_time_block.apt_id, blackout_id: @upcoming_time_block.blackout_id, start_time: @upcoming_time_block.start_time }
-
end
-
-
assert_redirected_to upcoming_time_block_path(assigns(:upcoming_time_block))
-
end
-
-
1
test "should show upcoming_time_block" do
-
get :show, id: @upcoming_time_block
-
assert_response :success
-
end
-
-
1
test "should get edit" do
-
get :edit, id: @upcoming_time_block
-
assert_response :success
-
end
-
-
1
test "should update upcoming_time_block" do
-
put :update, id: @upcoming_time_block, upcoming_time_block: { apt_id: @upcoming_time_block.apt_id, blackout_id: @upcoming_time_block.blackout_id, start_time: @upcoming_time_block.start_time }
-
assert_redirected_to upcoming_time_block_path(assigns(:upcoming_time_block))
-
end
-
-
1
test "should destroy upcoming_time_block" do
-
assert_difference('UpcomingTimeBlock.count', -1) do
-
delete :destroy, id: @upcoming_time_block
-
end
-
-
assert_redirected_to upcoming_time_blocks_path
-
end
-
end
-
1
require 'test_helper'
-
-
1
class UsersControllerTest < ActionController::TestCase
-
1
setup do
-
7
@user = users(:one)
-
end
-
-
1
test "should get index" do
-
get :index
-
assert_response :success
-
assert_not_nil assigns(:users)
-
end
-
-
1
test "should get new" do
-
get :new
-
assert_response :success
-
end
-
-
1
test "should create user" do
-
assert_difference('User.count') do
-
post :create, user: { email: @user.email, password_digest: @user.password_digest }
-
end
-
-
assert_redirected_to user_path(assigns(:user))
-
end
-
-
1
test "should show user" do
-
get :show, id: @user
-
assert_response :success
-
end
-
-
1
test "should get edit" do
-
get :edit, id: @user
-
assert_response :success
-
end
-
-
1
test "should update user" do
-
put :update, id: @user, user: { email: @user.email, password_digest: @user.password_digest }
-
assert_redirected_to user_path(assigns(:user))
-
end
-
-
1
test "should destroy user" do
-
assert_difference('User.count', -1) do
-
delete :destroy, id: @user
-
end
-
-
assert_redirected_to users_path
-
end
-
end
-
1
require 'test_helper'
-
-
1
class WeeklyRepeatedDaysControllerTest < ActionController::TestCase
-
1
setup do
-
7
@weekly_repeated_day = weekly_repeated_days(:one)
-
end
-
-
1
test "should get index" do
-
1
get :index
-
assert_response :success
-
assert_not_nil assigns(:weekly_repeated_days)
-
end
-
-
1
test "should get new" do
-
1
get :new
-
assert_response :success
-
end
-
-
1
test "should create weekly_repeated_day" do
-
1
assert_difference('WeeklyRepeatedDay.count') do
-
1
post :create, weekly_repeated_day: { blackout_id: @weekly_repeated_day.blackout_id, friday: @weekly_repeated_day.friday, monday: @weekly_repeated_day.monday, saturday: @weekly_repeated_day.saturday, sunday: @weekly_repeated_day.sunday, thursday: @weekly_repeated_day.thursday, tuesday: @weekly_repeated_day.tuesday, wednesday: @weekly_repeated_day.wednesday }
-
end
-
-
assert_redirected_to weekly_repeated_day_path(assigns(:weekly_repeated_day))
-
end
-
-
1
test "should show weekly_repeated_day" do
-
1
get :show, id: @weekly_repeated_day
-
assert_response :success
-
end
-
-
1
test "should get edit" do
-
1
get :edit, id: @weekly_repeated_day
-
assert_response :success
-
end
-
-
1
test "should update weekly_repeated_day" do
-
1
put :update, id: @weekly_repeated_day, weekly_repeated_day: { blackout_id: @weekly_repeated_day.blackout_id, friday: @weekly_repeated_day.friday, monday: @weekly_repeated_day.monday, saturday: @weekly_repeated_day.saturday, sunday: @weekly_repeated_day.sunday, thursday: @weekly_repeated_day.thursday, tuesday: @weekly_repeated_day.tuesday, wednesday: @weekly_repeated_day.wednesday }
-
assert_redirected_to weekly_repeated_day_path(assigns(:weekly_repeated_day))
-
end
-
-
1
test "should destroy weekly_repeated_day" do
-
1
assert_difference('WeeklyRepeatedDay.count', -1) do
-
1
delete :destroy, id: @weekly_repeated_day
-
end
-
-
assert_redirected_to weekly_repeated_days_path
-
end
-
end
-
1
require 'test_helper'
-
1
require 'time_helper'
-
1
class AppointmentTest < ActiveSupport::TestCase
-
1
include TimeHelper
-
1
should belong_to(:student)
-
1
should belong_to(:advisor)
-
1
should have_one(:upcoming_time_block)
-
-
1
context "an appointment" do
-
-
1
setup do
-
9
@brad_student = students(:brad)
-
9
@dave_advisor = advisors(:dave)
-
end
-
-
1
should "not have start and end before now" do
-
1
now = Time.current
-
1
start_dt = now - 14.days
-
1
end_dt = now - 14.days + 15.minutes
-
1
@past_appointment = Appointment.new(:start => start_dt,
-
:end => end_dt)
-
1
@past_appointment.student_id = @brad_student.id
-
1
@past_appointment.advisor_id = @dave_advisor.id
-
1
@past_appointment.save
-
-
1
base_err_msg = @past_appointment.errors.messages[:base][0]
-
1
assert_equal "It is too late to book that time slot now.", base_err_msg
-
end
-
-
1
should "allow appointment booking 2 weeks from now" do
-
# mysql datetime doesn't store microseconds so we want to ignore them
-
1
now = Time.current.round
-
1
start_dt = now + 14.days
-
1
end_dt = now + 14.days + 15.minutes
-
1
future_appointment = Appointment.new(:start => start_dt,
-
:end => end_dt)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
appointment = Appointment.find(future_appointment)
-
1
assert_not_equal(nil, appointment)
-
-
1
assert_equal(@brad_student.id, appointment.student_id)
-
1
assert_equal(@dave_advisor.id, appointment.advisor_id)
-
1
assert_equal(start_dt, appointment.start)
-
1
assert_equal(end_dt, appointment.end)
-
-
end
-
-
-
1
should "not allow appointment with start > end" do
-
1
now = Time.current.round
-
1
start_dt = now + 14.days
-
1
end_dt = now + 14.days + 15.minutes
-
1
future_appointment = Appointment.new(:start => end_dt,
-
:end => start_dt)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
-
1
base_err_msg = future_appointment.errors.messages[:base][0]
-
1
assert_equal "Invalid appointment time.", base_err_msg
-
end
-
-
-
1
should "not allow appointment that starts over 3 weeks from now" do
-
1
now = Time.current.round
-
1
start_dt = now + 50.days
-
1
end_dt = now + 50.days + 15.minutes
-
1
future_appointment = Appointment.new(:start => start_dt,
-
:end => end_dt)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
base_err_msg = future_appointment.errors.messages[:base][0]
-
1
end_of_time = @dave_advisor.end_of_time
-
1
error_message = "It is too early to book for that appointment time now. " +
-
"You cannot book an appointment with #{@dave_advisor.name} beyond #{end_of_time}."
-
1
assert_equal error_message, base_err_msg
-
end
-
-
1
should "not overlap another appointment with the same advisor" do
-
1
marco_student = students(:marco)
-
1
now = Time.current.round
-
1
start_dt = now + 14.days
-
1
end_dt = start_dt + 15.minutes
-
1
future_appointment = Appointment.new(:start => start_dt,
-
:end => end_dt)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
appointment = Appointment.find(future_appointment)
-
1
assert_not_equal(nil, appointment)
-
-
1
assert_equal(@brad_student.id, appointment.student_id)
-
1
assert_equal(@dave_advisor.id, appointment.advisor_id)
-
1
assert_equal(start_dt, appointment.start)
-
1
assert_equal(end_dt, appointment.end)
-
-
## Overlap 1: New appointment at exactly same time as existing appointment
-
1
future_appointment = Appointment.new(:start => start_dt,
-
:end => end_dt)
-
1
future_appointment.student_id = marco_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
base_err_msg = future_appointment.errors.messages[:base][0]
-
1
assert_equal "That appointment time is taken.", base_err_msg
-
-
## Use find_by_id as find throws RecordNotFound exception
-
1
appointment = Appointment.find_by_id(future_appointment)
-
1
assert_equal(nil, appointment)
-
-
## Overlap 2: New appointment starts before existing appointment starts and ends after existing appointment ends
-
-
1
future_appointment = Appointment.new(:start => start_dt - 1.minutes,
-
:end => end_dt + 1.minutes)
-
1
future_appointment.student_id = marco_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
-
1
base_err_msg = future_appointment.errors.messages[:base][0]
-
1
assert_equal "That appointment time is taken.", base_err_msg
-
-
## Use find_by_id as find throws RecordNotFound exception
-
1
appointment = Appointment.find_by_id(future_appointment)
-
1
assert_equal(nil, appointment)
-
-
## Overlap 3: New appointment starts before existing appointment starts and ends during existing appointment
-
-
1
future_appointment = Appointment.new(:start => start_dt - 1.minutes,
-
:end => end_dt - 1.minutes)
-
1
future_appointment.student_id = marco_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
-
1
base_err_msg = future_appointment.errors.messages[:base][0]
-
1
assert_equal "That appointment time is taken.", base_err_msg
-
-
## Use find_by_id as find throws RecordNotFound exception
-
1
appointment = Appointment.find_by_id(future_appointment)
-
1
assert_equal(nil, appointment)
-
-
## Overlap 4: New appointment starts during existing appointment and ends after existing appointment ends
-
-
1
future_appointment = Appointment.new(:start => start_dt + 1.minutes,
-
:end => end_dt + 1.minutes)
-
1
future_appointment.student_id = marco_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
-
-
1
base_err_msg = future_appointment.errors.messages[:base][0]
-
1
assert_equal "That appointment time is taken.", base_err_msg
-
-
## Use find_by_id as find throws RecordNotFound exception
-
1
appointment = Appointment.find_by_id(future_appointment)
-
1
assert_equal(nil, appointment)
-
-
## Overlap 5: New appointment starts and ends during existing appointment
-
-
1
future_appointment = Appointment.new(:start => start_dt + 1.minutes,
-
:end => end_dt - 1.minutes)
-
1
future_appointment.student_id = marco_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
-
-
1
base_err_msg = future_appointment.errors.messages[:base][0]
-
1
assert_equal "That appointment time is taken.", base_err_msg
-
-
## Use find_by_id as find throws RecordNotFound exception
-
1
appointment = Appointment.find_by_id(future_appointment)
-
1
assert_equal(nil, appointment)
-
-
end
-
-
1
should "be able to be booked consecutively" do
-
1
now = Time.current.round
-
-
1
marco_student = students(:marco)
-
1
start_dt = now + 14.days
-
1
end_dt = start_dt + 15.minutes
-
1
future_appointment = Appointment.new(:start => start_dt,
-
:end => end_dt)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
appointment = Appointment.find(future_appointment)
-
1
assert_not_equal(nil, appointment)
-
-
1
assert_equal(@brad_student.id, appointment.student_id)
-
1
assert_equal(@dave_advisor.id, appointment.advisor_id)
-
1
assert_equal(start_dt, appointment.start)
-
1
assert_equal(end_dt, appointment.end)
-
-
# After
-
1
future_appointment = Appointment.new(:start => start_dt + 15.minutes,
-
:end => end_dt + 15.minutes)
-
1
future_appointment.student_id = marco_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
-
1
appointment = Appointment.find(future_appointment)
-
1
assert_not_equal(nil, appointment)
-
-
1
assert_equal(marco_student.id, appointment.student_id)
-
1
assert_equal(@dave_advisor.id, appointment.advisor_id)
-
1
assert_equal(start_dt + 15.minutes, appointment.start)
-
1
assert_equal(end_dt + 15.minutes, appointment.end)
-
-
# Before
-
1
future_appointment = Appointment.new(:start => start_dt - 15.minutes,
-
:end => end_dt - 15.minutes)
-
1
future_appointment.student_id = marco_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
-
1
appointment = Appointment.find(future_appointment)
-
1
assert_not_equal(nil, appointment)
-
-
1
assert_equal(marco_student.id, appointment.student_id)
-
1
assert_equal(@dave_advisor.id, appointment.advisor_id)
-
1
assert_equal(start_dt - 15.minutes, appointment.start)
-
1
assert_equal(end_dt - 15.minutes, appointment.end)
-
-
end
-
-
1
should "not overlap with a blackout" do
-
1
now = Time.current.round
-
1
start_dt = now + 1.days
-
1
end_dt = now + 1.weeks + 30.minutes
-
1
blackout = Blackout.create(:advisor_id => @dave_advisor.id,
-
:frequency => "daily",
-
:name => "Test blackout",
-
:start_date => start_dt.to_date,
-
:start_time => start_dt,
-
:end_date => end_dt.to_date,
-
:end_time => end_dt)
-
## Overlap 1: New appointment at exactly same time as blackout
-
1
future_appointment = Appointment.new(:start => start_dt,
-
:end => end_dt)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
base_err_msg = future_appointment.errors.messages[:base][0]
-
1
assert_equal "That appointment time is taken.", base_err_msg
-
-
## Overlap 2: New appointment starts before blackout starts and ends after blackout ends
-
1
future_appointment = Appointment.new(:start => start_dt - 1.minute,
-
:end => end_dt + 1.minute)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
base_err_msg = future_appointment.errors.messages[:base][0]
-
1
assert_equal "That appointment time is taken.", base_err_msg
-
-
## Overlap 3: New appointment starts before blackout starts and ends during blackout
-
1
future_appointment = Appointment.new(:start => start_dt - 1.minute,
-
:end => end_dt - 1.minute)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
base_err_msg = future_appointment.errors.messages[:base][0]
-
1
assert_equal "That appointment time is taken.", base_err_msg
-
-
## Overlap 4: New appointment starts during blackout and ends after blackout ends
-
1
future_appointment = Appointment.new(:start => start_dt + 1.minute,
-
:end => end_dt + 1.minute)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
base_err_msg = future_appointment.errors.messages[:base][0]
-
1
assert_equal "That appointment time is taken.", base_err_msg
-
-
## Overlap 5: New appointment starts and ends during blackout
-
1
future_appointment = Appointment.new(:start => start_dt + 1.minute,
-
:end => end_dt - 1.minute)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
base_err_msg = future_appointment.errors.messages[:base][0]
-
1
assert_equal "That appointment time is taken.", base_err_msg
-
end
-
-
1
should "be bookable adjacent to a blackout" do
-
1
day = Date.current + 5.days
-
-
# Blackout from 16:30-17:00
-
1
blackout_start_time = day.to_time.utc.change(hour:16, min:30)
-
1
blackout_end_time = day.to_time.utc.change(hour:17, min:00)
-
1
blackout = Blackout.create(:advisor_id => @dave_advisor.id,
-
:frequency => "never",
-
:name => "Test blackout (adjacency)",
-
:start_date => day,
-
:start_time => blackout_start_time,
-
:end_date => day,
-
:end_time => blackout_end_time)
-
-
## Adjacency 1: Preceding: Appointment from 16:15-16:30
-
1
appointment_start = TimeHelper.combine_date_time(day, day.to_time.change(hour:16, min:15))
-
1
appointment_end = TimeHelper.combine_date_time(day, day.to_time.change(hour:16, min:30))
-
-
1
appointment = Appointment.new(:start => appointment_start,
-
:end => appointment_end)
-
1
appointment.student_id = @brad_student.id
-
1
appointment.advisor_id = @dave_advisor.id
-
1
appointment.save
-
-
1
preceding_appointment = Appointment.find(appointment)
-
1
assert_not_equal(nil, preceding_appointment)
-
-
1
assert_equal(@brad_student.id, preceding_appointment.student_id)
-
1
assert_equal(@dave_advisor.id, preceding_appointment.advisor_id)
-
1
assert_equal(appointment_start, preceding_appointment.start)
-
1
assert_equal(appointment_end, preceding_appointment.end)
-
-
## Adjacency 2: Following: Appointment from 17:00-17:15
-
1
appointment_start = TimeHelper.combine_date_time(day, day.to_time.change(hour:17, min:00))
-
1
appointment_end = TimeHelper.combine_date_time(day, day.to_time.change(hour:17, min:15))
-
-
1
appointment = Appointment.new(:start => appointment_start,
-
:end => appointment_end)
-
1
appointment.student_id = @brad_student.id
-
1
appointment.advisor_id = @dave_advisor.id
-
1
appointment.save
-
-
1
following_appointment = Appointment.find(appointment)
-
1
assert_not_equal(nil, following_appointment)
-
-
1
assert_equal(@brad_student.id, following_appointment.student_id)
-
1
assert_equal(@dave_advisor.id, following_appointment.advisor_id)
-
1
assert_equal(appointment_start, following_appointment.start)
-
1
assert_equal(appointment_end, following_appointment.end)
-
end
-
-
1
should "be able to be booked over a cancelled appointment" do
-
1
now = Time.current.round
-
1
start_dt = now + 14.days
-
1
end_dt = start_dt + 15.minutes
-
1
future_appointment = Appointment.new(:start => start_dt,
-
:end => end_dt)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
appointment = Appointment.find(future_appointment)
-
1
assert_not_equal(nil, appointment)
-
-
1
assert_equal(@brad_student.id, appointment.student_id)
-
1
assert_equal(@dave_advisor.id, appointment.advisor_id)
-
1
assert_equal(start_dt, appointment.start)
-
1
assert_equal(end_dt, appointment.end)
-
-
1
appointment.cancel
-
-
1
marco_student = students(:marco)
-
1
future_appointment = Appointment.new(:start => start_dt,
-
:end => end_dt)
-
1
future_appointment.student_id = marco_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
appointment = Appointment.find(future_appointment)
-
1
assert_equal(marco_student.id, appointment.student_id)
-
1
assert_equal(@dave_advisor.id, appointment.advisor_id)
-
1
assert_equal(start_dt, appointment.start)
-
1
assert_equal(end_dt, appointment.end)
-
-
1
appointment.cancel
-
## after
-
1
future_appointment = Appointment.new(:start => start_dt + 15.minutes,
-
:end => end_dt + 15.minutes)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
appointment = Appointment.find(future_appointment)
-
1
assert_not_equal(nil, appointment)
-
-
1
assert_equal(@brad_student.id, appointment.student_id)
-
1
assert_equal(@dave_advisor.id, appointment.advisor_id)
-
1
assert_equal(start_dt + 15.minutes, appointment.start)
-
1
assert_equal(end_dt + 15.minutes, appointment.end)
-
-
1
appointment.cancel
-
## before
-
1
future_appointment = Appointment.new(:start => start_dt,
-
:end => end_dt)
-
1
future_appointment.student_id = @brad_student.id
-
1
future_appointment.advisor_id = @dave_advisor.id
-
1
future_appointment.save
-
1
appointment = Appointment.find(future_appointment)
-
1
assert_not_equal(nil, appointment)
-
-
1
assert_equal(@brad_student.id, appointment.student_id)
-
1
assert_equal(@dave_advisor.id, appointment.advisor_id)
-
1
assert_equal(start_dt, appointment.start)
-
1
assert_equal(end_dt, appointment.end)
-
end
-
end
-
end
-
1
require 'test_helper'
-
1
require 'pp'
-
1
require 'time_helper'
-
-
1
class BlackoutTest < ActiveSupport::TestCase
-
1
include TimeHelper
-
1
should belong_to(:advisor)
-
1
should have_one(:weekly_repeated_day)
-
1
should have_many(:date_exceptions)
-
1
should have_many(:upcoming_time_blocks)
-
-
1
setup do
-
# @brad_student = students(:brad)
-
22
@dave_advisor = advisors(:dave)
-
end
-
-
1
context "any blackout" do
-
1
should "have a start time less than the end time" do
-
1
start_d = Date.current
-
1
end_d = Date.current
-
-
1
now_time = Time.current
-
# create blackout here.
-
1
blackout = Blackout.create(:advisor_id => @dave_advisor.id,
-
:frequency => "never",
-
:name => "Test blackout",
-
:start_date => start_d,
-
:start_time => now_time,
-
:end_date => end_d,
-
:end_time => now_time - 30.minutes)
-
1
assert_equal(false, blackout.valid?)
-
1
base_err_msg = blackout.errors.messages[:base][0]
-
1
assert_equal("Blackout start time should be before end time.", base_err_msg)
-
-
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
# def self.get_week(week_start, week_end, person, *advisor_id)
-
-
1
week_info = UpcomingTimeBlock::get_week(start_d, end_d,
-
:advisor_id => @dave_advisor.id)
-
1
assert_equal({}, week_info)
-
1
assert_equal(0, upcoming_time_blocks.count)
-
end
-
end
-
-
-
1
context "a daily blackout" do
-
-
1
should "be able to be made" do
-
1
start_d = Date.current
-
1
end_d = Date.current + 20.days
-
-
1
now_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("5:00 pm")
-
# create blackout here.
-
1
blackout = Blackout.create(:advisor_id => @dave_advisor.id,
-
:frequency => "daily",
-
:name => "Test blackout",
-
:start_date => start_d,
-
:start_time => now_time,
-
:end_date => end_d,
-
:end_time => end_time)
-
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
1
assert_equal(upcoming_time_blocks.count, 21)
-
-
1
end_time = Time.zone.local(end_d.year, end_d.month, end_d.day, 24, 0, 0)
-
1
week_info = UpcomingTimeBlock::get_week(start_d, end_time,
-
:advisor_id => @dave_advisor.id)
-
1
assert_equal(42, week_info.keys.length)
-
-
-
1
now_time = Time.zone.parse("4:30 pm")
-
# create blackout here.
-
-
-
# remove past upcoming time blocks
-
1
UpcomingTimeBlock.destroy_all
-
1
end_time = Time.zone.parse("5:00 pm")
-
1
end_t = Date.current + 15.days
-
1
blackout = Blackout.create(:advisor_id => @dave_advisor.id,
-
:frequency => "daily",
-
:name => "Test blackout",
-
:start_date => Date.current,
-
:start_time => now_time,
-
:end_date => end_t,
-
:end_time => end_time)
-
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
1
date = Date.current
-
1
upcoming_time_blocks.each do |utb|
-
16
assert_equal utb.start.to_date, date
-
-
16
assert_equal utb.start.hour, now_time.hour
-
16
assert_equal utb.start.min, now_time.min
-
16
assert_equal utb.start.sec, now_time.sec
-
-
-
16
assert_equal utb.end.hour, end_time.hour
-
16
assert_equal utb.end.min, end_time.min
-
16
assert_equal utb.end.sec, end_time.sec
-
16
date += 1.day
-
end
-
-
## TODO find out why get week end date exclusive
-
1
end_time = Time.zone.local(end_t.year, end_t.month, end_t.day, 24, 0, 0)
-
1
week_info = UpcomingTimeBlock::get_week(start_d, end_time,
-
:advisor_id => @dave_advisor.id)
-
1
assert_equal(32, week_info.keys.length)
-
-
1
assert_equal(16, upcoming_time_blocks.count)
-
end
-
-
=begin
-
TODO: review once hear from dave
-
should "not have start date before today" do
-
# use utc as we are using it in the db
-
start_time = Time.zone.parse("4:30 pm")
-
end_time = Time.zone.parse("4:45 pm")
-
-
-
## date in the past
-
date = Time.current - 1.day
-
# create blackout here.
-
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "daily",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => date + 5.days,
-
:end_time => end_time)
-
blackout.save
-
assert_equal(false, blackout.valid?)
-
base_err_msg = blackout.errors.messages[:base][0]
-
assert_equal("Invalid blackout time.", base_err_msg)
-
-
assert_equal(0, upcoming_time_blocks.count)
-
end
-
=end
-
-
1
should "not have end date before today" do
-
1
start_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("4:45 pm")
-
-
## date in the past
-
1
date = Date.current - 2.weeks
-
# create blackout here.
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "daily",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => Date.current - 1.day,
-
:end_time => end_time)
-
-
1
blackout.save
-
1
assert_equal(false, blackout.valid?)
-
1
base_err_msg = blackout.errors.messages[:base][0]
-
1
assert_equal("Blackout end datetime should not be before today", base_err_msg)
-
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
-
-
1
assert_equal(0, upcoming_time_blocks.count)
-
end
-
-
-
## CONSIDER: use a constant instead of 3 below
-
1
should "not have start date after 3 weeks" do
-
-
1
start_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("4:45 pm")
-
1
now = Time.current
-
1
date = now + 3.weeks
-
# create blackout here.
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "daily",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => date,
-
:end_time => end_time)
-
-
1
blackout.save
-
1
assert_equal(true, blackout.valid?)
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
-
1
assert_equal(0, upcoming_time_blocks.count)
-
end
-
-
-
-
1
should "have one exception" do
-
1
start_time = Time.zone.parse("1:30 am")
-
1
end_time = Time.zone.parse("1:45 am")
-
1
date = Date.current
-
# create blackout here.
-
1
end_d = date + 1.week
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "daily",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => end_d,
-
:end_time => end_time)
-
-
# blackout.build_weekly_repeated_day
-
1
blackout.date_exceptions.push(DateException.new(
-
:start_date => date + 1.day,
-
:end_date => date + 1.week - 1.day
-
))
-
-
1
blackout.save
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
-
## TODO find out why get week end date exclusive
-
1
end_time = Time.zone.local(end_d.year, end_d.month, end_d.day, 24, 0, 0)
-
1
week_info = UpcomingTimeBlock::get_week(date, end_time,
-
:advisor_id => @dave_advisor.id)
-
1
assert_equal(2, week_info.keys.length)
-
-
-
# puts "\n\n\n utb size = #{upcoming_time_blocks.count}\n\n\n"
-
1
assert_equal(2, upcoming_time_blocks.count)
-
1
assert_equal(Date.current, upcoming_time_blocks[0].start.to_date)
-
1
assert_equal(end_d, upcoming_time_blocks[1].start.to_date)
-
end
-
end
-
-
-
1
context "a weekly blackout" do
-
-
1
should "be able to be made" do
-
1
start_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("4:45 pm")
-
-
1
date = Date.current
-
1
end_d = date + 1.week
-
# create blackout here.
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "weekly",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => end_d,
-
:end_time => end_time)
-
-
1
blackout.build_weekly_repeated_day
-
-
1
set_weekly_repeated_day(blackout.weekly_repeated_day, date.wday)
-
# blackout.weekly_repeated_day.thursday = true
-
1
blackout.weekly_repeated_day.save
-
1
blackout.save
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
1
upcoming_time_blocks.each do |utb|
-
2
assert_equal(utb.start.wday, date.wday)
-
2
assert_equal(utb.end.wday, date.wday)
-
-
2
assert_equal utb.start.hour, start_time.hour
-
2
assert_equal utb.start.min, start_time.min
-
2
assert_equal utb.start.sec, start_time.sec
-
-
-
2
assert_equal utb.end.hour, end_time.hour
-
2
assert_equal utb.end.min, end_time.min
-
2
assert_equal utb.end.sec, end_time.sec
-
-
end
-
-
## TODO find out why get week end date exclusive
-
1
end_time = Time.zone.local(end_d.year, end_d.month, end_d.day, 24, 0, 0)
-
1
week_info = UpcomingTimeBlock::get_week(date, end_time,
-
:advisor_id => @dave_advisor.id)
-
-
1
assert_equal(2, week_info.keys.length)
-
1
assert_equal(2, upcoming_time_blocks.count)
-
end
-
-
=begin
-
TODO: review once hear from dave
-
should "not have start date before today" do
-
# use utc as we are using it in the db
-
start_time = Time.zone.parse("4:30 pm")
-
end_time = Time.zone.parse("4:45 pm")
-
-
## date in the past
-
date = Time.current - 1.day
-
# create blackout here.
-
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "weekly",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => date + 1.week,
-
:end_time => end_time)
-
-
blackout.build_weekly_repeated_day
-
-
set_weekly_repeated_day(blackout.weekly_repeated_day, date.wday)
-
blackout.weekly_repeated_day.save
-
blackout.save
-
assert_equal(false, blackout.valid?)
-
-
base_err_msg = blackout.errors.messages[:base][0]
-
assert_equal("Invalid blackout time.", base_err_msg)
-
assert_equal(upcoming_time_blocks.count, 0)
-
-
-
end
-
=end
-
-
-
1
should "not have end date before today" do
-
1
start_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("4:45 pm")
-
-
## date in the past
-
1
now = Time.current
-
1
date = now - 2.weeks
-
# create blackout here.
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "weekly",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => Date.current - 1.day,
-
:end_time => end_time)
-
-
1
blackout.build_weekly_repeated_day
-
-
1
set_weekly_repeated_day(blackout.weekly_repeated_day, date.wday)
-
1
blackout.weekly_repeated_day.save
-
1
blackout.save
-
1
assert_equal(false, blackout.valid?)
-
1
base_err_msg = blackout.errors.messages[:base][0]
-
1
assert_equal("Blackout end datetime should not be before today", base_err_msg)
-
-
-
1
assert_equal(upcoming_time_blocks.count, 0)
-
end
-
-
-
1
should "be able to have exceptions" do
-
1
start_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("4:45 pm")
-
1
now = Time.current
-
1
date = now.to_date
-
-
1
end_date = date + 1.weeks
-
# create blackout here.
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "weekly",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => end_date,
-
:end_time => end_time)
-
-
1
blackout.build_weekly_repeated_day
-
1
blackout.date_exceptions.push(DateException.new(
-
:start_date => date,
-
:end_date => date
-
))
-
-
1
set_weekly_repeated_day(blackout.weekly_repeated_day, date.wday)
-
1
blackout.weekly_repeated_day.save
-
1
blackout.save
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
-
1
assert_equal(1, upcoming_time_blocks.count)
-
-
-
## TODO find out why get week end date exclusive
-
1
end_t = Time.zone.local(end_date.year, end_date.month, end_date.day, 24, 0, 0)
-
1
week_info = UpcomingTimeBlock::get_week(date, end_t,
-
:advisor_id => @dave_advisor.id)
-
1
assert_equal(1, week_info.keys.length)
-
-
1
upcoming_time_blocks.each do |utb|
-
1
assert_equal(date.wday, utb.start.wday)
-
1
assert_equal(date.wday, utb.end.wday)
-
-
1
assert_not_equal(date.to_date, utb.start.to_date)
-
1
assert_equal(end_date.to_date, utb.start.to_date)
-
-
1
assert_equal start_time.hour, utb.start.hour
-
1
assert_equal start_time.min, utb.start.min
-
1
assert_equal start_time.sec, utb.start.sec
-
-
1
assert_equal end_time.hour, utb.end.hour
-
1
assert_equal end_time.min, utb.end.min
-
1
assert_equal end_time.sec, utb.end.sec
-
end
-
end
-
-
## CONSIDER: use a constant instead of 3 below
-
1
should "not have start date after 3 weeks" do
-
1
start_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("4:45 pm")
-
1
now = Time.current
-
1
date = now + 3.weeks
-
# create blackout here.
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "weekly",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => date,
-
:end_time => end_time)
-
1
blackout.build_weekly_repeated_day
-
-
1
blackout.weekly_repeated_day.sunday = true
-
1
blackout.weekly_repeated_day.monday = true
-
1
blackout.weekly_repeated_day.tuesday = true
-
1
blackout.weekly_repeated_day.wednesday = true
-
1
blackout.weekly_repeated_day.thursday = true
-
1
blackout.weekly_repeated_day.friday = true
-
1
blackout.weekly_repeated_day.saturday = true
-
1
blackout.weekly_repeated_day.save
-
-
1
blackout.save
-
1
assert_equal(true, blackout.valid?)
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
-
1
assert_equal(0, upcoming_time_blocks.count)
-
end
-
-
1
should "not overlap with appointments" do
-
1
@dave_long_advisor = advisors(:dave_long) # end_of_time = Date.current + 4.weeks
-
1
start_time = Time.zone.parse("12:15 pm") + 1.day
-
1
end_time = Time.zone.parse("12:30 pm") + 1.day
-
1
brad_student = students(:brad)
-
1
app1 = Appointment.new(:start => start_time,
-
:end => end_time)
-
1
app1.student_id = brad_student.id
-
1
app1.advisor_id = @dave_long_advisor.id
-
1
app1.save
-
-
# app2 to test beyond 3 weeks to ensure is_open_for_blackout? looks for
-
# conflicts through end_of_time (and not just for a 3 week window, as
-
# was done in the old system)
-
1
start_time = Time.zone.parse("12:15 pm") + 3.weeks + 1.day
-
1
end_time = Time.zone.parse("12:30 pm") + 3.weeks + 1.day
-
1
brad_student = students(:brad)
-
1
app2 = Appointment.new(:start => start_time,
-
:end => end_time)
-
1
app2.student_id = brad_student.id
-
1
app2.advisor_id = @dave_long_advisor.id
-
1
app2.save
-
1
start_time = Time.zone.parse("11:30 am")
-
1
end_time = Time.zone.parse("12:30 pm")
-
1
start_date = Date.current
-
1
end_date = Date.current + 3.weeks + 1.day
-
-
1
blackout = Blackout.new(:advisor_id => @dave_long_advisor.id,
-
:frequency => "weekly",
-
:name => "Test blackout",
-
:start_date => start_date,
-
:start_time => start_time,
-
:end_date => end_date,
-
:end_time => end_time)
-
1
blackout.build_weekly_repeated_day
-
1
blackout.weekly_repeated_day.send("#{app1.start.strftime("%A").downcase}=", true)
-
1
blackout.save
-
1
assert_equal(false, blackout.valid?)
-
1
base_err_msg = blackout.errors.messages[:base][0]
-
1
assert_equal("There were conflicts.", base_err_msg)
-
1
assert_equal(2, UpcomingTimeBlock.open_for_blackout?(blackout).count)
-
end
-
end
-
-
1
context "a never blackout" do
-
1
should "be able to be made" do
-
1
start_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("4:45 pm")
-
1
date = Date.current
-
# create blackout here.
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "never",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => date,
-
:end_time => end_time)
-
-
1
blackout.save
-
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
-
## TODO find out why get week end date exclusive
-
1
end_time = Time.zone.local(end_time.year, end_time.month, end_time.day, 24, 0, 0)
-
1
week_info = UpcomingTimeBlock::get_week(date, end_time,
-
:advisor_id => @dave_advisor.id)
-
1
assert_equal(1, week_info.keys.length)
-
-
1
assert_equal(date, upcoming_time_blocks.first.start.to_date)
-
1
assert_equal(1, upcoming_time_blocks.count)
-
end
-
-
1
should "not be able to be made before today" do
-
1
start_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("4:45 pm")
-
-
## date in the past
-
1
date = Date.current - 1.day
-
# create blackout here.
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "never",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => date,
-
:end_time => end_time)
-
1
blackout.save
-
1
assert_equal(false, blackout.valid?)
-
1
base_err_msg = blackout.errors.messages[:base][0]
-
1
assert_equal("Blackout end datetime should not be before today", base_err_msg)
-
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
# assert_equal(date, upcoming_time_blocks.first.start.to_date)
-
-
1
assert_equal(0, upcoming_time_blocks.count)
-
end
-
-
1
should "not be able to be made after three weeks" do
-
1
start_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("4:45 pm")
-
-
1
date = Date.current + 3.weeks + 1.day
-
# create blackout here.
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "never",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => date,
-
:end_time => end_time)
-
-
1
blackout.save
-
1
assert_equal(true, blackout.valid?)
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
-
1
assert_equal(0, upcoming_time_blocks.count)
-
end
-
-
# regression test: bug found by Dave on 10/25/13
-
1
should "not create blackout over appointments" do
-
-
1
start_time = Time.zone.parse("2:00 pm") + 1.day
-
1
end_time = Time.zone.parse("2:15 pm") + 1.day
-
-
1
@brad_student = students(:brad)
-
1
@dave_advisor = advisors(:dave)
-
-
1
@app1 = Appointment.new(:start => start_time,
-
:end => end_time)
-
1
@app1.student_id = @brad_student.id
-
1
@app1.advisor_id = @dave_advisor.id
-
1
@app1.save
-
-
1
@app2 = Appointment.new(:start => start_time + 30.minutes,
-
:end => end_time + 30.minutes)
-
1
@app2.student_id = @brad_student.id
-
1
@app2.advisor_id = @dave_advisor.id
-
1
@app2.save
-
-
1
@app3 = Appointment.new(:start => start_time + 60.minutes,
-
:end => end_time + 60.minutes)
-
1
@app3.student_id = @brad_student.id
-
1
@app3.advisor_id = @dave_advisor.id
-
1
@app3.save
-
-
1
@app4 = Appointment.new(:start => start_time + 75.minutes,
-
:end => end_time + 75.minutes)
-
1
@app4.student_id = @brad_student.id
-
1
@app4.advisor_id = @dave_advisor.id
-
1
@app4.save
-
-
-
1
start_time = Time.zone.parse("2:15 pm") + 1.day
-
1
end_time = Time.zone.parse("3:15 pm") + 1.day
-
-
1
date = start_time.to_date
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "never",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => date,
-
:end_time => end_time)
-
-
1
blackout.save
-
1
assert_equal(false, blackout.valid?)
-
1
base_err_msg = blackout.errors.messages[:base][0]
-
1
assert_equal("There were conflicts.", base_err_msg)
-
1
assert_equal(2, UpcomingTimeBlock.open_for_blackout?(blackout).count)
-
end
-
end
-
-
1
context "a monthly blackout" do
-
-
1
should "be able to be made" do
-
1
start_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("4:45 pm")
-
-
1
date = Date.current + 2.days
-
1
end_date = date + 6.weeks
-
# create blackout here.
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "monthly",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => end_date,
-
:end_time => end_time)
-
1
blackout.save
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
## TODO find out why get week end date exclusive
-
1
end_time = Time.zone.local(end_date.year, end_date.month, end_date.day, 24, 0, 0)
-
1
week_info = UpcomingTimeBlock::get_week(date, end_time,
-
:advisor_id => @dave_advisor.id)
-
1
assert_equal(1, week_info.keys.length)
-
-
1
assert_equal(date, upcoming_time_blocks.first.start.to_date)
-
1
assert_equal(1, upcoming_time_blocks.count)
-
end
-
-
1
should "be able to be made over a long time" do
-
1
@dave_advisor.set_weeks_in_advance 10
-
1
start_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("4:45 pm")
-
1
date = Date.current + 1.day
-
1
end_date = date + 10.weeks
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "monthly",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => end_date,
-
:end_time => end_time)
-
1
blackout.save
-
1
assert_equal(3, blackout.upcoming_time_blocks.count)
-
end
-
-
=begin
-
TODO: review this unit test after dave gets back to us.
-
should "not be able to be made before today" do
-
# use utc as we are using it in the db
-
start_time = Time.zone.parse("4:30 pm")
-
end_time = Time.zone.parse("4:45 pm")
-
-
date = Date.current - 10.days
-
# create blackout here.
-
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "monthly",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => Date.current + 1.days,
-
:end_time => end_time)
-
blackout.save
-
assert_equal(false, blackout.valid?)
-
base_err_msg = blackout.errors.messages[:base][0]
-
assert_equal("Invalid blackout time.", base_err_msg)
-
-
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
-
assert_equal(0, upcoming_time_blocks.count)
-
end
-
=end
-
-
1
should "not overlap with appointments" do
-
# @dave_advisor = advisors(:dave)
-
1
@dave_advisor.set_weeks_in_advance 10
-
1
start_time = Time.zone.parse("12:15 pm") + 1.day
-
1
end_time = Time.zone.parse("12:30 pm") + 1.day
-
1
brad_student = students(:brad)
-
1
app1 = Appointment.new(:start => start_time,
-
:end => end_time)
-
1
app1.student_id = brad_student.id
-
1
app1.advisor_id = @dave_advisor.id
-
1
app1.save
-
-
# app2 to test beyond 3 weeks to ensure is_open_for_blackout? looks for
-
# conflicts through end_of_time (and not just for a 3 week window, as
-
# was done in the old system)
-
1
start_time = Time.zone.parse("12:15 pm") + 1.month + 1.day
-
1
end_time = Time.zone.parse("12:30 pm") + 1.month + 1.day
-
1
brad_student = students(:brad)
-
1
app2 = Appointment.new(:start => start_time,
-
:end => end_time)
-
1
app2.student_id = brad_student.id
-
1
app2.advisor_id = @dave_advisor.id
-
1
app2.save
-
-
# app3 should not conflict with this blackout
-
1
start_time = Time.zone.parse("12:15 pm") + 1.month
-
1
end_time = Time.zone.parse("12:30 pm") + 1.month
-
1
brad_student = students(:brad)
-
1
app3 = Appointment.new(:start => start_time,
-
:end => end_time)
-
1
app3.student_id = brad_student.id
-
1
app3.advisor_id = @dave_advisor.id
-
1
app3.save
-
1
start_time = Time.zone.parse("11:30 am")
-
1
end_time = Time.zone.parse("12:30 pm")
-
1
start_date = Date.current + 1.day
-
1
end_date = Date.current + 2.months
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "monthly",
-
:name => "Test blackout",
-
:start_date => start_date,
-
:start_time => start_time,
-
:end_date => end_date,
-
:end_time => end_time)
-
1
blackout.save
-
1
assert_equal(false, blackout.valid?)
-
1
base_err_msg = blackout.errors.messages[:base][0]
-
1
assert_equal("There were conflicts.", base_err_msg)
-
1
assert_equal(2, UpcomingTimeBlock.open_for_blackout?(blackout).count)
-
end
-
-
1
should "not create a UTB if starting after end_of_time" do
-
1
start_time = Time.zone.parse("4:30 pm")
-
1
end_time = Time.zone.parse("4:45 pm")
-
-
-
1
date = Date.current + 3.weeks + 1.day
-
# create blackout here.
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "monthly",
-
:name => "Test blackout",
-
:start_date => date,
-
:start_time => start_time,
-
:end_date => date,
-
:end_time => end_time)
-
1
blackout.save
-
1
assert_equal(true, blackout.valid?)
-
1
upcoming_time_blocks = UpcomingTimeBlock.find_all_by_blackout_id(blackout)
-
-
1
assert_equal(0, upcoming_time_blocks.count)
-
end
-
-
-
end
-
-
-
## Helper function to set a weekly_repeated_day based on the wday
-
1
def set_weekly_repeated_day(weekly_repeated_day, wday)
-
3
if wday == 0
-
weekly_repeated_day.sunday = true
-
3
elsif wday == 1
-
3
weekly_repeated_day.monday = true
-
elsif wday == 2
-
weekly_repeated_day.tuesday = true
-
elsif wday == 3
-
weekly_repeated_day.wednesday = true
-
elsif wday == 4
-
weekly_repeated_day.thursday = true
-
elsif wday == 5
-
weekly_repeated_day.friday = true
-
elsif wday == 6
-
weekly_repeated_day.saturday = true
-
end
-
end
-
end
-
1
require 'test_helper'
-
-
1
class DateExceptionTest < ActiveSupport::TestCase
-
1
should belong_to :blackout
-
-
1
setup do
-
3
@brad_student = students(:brad)
-
3
@dave_advisor = advisors(:dave)
-
end
-
-
1
context "a date exception" do
-
1
context "when start_date > end_date" do
-
1
should "raise an error" do
-
1
de = DateException.create start_date: Date.tomorrow, end_date: Date.today
-
1
base_err_msg = de.errors.messages[:base][0]
-
1
assert_equal("Date exception start dates should be before end dates.", base_err_msg)
-
end
-
end
-
1
context "when removed" do
-
1
should "warn user of conflicts with appointments" do
-
1
start_time = Time.zone.parse("12:15 pm") + 1.day
-
1
end_time = Time.zone.parse("12:30 pm") + 1.day
-
1
app1 = Appointment.new(:start => start_time,
-
:end => end_time)
-
1
app1.student_id = @brad_student.id
-
1
app1.advisor_id = @dave_advisor.id
-
1
app1.save
-
1
start_time = Time.zone.parse("11:30 am")
-
1
end_time = Time.zone.parse("12:30 pm")
-
1
start_date = Date.current
-
1
end_date = Date.today + 1.week
-
1
blackout = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "daily",
-
:name => "Test blackout",
-
:start_date => start_date,
-
:start_time => start_time,
-
:end_date => end_date,
-
:end_time => end_time)
-
1
blackout.date_exceptions.push(DateException.new(
-
:start_date => Date.current + 1.day,
-
:end_date => Date.current + 1.day
-
))
-
1
blackout.save
-
1
assert_equal(true, blackout.valid?)
-
1
blackout.date_exceptions.first.mark_for_destruction
-
1
blackout.save
-
1
assert_equal(false, blackout.valid?)
-
1
base_err_msg = blackout.errors.messages[:base][0]
-
1
assert_equal("There were conflicts.", base_err_msg)
-
1
assert_equal(1, UpcomingTimeBlock.open_for_blackout?(blackout).count)
-
1
week_info = UpcomingTimeBlock::get_week(start_date.beginning_of_week, start_date.end_of_week,
-
:advisor_id => @dave_advisor.id)
-
1
assert_not_nil(week_info) # before marked_for_destruction fix, NoMethodError raised in get_week
-
end
-
end
-
end
-
end
-
1
require 'test_helper'
-
-
1
class DepartmentTest < ActiveSupport::TestCase
-
1
should have_many :students
-
1
should have_many :advisors
-
end
-
1
require 'test_helper'
-
-
1
class AdvisorsHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class AppointmentsHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class BlackoutsHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class CalendarsHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class CalendersHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class DateExceptionsHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class DayviewHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class DepartmentsHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class SessionsHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class SpecialStudentHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class SpecialStudentsHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class StudentsHelperTest < ActionView::TestCase
-
#test "name not nil" do
-
-
#end
-
end
-
-
1
require 'test_helper'
-
-
1
class UpcomingTimeBlocksHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class UsersHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class WeeklyRepeatedDaysHelperTest < ActionView::TestCase
-
end
-
1
require 'test_helper'
-
-
1
class SpecialStudentTest < ActiveSupport::TestCase
-
1
should belong_to :student
-
end
-
1
require 'test_helper'
-
-
1
class StudentTest < ActiveSupport::TestCase
-
1
should belong_to :advisor
-
1
should belong_to :department
-
1
should have_many :appointments
-
1
should have_many :upcoming_time_blocks
-
1
should have_one :user
-
end
-
1
require 'test_helper'
-
1
require 'time_shifter'
-
-
1
class TimeShifterTest < ActiveSupport::TestCase
-
1
include TimeShifter
-
-
1
def upcoming_time_blocks_eql(b, start_time, end_time)
-
b.upcoming_time_blocks.each do |utb|
-
assert_equal start_time, utb.start
-
assert_equal end_time, utb.end
-
end
-
end
-
-
1
def setup_appointments(direction)
-
2
if direction == :forward
-
1
offset = 15.minutes
-
elsif direction == :backward
-
1
offset = -15.minutes
-
else
-
raise ArgumentError, "direction must be :forward or :backward"
-
end
-
2
@appointment1 = Appointment.new(:start => @start_dt,
-
:end => @end_dt)
-
2
@appointment1.student_id = @brad_student.id
-
2
@appointment1.advisor_id = @dave_advisor.id
-
2
@appointment1.save validate: false
-
-
2
@appointment2 = Appointment.new(:start => @start_dt + offset,
-
:end => @end_dt + offset)
-
2
@appointment2.student_id = @brad_student.id
-
2
@appointment2.advisor_id = @dave_advisor.id
-
2
@appointment2.save validate: false
-
-
# now creating appointment during edt
-
# Timecop.travel Date.parse("29/6/2014")
-
2
@appointment_edt = Appointment.new(:start => @start_dt_edt,
-
:end => @end_dt_edt)
-
2
@appointment_edt.student_id = @brad_student.id
-
2
@appointment_edt.advisor_id = @dave_advisor.id
-
2
@appointment_edt.save validate: false
-
end
-
-
1
def setup_blackouts(direction)
-
2
if direction == :forward
-
1
offset = 15.minutes
-
elsif direction == :backward
-
1
offset = -15.minutes
-
else
-
raise ArgumentError, "direction must be :forward or :backward"
-
end
-
2
Timecop.travel @current_date
-
# need to update end_of_time so utb for blackout is created
-
2
@dave_advisor.update_column :end_of_time, @current_date + 5.days
-
-
2
@blackout1 = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "never",
-
:name => "Test blackout 1",
-
:start_date => @current_date,
-
:start_time => @start_dt,
-
:end_date => @current_date,
-
:end_time => @end_dt)
-
2
@blackout1.save validate: false
-
-
2
@blackout2 = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "never",
-
:name => "Test blackout 2",
-
:start_date => @current_date,
-
:start_time => @start_dt + offset,
-
:end_date => @current_date,
-
:end_time => @end_dt + offset)
-
2
@blackout2.save validate: false
-
-
2
Timecop.travel @current_date_edt
-
2
@dave_advisor.update_column :end_of_time, @current_date_edt + 5.days
-
-
2
@blackout_edt = Blackout.new(:advisor_id => @dave_advisor.id,
-
:frequency => "daily",
-
:name => "Test blackout edt",
-
:start_date => @current_date_edt,
-
:start_time => @start_dt_edt,
-
:end_date => @current_date_edt + 1.day,
-
:end_time => @end_dt_edt)
-
2
@blackout_edt.save validate: false
-
end
-
-
1
def verify_appointments(direction)
-
2
if direction == :forward
-
1
offset = 15.minutes
-
1
est_offset = 5.hours
-
1
edt_offset = 4.hours
-
elsif direction == :backward
-
1
offset = -15.minutes
-
1
est_offset = -5.hours
-
1
edt_offset = -4.hours
-
else
-
raise ArgumentError, "direction must be :forward or :backward"
-
end
-
2
appointment = Appointment.find @appointment1.id
-
2
assert_equal(@start_dt + est_offset, appointment.start)
-
2
assert_equal(@end_dt + est_offset, appointment.end)
-
2
assert_equal(@start_dt + est_offset, appointment.upcoming_time_block.start)
-
2
assert_equal(@end_dt + est_offset, appointment.upcoming_time_block.end)
-
-
2
appointment = Appointment.find @appointment2.id
-
2
assert_equal(@start_dt + est_offset + offset, appointment.start)
-
2
assert_equal(@end_dt + est_offset + offset, appointment.end)
-
2
assert_equal(@start_dt + est_offset + offset, appointment.upcoming_time_block.start)
-
2
assert_equal(@end_dt + est_offset + offset, appointment.upcoming_time_block.end)
-
-
2
appointment = Appointment.find @appointment_edt.id
-
2
assert_equal(@start_dt_edt + edt_offset, appointment.start)
-
2
assert_equal(@end_dt_edt + edt_offset, appointment.end)
-
2
assert_equal(@start_dt_edt + edt_offset, appointment.upcoming_time_block.start)
-
2
assert_equal(@end_dt_edt + edt_offset, appointment.upcoming_time_block.end)
-
end
-
-
1
def verify_blackouts(direction)
-
2
if direction == :forward
-
1
offset = 15.minutes
-
1
est_offset = 5.hours
-
1
edt_offset = 4.hours
-
elsif direction == :backward
-
1
offset = -15.minutes
-
1
est_offset = -5.hours
-
1
edt_offset = -4.hours
-
else
-
raise ArgumentError, "direction must be :forward or :backward"
-
end
-
# Blackout start_time and end_time will always be recorded in utc,
-
# so these values should not be shifted.
-
2
blackout = Blackout.find @blackout1.id
-
2
diff = TimeHelper.difference(@start_dt.to_time, blackout.start_time)
-
2
assert_equal(0, diff)
-
2
diff = TimeHelper.difference(@end_dt.to_time, blackout.end_time)
-
2
assert_equal(0, diff)
-
2
start_dt = TimeHelper.combine_date_time(@current_date, @start_dt)
-
2
end_dt = TimeHelper.combine_date_time(@current_date, @end_dt)
-
2
assert_equal(1, blackout.upcoming_time_blocks.count)
-
2
utb = blackout.upcoming_time_blocks.first
-
2
assert_equal(start_dt + est_offset, utb.start)
-
2
assert_equal(end_dt + est_offset, utb.end)
-
-
2
blackout = Blackout.find @blackout2.id
-
2
diff = TimeHelper.difference((@start_dt + offset).to_time, blackout.start_time)
-
2
assert_equal(0, diff)
-
2
diff = TimeHelper.difference((@end_dt + offset).to_time, blackout.end_time)
-
2
assert_equal(0, diff)
-
2
assert_equal(1, blackout.upcoming_time_blocks.count)
-
2
utb = blackout.upcoming_time_blocks.first
-
2
assert_equal(start_dt + est_offset + offset, utb.start)
-
2
assert_equal(end_dt + est_offset + offset, utb.end)
-
-
2
blackout = Blackout.find @blackout_edt.id
-
2
diff = TimeHelper.difference(@start_dt_edt.to_time, blackout.start_time)
-
2
assert_equal(0, diff)
-
2
diff = TimeHelper.difference(@end_dt_edt.to_time, blackout.end_time)
-
2
assert_equal(0, diff)
-
2
start_dt = TimeHelper.combine_date_time(@current_date_edt, @start_dt_edt)
-
2
end_dt = TimeHelper.combine_date_time(@current_date_edt, @end_dt_edt)
-
2
assert_equal(2, blackout.upcoming_time_blocks.count)
-
2
utb = blackout.upcoming_time_blocks.first
-
2
assert_equal(start_dt + edt_offset, utb.start)
-
2
assert_equal(end_dt + edt_offset, utb.end)
-
2
utb = blackout.upcoming_time_blocks.last
-
2
assert_equal(end_dt + edt_offset + 1.day, utb.end)
-
2
assert_equal(end_dt + edt_offset + 1.day, utb.end)
-
end
-
-
1
context "after shifting times" do
-
1
setup do
-
4
@brad_student = students(:brad)
-
4
@dave_advisor = advisors(:dave)
-
4
@start_dt = Time.zone.parse "31/1/2014 13:30"
-
4
@end_dt = Time.zone.parse "31/1/2014 13:45"
-
4
@start_dt_edt = Time.zone.parse "30/6/2014 13:30"
-
4
@end_dt_edt = Time.zone.parse "30/6/2014 13:45"
-
4
@current_date = Date.parse("30/1/2014")
-
4
@current_date_edt = Date.parse("29/6/2014")
-
end
-
-
1
context "forward" do
-
1
context "appointments" do
-
1
setup do
-
1
setup_appointments :forward
-
1
TimeShifter.shift_times :forward
-
end
-
-
1
should "stay the same time, but in et" do
-
1
verify_appointments :forward
-
end
-
end
-
-
1
context "blackouts" do
-
1
setup do
-
1
setup_blackouts :forward
-
1
TimeShifter.shift_times :forward
-
end
-
-
1
teardown do
-
1
Timecop.return
-
end
-
-
1
should "stay the same time, but in et" do
-
1
verify_blackouts :forward
-
end
-
end
-
-
end
-
-
1
context "backward" do
-
1
context "appointments" do
-
1
setup do
-
1
setup_appointments :backward
-
1
TimeShifter.shift_times :backward
-
end
-
-
1
should "stay the same time, but in utc" do
-
1
verify_appointments :backward
-
end
-
end
-
-
1
context "blackouts" do
-
1
setup do
-
1
setup_blackouts :backward
-
1
TimeShifter.shift_times :backward
-
end
-
-
1
teardown do
-
1
Timecop.return
-
end
-
-
1
should "stay the same time, but in utc" do
-
1
verify_blackouts :backward
-
end
-
end
-
end
-
end
-
end
-
1
require 'test_helper'
-
-
1
class UpcomingTimeBlockTest < ActiveSupport::TestCase
-
1
should belong_to :advisor
-
1
should belong_to :appointment
-
1
should belong_to :blackout
-
1
should belong_to :student
-
-
1
setup do
-
# @brad_student = students(:brad)
-
8
@dave_advisor = advisors(:dave)
-
end
-
-
1
context "when calling add_future_utbs, upcoming time blocks" do
-
1
should "be created for never blackouts for the new day" do
-
1
now = Time.current
-
1
date_start = Date.current + @dave_advisor.weeks_in_advance.weeks + 1.day
-
1
date_end = date_start
-
1
time_start = now + (15 - (now.min % 15)).minute
-
1
time_end = time_start + 15.minute
-
-
1
blackout = Blackout.create(:advisor_id => @dave_advisor.id,
-
:frequency => "never",
-
:name => "Test blackout",
-
:start_date => date_start,
-
:start_time => time_start,
-
:end_date => date_end,
-
:end_time => time_end)
-
-
1
assert_equal(true, blackout.valid?)
-
1
num_blocks_before = UpcomingTimeBlock.find_all_by_blackout_id(blackout).length
-
1
assert_equal(Date.current + 3.weeks, @dave_advisor.end_of_time)
-
-
# create upcoming time blocks for one more day
-
1
Timecop.travel(Date.tomorrow)
-
1
Blackout.add_future_utbs
-
1
Timecop.return
-
-
1
num_blocks_after = UpcomingTimeBlock.find_all_by_blackout_id(blackout).length
-
1
assert_equal(num_blocks_before + 1, num_blocks_after)
-
1
assert_equal(Date.current + 3.weeks + 1.day, @dave_advisor.reload.end_of_time)
-
-
end
-
-
1
should "be created for daily blackouts for the new day" do
-
1
now = Time.current
-
1
date_start = Date.today
-
1
date_end = Date.today + 1.month # repeated for longer than period of upcoming time blocks
-
1
time_start = now + (15 - (now.min % 15)).minute
-
1
time_end = time_start + 15.minute
-
-
1
blackout = Blackout.create(:advisor_id => @dave_advisor.id,
-
:frequency => "daily",
-
:name => "Test blackout",
-
:start_date => date_start,
-
:start_time => time_start,
-
:end_date => date_end,
-
:end_time => time_end)
-
-
1
assert_equal(true, blackout.valid?)
-
-
1
num_blocks_before = UpcomingTimeBlock.find_all_by_blackout_id(blackout).length
-
1
assert_equal(Date.current + 3.weeks, @dave_advisor.end_of_time)
-
-
# create upcoming time blocks for one more day
-
1
Timecop.travel(Date.tomorrow)
-
1
Blackout.add_future_utbs
-
1
Timecop.return
-
-
1
num_blocks_after = UpcomingTimeBlock.find_all_by_blackout_id(blackout).length
-
1
assert_equal(num_blocks_before + 1, num_blocks_after)
-
1
assert_equal(Date.current + 3.weeks + 1.day, @dave_advisor.reload.end_of_time)
-
end
-
-
1
should "be created for daily blackouts for 3 additional days" do
-
1
now = Time.current
-
1
date_start = Date.today
-
1
date_end = Date.today + 1.month # repeated for longer than period of upcoming time blocks
-
1
time_start = now + (15 - (now.min % 15)).minute
-
1
time_end = time_start + 15.minute
-
-
1
blackout = Blackout.create(:advisor_id => @dave_advisor.id,
-
:frequency => "daily",
-
:name => "Test blackout",
-
:start_date => date_start,
-
:start_time => time_start,
-
:end_date => date_end,
-
:end_time => time_end)
-
-
1
assert_equal(true, blackout.valid?)
-
-
1
num_blocks_before = UpcomingTimeBlock.find_all_by_blackout_id(blackout).length
-
1
assert_equal(Date.current + 3.weeks, @dave_advisor.end_of_time)
-
-
# create upcoming time blocks for one more day
-
1
Timecop.travel(Date.current + 3.days)
-
1
Blackout.add_future_utbs
-
1
Timecop.return
-
-
1
num_blocks_after = UpcomingTimeBlock.find_all_by_blackout_id(blackout).length
-
1
assert_equal(num_blocks_before + 3, num_blocks_after)
-
1
assert_equal(Date.current + 3.weeks + 3.day, @dave_advisor.reload.end_of_time)
-
end
-
-
1
should "not be created for a cancelled daily blackout" do
-
1
now = Time.current
-
1
date_start = Date.today
-
1
date_end = Date.today + 1.month # repeated for longer than period of upcoming time blocks
-
1
time_start = now + (15 - (now.min % 15)).minute
-
1
time_end = time_start + 15.minute
-
-
1
blackout = Blackout.create(:advisor_id => @dave_advisor.id,
-
:frequency => "daily",
-
:name => "Test blackout",
-
:start_date => date_start,
-
:start_time => time_start,
-
:end_date => date_end,
-
:end_time => time_end)
-
-
1
assert_equal(true, blackout.valid?)
-
-
1
num_blocks_before = UpcomingTimeBlock.find_all_by_blackout_id(blackout).length
-
1
assert_equal(Date.current + 3.weeks, @dave_advisor.end_of_time)
-
-
1
blackout.cancel
-
# no upcoming time blocks should be created since it's cancelled
-
1
Timecop.travel(Date.current + 3.days)
-
1
Blackout.add_future_utbs
-
1
Timecop.return
-
-
1
num_blocks_after = UpcomingTimeBlock.find_all_by_blackout_id(blackout).length
-
1
assert_equal(num_blocks_before, num_blocks_after)
-
1
assert_equal(Date.current + 3.weeks + 3.day, @dave_advisor.reload.end_of_time)
-
end
-
end
-
end
-
1
require 'test_helper'
-
-
1
class UserTest < ActiveSupport::TestCase
-
1
should belong_to :advisor
-
1
should belong_to :student
-
end
-
1
require 'test_helper'
-
-
1
class WeeklyRepeatedDayTest < ActiveSupport::TestCase
-
1
should belong_to :blackout
-
end
-
#--
-
# Copyright (c) 2004-2011 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
actionpack_path = File.expand_path('../../../actionpack/lib', __FILE__)
-
2
$:.unshift(actionpack_path) if File.directory?(actionpack_path) && !$:.include?(actionpack_path)
-
-
2
require 'abstract_controller'
-
2
require 'action_view'
-
2
require 'action_mailer/version'
-
-
# Common Active Support usage in Action Mailer
-
2
require 'active_support/core_ext/class'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/array/uniq_by'
-
2
require 'active_support/core_ext/module/attr_internal'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/lazy_load_hooks'
-
-
2
module ActionMailer
-
2
extend ::ActiveSupport::Autoload
-
-
2
autoload :Collector
-
2
autoload :Base
-
2
autoload :DeliveryMethods
-
2
autoload :MailHelper
-
2
autoload :TestCase
-
2
autoload :TestHelper
-
end
-
2
require 'mail'
-
2
require 'action_mailer/collector'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/proc'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'action_mailer/log_subscriber'
-
-
2
module ActionMailer #:nodoc:
-
# Action Mailer allows you to send email from your application using a mailer model and views.
-
#
-
# = Mailer Models
-
#
-
# To use Action Mailer, you need to create a mailer model.
-
#
-
# $ rails generate mailer Notifier
-
#
-
# The generated model inherits from <tt>ActionMailer::Base</tt>. Emails are defined by creating methods
-
# within the model which are then used to set variables to be used in the mail template, to
-
# change options on the mail, or to add attachments.
-
#
-
# Examples:
-
#
-
# class Notifier < ActionMailer::Base
-
# default :from => 'no-reply@example.com',
-
# :return_path => 'system@example.com'
-
#
-
# def welcome(recipient)
-
# @account = recipient
-
# mail(:to => recipient.email_address_with_name,
-
# :bcc => ["bcc@example.com", "Order Watcher <watcher@example.com>"])
-
# end
-
# end
-
#
-
# Within the mailer method, you have access to the following methods:
-
#
-
# * <tt>attachments[]=</tt> - Allows you to add attachments to your email in an intuitive
-
# manner; <tt>attachments['filename.png'] = File.read('path/to/filename.png')</tt>
-
#
-
# * <tt>attachments.inline[]=</tt> - Allows you to add an inline attachment to your email
-
# in the same manner as <tt>attachments[]=</tt>
-
#
-
# * <tt>headers[]=</tt> - Allows you to specify any header field in your email such
-
# as <tt>headers['X-No-Spam'] = 'True'</tt>. Note, while most fields like <tt>To:</tt>
-
# <tt>From:</tt> can only appear once in an email header, other fields like <tt>X-Anything</tt>
-
# can appear multiple times. If you want to change a field that can appear multiple times,
-
# you need to set it to nil first so that Mail knows you are replacing it and not adding
-
# another field of the same name.
-
#
-
# * <tt>headers(hash)</tt> - Allows you to specify multiple headers in your email such
-
# as <tt>headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234@message.id'})</tt>
-
#
-
# * <tt>mail</tt> - Allows you to specify email to be sent.
-
#
-
# The hash passed to the mail method allows you to specify any header that a Mail::Message
-
# will accept (any valid Email header including optional fields).
-
#
-
# The mail method, if not passed a block, will inspect your views and send all the views with
-
# the same name as the method, so the above action would send the +welcome.text.erb+ view
-
# file as well as the +welcome.text.html.erb+ view file in a +multipart/alternative+ email.
-
#
-
# If you want to explicitly render only certain templates, pass a block:
-
#
-
# mail(:to => user.email) do |format|
-
# format.text
-
# format.html
-
# end
-
#
-
# The block syntax is also useful in providing information specific to a part:
-
#
-
# mail(:to => user.email) do |format|
-
# format.text(:content_transfer_encoding => "base64")
-
# format.html
-
# end
-
#
-
# Or even to render a special view:
-
#
-
# mail(:to => user.email) do |format|
-
# format.text
-
# format.html { render "some_other_template" }
-
# end
-
#
-
# = Mailer views
-
#
-
# Like Action Controller, each mailer class has a corresponding view directory in which each
-
# method of the class looks for a template with its name.
-
#
-
# To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same
-
# name as the method in your mailer model. For example, in the mailer defined above, the template at
-
# <tt>app/views/notifier/welcome.text.erb</tt> would be used to generate the email.
-
#
-
# Variables defined in the model are accessible as instance variables in the view.
-
#
-
# Emails by default are sent in plain text, so a sample view for our model example might look like this:
-
#
-
# Hi <%= @account.name %>,
-
# Thanks for joining our service! Please check back often.
-
#
-
# You can even use Action Pack helpers in these views. For example:
-
#
-
# You got a new note!
-
# <%= truncate(@note.body, :length => 25) %>
-
#
-
# If you need to access the subject, from or the recipients in the view, you can do that through message object:
-
#
-
# You got a new note from <%= message.from %>!
-
# <%= truncate(@note.body, :length => 25) %>
-
#
-
#
-
# = Generating URLs
-
#
-
# URLs can be generated in mailer views using <tt>url_for</tt> or named routes. Unlike controllers from
-
# Action Pack, the mailer instance doesn't have any context about the incoming request, so you'll need
-
# to provide all of the details needed to generate a URL.
-
#
-
# When using <tt>url_for</tt> you'll need to provide the <tt>:host</tt>, <tt>:controller</tt>, and <tt>:action</tt>:
-
#
-
# <%= url_for(:host => "example.com", :controller => "welcome", :action => "greeting") %>
-
#
-
# When using named routes you only need to supply the <tt>:host</tt>:
-
#
-
# <%= users_url(:host => "example.com") %>
-
#
-
# You should use the <tt>named_route_url</tt> style (which generates absolute URLs) and avoid using the
-
# <tt>named_route_path</tt> style (which generates relative URLs), since clients reading the mail will
-
# have no concept of a current URL from which to determine a relative path.
-
#
-
# It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt>
-
# option as a configuration option in <tt>config/application.rb</tt>:
-
#
-
# config.action_mailer.default_url_options = { :host => "example.com" }
-
#
-
# When you decide to set a default <tt>:host</tt> for your mailers, then you need to make sure to use the
-
# <tt>:only_path => false</tt> option when using <tt>url_for</tt>. Since the <tt>url_for</tt> view helper
-
# will generate relative URLs by default when a <tt>:host</tt> option isn't explicitly provided, passing
-
# <tt>:only_path => false</tt> will ensure that absolute URLs are generated.
-
#
-
# = Sending mail
-
#
-
# Once a mailer action and template are defined, you can deliver your message or create it and save it
-
# for delivery later:
-
#
-
# Notifier.welcome(david).deliver # sends the email
-
# mail = Notifier.welcome(david) # => a Mail::Message object
-
# mail.deliver # sends the email
-
#
-
# You never instantiate your mailer class. Rather, you just call the method you defined on the class itself.
-
#
-
# = Multipart Emails
-
#
-
# Multipart messages can also be used implicitly because Action Mailer will automatically detect and use
-
# multipart templates, where each template is named after the name of the action, followed by the content
-
# type. Each such detected template will be added as a separate part to the message.
-
#
-
# For example, if the following templates exist:
-
# * signup_notification.text.erb
-
# * signup_notification.text.html.erb
-
# * signup_notification.text.xml.builder
-
# * signup_notification.text.yaml.erb
-
#
-
# Each would be rendered and added as a separate part to the message, with the corresponding content
-
# type. The content type for the entire message is automatically set to <tt>multipart/alternative</tt>,
-
# which indicates that the email contains multiple different representations of the same email
-
# body. The same instance variables defined in the action are passed to all email templates.
-
#
-
# Implicit template rendering is not performed if any attachments or parts have been added to the email.
-
# This means that you'll have to manually add each part to the email and set the content type of the email
-
# to <tt>multipart/alternative</tt>.
-
#
-
# = Attachments
-
#
-
# Sending attachment in emails is easy:
-
#
-
# class ApplicationMailer < ActionMailer::Base
-
# def welcome(recipient)
-
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
-
# mail(:to => recipient, :subject => "New account information")
-
# end
-
# end
-
#
-
# Which will (if it had both a <tt>welcome.text.erb</tt> and <tt>welcome.text.html.erb</tt>
-
# template in the view directory), send a complete <tt>multipart/mixed</tt> email with two parts,
-
# the first part being a <tt>multipart/alternative</tt> with the text and HTML email parts inside,
-
# and the second being a <tt>application/pdf</tt> with a Base64 encoded copy of the file.pdf book
-
# with the filename +free_book.pdf+.
-
#
-
# = Inline Attachments
-
#
-
# You can also specify that a file should be displayed inline with other HTML. This is useful
-
# if you want to display a corporate logo or a photo.
-
#
-
# class ApplicationMailer < ActionMailer::Base
-
# def welcome(recipient)
-
# attachments.inline['photo.png'] = File.read('path/to/photo.png')
-
# mail(:to => recipient, :subject => "Here is what we look like")
-
# end
-
# end
-
#
-
# And then to reference the image in the view, you create a <tt>welcome.html.erb</tt> file and
-
# make a call to +image_tag+ passing in the attachment you want to display and then call
-
# +url+ on the attachment to get the relative content id path for the image source:
-
#
-
# <h1>Please Don't Cringe</h1>
-
#
-
# <%= image_tag attachments['photo.png'].url -%>
-
#
-
# As we are using Action View's +image_tag+ method, you can pass in any other options you want:
-
#
-
# <h1>Please Don't Cringe</h1>
-
#
-
# <%= image_tag attachments['photo.png'].url, :alt => 'Our Photo', :class => 'photo' -%>
-
#
-
# = Observing and Intercepting Mails
-
#
-
# Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to
-
# register classes that are called during the mail delivery life cycle.
-
#
-
# An observer class must implement the <tt>:delivered_email(message)</tt> method which will be
-
# called once for every email sent after the email has been sent.
-
#
-
# An interceptor class must implement the <tt>:delivering_email(message)</tt> method which will be
-
# called before the email is sent, allowing you to make modifications to the email before it hits
-
# the delivery agents. Your class should make any needed modifications directly to the passed
-
# in Mail::Message instance.
-
#
-
# = Default Hash
-
#
-
# Action Mailer provides some intelligent defaults for your emails, these are usually specified in a
-
# default method inside the class definition:
-
#
-
# class Notifier < ActionMailer::Base
-
# default :sender => 'system@example.com'
-
# end
-
#
-
# You can pass in any header value that a <tt>Mail::Message</tt> accepts. Out of the box,
-
# <tt>ActionMailer::Base</tt> sets the following:
-
#
-
# * <tt>:mime_version => "1.0"</tt>
-
# * <tt>:charset => "UTF-8",</tt>
-
# * <tt>:content_type => "text/plain",</tt>
-
# * <tt>:parts_order => [ "text/plain", "text/enriched", "text/html" ]</tt>
-
#
-
# <tt>parts_order</tt> and <tt>charset</tt> are not actually valid <tt>Mail::Message</tt> header fields,
-
# but Action Mailer translates them appropriately and sets the correct values.
-
#
-
# As you can pass in any header, you need to either quote the header as a string, or pass it in as
-
# an underscored symbol, so the following will work:
-
#
-
# class Notifier < ActionMailer::Base
-
# default 'Content-Transfer-Encoding' => '7bit',
-
# :content_description => 'This is a description'
-
# end
-
#
-
# Finally, Action Mailer also supports passing <tt>Proc</tt> objects into the default hash, so you
-
# can define methods that evaluate as the message is being generated:
-
#
-
# class Notifier < ActionMailer::Base
-
# default 'X-Special-Header' => Proc.new { my_method }
-
#
-
# private
-
#
-
# def my_method
-
# 'some complex call'
-
# end
-
# end
-
#
-
# Note that the proc is evaluated right at the start of the mail message generation, so if you
-
# set something in the defaults using a proc, and then set the same thing inside of your
-
# mailer method, it will get over written by the mailer method.
-
#
-
# = Configuration options
-
#
-
# These options are specified on the class level, like
-
# <tt>ActionMailer::Base.raise_delivery_errors = true</tt>
-
#
-
# * <tt>default</tt> - You can pass this in at a class level as well as within the class itself as
-
# per the above section.
-
#
-
# * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
-
# Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
-
#
-
# * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
-
# * <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default
-
# "localhost" setting.
-
# * <tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.
-
# * <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
-
# * <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
-
# * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
-
# * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the
-
# authentication type here.
-
# This is a symbol and one of <tt>:plain</tt> (will send the password in the clear), <tt>:login</tt> (will
-
# send password Base64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange
-
# information and a cryptographic Message Digest 5 algorithm to hash important information)
-
# * <tt>:enable_starttls_auto</tt> - When set to true, detects if STARTTLS is enabled in your SMTP server
-
# and starts to use it.
-
# * <tt>:openssl_verify_mode</tt> - When using TLS, you can set how OpenSSL checks the certificate. This is
-
# really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name
-
# of an OpenSSL verify constant ('none', 'peer', 'client_once','fail_if_no_peer_cert') or directly the
-
# constant (OpenSSL::SSL::VERIFY_NONE, OpenSSL::SSL::VERIFY_PEER,...).
-
#
-
# * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
-
# * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
-
# * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@address</tt>
-
# added automatically before the message is sent.
-
#
-
# * <tt>file_settings</tt> - Allows you to override options for the <tt>:file</tt> delivery method.
-
# * <tt>:location</tt> - The directory into which emails will be written. Defaults to the application
-
# <tt>tmp/mails</tt>.
-
#
-
# * <tt>raise_delivery_errors</tt> - Whether or not errors should be raised if the email fails to be delivered.
-
#
-
# * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default),
-
# <tt>:sendmail</tt>, <tt>:test</tt>, and <tt>:file</tt>. Or you may provide a custom delivery method
-
# object eg. MyOwnDeliveryMethodClass.new. See the Mail gem documentation on the interface you need to
-
# implement for a custom delivery agent.
-
#
-
# * <tt>perform_deliveries</tt> - Determines whether emails are actually sent from Action Mailer when you
-
# call <tt>.deliver</tt> on an mail message or on an Action Mailer method. This is on by default but can
-
# be turned off to aid in functional testing.
-
#
-
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with
-
# <tt>delivery_method :test</tt>. Most useful for unit and functional testing.
-
#
-
2
class Base < AbstractController::Base
-
2
include DeliveryMethods
-
2
abstract!
-
-
2
include AbstractController::Logger
-
2
include AbstractController::Rendering
-
2
include AbstractController::Layouts
-
2
include AbstractController::Helpers
-
2
include AbstractController::Translation
-
2
include AbstractController::AssetPaths
-
-
2
self.protected_instance_variables = %w(@_action_has_layout)
-
-
2
helper ActionMailer::MailHelper
-
-
2
private_class_method :new #:nodoc:
-
-
2
class_attribute :default_params
-
2
self.default_params = {
-
:mime_version => "1.0",
-
:charset => "UTF-8",
-
:content_type => "text/plain",
-
:parts_order => [ "text/plain", "text/enriched", "text/html" ]
-
}.freeze
-
-
2
class << self
-
# Register one or more Observers which will be notified when mail is delivered.
-
2
def register_observers(*observers)
-
2
observers.flatten.compact.each { |observer| register_observer(observer) }
-
end
-
-
# Register one or more Interceptors which will be called before mail is sent.
-
2
def register_interceptors(*interceptors)
-
2
interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }
-
end
-
-
# Register an Observer which will be notified when mail is delivered.
-
# Either a class or a string can be passed in as the Observer. If a string is passed in
-
# it will be <tt>constantize</tt>d.
-
2
def register_observer(observer)
-
delivery_observer = (observer.is_a?(String) ? observer.constantize : observer)
-
Mail.register_observer(delivery_observer)
-
end
-
-
# Register an Interceptor which will be called before mail is sent.
-
# Either a class or a string can be passed in as the Interceptor. If a string is passed in
-
# it will be <tt>constantize</tt>d.
-
2
def register_interceptor(interceptor)
-
delivery_interceptor = (interceptor.is_a?(String) ? interceptor.constantize : interceptor)
-
Mail.register_interceptor(delivery_interceptor)
-
end
-
-
2
def mailer_name
-
20
@mailer_name ||= anonymous? ? "anonymous" : name.underscore
-
end
-
2
attr_writer :mailer_name
-
2
alias :controller_path :mailer_name
-
-
2
def default(value = nil)
-
14
self.default_params = default_params.merge(value).freeze if value
-
14
default_params
-
end
-
-
# Receives a raw email, parses it into an email object, decodes it,
-
# instantiates a new mailer, and passes the email object to the mailer
-
# object's +receive+ method. If you want your mailer to be able to
-
# process incoming messages, you'll need to implement a +receive+
-
# method that accepts the raw email string as a parameter:
-
#
-
# class MyMailer < ActionMailer::Base
-
# def receive(mail)
-
# ...
-
# end
-
# end
-
2
def receive(raw_mail)
-
ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload|
-
mail = Mail.new(raw_mail)
-
set_payload_for_mail(payload, mail)
-
new.receive(mail)
-
end
-
end
-
-
# Wraps an email delivery inside of Active Support Notifications instrumentation. This
-
# method is actually called by the <tt>Mail::Message</tt> object itself through a callback
-
# when you call <tt>:deliver</tt> on the Mail::Message, calling +deliver_mail+ directly
-
# and passing a Mail::Message will do nothing except tell the logger you sent the email.
-
2
def deliver_mail(mail) #:nodoc:
-
4
ActiveSupport::Notifications.instrument("deliver.action_mailer") do |payload|
-
4
self.set_payload_for_mail(payload, mail)
-
4
yield # Let Mail do the delivery actions
-
end
-
end
-
-
2
def respond_to?(method, include_private = false) #:nodoc:
-
60
super || action_methods.include?(method.to_s)
-
end
-
-
2
protected
-
-
2
def set_payload_for_mail(payload, mail) #:nodoc:
-
4
payload[:mailer] = name
-
4
payload[:message_id] = mail.message_id
-
4
payload[:subject] = mail.subject
-
4
payload[:to] = mail.to
-
4
payload[:from] = mail.from
-
4
payload[:bcc] = mail.bcc if mail.bcc.present?
-
4
payload[:cc] = mail.cc if mail.cc.present?
-
4
payload[:date] = mail.date
-
4
payload[:mail] = mail.encoded
-
end
-
-
2
def method_missing(method, *args) #:nodoc:
-
28
return super unless respond_to?(method)
-
4
new(method, *args).message
-
end
-
end
-
-
2
attr_internal :message
-
-
# Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
-
# will be initialized according to the named method. If not, the mailer will
-
# remain uninitialized (useful when you only need to invoke the "receive"
-
# method, for instance).
-
2
def initialize(method_name=nil, *args)
-
4
super()
-
4
@mail_was_called = false
-
4
@_message = Mail.new
-
4
process(method_name, *args) if method_name
-
end
-
-
2
def process(*args) #:nodoc:
-
4
lookup_context.skip_default_locale!
-
-
4
super
-
4
@_message = NullMail.new unless @mail_was_called
-
end
-
-
2
class NullMail #:nodoc:
-
2
def body; '' end
-
-
2
def method_missing(*args)
-
nil
-
end
-
end
-
-
2
def mailer_name
-
self.class.mailer_name
-
end
-
-
# Allows you to pass random and unusual headers to the new +Mail::Message+ object
-
# which will add them to itself.
-
#
-
# headers['X-Special-Domain-Specific-Header'] = "SecretValue"
-
#
-
# You can also pass a hash into headers of header field names and values, which
-
# will then be set on the Mail::Message object:
-
#
-
# headers 'X-Special-Domain-Specific-Header' => "SecretValue",
-
# 'In-Reply-To' => incoming.message_id
-
#
-
# The resulting Mail::Message will have the following in it's header:
-
#
-
# X-Special-Domain-Specific-Header: SecretValue
-
2
def headers(args=nil)
-
if args
-
@_message.headers(args)
-
else
-
@_message
-
end
-
end
-
-
# Allows you to add attachments to an email, like so:
-
#
-
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
-
#
-
# If you do this, then Mail will take the file name and work out the mime type
-
# set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
-
# base64 encode the contents of the attachment all for you.
-
#
-
# You can also specify overrides if you want by passing a hash instead of a string:
-
#
-
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
-
# :content => File.read('/path/to/filename.jpg')}
-
#
-
# If you want to use a different encoding than Base64, you can pass an encoding in,
-
# but then it is up to you to pass in the content pre-encoded, and don't expect
-
# Mail to know how to decode this data:
-
#
-
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
-
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
-
# :encoding => 'SpecialEncoding',
-
# :content => file_content }
-
#
-
# You can also search for specific attachments:
-
#
-
# # By Filename
-
# mail.attachments['filename.jpg'] # => Mail::Part object or nil
-
#
-
# # or by index
-
# mail.attachments[0] # => Mail::Part (first attachment)
-
#
-
2
def attachments
-
@_message.attachments
-
end
-
-
# The main method that creates the message and renders the email templates. There are
-
# two ways to call this method, with a block, or without a block.
-
#
-
# Both methods accept a headers hash. This hash allows you to specify the most used headers
-
# in an email message, these are:
-
#
-
# * <tt>:subject</tt> - The subject of the message, if this is omitted, Action Mailer will
-
# ask the Rails I18n class for a translated <tt>:subject</tt> in the scope of
-
# <tt>[mailer_scope, action_name]</tt> or if this is missing, will translate the
-
# humanized version of the <tt>action_name</tt>
-
# * <tt>:to</tt> - Who the message is destined for, can be a string of addresses, or an array
-
# of addresses.
-
# * <tt>:from</tt> - Who the message is from
-
# * <tt>:cc</tt> - Who you would like to Carbon-Copy on this email, can be a string of addresses,
-
# or an array of addresses.
-
# * <tt>:bcc</tt> - Who you would like to Blind-Carbon-Copy on this email, can be a string of
-
# addresses, or an array of addresses.
-
# * <tt>:reply_to</tt> - Who to set the Reply-To header of the email to.
-
# * <tt>:date</tt> - The date to say the email was sent on.
-
#
-
# You can set default values for any of the above headers (except :date) by using the <tt>default</tt>
-
# class method:
-
#
-
# class Notifier < ActionMailer::Base
-
# self.default :from => 'no-reply@test.lindsaar.net',
-
# :bcc => 'email_logger@test.lindsaar.net',
-
# :reply_to => 'bounces@test.lindsaar.net'
-
# end
-
#
-
# If you need other headers not listed above, you can either pass them in
-
# as part of the headers hash or use the <tt>headers['name'] = value</tt>
-
# method.
-
#
-
# When a <tt>:return_path</tt> is specified as header, that value will be used as the 'envelope from'
-
# address for the Mail message. Setting this is useful when you want delivery notifications
-
# sent to a different address than the one in <tt>:from</tt>. Mail will actually use the
-
# <tt>:return_path</tt> in preference to the <tt>:sender</tt> in preference to the <tt>:from</tt>
-
# field for the 'envelope from' value.
-
#
-
# If you do not pass a block to the +mail+ method, it will find all templates in the
-
# view paths using by default the mailer name and the method name that it is being
-
# called from, it will then create parts for each of these templates intelligently,
-
# making educated guesses on correct content type and sequence, and return a fully
-
# prepared Mail::Message ready to call <tt>:deliver</tt> on to send.
-
#
-
# For example:
-
#
-
# class Notifier < ActionMailer::Base
-
# default :from => 'no-reply@test.lindsaar.net',
-
#
-
# def welcome
-
# mail(:to => 'mikel@test.lindsaar.net')
-
# end
-
# end
-
#
-
# Will look for all templates at "app/views/notifier" with name "welcome". However, those
-
# can be customized:
-
#
-
# mail(:template_path => 'notifications', :template_name => 'another')
-
#
-
# And now it will look for all templates at "app/views/notifications" with name "another".
-
#
-
# If you do pass a block, you can render specific templates of your choice:
-
#
-
# mail(:to => 'mikel@test.lindsaar.net') do |format|
-
# format.text
-
# format.html
-
# end
-
#
-
# You can even render text directly without using a template:
-
#
-
# mail(:to => 'mikel@test.lindsaar.net') do |format|
-
# format.text { render :text => "Hello Mikel!" }
-
# format.html { render :text => "<h1>Hello Mikel!</h1>" }
-
# end
-
#
-
# Which will render a <tt>multipart/alternative</tt> email with <tt>text/plain</tt> and
-
# <tt>text/html</tt> parts.
-
#
-
# The block syntax also allows you to customize the part headers if desired:
-
#
-
# mail(:to => 'mikel@test.lindsaar.net') do |format|
-
# format.text(:content_transfer_encoding => "base64")
-
# format.html
-
# end
-
#
-
2
def mail(headers={}, &block)
-
# Guard flag to prevent both the old and the new API from firing.
-
# On master this flag was renamed to `@_mail_was_called`.
-
# On master there is only one API and this flag is no longer used as a guard.
-
4
@mail_was_called = true
-
4
m = @_message
-
-
# At the beginning, do not consider class default for parts order neither content_type
-
4
content_type = headers[:content_type]
-
4
parts_order = headers[:parts_order]
-
-
# Call all the procs (if any)
-
4
default_values = self.class.default.merge(self.class.default) do |k,v|
-
20
v.respond_to?(:call) ? v.bind(self).call : v
-
end
-
-
# Handle defaults
-
4
headers = headers.reverse_merge(default_values)
-
4
headers[:subject] ||= default_i18n_subject
-
-
# Apply charset at the beginning so all fields are properly quoted
-
4
m.charset = charset = headers[:charset]
-
-
# Set configure delivery behavior
-
4
wrap_delivery_behavior!(headers.delete(:delivery_method))
-
-
# Assign all headers except parts_order, content_type and body
-
4
assignable = headers.except(:parts_order, :content_type, :body, :template_name, :template_path)
-
24
assignable.each { |k, v| m[k] = v }
-
-
# Render the templates and blocks
-
4
responses, explicit_order = collect_responses_and_parts_order(headers, &block)
-
4
create_parts_from_responses(m, responses)
-
-
# Setup content type, reapply charset and handle parts order
-
4
m.content_type = set_content_type(m, content_type, headers[:content_type])
-
4
m.charset = charset
-
-
4
if m.multipart?
-
parts_order ||= explicit_order || headers[:parts_order]
-
m.body.set_sort_order(parts_order)
-
m.body.sort_parts!
-
end
-
-
4
m
-
end
-
-
2
protected
-
-
2
def set_content_type(m, user_content_type, class_default)
-
4
params = m.content_type_parameters || {}
-
case
-
when user_content_type.present?
-
user_content_type
-
when m.has_attachments?
-
if m.attachments.detect { |a| a.inline? }
-
["multipart", "related", params]
-
else
-
["multipart", "mixed", params]
-
end
-
when m.multipart?
-
["multipart", "alternative", params]
-
else
-
4
m.content_type || class_default
-
4
end
-
end
-
-
# Translates the +subject+ using Rails I18n class under <tt>[:actionmailer, mailer_scope, action_name]</tt> scope.
-
# If it does not find a translation for the +subject+ under the specified scope it will default to a
-
# humanized version of the <tt>action_name</tt>.
-
2
def default_i18n_subject #:nodoc:
-
mailer_scope = self.class.mailer_name.gsub('/', '.')
-
I18n.t(:subject, :scope => [mailer_scope, action_name], :default => action_name.humanize)
-
end
-
-
2
def collect_responses_and_parts_order(headers) #:nodoc:
-
4
responses, parts_order = [], nil
-
-
4
if block_given?
-
collector = ActionMailer::Collector.new(lookup_context) { render(action_name) }
-
yield(collector)
-
parts_order = collector.responses.map { |r| r[:content_type] }
-
responses = collector.responses
-
elsif headers[:body]
-
responses << {
-
:body => headers.delete(:body),
-
:content_type => self.class.default[:content_type] || "text/plain"
-
}
-
else
-
4
templates_path = headers.delete(:template_path) || self.class.mailer_name
-
4
templates_name = headers.delete(:template_name) || action_name
-
-
4
each_template(templates_path, templates_name) do |template|
-
4
self.formats = template.formats
-
-
responses << {
-
:body => render(:template => template),
-
:content_type => template.mime_type.to_s
-
4
}
-
end
-
end
-
-
4
[responses, parts_order]
-
end
-
-
2
def each_template(paths, name, &block) #:nodoc:
-
4
templates = lookup_context.find_all(name, Array.wrap(paths))
-
8
templates.uniq_by { |t| t.formats }.each(&block)
-
end
-
-
2
def create_parts_from_responses(m, responses) #:nodoc:
-
4
if responses.size == 1 && !m.has_attachments?
-
12
responses[0].each { |k,v| m[k] = v }
-
elsif responses.size > 1 && m.has_attachments?
-
container = Mail::Part.new
-
container.content_type = "multipart/alternative"
-
responses.each { |r| insert_part(container, r, m.charset) }
-
m.add_part(container)
-
else
-
responses.each { |r| insert_part(m, r, m.charset) }
-
end
-
end
-
-
2
def insert_part(container, response, charset) #:nodoc:
-
response[:charset] ||= charset
-
part = Mail::Part.new(response)
-
container.add_part(part)
-
end
-
-
2
ActiveSupport.run_load_hooks(:action_mailer, self)
-
end
-
end
-
-
2
require 'abstract_controller/collector'
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
module ActionMailer #:nodoc:
-
2
class Collector
-
2
include AbstractController::Collector
-
2
attr_reader :responses
-
-
2
def initialize(context, &block)
-
@context = context
-
@responses = []
-
@default_render = block
-
end
-
-
2
def any(*args, &block)
-
options = args.extract_options!
-
raise "You have to supply at least one format" if args.empty?
-
args.each { |type| send(type, options.dup, &block) }
-
end
-
2
alias :all :any
-
-
2
def custom(mime, options={})
-
options.reverse_merge!(:content_type => mime.to_s)
-
@context.formats = [mime.to_sym]
-
options[:body] = block_given? ? yield : @default_render.call
-
@responses << options
-
end
-
end
-
end
-
2
require 'tmpdir'
-
-
2
module ActionMailer
-
# This module handles everything related to mail delivery, from registering new
-
# delivery methods to configuring the mail object to be sent.
-
2
module DeliveryMethods
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :delivery_methods, :delivery_method
-
-
# Do not make this inheritable, because we always want it to propagate
-
2
cattr_accessor :raise_delivery_errors
-
2
self.raise_delivery_errors = true
-
-
2
cattr_accessor :perform_deliveries
-
2
self.perform_deliveries = true
-
-
2
self.delivery_methods = {}.freeze
-
2
self.delivery_method = :smtp
-
-
2
add_delivery_method :smtp, Mail::SMTP,
-
:address => "localhost",
-
:port => 25,
-
:domain => 'localhost.localdomain',
-
:user_name => nil,
-
:password => nil,
-
:authentication => nil,
-
:enable_starttls_auto => true
-
-
2
add_delivery_method :file, Mail::FileDelivery,
-
:location => defined?(Rails.root) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails"
-
-
2
add_delivery_method :sendmail, Mail::Sendmail,
-
:location => '/usr/sbin/sendmail',
-
:arguments => '-i -t'
-
-
2
add_delivery_method :test, Mail::TestMailer
-
end
-
-
2
module ClassMethods
-
# Provides a list of emails that have been delivered by Mail::TestMailer
-
2
delegate :deliveries, :deliveries=, :to => Mail::TestMailer
-
-
# Adds a new delivery method through the given class using the given symbol
-
# as alias and the default options supplied:
-
#
-
# Example:
-
#
-
# add_delivery_method :sendmail, Mail::Sendmail,
-
# :location => '/usr/sbin/sendmail',
-
# :arguments => '-i -t'
-
#
-
2
def add_delivery_method(symbol, klass, default_options={})
-
8
class_attribute(:"#{symbol}_settings") unless respond_to?(:"#{symbol}_settings")
-
8
send(:"#{symbol}_settings=", default_options)
-
8
self.delivery_methods = delivery_methods.merge(symbol.to_sym => klass).freeze
-
end
-
-
2
def wrap_delivery_behavior(mail, method=nil) #:nodoc:
-
4
method ||= self.delivery_method
-
4
mail.delivery_handler = self
-
-
4
case method
-
when NilClass
-
raise "Delivery method cannot be nil"
-
when Symbol
-
4
if klass = delivery_methods[method.to_sym]
-
4
mail.delivery_method(klass, send(:"#{method}_settings"))
-
else
-
raise "Invalid delivery method #{method.inspect}"
-
end
-
else
-
mail.delivery_method(method)
-
end
-
-
4
mail.perform_deliveries = perform_deliveries
-
4
mail.raise_delivery_errors = raise_delivery_errors
-
end
-
end
-
-
2
def wrap_delivery_behavior!(*args) #:nodoc:
-
4
self.class.wrap_delivery_behavior(message, *args)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
-
2
module ActionMailer
-
2
class LogSubscriber < ActiveSupport::LogSubscriber
-
2
def deliver(event)
-
4
recipients = Array.wrap(event.payload[:to]).join(', ')
-
4
info("\nSent mail to #{recipients} (#{format_duration(event.duration)})")
-
4
debug(event.payload[:mail])
-
end
-
-
2
def receive(event)
-
info("\nReceived mail (#{format_duration(event.duration)})")
-
debug(event.payload[:mail])
-
end
-
-
2
def logger
-
20
ActionMailer::Base.logger
-
end
-
end
-
end
-
-
2
ActionMailer::LogSubscriber.attach_to :action_mailer
-
2
module ActionMailer
-
2
module MailHelper
-
# Uses Text::Format to take the text and format it, indented two spaces for
-
# each line, and wrapped at 72 columns.
-
2
def block_format(text)
-
formatted = text.split(/\n\r\n/).collect { |paragraph|
-
format_paragraph(paragraph)
-
}.join("\n")
-
-
# Make list points stand on their own line
-
formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
-
formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
-
-
formatted
-
end
-
-
# Access the mailer instance.
-
2
def mailer
-
@_controller
-
end
-
-
# Access the message instance.
-
2
def message
-
@_message
-
end
-
-
# Access the message attachments list.
-
2
def attachments
-
@_message.attachments
-
end
-
-
# Returns +text+ wrapped at +len+ columns and indented +indent+ spaces.
-
#
-
# === Examples
-
#
-
# my_text = "Here is a sample text with more than 40 characters"
-
#
-
# format_paragraph(my_text, 25, 4)
-
# # => " Here is a sample text with\n more than 40 characters"
-
2
def format_paragraph(text, len = 72, indent = 2)
-
sentences = [[]]
-
-
text.split.each do |word|
-
if (sentences.last + [word]).join(' ').length > len
-
sentences << [word]
-
else
-
sentences.last << word
-
end
-
end
-
-
sentences.map { |sentence|
-
"#{" " * indent}#{sentence.join(' ')}"
-
}.join "\n"
-
end
-
end
-
end
-
2
require "action_mailer"
-
2
require "rails"
-
2
require "abstract_controller/railties/routes_helpers"
-
-
2
module ActionMailer
-
2
class Railtie < Rails::Railtie
-
2
config.action_mailer = ActiveSupport::OrderedOptions.new
-
-
2
initializer "action_mailer.logger" do
-
4
ActiveSupport.on_load(:action_mailer) { self.logger ||= Rails.logger }
-
end
-
-
2
initializer "action_mailer.set_configs" do |app|
-
2
paths = app.config.paths
-
2
options = app.config.action_mailer
-
-
2
options.assets_dir ||= paths["public"].first
-
2
options.javascripts_dir ||= paths["public/javascripts"].first
-
2
options.stylesheets_dir ||= paths["public/stylesheets"].first
-
-
# make sure readers methods get compiled
-
2
options.asset_path ||= app.config.asset_path
-
2
options.asset_host ||= app.config.asset_host
-
2
options.relative_url_root ||= app.config.relative_url_root
-
-
2
ActiveSupport.on_load(:action_mailer) do
-
2
include AbstractController::UrlFor
-
2
extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
-
2
include app.routes.mounted_helpers
-
-
2
register_interceptors(options.delete(:interceptors))
-
2
register_observers(options.delete(:observers))
-
-
16
options.each { |k,v| send("#{k}=", v) }
-
end
-
end
-
-
2
initializer "action_mailer.compile_config_methods" do
-
2
ActiveSupport.on_load(:action_mailer) do
-
2
config.compile_methods! if config.respond_to?(:compile_methods!)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/class/attribute'
-
-
1
module ActionMailer
-
1
class NonInferrableMailerError < ::StandardError
-
1
def initialize(name)
-
super "Unable to determine the mailer to test from #{name}. " +
-
"You'll need to specify it using tests YourMailer in your " +
-
"test case definition"
-
end
-
end
-
-
1
class TestCase < ActiveSupport::TestCase
-
1
module Behavior
-
1
extend ActiveSupport::Concern
-
-
1
include TestHelper
-
-
1
included do
-
1
class_attribute :_mailer_class
-
1
setup :initialize_test_deliveries
-
1
setup :set_expected_mail
-
end
-
-
1
module ClassMethods
-
1
def tests(mailer)
-
case mailer
-
when String, Symbol
-
self._mailer_class = mailer.to_s.camelize.constantize
-
when Module
-
self._mailer_class = mailer
-
else
-
raise NonInferrableMailerError.new(mailer)
-
end
-
end
-
-
1
def mailer_class
-
if mailer = self._mailer_class
-
mailer
-
else
-
tests determine_default_mailer(name)
-
end
-
end
-
-
1
def determine_default_mailer(name)
-
name.sub(/Test$/, '').constantize
-
rescue NameError
-
raise NonInferrableMailerError.new(name)
-
end
-
end
-
-
1
protected
-
-
1
def initialize_test_deliveries
-
ActionMailer::Base.delivery_method = :test
-
ActionMailer::Base.perform_deliveries = true
-
ActionMailer::Base.deliveries.clear
-
end
-
-
1
def set_expected_mail
-
@expected = Mail.new
-
@expected.content_type ["text", "plain", { "charset" => charset }]
-
@expected.mime_version = '1.0'
-
end
-
-
1
private
-
-
1
def charset
-
"UTF-8"
-
end
-
-
1
def encode(subject)
-
Mail::Encodings.q_value_encode(subject, charset)
-
end
-
-
1
def read_fixture(action)
-
IO.readlines(File.join(Rails.root, 'test', 'fixtures', self.class.mailer_class.name.underscore, action))
-
end
-
end
-
-
1
include Behavior
-
end
-
end
-
1
module ActionMailer
-
1
module TestHelper
-
1
extend ActiveSupport::Concern
-
-
# Asserts that the number of emails sent matches the given number.
-
#
-
# def test_emails
-
# assert_emails 0
-
# ContactMailer.deliver_contact
-
# assert_emails 1
-
# ContactMailer.deliver_contact
-
# assert_emails 2
-
# end
-
#
-
# If a block is passed, that block should cause the specified number of emails to be sent.
-
#
-
# def test_emails_again
-
# assert_emails 1 do
-
# ContactMailer.deliver_contact
-
# end
-
#
-
# assert_emails 2 do
-
# ContactMailer.deliver_contact
-
# ContactMailer.deliver_contact
-
# end
-
# end
-
1
def assert_emails(number)
-
if block_given?
-
original_count = ActionMailer::Base.deliveries.size
-
yield
-
new_count = ActionMailer::Base.deliveries.size
-
assert_equal original_count + number, new_count, "#{number} emails expected, but #{new_count - original_count} were sent"
-
else
-
assert_equal number, ActionMailer::Base.deliveries.size
-
end
-
end
-
-
# Assert that no emails have been sent.
-
#
-
# def test_emails
-
# assert_no_emails
-
# ContactMailer.deliver_contact
-
# assert_emails 1
-
# end
-
#
-
# If a block is passed, that block should not cause any emails to be sent.
-
#
-
# def test_emails_again
-
# assert_no_emails do
-
# # No emails should be sent from this block
-
# end
-
# end
-
#
-
# Note: This assertion is simply a shortcut for:
-
#
-
# assert_emails 0
-
1
def assert_no_emails(&block)
-
assert_emails 0, &block
-
end
-
end
-
end
-
2
module ActionMailer
-
2
module VERSION #:nodoc:
-
2
MAJOR = 3
-
2
MINOR = 2
-
2
TINY = 16
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
-
end
-
end
-
2
activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
-
2
$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-
-
2
require 'action_pack'
-
2
require 'active_support/concern'
-
2
require 'active_support/ruby/shim'
-
2
require 'active_support/dependencies/autoload'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/module/attr_internal'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'active_support/i18n'
-
-
2
module AbstractController
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Base
-
2
autoload :Callbacks
-
2
autoload :Collector
-
2
autoload :Helpers
-
2
autoload :Layouts
-
2
autoload :Logger
-
2
autoload :Rendering
-
2
autoload :Translation
-
2
autoload :AssetPaths
-
2
autoload :ViewPaths
-
2
autoload :UrlFor
-
end
-
2
module AbstractController
-
2
module AssetPaths
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
4
config_accessor :asset_host, :asset_path, :assets_dir, :javascripts_dir,
-
:stylesheets_dir, :default_asset_host_protocol, :relative_url_root
-
end
-
end
-
end
-
2
require 'erubis'
-
2
require 'active_support/configurable'
-
2
require 'active_support/descendants_tracker'
-
2
require 'active_support/core_ext/module/anonymous'
-
-
2
module AbstractController
-
2
class Error < StandardError; end
-
2
class ActionNotFound < StandardError; end
-
-
# <tt>AbstractController::Base</tt> is a low-level API. Nobody should be
-
# using it directly, and subclasses (like ActionController::Base) are
-
# expected to provide their own +render+ method, since rendering means
-
# different things depending on the context.
-
2
class Base
-
2
attr_internal :response_body
-
2
attr_internal :action_name
-
2
attr_internal :formats
-
-
2
include ActiveSupport::Configurable
-
2
extend ActiveSupport::DescendantsTracker
-
-
2
undef_method :not_implemented
-
2
class << self
-
2
attr_reader :abstract
-
2
alias_method :abstract?, :abstract
-
-
# Define a controller as abstract. See internal_methods for more
-
# details.
-
2
def abstract!
-
8
@abstract = true
-
end
-
-
# A list of all internal methods for a controller. This finds the first
-
# abstract superclass of a controller, and gets a list of all public
-
# instance methods on that abstract class. Public instance methods of
-
# a controller would normally be considered action methods, so methods
-
# declared on abstract classes are being removed.
-
# (ActionController::Metal and ActionController::Base are defined as abstract)
-
2
def internal_methods
-
16
controller = self
-
16
controller = controller.superclass until controller.abstract?
-
16
controller.public_instance_methods(true)
-
end
-
-
# The list of hidden actions to an empty array. Defaults to an
-
# empty array. This can be modified by other modules or subclasses
-
# to specify particular actions as hidden.
-
#
-
# ==== Returns
-
# * <tt>array</tt> - An array of method names that should not be considered actions.
-
2
def hidden_actions
-
7
[]
-
end
-
-
# A list of method names that should be considered actions. This
-
# includes all public instance methods on a controller, less
-
# any internal methods (see #internal_methods), adding back in
-
# any methods that are internal, but still exist on the class
-
# itself. Finally, #hidden_actions are removed.
-
#
-
# ==== Returns
-
# * <tt>array</tt> - A list of all methods that should be considered actions.
-
2
def action_methods
-
@action_methods ||= begin
-
# All public instance methods of this class, including ancestors
-
16
methods = (public_instance_methods(true) -
-
# Except for public instance methods of Base and its ancestors
-
internal_methods +
-
# Be sure to include shadowed public instance methods of this class
-
1204
public_instance_methods(false)).uniq.map { |x| x.to_s } -
-
# And always exclude explicitly hidden actions
-
hidden_actions.to_a
-
-
# Clear out AS callback method pollution
-
1204
methods.reject { |method| method =~ /_one_time_conditions/ }
-
16
end
-
end
-
-
# action_methods are cached and there is sometimes need to refresh
-
# them. clear_action_methods! allows you to do that, so next time
-
# you run action_methods, they will be recalculated
-
2
def clear_action_methods!
-
682
@action_methods = nil
-
end
-
-
# Returns the full controller name, underscored, without the ending Controller.
-
# For instance, MyApp::MyPostsController would return "my_app/my_posts" for
-
# controller_name.
-
#
-
# ==== Returns
-
# * <tt>string</tt>
-
2
def controller_path
-
89
@controller_path ||= name.sub(/Controller$/, '').underscore unless anonymous?
-
end
-
-
2
def method_added(name)
-
682
super
-
682
clear_action_methods!
-
end
-
end
-
-
2
abstract!
-
-
# Calls the action going through the entire action dispatch stack.
-
#
-
# The actual method that is called is determined by calling
-
# #method_for_action. If no method can handle the action, then an
-
# ActionNotFound error is raised.
-
#
-
# ==== Returns
-
# * <tt>self</tt>
-
2
def process(action, *args)
-
13
@_action_name = action_name = action.to_s
-
-
13
unless action_name = method_for_action(action_name)
-
raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}"
-
end
-
-
13
@_response_body = nil
-
-
13
process_action(action_name, *args)
-
end
-
-
# Delegates to the class' #controller_path
-
2
def controller_path
-
14
self.class.controller_path
-
end
-
-
2
def action_methods
-
self.class.action_methods
-
end
-
-
# Returns true if a method for the action is available and
-
# can be dispatched, false otherwise.
-
#
-
# Notice that <tt>action_methods.include?("foo")</tt> may return
-
# false and <tt>available_action?("foo")</tt> returns true because
-
# available action consider actions that are also available
-
# through other means, for example, implicit render ones.
-
2
def available_action?(action_name)
-
method_for_action(action_name).present?
-
end
-
-
2
private
-
-
# Returns true if the name can be considered an action because
-
# it has a method defined in the controller.
-
#
-
# ==== Parameters
-
# * <tt>name</tt> - The name of an action to be tested
-
#
-
# ==== Returns
-
# * <tt>TrueClass</tt>, <tt>FalseClass</tt>
-
#
-
# :api: private
-
2
def action_method?(name)
-
13
self.class.action_methods.include?(name)
-
end
-
-
# Call the action. Override this in a subclass to modify the
-
# behavior around processing an action. This, and not #process,
-
# is the intended way to override action dispatching.
-
#
-
# Notice that the first argument is the method to be dispatched
-
# which is *not* necessarily the same as the action name.
-
2
def process_action(method_name, *args)
-
4
send_action(method_name, *args)
-
end
-
-
# Actually call the method associated with the action. Override
-
# this method if you wish to change how action methods are called,
-
# not to add additional behavior around it. For example, you would
-
# override #send_action if you want to inject arguments into the
-
# method.
-
2
alias send_action send
-
-
# If the action name was not found, but a method called "action_missing"
-
# was found, #method_for_action will return "_handle_action_missing".
-
# This method calls #action_missing with the current action name.
-
2
def _handle_action_missing(*args)
-
action_missing(@_action_name, *args)
-
end
-
-
# Takes an action name and returns the name of the method that will
-
# handle the action. In normal cases, this method returns the same
-
# name as it receives. By default, if #method_for_action receives
-
# a name that is not an action, it will look for an #action_missing
-
# method and return "_handle_action_missing" if one is found.
-
#
-
# Subclasses may override this method to add additional conditions
-
# that should be considered an action. For instance, an HTTP controller
-
# with a template matching the action name is considered to exist.
-
#
-
# If you override this method to handle additional cases, you may
-
# also provide a method (like _handle_method_missing) to handle
-
# the case.
-
#
-
# If none of these conditions are true, and method_for_action
-
# returns nil, an ActionNotFound exception will be raised.
-
#
-
# ==== Parameters
-
# * <tt>action_name</tt> - An action name to find a method name for
-
#
-
# ==== Returns
-
# * <tt>string</tt> - The name of the method that handles the action
-
# * <tt>nil</tt> - No method name could be found. Raise ActionNotFound.
-
2
def method_for_action(action_name)
-
13
if action_method?(action_name) then action_name
-
elsif respond_to?(:action_missing, true) then "_handle_action_missing"
-
end
-
end
-
end
-
end
-
2
module AbstractController
-
2
module Callbacks
-
2
extend ActiveSupport::Concern
-
-
# Uses ActiveSupport::Callbacks as the base functionality. For
-
# more details on the whole callback system, read the documentation
-
# for ActiveSupport::Callbacks.
-
2
include ActiveSupport::Callbacks
-
-
2
included do
-
2
define_callbacks :process_action, :terminator => "response_body"
-
end
-
-
# Override AbstractController::Base's process_action to run the
-
# process_action callbacks around the normal behavior.
-
2
def process_action(*args)
-
9
run_callbacks(:process_action, action_name) do
-
super
-
end
-
end
-
-
2
module ClassMethods
-
# If :only or :except are used, convert the options into the
-
# primitive form (:per_key) used by ActiveSupport::Callbacks.
-
# The basic idea is that :only => :index gets converted to
-
# :if => proc {|c| c.action_name == "index" }, but that the
-
# proc is only evaluated once per action for the lifetime of
-
# a Rails process.
-
#
-
# ==== Options
-
# * <tt>only</tt> - The callback should be run only for this action
-
# * <tt>except</tt> - The callback should be run for all actions except this action
-
2
def _normalize_callback_options(options)
-
28
if only = options[:only]
-
12
only = Array(only).map {|o| "action_name == '#{o}'"}.join(" || ")
-
4
options[:per_key] = {:if => only}
-
end
-
28
if except = options[:except]
-
except = Array(except).map {|e| "action_name == '#{e}'"}.join(" || ")
-
options[:per_key] = {:unless => except}
-
end
-
end
-
-
# Skip before, after, and around filters matching any of the names
-
#
-
# ==== Parameters
-
# * <tt>names</tt> - A list of valid names that could be used for
-
# callbacks. Note that skipping uses Ruby equality, so it's
-
# impossible to skip a callback defined using an anonymous proc
-
# using #skip_filter
-
2
def skip_filter(*names, &blk)
-
skip_before_filter(*names)
-
skip_after_filter(*names)
-
skip_around_filter(*names)
-
end
-
-
# Take callback names and an optional callback proc, normalize them,
-
# then call the block with each callback. This allows us to abstract
-
# the normalization across several methods that use it.
-
#
-
# ==== Parameters
-
# * <tt>callbacks</tt> - An array of callbacks, with an optional
-
# options hash as the last parameter.
-
# * <tt>block</tt> - A proc that should be added to the callbacks.
-
#
-
# ==== Block Parameters
-
# * <tt>name</tt> - The callback to be added
-
# * <tt>options</tt> - A hash of options to be used when adding the callback
-
2
def _insert_callbacks(callbacks, block)
-
28
options = callbacks.last.is_a?(Hash) ? callbacks.pop : {}
-
28
_normalize_callback_options(options)
-
28
callbacks.push(block) if block
-
28
callbacks.each do |callback|
-
28
yield callback, options
-
end
-
end
-
-
##
-
# :method: before_filter
-
#
-
# :call-seq: before_filter(names, block)
-
#
-
# Append a before filter. See _insert_callbacks for parameter details.
-
-
##
-
# :method: prepend_before_filter
-
#
-
# :call-seq: prepend_before_filter(names, block)
-
#
-
# Prepend a before filter. See _insert_callbacks for parameter details.
-
-
##
-
# :method: skip_before_filter
-
#
-
# :call-seq: skip_before_filter(names, block)
-
#
-
# Skip a before filter. See _insert_callbacks for parameter details.
-
-
##
-
# :method: append_before_filter
-
#
-
# :call-seq: append_before_filter(names, block)
-
#
-
# Append a before filter. See _insert_callbacks for parameter details.
-
-
##
-
# :method: after_filter
-
#
-
# :call-seq: after_filter(names, block)
-
#
-
# Append an after filter. See _insert_callbacks for parameter details.
-
-
##
-
# :method: prepend_after_filter
-
#
-
# :call-seq: prepend_after_filter(names, block)
-
#
-
# Prepend an after filter. See _insert_callbacks for parameter details.
-
-
##
-
# :method: skip_after_filter
-
#
-
# :call-seq: skip_after_filter(names, block)
-
#
-
# Skip an after filter. See _insert_callbacks for parameter details.
-
-
##
-
# :method: append_after_filter
-
#
-
# :call-seq: append_after_filter(names, block)
-
#
-
# Append an after filter. See _insert_callbacks for parameter details.
-
-
##
-
# :method: around_filter
-
#
-
# :call-seq: around_filter(names, block)
-
#
-
# Append an around filter. See _insert_callbacks for parameter details.
-
-
##
-
# :method: prepend_around_filter
-
#
-
# :call-seq: prepend_around_filter(names, block)
-
#
-
# Prepend an around filter. See _insert_callbacks for parameter details.
-
-
##
-
# :method: skip_around_filter
-
#
-
# :call-seq: skip_around_filter(names, block)
-
#
-
# Skip an around filter. See _insert_callbacks for parameter details.
-
-
##
-
# :method: append_around_filter
-
#
-
# :call-seq: append_around_filter(names, block)
-
#
-
# Append an around filter. See _insert_callbacks for parameter details.
-
-
# set up before_filter, prepend_before_filter, skip_before_filter, etc.
-
# for each of before, after, and around.
-
2
[:before, :after, :around].each do |filter|
-
6
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
# Append a before, after or around filter. See _insert_callbacks
-
# for details on the allowed parameters.
-
def #{filter}_filter(*names, &blk) # def before_filter(*names, &blk)
-
_insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
-
options[:if] = (Array.wrap(options[:if]) << "!halted") if #{filter == :after} # options[:if] = (Array.wrap(options[:if]) << "!halted") if false
-
set_callback(:process_action, :#{filter}, name, options) # set_callback(:process_action, :before, name, options)
-
end # end
-
end # end
-
-
# Prepend a before, after or around filter. See _insert_callbacks
-
# for details on the allowed parameters.
-
def prepend_#{filter}_filter(*names, &blk) # def prepend_before_filter(*names, &blk)
-
_insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
-
options[:if] = (Array.wrap(options[:if]) << "!halted") if #{filter == :after} # options[:if] = (Array.wrap(options[:if]) << "!halted") if false
-
set_callback(:process_action, :#{filter}, name, options.merge(:prepend => true)) # set_callback(:process_action, :before, name, options.merge(:prepend => true))
-
end # end
-
end # end
-
-
# Skip a before, after or around filter. See _insert_callbacks
-
# for details on the allowed parameters.
-
def skip_#{filter}_filter(*names, &blk) # def skip_before_filter(*names, &blk)
-
_insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
-
skip_callback(:process_action, :#{filter}, name, options) # skip_callback(:process_action, :before, name, options)
-
end # end
-
end # end
-
-
# *_filter is the same as append_*_filter
-
alias_method :append_#{filter}_filter, :#{filter}_filter # alias_method :append_before_filter, :before_filter
-
RUBY_EVAL
-
end
-
end
-
end
-
end
-
2
require "action_dispatch/http/mime_type"
-
-
2
module AbstractController
-
2
module Collector
-
2
def self.generate_method_for_mime(mime)
-
42
sym = mime.is_a?(Symbol) ? mime : mime.to_sym
-
42
const = sym.to_s.upcase
-
42
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{sym}(*args, &block) # def html(*args, &block)
-
custom(Mime::#{const}, *args, &block) # custom(Mime::HTML, *args, &block)
-
end # end
-
RUBY
-
end
-
-
2
Mime::SET.each do |mime|
-
42
generate_method_for_mime(mime)
-
end
-
-
2
protected
-
-
2
def method_missing(symbol, &block)
-
mime_constant = Mime.const_get(symbol.to_s.upcase)
-
-
if Mime::SET.include?(mime_constant)
-
AbstractController::Collector.generate_method_for_mime(mime_constant)
-
send(symbol, &block)
-
else
-
super
-
end
-
end
-
end
-
end
-
2
require 'active_support/dependencies'
-
-
2
module AbstractController
-
2
module Helpers
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
5
class_attribute :_helpers
-
5
self._helpers = Module.new
-
-
5
class_attribute :_helper_methods
-
5
self._helper_methods = Array.new
-
end
-
-
2
module ClassMethods
-
# When a class is inherited, wrap its helper module in a new module.
-
# This ensures that the parent class's module can be changed
-
# independently of the child class's.
-
2
def inherited(klass)
-
50
helpers = _helpers
-
100
klass._helpers = Module.new { include helpers }
-
100
klass.class_eval { default_helper_module! unless anonymous? }
-
50
super
-
end
-
-
# Declare a controller method as a helper. For example, the following
-
# makes the +current_user+ controller method available to the view:
-
# class ApplicationController < ActionController::Base
-
# helper_method :current_user, :logged_in?
-
#
-
# def current_user
-
# @current_user ||= User.find_by_id(session[:user])
-
# end
-
#
-
# def logged_in?
-
# current_user != nil
-
# end
-
# end
-
#
-
# In a view:
-
# <% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>
-
#
-
# ==== Parameters
-
# * <tt>method[, method]</tt> - A name or names of a method on the controller
-
# to be made available on the view.
-
2
def helper_method(*meths)
-
14
meths.flatten!
-
14
self._helper_methods += meths
-
-
14
meths.each do |meth|
-
20
_helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1
-
def #{meth}(*args, &blk)
-
controller.send(%(#{meth}), *args, &blk)
-
end
-
ruby_eval
-
end
-
end
-
-
# The +helper+ class method can take a series of helper module names, a block, or both.
-
#
-
# ==== Parameters
-
# * <tt>*args</tt> - Module, Symbol, String, :all
-
# * <tt>block</tt> - A block defining helper methods
-
#
-
# ==== Examples
-
# When the argument is a module it will be included directly in the template class.
-
# helper FooHelper # => includes FooHelper
-
#
-
# When the argument is a string or symbol, the method will provide the "_helper" suffix, require the file
-
# and include the module in the template class. The second form illustrates how to include custom helpers
-
# when working with namespaced controllers, or other cases where the file containing the helper definition is not
-
# in one of Rails' standard load paths:
-
# helper :foo # => requires 'foo_helper' and includes FooHelper
-
# helper 'resources/foo' # => requires 'resources/foo_helper' and includes Resources::FooHelper
-
#
-
# Additionally, the +helper+ class method can receive and evaluate a block, making the methods defined available
-
# to the template.
-
#
-
# # One line
-
# helper { def hello() "Hello, world!" end }
-
#
-
# # Multi-line
-
# helper do
-
# def foo(bar)
-
# "#{bar} is the very best"
-
# end
-
# end
-
#
-
# Finally, all the above styles can be mixed together, and the +helper+ method can be invoked with a mix of
-
# +symbols+, +strings+, +modules+ and blocks.
-
#
-
# helper(:three, BlindHelper) { def mice() 'mice' end }
-
#
-
2
def helper(*args, &block)
-
63
modules_for_helpers(args).each do |mod|
-
98
add_template_helper(mod)
-
end
-
-
35
_helpers.module_eval(&block) if block_given?
-
end
-
-
# Clears up all existing helpers in this class, only keeping the helper
-
# with the same name as this class.
-
2
def clear_helpers
-
inherited_helper_methods = _helper_methods
-
self._helpers = Module.new
-
self._helper_methods = Array.new
-
-
inherited_helper_methods.each { |meth| helper_method meth }
-
default_helper_module! unless anonymous?
-
end
-
-
# Returns a list of modules, normalized from the acceptable kinds of
-
# helpers with the following behavior:
-
#
-
# String or Symbol:: :FooBar or "FooBar" becomes "foo_bar_helper",
-
# and "foo_bar_helper.rb" is loaded using require_dependency.
-
#
-
# Module:: No further processing
-
#
-
# After loading the appropriate files, the corresponding modules
-
# are returned.
-
#
-
# ==== Parameters
-
# * <tt>args</tt> - An array of helpers
-
#
-
# ==== Returns
-
# * <tt>Array</tt> - A normalized list of modules for the list of
-
# helpers provided.
-
2
def modules_for_helpers(args)
-
63
args.flatten.map! do |arg|
-
126
case arg
-
when String, Symbol
-
116
file_name = "#{arg.to_s.underscore}_helper"
-
116
require_dependency(file_name, "Missing helper file helpers/%s.rb")
-
88
file_name.camelize.constantize
-
when Module
-
10
arg
-
else
-
raise ArgumentError, "helper must be a String, Symbol, or Module"
-
end
-
end
-
end
-
-
2
private
-
# Makes all the (instance) methods in the helper module available to templates
-
# rendered through this controller.
-
#
-
# ==== Parameters
-
# * <tt>module</tt> - The module to include into the current helper module
-
# for the class
-
2
def add_template_helper(mod)
-
196
_helpers.module_eval { include mod }
-
end
-
-
2
def default_helper_module!
-
50
module_name = name.sub(/Controller$/, '')
-
50
module_path = module_name.underscore
-
50
helper module_path
-
rescue MissingSourceFile => e
-
28
raise e unless e.is_missing? "helpers/#{module_path}_helper"
-
rescue NameError => e
-
raise e unless e.missing_name? "#{module_name}Helper"
-
end
-
end
-
end
-
end
-
2
require "active_support/core_ext/module/remove_method"
-
-
2
module AbstractController
-
# Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in
-
# repeated setups. The inclusion pattern has pages that look like this:
-
#
-
# <%= render "shared/header" %>
-
# Hello World
-
# <%= render "shared/footer" %>
-
#
-
# This approach is a decent way of keeping common structures isolated from the changing content, but it's verbose
-
# and if you ever want to change the structure of these two includes, you'll have to change all the templates.
-
#
-
# With layouts, you can flip it around and have the common structure know where to insert changing content. This means
-
# that the header and footer are only mentioned in one place, like this:
-
#
-
# // The header part of this layout
-
# <%= yield %>
-
# // The footer part of this layout
-
#
-
# And then you have content pages that look like this:
-
#
-
# hello world
-
#
-
# At rendering time, the content page is computed and then inserted in the layout, like this:
-
#
-
# // The header part of this layout
-
# hello world
-
# // The footer part of this layout
-
#
-
# == Accessing shared variables
-
#
-
# Layouts have access to variables specified in the content pages and vice versa. This allows you to have layouts with
-
# references that won't materialize before rendering time:
-
#
-
# <h1><%= @page_title %></h1>
-
# <%= yield %>
-
#
-
# ...and content pages that fulfill these references _at_ rendering time:
-
#
-
# <% @page_title = "Welcome" %>
-
# Off-world colonies offers you a chance to start a new life
-
#
-
# The result after rendering is:
-
#
-
# <h1>Welcome</h1>
-
# Off-world colonies offers you a chance to start a new life
-
#
-
# == Layout assignment
-
#
-
# You can either specify a layout declaratively (using the #layout class method) or give
-
# it the same name as your controller, and place it in <tt>app/views/layouts</tt>.
-
# If a subclass does not have a layout specified, it inherits its layout using normal Ruby inheritance.
-
#
-
# For instance, if you have PostsController and a template named <tt>app/views/layouts/posts.html.erb</tt>,
-
# that template will be used for all actions in PostsController and controllers inheriting
-
# from PostsController.
-
#
-
# If you use a module, for instance Weblog::PostsController, you will need a template named
-
# <tt>app/views/layouts/weblog/posts.html.erb</tt>.
-
#
-
# Since all your controllers inherit from ApplicationController, they will use
-
# <tt>app/views/layouts/application.html.erb</tt> if no other layout is specified
-
# or provided.
-
#
-
# == Inheritance Examples
-
#
-
# class BankController < ActionController::Base
-
# # bank.html.erb exists
-
#
-
# class ExchangeController < BankController
-
# # exchange.html.erb exists
-
#
-
# class CurrencyController < BankController
-
#
-
# class InformationController < BankController
-
# layout "information"
-
#
-
# class TellerController < InformationController
-
# # teller.html.erb exists
-
#
-
# class EmployeeController < InformationController
-
# # employee.html.erb exists
-
# layout nil
-
#
-
# class VaultController < BankController
-
# layout :access_level_layout
-
#
-
# class TillController < BankController
-
# layout false
-
#
-
# In these examples, we have three implicit lookup scenrios:
-
# * The BankController uses the "bank" layout.
-
# * The ExchangeController uses the "exchange" layout.
-
# * The CurrencyController inherits the layout from BankController.
-
#
-
# However, when a layout is explicitly set, the explicitly set layout wins:
-
# * The InformationController uses the "information" layout, explicitly set.
-
# * The TellerController also uses the "information" layout, because the parent explicitly set it.
-
# * The EmployeeController uses the "employee" layout, because it set the layout to nil, resetting the parent configuration.
-
# * The VaultController chooses a layout dynamically by calling the <tt>access_level_layout</tt> method.
-
# * The TillController does not use a layout at all.
-
#
-
# == Types of layouts
-
#
-
# Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes
-
# you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can
-
# be done either by specifying a method reference as a symbol or using an inline method (as a proc).
-
#
-
# The method reference is the preferred approach to variable layouts and is used like this:
-
#
-
# class WeblogController < ActionController::Base
-
# layout :writers_and_readers
-
#
-
# def index
-
# # fetching posts
-
# end
-
#
-
# private
-
# def writers_and_readers
-
# logged_in? ? "writer_layout" : "reader_layout"
-
# end
-
#
-
# Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing
-
# is logged in or not.
-
#
-
# If you want to use an inline method, such as a proc, do something like this:
-
#
-
# class WeblogController < ActionController::Base
-
# layout proc{ |controller| controller.logged_in? ? "writer_layout" : "reader_layout" }
-
# end
-
#
-
# Of course, the most common way of specifying a layout is still just as a plain template name:
-
#
-
# class WeblogController < ActionController::Base
-
# layout "weblog_standard"
-
# end
-
#
-
# If no directory is specified for the template name, the template will by default be looked for in <tt>app/views/layouts/</tt>.
-
# Otherwise, it will be looked up relative to the template root.
-
#
-
# Setting the layout to nil forces it to be looked up in the filesystem and fallbacks to the parent behavior if none exists.
-
# Setting it to nil is useful to re-enable template lookup overriding a previous configuration set in the parent:
-
#
-
# class ApplicationController < ActionController::Base
-
# layout "application"
-
# end
-
#
-
# class PostsController < ApplicationController
-
# # Will use "application" layout
-
# end
-
#
-
# class CommentsController < ApplicationController
-
# # Will search for "comments" layout and fallback "application" layout
-
# layout nil
-
# end
-
#
-
# == Conditional layouts
-
#
-
# If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
-
# a given action or set of actions without a layout, or restricting a layout to only a single action or a set of actions. The
-
# <tt>:only</tt> and <tt>:except</tt> options can be passed to the layout call. For example:
-
#
-
# class WeblogController < ActionController::Base
-
# layout "weblog_standard", :except => :rss
-
#
-
# # ...
-
#
-
# end
-
#
-
# This will assign "weblog_standard" as the WeblogController's layout for all actions except for the +rss+ action, which will
-
# be rendered directly, without wrapping a layout around the rendered view.
-
#
-
# Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so
-
# #<tt>:except => [ :rss, :text_only ]</tt> is valid, as is <tt>:except => :rss</tt>.
-
#
-
# == Using a different layout in the action render call
-
#
-
# If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above.
-
# Sometimes you'll have exceptions where one action wants to use a different layout than the rest of the controller.
-
# You can do this by passing a <tt>:layout</tt> option to the <tt>render</tt> call. For example:
-
#
-
# class WeblogController < ActionController::Base
-
# layout "weblog_standard"
-
#
-
# def help
-
# render :action => "help", :layout => "help"
-
# end
-
# end
-
#
-
# This will override the controller-wide "weblog_standard" layout, and will render the help action with the "help" layout instead.
-
2
module Layouts
-
2
extend ActiveSupport::Concern
-
-
2
include Rendering
-
-
2
included do
-
4
class_attribute :_layout_conditions
-
4
remove_possible_method :_layout_conditions
-
4
self._layout_conditions = {}
-
4
_write_layout_method
-
end
-
-
2
delegate :_layout_conditions, :to => "self.class"
-
-
2
module ClassMethods
-
2
def inherited(klass)
-
35
super
-
35
klass._write_layout_method
-
end
-
-
# This module is mixed in if layout conditions are provided. This means
-
# that if no layout conditions are used, this method is not used
-
2
module LayoutConditions
-
# Determines whether the current action has a layout by checking the
-
# action name against the :only and :except conditions set on the
-
# layout.
-
#
-
# ==== Returns
-
# * <tt> Boolean</tt> - True if the action has a layout, false otherwise.
-
2
def conditional_layout?
-
return unless super
-
-
conditions = _layout_conditions
-
-
if only = conditions[:only]
-
only.include?(action_name)
-
elsif except = conditions[:except]
-
!except.include?(action_name)
-
else
-
true
-
end
-
end
-
end
-
-
# Specify the layout to use for this class.
-
#
-
# If the specified layout is a:
-
# String:: the String is the template name
-
# Symbol:: call the method specified by the symbol, which will return the template name
-
# false:: There is no layout
-
# true:: raise an ArgumentError
-
# nil:: Force default layout behavior with inheritance
-
#
-
# ==== Parameters
-
# * <tt>layout</tt> - The layout to use.
-
#
-
# ==== Options (conditions)
-
# * :only - A list of actions to apply this layout to.
-
# * :except - Apply this layout to all actions but this one.
-
2
def layout(layout, conditions = {})
-
include LayoutConditions unless conditions.empty?
-
-
conditions.each {|k, v| conditions[k] = Array(v).map {|a| a.to_s} }
-
self._layout_conditions = conditions
-
-
@_layout = layout
-
_write_layout_method
-
end
-
-
# If no layout is supplied, look for a template named the return
-
# value of this method.
-
#
-
# ==== Returns
-
# * <tt>String</tt> - A template name
-
2
def _implied_layout_name
-
78
controller_path
-
end
-
-
# Creates a _layout method to be called by _default_layout .
-
#
-
# If a layout is not explicitly mentioned then look for a layout with the controller's name.
-
# if nothing is found then try same procedure to find super class's layout.
-
2
def _write_layout_method
-
39
remove_possible_method(:_layout)
-
-
39
prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"]
-
39
name_clause = if name
-
<<-RUBY
-
39
lookup_context.find_all("#{_implied_layout_name}", #{prefixes.inspect}).first || super
-
RUBY
-
end
-
-
39
if defined?(@_layout)
-
layout_definition = case @_layout
-
when String
-
@_layout.inspect
-
when Symbol
-
<<-RUBY
-
#{@_layout}.tap do |layout|
-
unless layout.is_a?(String) || !layout
-
raise ArgumentError, "Your layout method :#{@_layout} returned \#{layout}. It " \
-
"should have returned a String, false, or nil"
-
end
-
end
-
RUBY
-
when Proc
-
define_method :_layout_from_proc, &@_layout
-
"_layout_from_proc(self)"
-
when false
-
nil
-
when true
-
raise ArgumentError, "Layouts must be specified as a String, Symbol, false, or nil"
-
when nil
-
name_clause
-
end
-
else
-
# Add a deprecation if the parent layout was explicitly set and the child
-
# still does a dynamic lookup. In next Rails release, we should @_layout
-
# to be inheritable so we can skip the child lookup if the parent explicitly
-
# set the layout.
-
78
parent = self.superclass.instance_eval { @_layout if defined?(@_layout) }
-
39
@_layout = nil
-
39
inspect = parent.is_a?(Proc) ? parent.inspect : parent
-
-
39
layout_definition = if parent.nil?
-
39
name_clause
-
elsif name
-
<<-RUBY
-
if template = lookup_context.find_all("#{_implied_layout_name}", #{prefixes.inspect}).first
-
ActiveSupport::Deprecation.warn 'Layout found at "#{_implied_layout_name}" for #{name} but parent controller ' \
-
'set layout to #{inspect.inspect}. Please explicitly set your layout to "#{_implied_layout_name}" ' \
-
'or set it to nil to force a dynamic lookup.'
-
template
-
else
-
super
-
end
-
RUBY
-
end
-
end
-
-
39
self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def _layout
-
if conditional_layout?
-
#{layout_definition}
-
else
-
#{name_clause}
-
end
-
end
-
private :_layout
-
RUBY
-
end
-
end
-
-
2
def _normalize_options(options)
-
4
super
-
-
4
if _include_layout?(options)
-
4
layout = options.key?(:layout) ? options.delete(:layout) : :default
-
4
options[:layout] = _layout_for_option(layout)
-
end
-
end
-
-
2
attr_internal_writer :action_has_layout
-
-
2
def initialize(*)
-
56
@_action_has_layout = true
-
56
super
-
end
-
-
2
def action_has_layout?
-
4
@_action_has_layout
-
end
-
-
2
def conditional_layout?
-
8
true
-
end
-
-
2
private
-
-
# This will be overwritten by _write_layout_method
-
2
def _layout; end
-
-
# Determine the layout for a given name, taking into account the name type.
-
#
-
# ==== Parameters
-
# * <tt>name</tt> - The name of the template
-
2
def _layout_for_option(name)
-
4
case name
-
when String then _normalize_layout(name)
-
when Proc then name
-
when true then Proc.new { _default_layout(true) }
-
8
when :default then Proc.new { _default_layout(false) }
-
when false, nil then nil
-
else
-
raise ArgumentError,
-
"String, true, or false, expected for `layout'; you passed #{name.inspect}"
-
end
-
end
-
-
2
def _normalize_layout(value)
-
4
value.is_a?(String) && value !~ /\blayouts/ ? "layouts/#{value}" : value
-
end
-
-
# Returns the default layout for this controller.
-
# Optionally raises an exception if the layout could not be found.
-
#
-
# ==== Parameters
-
# * <tt>require_layout</tt> - If set to true and layout is not found,
-
# an ArgumentError exception is raised (defaults to false)
-
#
-
# ==== Returns
-
# * <tt>template</tt> - The template object for the default layout (or nil)
-
2
def _default_layout(require_layout = false)
-
4
begin
-
4
value = _layout if action_has_layout?
-
rescue NameError => e
-
raise e, "Could not render layout: #{e.message}"
-
end
-
-
4
if require_layout && action_has_layout? && !value
-
raise ArgumentError,
-
"There was no default layout for #{self.class} in #{view_paths.inspect}"
-
end
-
-
4
_normalize_layout(value)
-
end
-
-
2
def _include_layout?(options)
-
4
(options.keys & [:text, :inline, :partial]).empty? || options.key?(:layout)
-
end
-
end
-
end
-
2
require "active_support/core_ext/logger"
-
2
require "active_support/benchmarkable"
-
-
2
module AbstractController
-
2
module Logger
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
4
config_accessor :logger
-
4
include ActiveSupport::Benchmarkable
-
end
-
end
-
end
-
2
module AbstractController
-
2
module Railties
-
2
module RoutesHelpers
-
2
def self.with(routes)
-
4
Module.new do
-
4
define_method(:inherited) do |klass|
-
35
super(klass)
-
72
if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_routes_url_helpers) }
-
klass.send(:include, namespace.railtie_routes_url_helpers)
-
else
-
35
klass.send(:include, routes.url_helpers)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require "abstract_controller/base"
-
2
require "action_view"
-
2
require "active_support/core_ext/object/instance_variables"
-
-
2
module AbstractController
-
2
class DoubleRenderError < Error
-
2
DEFAULT_MESSAGE = "Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like \"redirect_to(...) and return\"."
-
-
2
def initialize(message = nil)
-
super(message || DEFAULT_MESSAGE)
-
end
-
end
-
-
# This is a class to fix I18n global state. Whenever you provide I18n.locale during a request,
-
# it will trigger the lookup_context and consequently expire the cache.
-
2
class I18nProxy < ::I18n::Config #:nodoc:
-
2
attr_reader :original_config, :lookup_context
-
-
2
def initialize(original_config, lookup_context)
-
13
original_config = original_config.original_config if original_config.respond_to?(:original_config)
-
13
@original_config, @lookup_context = original_config, lookup_context
-
end
-
-
2
def locale
-
@original_config.locale
-
end
-
-
2
def locale=(value)
-
@lookup_context.locale = value
-
end
-
end
-
-
2
module Rendering
-
2
extend ActiveSupport::Concern
-
2
include AbstractController::ViewPaths
-
-
2
included do
-
4
class_attribute :protected_instance_variables
-
4
self.protected_instance_variables = []
-
end
-
-
# Overwrite process to setup I18n proxy.
-
2
def process(*) #:nodoc:
-
13
old_config, I18n.config = I18n.config, I18nProxy.new(I18n.config, lookup_context)
-
13
super
-
ensure
-
13
I18n.config = old_config
-
end
-
-
2
module ClassMethods
-
2
def view_context_class
-
@view_context_class ||= begin
-
1
routes = _routes if respond_to?(:_routes)
-
1
helpers = _helpers if respond_to?(:_helpers)
-
1
ActionView::Base.prepare(routes, helpers)
-
4
end
-
end
-
end
-
-
2
attr_internal_writer :view_context_class
-
-
2
def view_context_class
-
4
@_view_context_class ||= self.class.view_context_class
-
end
-
-
# An instance of a view class. The default view class is ActionView::Base
-
#
-
# The view class must have the following methods:
-
# View.new[lookup_context, assigns, controller]
-
# Create a new ActionView instance for a controller
-
# View#render[options]
-
# Returns String with the rendered template
-
#
-
# Override this method in a module to change the default behavior.
-
2
def view_context
-
4
view_context_class.new(view_renderer, view_assigns, self)
-
end
-
-
# Returns an object that is able to render templates.
-
2
def view_renderer
-
8
@_view_renderer ||= ActionView::Renderer.new(lookup_context)
-
end
-
-
# Normalize arguments, options and then delegates render_to_body and
-
# sticks the result in self.response_body.
-
2
def render(*args, &block)
-
4
options = _normalize_render(*args, &block)
-
4
self.response_body = render_to_body(options)
-
end
-
-
# Raw rendering of a template to a string. Just convert the results of
-
# render_response into a String.
-
# :api: plugin
-
2
def render_to_string(*args, &block)
-
options = _normalize_render(*args, &block)
-
render_to_body(options)
-
end
-
-
# Raw rendering of a template to a Rack-compatible body.
-
# :api: plugin
-
2
def render_to_body(options = {})
-
4
_process_options(options)
-
4
_render_template(options)
-
end
-
-
# Find and renders a template based on the options given.
-
# :api: private
-
2
def _render_template(options) #:nodoc:
-
4
lookup_context.rendered_format = nil if options[:formats]
-
4
view_renderer.render(view_context, options)
-
end
-
-
2
DEFAULT_PROTECTED_INSTANCE_VARIABLES = %w(
-
@_action_name @_response_body @_formats @_prefixes @_config
-
@_view_context_class @_view_renderer @_lookup_context
-
)
-
-
# This method should return a hash with assigns.
-
# You can overwrite this configuration per controller.
-
# :api: public
-
2
def view_assigns
-
14
hash = {}
-
14
variables = instance_variable_names
-
14
variables -= protected_instance_variables
-
14
variables -= DEFAULT_PROTECTED_INSTANCE_VARIABLES
-
40
variables.each { |name| hash[name.to_s[1, name.length]] = instance_variable_get(name) }
-
14
hash
-
end
-
-
2
private
-
-
# Normalize args and options.
-
# :api: private
-
2
def _normalize_render(*args, &block)
-
4
options = _normalize_args(*args, &block)
-
4
_normalize_options(options)
-
4
options
-
end
-
-
# Normalize args by converting render "foo" to render :action => "foo" and
-
# render "foo/bar" to render :file => "foo/bar".
-
# :api: plugin
-
2
def _normalize_args(action=nil, options={})
-
4
case action
-
when NilClass
-
when Hash
-
4
options = action
-
when String, Symbol
-
action = action.to_s
-
key = action.include?(?/) ? :file : :action
-
options[key] = action
-
else
-
options[:partial] = action
-
end
-
-
4
options
-
end
-
-
# Normalize options.
-
# :api: plugin
-
2
def _normalize_options(options)
-
4
if options[:partial] == true
-
options[:partial] = action_name
-
end
-
-
4
if (options.keys & [:partial, :file, :template]).empty?
-
options[:prefixes] ||= _prefixes
-
end
-
-
4
options[:template] ||= (options[:action] || action_name).to_s
-
4
options
-
end
-
-
# Process extra options.
-
# :api: plugin
-
2
def _process_options(options)
-
end
-
end
-
end
-
2
module AbstractController
-
2
module Translation
-
2
def translate(*args)
-
I18n.translate(*args)
-
end
-
2
alias :t :translate
-
-
2
def localize(*args)
-
I18n.localize(*args)
-
end
-
2
alias :l :localize
-
end
-
end
-
# Includes +url_for+ into the host class (e.g. an abstract controller or mailer). The class
-
# has to provide a +RouteSet+ by implementing the <tt>_routes</tt> methods. Otherwise, an
-
# exception will be raised.
-
#
-
# Note that this module is completely decoupled from HTTP - the only requirement is a valid
-
# <tt>_routes</tt> implementation.
-
2
module AbstractController
-
2
module UrlFor
-
2
extend ActiveSupport::Concern
-
2
include ActionDispatch::Routing::UrlFor
-
-
2
def _routes
-
raise "In order to use #url_for, you must include routing helpers explicitly. " \
-
"For instance, `include Rails.application.routes.url_helpers"
-
end
-
-
2
module ClassMethods
-
2
def _routes
-
nil
-
end
-
-
2
def action_methods
-
@action_methods ||= begin
-
16
if _routes
-
10
super - _routes.named_routes.helper_names
-
else
-
6
super
-
end
-
65
end
-
end
-
end
-
end
-
end
-
2
require 'action_view/base'
-
-
2
module AbstractController
-
2
module ViewPaths
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
4
class_attribute :_view_paths
-
4
self._view_paths = ActionView::PathSet.new
-
4
self._view_paths.freeze
-
end
-
-
2
delegate :template_exists?, :view_paths, :formats, :formats=,
-
:locale, :locale=, :to => :lookup_context
-
-
2
module ClassMethods
-
2
def parent_prefixes
-
@parent_prefixes ||= begin
-
4
parent_controller = superclass
-
4
prefixes = []
-
-
4
until parent_controller.abstract?
-
3
prefixes << parent_controller.controller_path
-
3
parent_controller = parent_controller.superclass
-
end
-
-
4
prefixes
-
14
end
-
end
-
end
-
-
# The prefixes used in render "foo" shortcuts.
-
2
def _prefixes
-
@_prefixes ||= begin
-
14
parent_prefixes = self.class.parent_prefixes
-
14
parent_prefixes.dup.unshift(controller_path)
-
14
end
-
end
-
-
# LookupContext is the object responsible to hold all information required to lookup
-
# templates, i.e. view paths and details. Check ActionView::LookupContext for more
-
# information.
-
2
def lookup_context
-
@_lookup_context ||=
-
47
ActionView::LookupContext.new(self.class._view_paths, details_for_lookup, _prefixes)
-
end
-
-
2
def details_for_lookup
-
14
{ }
-
end
-
-
2
def append_view_path(path)
-
lookup_context.view_paths.push(*path)
-
end
-
-
2
def prepend_view_path(path)
-
lookup_context.view_paths.unshift(*path)
-
end
-
-
2
module ClassMethods
-
# Append a path to the list of view paths for this controller.
-
#
-
# ==== Parameters
-
# * <tt>path</tt> - If a String is provided, it gets converted into
-
# the default view path. You may also provide a custom view path
-
# (see ActionView::PathSet for more information)
-
2
def append_view_path(path)
-
self._view_paths = view_paths + Array(path)
-
end
-
-
# Prepend a path to the list of view paths for this controller.
-
#
-
# ==== Parameters
-
# * <tt>path</tt> - If a String is provided, it gets converted into
-
# the default view path. You may also provide a custom view path
-
# (see ActionView::PathSet for more information)
-
2
def prepend_view_path(path)
-
8
self._view_paths = ActionView::PathSet.new(Array(path) + view_paths)
-
end
-
-
# A list of all of the default view paths for this controller.
-
2
def view_paths
-
8
_view_paths
-
end
-
-
# Set the view paths.
-
#
-
# ==== Parameters
-
# * <tt>paths</tt> - If a PathSet is provided, use that;
-
# otherwise, process the parameter into a PathSet.
-
2
def view_paths=(paths)
-
self._view_paths = ActionView::PathSet.new(Array.wrap(paths))
-
end
-
end
-
end
-
end
-
2
require 'abstract_controller'
-
2
require 'action_dispatch'
-
-
2
module ActionController
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Base
-
2
autoload :Caching
-
2
autoload :Metal
-
2
autoload :Middleware
-
-
2
autoload_under "metal" do
-
2
autoload :Compatibility
-
2
autoload :ConditionalGet
-
2
autoload :Cookies
-
2
autoload :DataStreaming
-
2
autoload :Flash
-
2
autoload :ForceSSL
-
2
autoload :Head
-
2
autoload :Helpers
-
2
autoload :HideActions
-
2
autoload :HttpAuthentication
-
2
autoload :ImplicitRender
-
2
autoload :Instrumentation
-
2
autoload :MimeResponds
-
2
autoload :ParamsWrapper
-
2
autoload :RackDelegation
-
2
autoload :Redirecting
-
2
autoload :Renderers
-
2
autoload :Rendering
-
2
autoload :RequestForgeryProtection
-
2
autoload :Rescue
-
2
autoload :Responder
-
2
autoload :SessionManagement
-
2
autoload :Streaming
-
2
autoload :Testing
-
2
autoload :UrlFor
-
end
-
-
2
autoload :Integration, 'action_controller/deprecated/integration_test'
-
2
autoload :IntegrationTest, 'action_controller/deprecated/integration_test'
-
2
autoload :PerformanceTest, 'action_controller/deprecated/performance_test'
-
2
autoload :UrlWriter, 'action_controller/deprecated'
-
2
autoload :Routing, 'action_controller/deprecated'
-
2
autoload :TestCase, 'action_controller/test_case'
-
2
autoload :TemplateAssertions, 'action_controller/test_case'
-
-
2
eager_autoload do
-
2
autoload :RecordIdentifier
-
end
-
end
-
-
# All of these simply register additional autoloads
-
2
require 'action_view'
-
2
require 'action_controller/vendor/html-scanner'
-
-
# Common Active Support usage in Action Controller
-
2
require 'active_support/concern'
-
2
require 'active_support/core_ext/class/attribute_accessors'
-
2
require 'active_support/core_ext/load_error'
-
2
require 'active_support/core_ext/module/attr_internal'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/name_error'
-
2
require 'active_support/core_ext/uri'
-
2
require 'active_support/inflector'
-
2
require "action_controller/log_subscriber"
-
-
2
module ActionController
-
# Action Controllers are the core of a web request in \Rails. They are made up of one or more actions that are executed
-
# on request and then either render a template or redirect to another action. An action is defined as a public method
-
# on the controller, which will automatically be made accessible to the web-server through \Rails Routes.
-
#
-
# By default, only the ApplicationController in a \Rails application inherits from <tt>ActionController::Base</tt>. All other
-
# controllers in turn inherit from ApplicationController. This gives you one class to configure things such as
-
# request forgery protection and filtering of sensitive request parameters.
-
#
-
# A sample controller could look like this:
-
#
-
# class PostsController < ApplicationController
-
# def index
-
# @posts = Post.all
-
# end
-
#
-
# def create
-
# @post = Post.create params[:post]
-
# redirect_to posts_path
-
# end
-
# end
-
#
-
# Actions, by default, render a template in the <tt>app/views</tt> directory corresponding to the name of the controller and action
-
# after executing code in the action. For example, the +index+ action of the PostsController would render the
-
# template <tt>app/views/posts/index.html.erb</tt> by default after populating the <tt>@posts</tt> instance variable.
-
#
-
# Unlike index, the create action will not render a template. After performing its main purpose (creating a
-
# new post), it initiates a redirect instead. This redirect works by returning an external
-
# "302 Moved" HTTP response that takes the user to the index action.
-
#
-
# These two methods represent the two basic action archetypes used in Action Controllers. Get-and-show and do-and-redirect.
-
# Most actions are variations on these themes.
-
#
-
# == Requests
-
#
-
# For every request, the router determines the value of the +controller+ and +action+ keys. These determine which controller
-
# and action are called. The remaining request parameters, the session (if one is available), and the full request with
-
# all the HTTP headers are made available to the action through accessor methods. Then the action is performed.
-
#
-
# The full request object is available via the request accessor and is primarily used to query for HTTP headers:
-
#
-
# def server_ip
-
# location = request.env["SERVER_ADDR"]
-
# render :text => "This server hosted at #{location}"
-
# end
-
#
-
# == Parameters
-
#
-
# All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params method
-
# which returns a hash. For example, an action that was performed through <tt>/posts?category=All&limit=5</tt> will include
-
# <tt>{ "category" => "All", "limit" => "5" }</tt> in params.
-
#
-
# It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
-
#
-
# <input type="text" name="post[name]" value="david">
-
# <input type="text" name="post[address]" value="hyacintvej">
-
#
-
# A request stemming from a form holding these inputs will include <tt>{ "post" => { "name" => "david", "address" => "hyacintvej" } }</tt>.
-
# If the address input had been named "post[address][street]", the params would have included
-
# <tt>{ "post" => { "address" => { "street" => "hyacintvej" } } }</tt>. There's no limit to the depth of the nesting.
-
#
-
# == Sessions
-
#
-
# Sessions allow you to store objects in between requests. This is useful for objects that are not yet ready to be persisted,
-
# such as a Signup object constructed in a multi-paged process, or objects that don't change much and are needed all the time, such
-
# as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it's likely
-
# they could be changed unknowingly. It's usually too much work to keep it all synchronized -- something databases already excel at.
-
#
-
# You can place objects in the session by using the <tt>session</tt> method, which accesses a hash:
-
#
-
# session[:person] = Person.authenticate(user_name, password)
-
#
-
# And retrieved again through the same hash:
-
#
-
# Hello #{session[:person]}
-
#
-
# For removing objects from the session, you can either assign a single key to +nil+:
-
#
-
# # removes :person from session
-
# session[:person] = nil
-
#
-
# or you can remove the entire session with +reset_session+.
-
#
-
# Sessions are stored by default in a browser cookie that's cryptographically signed, but unencrypted.
-
# This prevents the user from tampering with the session but also allows him to see its contents.
-
#
-
# Do not put secret information in cookie-based sessions!
-
#
-
# Other options for session storage:
-
#
-
# * ActiveRecord::SessionStore - Sessions are stored in your database, which works better than PStore with multiple app servers and,
-
# unlike CookieStore, hides your session contents from the user. To use ActiveRecord::SessionStore, set
-
#
-
# MyApplication::Application.config.session_store :active_record_store
-
#
-
# in your <tt>config/initializers/session_store.rb</tt> and run <tt>script/rails g session_migration</tt>.
-
#
-
# == Responses
-
#
-
# Each action results in a response, which holds the headers and document to be sent to the user's browser. The actual response
-
# object is generated automatically through the use of renders and redirects and requires no user intervention.
-
#
-
# == Renders
-
#
-
# Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering
-
# of a template. Included in the Action Pack is the Action View, which enables rendering of ERB templates. It's automatically configured.
-
# The controller passes objects to the view by assigning instance variables:
-
#
-
# def show
-
# @post = Post.find(params[:id])
-
# end
-
#
-
# Which are then automatically available to the view:
-
#
-
# Title: <%= @post.title %>
-
#
-
# You don't have to rely on the automated rendering. For example, actions that could result in the rendering of different templates
-
# will use the manual rendering methods:
-
#
-
# def search
-
# @results = Search.find(params[:query])
-
# case @results.count
-
# when 0 then render :action => "no_results"
-
# when 1 then render :action => "show"
-
# when 2..10 then render :action => "show_many"
-
# end
-
# end
-
#
-
# Read more about writing ERB and Builder templates in ActionView::Base.
-
#
-
# == Redirects
-
#
-
# Redirects are used to move from one action to another. For example, after a <tt>create</tt> action, which stores a blog entry to the
-
# database, we might like to show the user the new entry. Because we're following good DRY principles (Don't Repeat Yourself), we're
-
# going to reuse (and redirect to) a <tt>show</tt> action that we'll assume has already been created. The code might look like this:
-
#
-
# def create
-
# @entry = Entry.new(params[:entry])
-
# if @entry.save
-
# # The entry was saved correctly, redirect to show
-
# redirect_to :action => 'show', :id => @entry.id
-
# else
-
# # things didn't go so well, do something else
-
# end
-
# end
-
#
-
# In this case, after saving our new entry to the database, the user is redirected to the <tt>show</tt> method, which is then executed.
-
# Note that this is an external HTTP-level redirection which will cause the browser to make a second request (a GET to the show action),
-
# and not some internal re-routing which calls both "create" and then "show" within one request.
-
#
-
# Learn more about <tt>redirect_to</tt> and what options you have in ActionController::Redirecting.
-
#
-
# == Calling multiple redirects or renders
-
#
-
# An action may contain only a single render or a single redirect. Attempting to try to do either again will result in a DoubleRenderError:
-
#
-
# def do_something
-
# redirect_to :action => "elsewhere"
-
# render :action => "overthere" # raises DoubleRenderError
-
# end
-
#
-
# If you need to redirect on the condition of something, then be sure to add "and return" to halt execution.
-
#
-
# def do_something
-
# redirect_to(:action => "elsewhere") and return if monkeys.nil?
-
# render :action => "overthere" # won't be called if monkeys is nil
-
# end
-
#
-
2
class Base < Metal
-
2
abstract!
-
-
2
def self.without_modules(*modules)
-
modules = modules.map do |m|
-
m.is_a?(Symbol) ? ActionController.const_get(m) : m
-
end
-
-
MODULES - modules
-
end
-
-
2
MODULES = [
-
AbstractController::Layouts,
-
AbstractController::Translation,
-
AbstractController::AssetPaths,
-
-
Helpers,
-
HideActions,
-
UrlFor,
-
Redirecting,
-
Rendering,
-
Renderers::All,
-
ConditionalGet,
-
RackDelegation,
-
Caching,
-
MimeResponds,
-
ImplicitRender,
-
-
Cookies,
-
Flash,
-
RequestForgeryProtection,
-
ForceSSL,
-
Streaming,
-
DataStreaming,
-
RecordIdentifier,
-
HttpAuthentication::Basic::ControllerMethods,
-
HttpAuthentication::Digest::ControllerMethods,
-
HttpAuthentication::Token::ControllerMethods,
-
-
# Before callbacks should also be executed the earliest as possible, so
-
# also include them at the bottom.
-
AbstractController::Callbacks,
-
-
# Append rescue at the bottom to wrap as much as possible.
-
Rescue,
-
-
# Add instrumentations hooks at the bottom, to ensure they instrument
-
# all the methods properly.
-
Instrumentation,
-
-
# Params wrapper should come before instrumentation so they are
-
# properly showed in logs
-
ParamsWrapper
-
]
-
-
2
MODULES.each do |mod|
-
56
include mod
-
end
-
-
# Rails 2.x compatibility
-
2
include ActionController::Compatibility
-
-
2
ActiveSupport.run_load_hooks(:action_controller, self)
-
end
-
end
-
2
require 'fileutils'
-
2
require 'uri'
-
2
require 'set'
-
-
2
module ActionController #:nodoc:
-
# \Caching is a cheap way of speeding up slow applications by keeping the result of
-
# calculations, renderings, and database calls around for subsequent requests.
-
# Action Controller affords you three approaches in varying levels of granularity:
-
# Page, Action, Fragment.
-
#
-
# You can read more about each approach and the sweeping assistance by clicking the
-
# modules below.
-
#
-
# Note: To turn off all caching and sweeping, set
-
# config.action_controller.perform_caching = false.
-
#
-
# == \Caching stores
-
#
-
# All the caching stores from ActiveSupport::Cache are available to be used as backends
-
# for Action Controller caching. This setting only affects action and fragment caching
-
# as page caching is always written to disk.
-
#
-
# Configuration examples (MemoryStore is the default):
-
#
-
# config.action_controller.cache_store = :memory_store
-
# config.action_controller.cache_store = :file_store, "/path/to/cache/directory"
-
# config.action_controller.cache_store = :mem_cache_store, "localhost"
-
# config.action_controller.cache_store = :mem_cache_store, Memcached::Rails.new("localhost:11211")
-
# config.action_controller.cache_store = MyOwnStore.new("parameter")
-
2
module Caching
-
2
extend ActiveSupport::Concern
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :Actions
-
2
autoload :Fragments
-
2
autoload :Pages
-
2
autoload :Sweeper, 'action_controller/caching/sweeping'
-
2
autoload :Sweeping, 'action_controller/caching/sweeping'
-
end
-
-
2
module ConfigMethods
-
2
def cache_store
-
2
config.cache_store
-
end
-
-
2
def cache_store=(store)
-
2
config.cache_store = ActiveSupport::Cache.lookup_store(store)
-
end
-
-
2
private
-
-
2
def cache_configured?
-
perform_caching && cache_store
-
end
-
end
-
-
2
include RackDelegation
-
2
include AbstractController::Callbacks
-
-
2
include ConfigMethods
-
2
include Pages, Actions, Fragments
-
2
include Sweeping if defined?(ActiveRecord)
-
-
2
included do
-
2
extend ConfigMethods
-
-
2
config_accessor :perform_caching
-
2
self.perform_caching = true if perform_caching.nil?
-
end
-
-
2
def caching_allowed?
-
request.get? && response.status == 200
-
end
-
-
2
protected
-
# Convenience accessor
-
2
def cache(key, options = {}, &block)
-
if cache_configured?
-
cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block)
-
else
-
yield
-
end
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module ActionController #:nodoc:
-
2
module Caching
-
# Action caching is similar to page caching by the fact that the entire
-
# output of the response is cached, but unlike page caching, every
-
# request still goes through Action Pack. The key benefit of this is
-
# that filters run before the cache is served, which allows for
-
# authentication and other restrictions on whether someone is allowed
-
# to execute such action. Example:
-
#
-
# class ListsController < ApplicationController
-
# before_filter :authenticate, :except => :public
-
#
-
# caches_page :public
-
# caches_action :index, :show
-
# end
-
#
-
# In this example, the +public+ action doesn't require authentication
-
# so it's possible to use the faster page caching. On the other hand
-
# +index+ and +show+ require authentication. They can still be cached,
-
# but we need action caching for them.
-
#
-
# Action caching uses fragment caching internally and an around
-
# filter to do the job. The fragment cache is named according to
-
# the host and path of the request. A page that is accessed at
-
# <tt>http://david.example.com/lists/show/1</tt> will result in a fragment named
-
# <tt>david.example.com/lists/show/1</tt>. This allows the cacher to
-
# differentiate between <tt>david.example.com/lists/</tt> and
-
# <tt>jamis.example.com/lists/</tt> -- which is a helpful way of assisting
-
# the subdomain-as-account-key pattern.
-
#
-
# Different representations of the same resource, e.g.
-
# <tt>http://david.example.com/lists</tt> and
-
# <tt>http://david.example.com/lists.xml</tt>
-
# are treated like separate requests and so are cached separately.
-
# Keep in mind when expiring an action cache that
-
# <tt>:action => 'lists'</tt> is not the same as
-
# <tt>:action => 'list', :format => :xml</tt>.
-
#
-
# You can modify the default action cache path by passing a
-
# <tt>:cache_path</tt> option. This will be passed directly to
-
# <tt>ActionCachePath.path_for</tt>. This is handy for actions with
-
# multiple possible routes that should be cached differently. If a
-
# block is given, it is called with the current controller instance.
-
#
-
# And you can also use <tt>:if</tt> (or <tt>:unless</tt>) to pass a
-
# proc that specifies when the action should be cached.
-
#
-
# Finally, if you are using memcached, you can also pass <tt>:expires_in</tt>.
-
#
-
# The following example depicts some of the points made above:
-
#
-
# class ListsController < ApplicationController
-
# before_filter :authenticate, :except => :public
-
#
-
# caches_page :public
-
#
-
# caches_action :index, :if => proc do
-
# !request.format.json? # cache if is not a JSON request
-
# end
-
#
-
# caches_action :show, :cache_path => { :project => 1 },
-
# :expires_in => 1.hour
-
#
-
# caches_action :feed, :cache_path => proc do
-
# if params[:user_id]
-
# user_list_url(params[:user_id, params[:id])
-
# else
-
# list_url(params[:id])
-
# end
-
# end
-
# end
-
#
-
# If you pass <tt>:layout => false</tt>, it will only cache your action
-
# content. That's useful when your layout has dynamic information.
-
#
-
# Warning: If the format of the request is determined by the Accept HTTP
-
# header the Content-Type of the cached response could be wrong because
-
# no information about the MIME type is stored in the cache key. So, if
-
# you first ask for MIME type M in the Accept header, a cache entry is
-
# created, and then perform a second request to the same resource asking
-
# for a different MIME type, you'd get the content cached for M.
-
#
-
# The <tt>:format</tt> parameter is taken into account though. The safest
-
# way to cache by MIME type is to pass the format in the route.
-
2
module Actions
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
# Declares that +actions+ should be cached.
-
# See ActionController::Caching::Actions for details.
-
2
def caches_action(*actions)
-
return unless cache_configured?
-
options = actions.extract_options!
-
options[:layout] = true unless options.key?(:layout)
-
filter_options = options.extract!(:if, :unless).merge(:only => actions)
-
cache_options = options.extract!(:layout, :cache_path).merge(:store_options => options)
-
-
around_filter ActionCacheFilter.new(cache_options), filter_options
-
end
-
end
-
-
2
def _save_fragment(name, options)
-
content = ""
-
response_body.each do |parts|
-
content << parts
-
end
-
-
if caching_allowed?
-
write_fragment(name, content, options)
-
else
-
content
-
end
-
end
-
-
2
protected
-
2
def expire_action(options = {})
-
return unless cache_configured?
-
-
if options.is_a?(Hash) && options[:action].is_a?(Array)
-
options[:action].each {|action| expire_action(options.merge(:action => action)) }
-
else
-
expire_fragment(ActionCachePath.new(self, options, false).path)
-
end
-
end
-
-
2
class ActionCacheFilter #:nodoc:
-
2
def initialize(options, &block)
-
@cache_path, @store_options, @cache_layout =
-
options.values_at(:cache_path, :store_options, :layout)
-
end
-
-
2
def filter(controller)
-
path_options = if @cache_path.respond_to?(:call)
-
controller.instance_exec(controller, &@cache_path)
-
else
-
@cache_path
-
end
-
-
cache_path = ActionCachePath.new(controller, path_options || {})
-
-
body = controller.read_fragment(cache_path.path, @store_options)
-
-
unless body
-
controller.action_has_layout = false unless @cache_layout
-
yield
-
controller.action_has_layout = true
-
body = controller._save_fragment(cache_path.path, @store_options)
-
end
-
-
body = controller.render_to_string(:text => body, :layout => true) unless @cache_layout
-
-
controller.response_body = body
-
controller.content_type = Mime[cache_path.extension || :html]
-
end
-
end
-
-
2
class ActionCachePath
-
2
attr_reader :path, :extension
-
-
# If +infer_extension+ is true, the cache path extension is looked up from the request's
-
# path and format. This is desirable when reading and writing the cache, but not when
-
# expiring the cache - expire_action should expire the same files regardless of the
-
# request format.
-
2
def initialize(controller, options = {}, infer_extension = true)
-
if infer_extension
-
@extension = controller.params[:format]
-
options.reverse_merge!(:format => @extension) if options.is_a?(Hash)
-
end
-
-
path = controller.url_for(options).split(%r{://}).last
-
@path = normalize!(path)
-
end
-
-
2
private
-
2
def normalize!(path)
-
path << 'index' if path[-1] == ?/
-
path << ".#{extension}" if extension and !path.split('?').first.ends_with?(".#{extension}")
-
URI.parser.unescape(path)
-
end
-
end
-
end
-
end
-
end
-
2
module ActionController #:nodoc:
-
2
module Caching
-
# Fragment caching is used for caching various blocks within
-
# views without caching the entire action as a whole. This is
-
# useful when certain elements of an action change frequently or
-
# depend on complicated state while other parts rarely change or
-
# can be shared amongst multiple parties. The caching is done using
-
# the <tt>cache</tt> helper available in the Action View. A
-
# template with fragment caching might look like:
-
#
-
# <b>Hello <%= @name %></b>
-
#
-
# <% cache do %>
-
# All the topics in the system:
-
# <%= render :partial => "topic", :collection => Topic.all %>
-
# <% end %>
-
#
-
# This cache will bind the name of the action that called it, so if
-
# this code was part of the view for the topics/list action, you
-
# would be able to invalidate it using:
-
#
-
# expire_fragment(:controller => "topics", :action => "list")
-
#
-
# This default behavior is limited if you need to cache multiple
-
# fragments per action or if the action itself is cached using
-
# <tt>caches_action</tt>. To remedy this, there is an option to
-
# qualify the name of the cached fragment by using the
-
# <tt>:action_suffix</tt> option:
-
#
-
# <% cache(:action => "list", :action_suffix => "all_topics") do %>
-
#
-
# That would result in a name such as
-
# <tt>/topics/list/all_topics</tt>, avoiding conflicts with the
-
# action cache and with any fragments that use a different suffix.
-
# Note that the URL doesn't have to really exist or be callable
-
# - the url_for system is just used to generate unique cache names
-
# that we can refer to when we need to expire the cache.
-
#
-
# The expiration call for this example is:
-
#
-
# expire_fragment(:controller => "topics",
-
# :action => "list",
-
# :action_suffix => "all_topics")
-
2
module Fragments
-
# Given a key (as described in <tt>expire_fragment</tt>), returns
-
# a key suitable for use in reading, writing, or expiring a
-
# cached fragment. If the key is a hash, the generated key is the
-
# return value of url_for on that hash (without the protocol).
-
# All keys are prefixed with <tt>views/</tt> and uses
-
# ActiveSupport::Cache.expand_cache_key for the expansion.
-
2
def fragment_cache_key(key)
-
ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
-
end
-
-
# Writes <tt>content</tt> to the location signified by
-
# <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats).
-
2
def write_fragment(key, content, options = nil)
-
return content unless cache_configured?
-
-
key = fragment_cache_key(key)
-
instrument_fragment_cache :write_fragment, key do
-
content = content.to_str
-
cache_store.write(key, content, options)
-
end
-
content
-
end
-
-
# Reads a cached fragment from the location signified by <tt>key</tt>
-
# (see <tt>expire_fragment</tt> for acceptable formats).
-
2
def read_fragment(key, options = nil)
-
return unless cache_configured?
-
-
key = fragment_cache_key(key)
-
instrument_fragment_cache :read_fragment, key do
-
result = cache_store.read(key, options)
-
result.respond_to?(:html_safe) ? result.html_safe : result
-
end
-
end
-
-
# Check if a cached fragment from the location signified by
-
# <tt>key</tt> exists (see <tt>expire_fragment</tt> for acceptable formats)
-
2
def fragment_exist?(key, options = nil)
-
return unless cache_configured?
-
key = fragment_cache_key(key)
-
-
instrument_fragment_cache :exist_fragment?, key do
-
cache_store.exist?(key, options)
-
end
-
end
-
-
# Removes fragments from the cache.
-
#
-
# +key+ can take one of three forms:
-
#
-
# * String - This would normally take the form of a path, like
-
# <tt>pages/45/notes</tt>.
-
# * Hash - Treated as an implicit call to +url_for+, like
-
# <tt>{:controller => "pages", :action => "notes", :id => 45}</tt>
-
# * Regexp - Will remove any fragment that matches, so
-
# <tt>%r{pages/\d*/notes}</tt> might remove all notes. Make sure you
-
# don't use anchors in the regex (<tt>^</tt> or <tt>$</tt>) because
-
# the actual filename matched looks like
-
# <tt>./cache/filename/path.cache</tt>. Note: Regexp expiration is
-
# only supported on caches that can iterate over all keys (unlike
-
# memcached).
-
#
-
# +options+ is passed through to the cache store's <tt>delete</tt>
-
# method (or <tt>delete_matched</tt>, for Regexp keys.)
-
2
def expire_fragment(key, options = nil)
-
return unless cache_configured?
-
key = fragment_cache_key(key) unless key.is_a?(Regexp)
-
-
instrument_fragment_cache :expire_fragment, key do
-
if key.is_a?(Regexp)
-
cache_store.delete_matched(key, options)
-
else
-
cache_store.delete(key, options)
-
end
-
end
-
end
-
-
2
def instrument_fragment_cache(name, key)
-
ActiveSupport::Notifications.instrument("#{name}.action_controller", :key => key){ yield }
-
end
-
end
-
end
-
end
-
2
require 'fileutils'
-
2
require 'active_support/core_ext/class/attribute_accessors'
-
-
2
module ActionController #:nodoc:
-
2
module Caching
-
# Page caching is an approach to caching where the entire action output of is stored as a HTML file that the web server
-
# can serve without going through Action Pack. This is the fastest way to cache your content as opposed to going dynamically
-
# through the process of generating the content. Unfortunately, this incredible speed-up is only available to stateless pages
-
# where all visitors are treated the same. Content management systems -- including weblogs and wikis -- have many pages that are
-
# a great fit for this approach, but account-based systems where people log in and manipulate their own data are often less
-
# likely candidates.
-
#
-
# Specifying which actions to cache is done through the <tt>caches_page</tt> class method:
-
#
-
# class WeblogController < ActionController::Base
-
# caches_page :show, :new
-
# end
-
#
-
# This will generate cache files such as <tt>weblog/show/5.html</tt> and <tt>weblog/new.html</tt>, which match the URLs used
-
# that would normally trigger dynamic page generation. Page caching works by configuring a web server to first check for the
-
# existence of files on disk, and to serve them directly when found, without passing the request through to Action Pack.
-
# This is much faster than handling the full dynamic request in the usual way.
-
#
-
# Expiration of the cache is handled by deleting the cached file, which results in a lazy regeneration approach where the cache
-
# is not restored before another hit is made against it. The API for doing so mimics the options from +url_for+ and friends:
-
#
-
# class WeblogController < ActionController::Base
-
# def update
-
# List.update(params[:list][:id], params[:list])
-
# expire_page :action => "show", :id => params[:list][:id]
-
# redirect_to :action => "show", :id => params[:list][:id]
-
# end
-
# end
-
#
-
# Additionally, you can expire caches using Sweepers that act on changes in the model to determine when a cache is supposed to be
-
# expired.
-
2
module Pages
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
# The cache directory should be the document root for the web server and is set using <tt>Base.page_cache_directory = "/document/root"</tt>.
-
# For Rails, this directory has already been set to Rails.public_path (which is usually set to <tt>Rails.root + "/public"</tt>). Changing
-
# this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your
-
# web server to look in the new location for cached files.
-
2
class_attribute :page_cache_directory
-
2
self.page_cache_directory ||= ''
-
-
# Most Rails requests do not have an extension, such as <tt>/weblog/new</tt>. In these cases, the page caching mechanism will add one in
-
# order to make it easy for the cached files to be picked up properly by the web server. By default, this cache extension is <tt>.html</tt>.
-
# If you want something else, like <tt>.php</tt> or <tt>.shtml</tt>, just set Base.page_cache_extension. In cases where a request already has an
-
# extension, such as <tt>.xml</tt> or <tt>.rss</tt>, page caching will not add an extension. This allows it to work well with RESTful apps.
-
2
class_attribute :page_cache_extension
-
2
self.page_cache_extension ||= '.html'
-
-
# The compression used for gzip. If false (default), the page is not compressed.
-
# If can be a symbol showing the ZLib compression method, for example, :best_compression
-
# or :best_speed or an integer configuring the compression level.
-
2
class_attribute :page_cache_compression
-
2
self.page_cache_compression ||= false
-
end
-
-
2
module ClassMethods
-
# Expires the page that was cached with the +path+ as a key. Example:
-
# expire_page "/lists/show"
-
2
def expire_page(path)
-
return unless perform_caching
-
path = page_cache_path(path)
-
-
instrument_page_cache :expire_page, path do
-
File.delete(path) if File.exist?(path)
-
File.delete(path + '.gz') if File.exist?(path + '.gz')
-
end
-
end
-
-
# Manually cache the +content+ in the key determined by +path+. Example:
-
# cache_page "I'm the cached content", "/lists/show"
-
2
def cache_page(content, path, extension = nil, gzip = Zlib::BEST_COMPRESSION)
-
return unless perform_caching
-
path = page_cache_path(path, extension)
-
-
instrument_page_cache :write_page, path do
-
FileUtils.makedirs(File.dirname(path))
-
File.open(path, "wb+") { |f| f.write(content) }
-
if gzip
-
Zlib::GzipWriter.open(path + '.gz', gzip) { |f| f.write(content) }
-
end
-
end
-
end
-
-
# Caches the +actions+ using the page-caching approach that'll store
-
# the cache in a path within the page_cache_directory that
-
# matches the triggering url.
-
#
-
# You can also pass a :gzip option to override the class configuration one.
-
#
-
# Usage:
-
#
-
# # cache the index action
-
# caches_page :index
-
#
-
# # cache the index action except for JSON requests
-
# caches_page :index, :if => Proc.new { |c| !c.request.format.json? }
-
#
-
# # don't gzip images
-
# caches_page :image, :gzip => false
-
2
def caches_page(*actions)
-
return unless perform_caching
-
options = actions.extract_options!
-
-
gzip_level = options.fetch(:gzip, page_cache_compression)
-
gzip_level = case gzip_level
-
when Symbol
-
Zlib.const_get(gzip_level.to_s.upcase)
-
when Fixnum
-
gzip_level
-
when false
-
nil
-
else
-
Zlib::BEST_COMPRESSION
-
end
-
-
after_filter({:only => actions}.merge(options)) do |c|
-
c.cache_page(nil, nil, gzip_level)
-
end
-
end
-
-
2
private
-
2
def page_cache_file(path, extension)
-
name = (path.empty? || path == "/") ? "/index" : URI.parser.unescape(path.chomp('/'))
-
unless (name.split('/').last || name).include? '.'
-
name << (extension || self.page_cache_extension)
-
end
-
return name
-
end
-
-
2
def page_cache_path(path, extension = nil)
-
page_cache_directory.to_s + page_cache_file(path, extension)
-
end
-
-
2
def instrument_page_cache(name, path)
-
ActiveSupport::Notifications.instrument("#{name}.action_controller", :path => path){ yield }
-
end
-
end
-
-
# Expires the page that was cached with the +options+ as a key. Example:
-
# expire_page :controller => "lists", :action => "show"
-
2
def expire_page(options = {})
-
return unless self.class.perform_caching
-
-
if options.is_a?(Hash)
-
if options[:action].is_a?(Array)
-
options[:action].each do |action|
-
self.class.expire_page(url_for(options.merge(:only_path => true, :action => action)))
-
end
-
else
-
self.class.expire_page(url_for(options.merge(:only_path => true)))
-
end
-
else
-
self.class.expire_page(options)
-
end
-
end
-
-
# Manually cache the +content+ in the key determined by +options+. If no content is provided, the contents of response.body is used.
-
# If no options are provided, the url of the current request being handled is used. Example:
-
# cache_page "I'm the cached content", :controller => "lists", :action => "show"
-
2
def cache_page(content = nil, options = nil, gzip = Zlib::BEST_COMPRESSION)
-
return unless self.class.perform_caching && caching_allowed?
-
-
path = case options
-
when Hash
-
url_for(options.merge(:only_path => true, :format => params[:format]))
-
when String
-
options
-
else
-
request.path
-
end
-
-
if (type = Mime::LOOKUP[self.content_type]) && (type_symbol = type.symbol).present?
-
extension = ".#{type_symbol}"
-
end
-
-
self.class.cache_page(content || response.body, path, extension, gzip)
-
end
-
-
end
-
end
-
end
-
2
module ActionController #:nodoc:
-
2
module Caching
-
# Sweepers are the terminators of the caching world and responsible for expiring caches when model objects change.
-
# They do this by being half-observers, half-filters and implementing callbacks for both roles. A Sweeper example:
-
#
-
# class ListSweeper < ActionController::Caching::Sweeper
-
# observe List, Item
-
#
-
# def after_save(record)
-
# list = record.is_a?(List) ? record : record.list
-
# expire_page(:controller => "lists", :action => %w( show public feed ), :id => list.id)
-
# expire_action(:controller => "lists", :action => "all")
-
# list.shares.each { |share| expire_page(:controller => "lists", :action => "show", :id => share.url_key) }
-
# end
-
# end
-
#
-
# The sweeper is assigned in the controllers that wish to have its job performed using the <tt>cache_sweeper</tt> class method:
-
#
-
# class ListsController < ApplicationController
-
# caches_action :index, :show, :public, :feed
-
# cache_sweeper :list_sweeper, :only => [ :edit, :destroy, :share ]
-
# end
-
#
-
# In the example above, four actions are cached and three actions are responsible for expiring those caches.
-
#
-
# You can also name an explicit class in the declaration of a sweeper, which is needed if the sweeper is in a module:
-
#
-
# class ListsController < ApplicationController
-
# caches_action :index, :show, :public, :feed
-
# cache_sweeper OpenBar::Sweeper, :only => [ :edit, :destroy, :share ]
-
# end
-
2
module Sweeping
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods #:nodoc:
-
2
def cache_sweeper(*sweepers)
-
configuration = sweepers.extract_options!
-
-
sweepers.each do |sweeper|
-
ActiveRecord::Base.observers << sweeper if defined?(ActiveRecord) and defined?(ActiveRecord::Base)
-
sweeper_instance = (sweeper.is_a?(Symbol) ? Object.const_get(sweeper.to_s.classify) : sweeper).instance
-
-
if sweeper_instance.is_a?(Sweeper)
-
around_filter(sweeper_instance, :only => configuration[:only])
-
else
-
after_filter(sweeper_instance, :only => configuration[:only])
-
end
-
end
-
end
-
end
-
end
-
-
2
if defined?(ActiveRecord) and defined?(ActiveRecord::Observer)
-
2
class Sweeper < ActiveRecord::Observer #:nodoc:
-
2
attr_accessor :controller
-
-
2
def before(controller)
-
self.controller = controller
-
callback(:before) if controller.perform_caching
-
true # before method from sweeper should always return true
-
end
-
-
2
def after(controller)
-
self.controller = controller
-
callback(:after) if controller.perform_caching
-
# Clean up, so that the controller can be collected after this request
-
self.controller = nil
-
end
-
-
2
protected
-
# gets the action cache path for the given options.
-
2
def action_path_for(options)
-
Actions::ActionCachePath.new(controller, options).path
-
end
-
-
# Retrieve instance variables set in the controller.
-
2
def assigns(key)
-
controller.instance_variable_get("@#{key}")
-
end
-
-
2
private
-
2
def callback(timing)
-
controller_callback_method_name = "#{timing}_#{controller.controller_name.underscore}"
-
action_callback_method_name = "#{controller_callback_method_name}_#{controller.action_name}"
-
-
__send__(controller_callback_method_name) if respond_to?(controller_callback_method_name, true)
-
__send__(action_callback_method_name) if respond_to?(action_callback_method_name, true)
-
end
-
-
2
def method_missing(method, *arguments, &block)
-
return unless @controller
-
@controller.__send__(method, *arguments, &block)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActionController
-
2
class LogSubscriber < ActiveSupport::LogSubscriber
-
2
INTERNAL_PARAMS = %w(controller action format _method only_path)
-
-
2
def start_processing(event)
-
9
payload = event.payload
-
9
params = payload[:params].except(*INTERNAL_PARAMS)
-
9
format = payload[:format]
-
9
format = format.to_s.upcase if format.is_a?(Symbol)
-
-
9
info "Processing by #{payload[:controller]}##{payload[:action]} as #{format}"
-
9
info " Parameters: #{params.inspect}" unless params.empty?
-
end
-
-
2
def process_action(event)
-
9
payload = event.payload
-
9
additions = ActionController::Base.log_process_action(payload)
-
-
9
status = payload[:status]
-
9
if status.nil? && payload[:exception].present?
-
exception_class_name = payload[:exception].first
-
status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name)
-
end
-
9
message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in #{format_duration(event.duration)}"
-
9
message << " (#{additions.join(" | ")})" unless additions.blank?
-
-
9
info(message)
-
end
-
-
2
def halted_callback(event)
-
9
info "Filter chain halted as #{event.payload[:filter]} rendered or redirected"
-
end
-
-
2
def send_file(event)
-
info("Sent file #{event.payload[:path]} (#{format_duration(event.duration)})")
-
end
-
-
2
def redirect_to(event)
-
9
info "Redirected to #{event.payload[:location]}"
-
end
-
-
2
def send_data(event)
-
info("Sent data #{event.payload[:filename]} (#{format_duration(event.duration)})")
-
end
-
-
2
%w(write_fragment read_fragment exist_fragment?
-
expire_fragment expire_page write_page).each do |method|
-
12
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{method}(event)
-
key_or_path = event.payload[:key] || event.payload[:path]
-
human_name = #{method.to_s.humanize.inspect}
-
duration = format_duration(event.duration)
-
info("\#{human_name} \#{key_or_path} \#{duration}")
-
end
-
METHOD
-
end
-
-
2
def logger
-
118
ActionController::Base.logger
-
end
-
end
-
end
-
-
2
ActionController::LogSubscriber.attach_to :action_controller
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'action_dispatch/middleware/stack'
-
-
2
module ActionController
-
# Extend ActionDispatch middleware stack to make it aware of options
-
# allowing the following syntax in controllers:
-
#
-
# class PostsController < ApplicationController
-
# use AuthenticationMiddleware, :except => [:index, :show]
-
# end
-
#
-
2
class MiddlewareStack < ActionDispatch::MiddlewareStack #:nodoc:
-
2
class Middleware < ActionDispatch::MiddlewareStack::Middleware #:nodoc:
-
2
def initialize(klass, *args, &block)
-
options = args.extract_options!
-
@only = Array(options.delete(:only)).map(&:to_s)
-
@except = Array(options.delete(:except)).map(&:to_s)
-
args << options unless options.empty?
-
super
-
end
-
-
2
def valid?(action)
-
if @only.present?
-
@only.include?(action)
-
elsif @except.present?
-
!@except.include?(action)
-
else
-
true
-
end
-
end
-
end
-
-
2
def build(action, app=nil, &block)
-
app ||= block
-
action = action.to_s
-
raise "MiddlewareStack#build requires an app" unless app
-
-
middlewares.reverse.inject(app) do |a, middleware|
-
middleware.valid?(action) ?
-
middleware.build(a) : a
-
end
-
end
-
end
-
-
# <tt>ActionController::Metal</tt> is the simplest possible controller, providing a
-
# valid Rack interface without the additional niceties provided by
-
# <tt>ActionController::Base</tt>.
-
#
-
# A sample metal controller might look like this:
-
#
-
# class HelloController < ActionController::Metal
-
# def index
-
# self.response_body = "Hello World!"
-
# end
-
# end
-
#
-
# And then to route requests to your metal controller, you would add
-
# something like this to <tt>config/routes.rb</tt>:
-
#
-
# match 'hello', :to => HelloController.action(:index)
-
#
-
# The +action+ method returns a valid Rack application for the \Rails
-
# router to dispatch to.
-
#
-
# == Rendering Helpers
-
#
-
# <tt>ActionController::Metal</tt> by default provides no utilities for rendering
-
# views, partials, or other responses aside from explicitly calling of
-
# <tt>response_body=</tt>, <tt>content_type=</tt>, and <tt>status=</tt>. To
-
# add the render helpers you're used to having in a normal controller, you
-
# can do the following:
-
#
-
# class HelloController < ActionController::Metal
-
# include ActionController::Rendering
-
# append_view_path "#{Rails.root}/app/views"
-
#
-
# def index
-
# render "hello/index"
-
# end
-
# end
-
#
-
# == Redirection Helpers
-
#
-
# To add redirection helpers to your metal controller, do the following:
-
#
-
# class HelloController < ActionController::Metal
-
# include ActionController::Redirecting
-
# include Rails.application.routes.url_helpers
-
#
-
# def index
-
# redirect_to root_url
-
# end
-
# end
-
#
-
# == Other Helpers
-
#
-
# You can refer to the modules included in <tt>ActionController::Base</tt> to see
-
# other features you can bring into your metal controller.
-
#
-
2
class Metal < AbstractController::Base
-
2
abstract!
-
-
2
attr_internal_writer :env
-
-
2
def env
-
19
@_env ||= {}
-
end
-
-
# Returns the last part of the controller's name, underscored, without the ending
-
# <tt>Controller</tt>. For instance, PostsController returns <tt>posts</tt>.
-
# Namespaces are left out, so Admin::PostsController returns <tt>posts</tt> as well.
-
#
-
# ==== Returns
-
# * <tt>string</tt>
-
2
def self.controller_name
-
12
@controller_name ||= self.name.demodulize.sub(/Controller$/, '').underscore
-
end
-
-
# Delegates to the class' <tt>controller_name</tt>
-
2
def controller_name
-
self.class.controller_name
-
end
-
-
# The details below can be overridden to support a specific
-
# Request and Response object. The default ActionController::Base
-
# implementation includes RackDelegation, which makes a request
-
# and response object available. You might wish to control the
-
# environment and response manually for performance reasons.
-
-
2
attr_internal :headers, :response, :request
-
2
delegate :session, :to => "@_request"
-
-
2
def initialize
-
52
@_headers = {"Content-Type" => "text/html"}
-
52
@_status = 200
-
52
@_request = nil
-
52
@_response = nil
-
52
@_routes = nil
-
52
super
-
end
-
-
2
def params
-
@_params ||= request.parameters
-
end
-
-
2
def params=(val)
-
62
@_params = val
-
end
-
-
# Basic implementations for content_type=, location=, and headers are
-
# provided to reduce the dependency on the RackDelegation module
-
# in Renderer and Redirector.
-
-
2
def content_type=(type)
-
headers["Content-Type"] = type.to_s
-
end
-
-
2
def content_type
-
headers["Content-Type"]
-
end
-
-
2
def location
-
headers["Location"]
-
end
-
-
2
def location=(url)
-
headers["Location"] = url
-
end
-
-
# basic url_for that can be overridden for more robust functionality
-
2
def url_for(string)
-
string
-
end
-
-
2
def status
-
@_status
-
end
-
-
2
def status=(status)
-
@_status = Rack::Utils.status_code(status)
-
end
-
-
2
def response_body=(val)
-
19
body = if val.is_a?(String)
-
9
[val]
-
elsif val.nil? || val.respond_to?(:each)
-
10
val
-
else
-
[val]
-
end
-
19
super body
-
end
-
-
2
def performed?
-
response_body
-
end
-
-
2
def dispatch(name, request) #:nodoc:
-
@_request = request
-
@_env = request.env
-
@_env['action_controller.instance'] = self
-
process(name)
-
to_a
-
end
-
-
2
def to_a #:nodoc:
-
response ? response.to_a : [status, headers, response_body]
-
end
-
-
2
class_attribute :middleware_stack
-
2
self.middleware_stack = ActionController::MiddlewareStack.new
-
-
2
def self.inherited(base) #nodoc:
-
31
base.middleware_stack = self.middleware_stack.dup
-
31
super
-
end
-
-
# Adds given middleware class and its args to bottom of middleware_stack
-
2
def self.use(*args, &block)
-
middleware_stack.use(*args, &block)
-
end
-
-
# Alias for middleware_stack
-
2
def self.middleware
-
middleware_stack
-
end
-
-
# Makes the controller a rack endpoint that points to the action in
-
# the given env's action_dispatch.request.path_parameters key.
-
2
def self.call(env)
-
action(env['action_dispatch.request.path_parameters'][:action]).call(env)
-
end
-
-
# Return a rack endpoint for the given action. Memoize the endpoint, so
-
# multiple calls into MyController.action will return the same object
-
# for the same action.
-
#
-
# ==== Parameters
-
# * <tt>action</tt> - An action name
-
#
-
# ==== Returns
-
# * <tt>proc</tt> - A rack application
-
2
def self.action(name, klass = ActionDispatch::Request)
-
middleware_stack.build(name.to_s) do |env|
-
new.dispatch(name, klass.new(env))
-
end
-
end
-
end
-
end
-
2
require 'active_support/deprecation'
-
-
2
module ActionController
-
2
module Compatibility
-
2
extend ActiveSupport::Concern
-
-
# Temporary hax
-
2
included do
-
2
::ActionController::UnknownAction = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('ActionController::UnknownAction', '::AbstractController::ActionNotFound')
-
2
::ActionController::DoubleRenderError = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('ActionController::DoubleRenderError', '::AbstractController::DoubleRenderError')
-
-
# ROUTES TODO: This should be handled by a middleware and route generation
-
# should be able to handle SCRIPT_NAME
-
2
self.config.relative_url_root = ENV['RAILS_RELATIVE_URL_ROOT']
-
-
2
def self.default_charset=(new_charset)
-
ActiveSupport::Deprecation.warn "Setting default charset at controller level" \
-
" is deprecated, please use `config.action_dispatch.default_charset` instead", caller
-
ActionDispatch::Response.default_charset = new_charset
-
end
-
-
2
self.protected_instance_variables = %w(
-
@_status @_headers @_params @_env @_response @_request
-
@_view_runtime @_stream @_url_options @_action_has_layout
-
)
-
-
2
def rescue_action(env)
-
ActiveSupport::Deprecation.warn "Calling `rescue_action` is deprecated and will be removed in Rails 4.0.", caller
-
raise env["action_dispatch.rescue.exception"]
-
end
-
end
-
-
# For old tests
-
2
def initialize_template_class(*)
-
ActiveSupport::Deprecation.warn "Calling `initialize_template_class` is deprecated and has no effect anymore.", caller
-
end
-
-
2
def assign_shortcuts(*)
-
ActiveSupport::Deprecation.warn "Calling `assign_shortcuts` is deprecated and has no effect anymore.", caller
-
end
-
-
2
def _normalize_options(options)
-
options[:text] = nil if options.delete(:nothing) == true
-
options[:text] = " " if options.key?(:text) && options[:text].nil?
-
super
-
end
-
-
2
def render_to_body(options)
-
options[:template].sub!(/^\//, '') if options.key?(:template)
-
super || " "
-
end
-
-
2
def _handle_method_missing
-
ActiveSupport::Deprecation.warn "Using `method_missing` to handle non" \
-
" existing actions is deprecated and will be removed in Rails 4.0, " \
-
" please use `action_missing` instead.", caller
-
method_missing(@_action_name.to_sym)
-
end
-
-
2
def method_for_action(action_name)
-
super || ((self.class.public_method_defined?(:method_missing) ||
-
9
self.class.protected_method_defined?(:method_missing)) && "_handle_method_missing")
-
end
-
end
-
end
-
2
module ActionController
-
2
module ConditionalGet
-
2
extend ActiveSupport::Concern
-
-
2
include RackDelegation
-
2
include Head
-
-
# Sets the etag, last_modified, or both on the response and renders a
-
# <tt>304 Not Modified</tt> response if the request is already fresh.
-
#
-
# Parameters:
-
# * <tt>:etag</tt>
-
# * <tt>:last_modified</tt>
-
# * <tt>:public</tt> By default the Cache-Control header is private, set this to true if you want your application to be cachable by other devices (proxy caches).
-
#
-
# Example:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# fresh_when(:etag => @article, :last_modified => @article.created_at, :public => true)
-
# end
-
#
-
# This will render the show template if the request isn't sending a matching etag or
-
# If-Modified-Since header and just a <tt>304 Not Modified</tt> response if there's a match.
-
#
-
# You can also just pass a record where last_modified will be set by calling updated_at and the etag by passing the object itself. Example:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# fresh_when(@article)
-
# end
-
#
-
# When passing a record, you can still set whether the public header:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# fresh_when(@article, :public => true)
-
# end
-
2
def fresh_when(record_or_options, additional_options = {})
-
if record_or_options.is_a? Hash
-
options = record_or_options
-
options.assert_valid_keys(:etag, :last_modified, :public)
-
else
-
record = record_or_options
-
options = { :etag => record, :last_modified => record.try(:updated_at) }.merge(additional_options)
-
end
-
-
response.etag = options[:etag] if options[:etag]
-
response.last_modified = options[:last_modified] if options[:last_modified]
-
response.cache_control[:public] = true if options[:public]
-
-
head :not_modified if request.fresh?(response)
-
end
-
-
# Sets the etag and/or last_modified on the response and checks it against
-
# the client request. If the request doesn't match the options provided, the
-
# request is considered stale and should be generated from scratch. Otherwise,
-
# it's fresh and we don't need to generate anything and a reply of <tt>304 Not Modified</tt> is sent.
-
#
-
# Parameters:
-
# * <tt>:etag</tt>
-
# * <tt>:last_modified</tt>
-
# * <tt>:public</tt> By default the Cache-Control header is private, set this to true if you want your application to be cachable by other devices (proxy caches).
-
#
-
# Example:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
#
-
# if stale?(:etag => @article, :last_modified => @article.created_at)
-
# @statistics = @article.really_expensive_call
-
# respond_to do |format|
-
# # all the supported formats
-
# end
-
# end
-
# end
-
#
-
# You can also just pass a record where last_modified will be set by calling updated_at and the etag by passing the object itself. Example:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
#
-
# if stale?(@article)
-
# @statistics = @article.really_expensive_call
-
# respond_to do |format|
-
# # all the supported formats
-
# end
-
# end
-
# end
-
#
-
# When passing a record, you can still set whether the public header:
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
#
-
# if stale?(@article, :public => true)
-
# @statistics = @article.really_expensive_call
-
# respond_to do |format|
-
# # all the supported formats
-
# end
-
# end
-
# end
-
2
def stale?(record_or_options, additional_options = {})
-
fresh_when(record_or_options, additional_options)
-
!request.fresh?(response)
-
end
-
-
# Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a <tt>private</tt> instruction, so that
-
# intermediate caches must not cache the response.
-
#
-
# Examples:
-
# expires_in 20.minutes
-
# expires_in 3.hours, :public => true
-
# expires_in 3.hours, 'max-stale' => 5.hours, :public => true
-
#
-
# This method will overwrite an existing Cache-Control header.
-
# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities.
-
2
def expires_in(seconds, options = {}) #:doc:
-
response.cache_control.merge!(:max_age => seconds, :public => options.delete(:public))
-
options.delete(:private)
-
-
response.cache_control[:extras] = options.map {|k,v| "#{k}=#{v}"}
-
end
-
-
# Sets a HTTP 1.1 Cache-Control header of <tt>no-cache</tt> so no caching should occur by the browser or
-
# intermediate caches (like caching proxy servers).
-
2
def expires_now #:doc:
-
response.cache_control.replace(:no_cache => true)
-
end
-
end
-
end
-
2
module ActionController #:nodoc:
-
2
module Cookies
-
2
extend ActiveSupport::Concern
-
-
2
include RackDelegation
-
-
2
included do
-
2
helper_method :cookies
-
end
-
-
2
private
-
2
def cookies
-
request.cookie_jar
-
end
-
end
-
end
-
2
require 'active_support/core_ext/file/path'
-
2
require 'action_controller/metal/exceptions'
-
-
2
module ActionController #:nodoc:
-
# Methods for sending arbitrary data and for streaming files to the browser,
-
# instead of rendering.
-
2
module DataStreaming
-
2
extend ActiveSupport::Concern
-
-
2
include ActionController::Rendering
-
-
2
DEFAULT_SEND_FILE_OPTIONS = {
-
:type => 'application/octet-stream'.freeze,
-
:disposition => 'attachment'.freeze,
-
}.freeze
-
-
2
protected
-
# Sends the file. This uses a server-appropriate method (such as X-Sendfile)
-
# via the Rack::Sendfile middleware. The header to use is set via
-
# config.action_dispatch.x_sendfile_header.
-
# Your server can also configure this for you by setting the X-Sendfile-Type header.
-
#
-
# Be careful to sanitize the path parameter if it is coming from a web
-
# page. <tt>send_file(params[:path])</tt> allows a malicious user to
-
# download any file on your server.
-
#
-
# Options:
-
# * <tt>:filename</tt> - suggests a filename for the browser to use.
-
# Defaults to <tt>File.basename(path)</tt>.
-
# * <tt>:type</tt> - specifies an HTTP content type.
-
# You can specify either a string or a symbol for a registered type register with
-
# <tt>Mime::Type.register</tt>, for example :json
-
# If omitted, type will be guessed from the file extension specified in <tt>:filename</tt>.
-
# If no content type is registered for the extension, default type 'application/octet-stream' will be used.
-
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
-
# Valid values are 'inline' and 'attachment' (default).
-
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
-
# * <tt>:url_based_filename</tt> - set to +true+ if you want the browser guess the filename from
-
# the URL, which is necessary for i18n filenames on certain browsers
-
# (setting <tt>:filename</tt> overrides this option).
-
#
-
# The default Content-Type and Content-Disposition headers are
-
# set to download arbitrary binary files in as many browsers as
-
# possible. IE versions 4, 5, 5.5, and 6 are all known to have
-
# a variety of quirks (especially when downloading over SSL).
-
#
-
# Simple download:
-
#
-
# send_file '/path/to.zip'
-
#
-
# Show a JPEG in the browser:
-
#
-
# send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline'
-
#
-
# Show a 404 page in the browser:
-
#
-
# send_file '/path/to/404.html', :type => 'text/html; charset=utf-8', :status => 404
-
#
-
# Read about the other Content-* HTTP headers if you'd like to
-
# provide the user with more information (such as Content-Description) in
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11.
-
#
-
# Also be aware that the document may be cached by proxies and browsers.
-
# The Pragma and Cache-Control headers declare how the file may be cached
-
# by intermediaries. They default to require clients to validate with
-
# the server before releasing cached responses. See
-
# http://www.mnot.net/cache_docs/ for an overview of web caching and
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
-
# for the Cache-Control header spec.
-
2
def send_file(path, options = {}) #:doc:
-
raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path)
-
-
options[:filename] ||= File.basename(path) unless options[:url_based_filename]
-
send_file_headers! options
-
-
self.status = options[:status] || 200
-
self.content_type = options[:content_type] if options.key?(:content_type)
-
self.response_body = FileBody.new(path)
-
end
-
-
# Avoid having to pass an open file handle as the response body.
-
# Rack::Sendfile will usually intercept the response and uses
-
# the path directly, so there is no reason to open the file.
-
2
class FileBody #:nodoc:
-
2
attr_reader :to_path
-
-
2
def initialize(path)
-
@to_path = path
-
end
-
-
# Stream the file's contents if Rack::Sendfile isn't present.
-
2
def each
-
File.open(to_path, 'rb') do |file|
-
while chunk = file.read(16384)
-
yield chunk
-
end
-
end
-
end
-
end
-
-
# Sends the given binary data to the browser. This method is similar to
-
# <tt>render :text => data</tt>, but also allows you to specify whether
-
# the browser should display the response as a file attachment (i.e. in a
-
# download dialog) or as inline data. You may also set the content type,
-
# the apparent file name, and other things.
-
#
-
# Options:
-
# * <tt>:filename</tt> - suggests a filename for the browser to use.
-
# * <tt>:type</tt> - specifies an HTTP content type. Defaults to 'application/octet-stream'. You can specify
-
# either a string or a symbol for a registered type register with <tt>Mime::Type.register</tt>, for example :json
-
# If omitted, type will be guessed from the file extension specified in <tt>:filename</tt>.
-
# If no content type is registered for the extension, default type 'application/octet-stream' will be used.
-
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
-
# Valid values are 'inline' and 'attachment' (default).
-
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
-
#
-
# Generic data download:
-
#
-
# send_data buffer
-
#
-
# Download a dynamically-generated tarball:
-
#
-
# send_data generate_tgz('dir'), :filename => 'dir.tgz'
-
#
-
# Display an image Active Record in the browser:
-
#
-
# send_data image.data, :type => image.content_type, :disposition => 'inline'
-
#
-
# See +send_file+ for more information on HTTP Content-* headers and caching.
-
2
def send_data(data, options = {}) #:doc:
-
send_file_headers! options.dup
-
render options.slice(:status, :content_type).merge(:text => data)
-
end
-
-
2
private
-
2
def send_file_headers!(options)
-
type_provided = options.has_key?(:type)
-
-
options.update(DEFAULT_SEND_FILE_OPTIONS.merge(options))
-
[:type, :disposition].each do |arg|
-
raise ArgumentError, ":#{arg} option required" if options[arg].nil?
-
end
-
-
disposition = options[:disposition].to_s
-
disposition += %(; filename="#{options[:filename]}") if options[:filename]
-
-
content_type = options[:type]
-
-
if content_type.is_a?(Symbol)
-
extension = Mime[content_type]
-
raise ArgumentError, "Unknown MIME type #{options[:type]}" unless extension
-
self.content_type = extension
-
else
-
if !type_provided && options[:filename]
-
# If type wasn't provided, try guessing from file extension.
-
content_type = Mime::Type.lookup_by_extension(File.extname(options[:filename]).downcase.tr('.','')) || content_type
-
end
-
self.content_type = content_type
-
end
-
-
headers.merge!(
-
'Content-Disposition' => disposition,
-
'Content-Transfer-Encoding' => 'binary'
-
)
-
-
response.sending_file = true
-
-
# Fix a problem with IE 6.0 on opening downloaded files:
-
# If Cache-Control: no-cache is set (which Rails does by default),
-
# IE removes the file it just downloaded from its cache immediately
-
# after it displays the "open/save" dialog, which means that if you
-
# hit "open" the file isn't there anymore when the application that
-
# is called for handling the download is run, so let's workaround that
-
response.cache_control[:public] ||= false
-
end
-
end
-
end
-
2
module ActionController
-
2
class ActionControllerError < StandardError #:nodoc:
-
end
-
-
2
class RenderError < ActionControllerError #:nodoc:
-
end
-
-
2
class RoutingError < ActionControllerError #:nodoc:
-
2
attr_reader :failures
-
2
def initialize(message, failures=[])
-
2
super(message)
-
2
@failures = failures
-
end
-
end
-
-
2
class MethodNotAllowed < ActionControllerError #:nodoc:
-
2
attr_reader :allowed_methods
-
-
2
def initialize(*allowed_methods)
-
super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.")
-
end
-
end
-
-
2
class NotImplemented < MethodNotAllowed #:nodoc:
-
end
-
-
2
class UnknownController < ActionControllerError #:nodoc:
-
end
-
-
2
class MissingFile < ActionControllerError #:nodoc:
-
end
-
-
2
class RenderError < ActionControllerError #:nodoc:
-
end
-
-
2
class SessionOverflowError < ActionControllerError #:nodoc:
-
2
DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.'
-
-
2
def initialize(message = nil)
-
super(message || DEFAULT_MESSAGE)
-
end
-
end
-
-
2
class UnknownHttpMethod < ActionControllerError #:nodoc:
-
end
-
end
-
2
module ActionController #:nodoc:
-
2
module Flash
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
delegate :flash, :to => :request
-
2
delegate :alert, :notice, :to => "request.flash"
-
2
helper_method :alert, :notice
-
end
-
-
2
protected
-
2
def redirect_to(options = {}, response_status_and_flash = {}) #:doc:
-
9
if alert = response_status_and_flash.delete(:alert)
-
9
flash[:alert] = alert
-
end
-
-
9
if notice = response_status_and_flash.delete(:notice)
-
flash[:notice] = notice
-
end
-
-
9
if other_flashes = response_status_and_flash.delete(:flash)
-
flash.update(other_flashes)
-
end
-
-
9
super(options, response_status_and_flash)
-
end
-
end
-
end
-
2
module ActionController
-
# This module provides a method which will redirect browser to use HTTPS
-
# protocol. This will ensure that user's sensitive information will be
-
# transferred safely over the internet. You _should_ always force browser
-
# to use HTTPS when you're transferring sensitive information such as
-
# user authentication, account information, or credit card information.
-
#
-
# Note that if you are really concerned about your application security,
-
# you might consider using +config.force_ssl+ in your config file instead.
-
# That will ensure all the data transferred via HTTPS protocol and prevent
-
# user from getting session hijacked when accessing the site under unsecured
-
# HTTP protocol.
-
2
module ForceSSL
-
2
extend ActiveSupport::Concern
-
2
include AbstractController::Callbacks
-
-
2
module ClassMethods
-
# Force the request to this particular controller or specified actions to be
-
# under HTTPS protocol.
-
#
-
# Note that this method will not be effective on development environment.
-
#
-
# ==== Options
-
# * <tt>only</tt> - The callback should be run only for this action
-
# * <tt>except<tt> - The callback should be run for all actions except this action
-
2
def force_ssl(options = {})
-
host = options.delete(:host)
-
before_filter(options) do
-
if !request.ssl? && !Rails.env.development?
-
redirect_options = {:protocol => 'https://', :status => :moved_permanently}
-
redirect_options.merge!(:host => host) if host
-
redirect_options.merge!(:params => request.query_parameters)
-
redirect_to redirect_options
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module ActionController
-
2
module Head
-
2
extend ActiveSupport::Concern
-
-
# Return a response that has no content (merely headers). The options
-
# argument is interpreted to be a hash of header names and values.
-
# This allows you to easily return a response that consists only of
-
# significant headers:
-
#
-
# head :created, :location => person_path(@person)
-
#
-
# head :created, :location => @person
-
#
-
# It can also be used to return exceptional conditions:
-
#
-
# return head(:method_not_allowed) unless request.post?
-
# return head(:bad_request) unless valid_request?
-
# render
-
2
def head(status, options = {})
-
options, status = status, nil if status.is_a?(Hash)
-
status ||= options.delete(:status) || :ok
-
location = options.delete(:location)
-
content_type = options.delete(:content_type)
-
-
options.each do |key, value|
-
headers[key.to_s.dasherize.split('-').each { |v| v[0] = v[0].chr.upcase }.join('-')] = value.to_s
-
end
-
-
self.status = status
-
self.location = url_for(location) if location
-
self.content_type = content_type || (Mime[formats.first] if formats)
-
self.response_body = " "
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/class/attribute'
-
-
2
module ActionController
-
# The \Rails framework provides a large number of helpers for working with assets, dates, forms,
-
# numbers and model objects, to name a few. These helpers are available to all templates
-
# by default.
-
#
-
# In addition to using the standard template helpers provided, creating custom helpers to
-
# extract complicated logic or reusable functionality is strongly encouraged. By default, each controller
-
# will include all helpers.
-
#
-
# In previous versions of \Rails the controller will include a helper whose
-
# name matches that of the controller, e.g., <tt>MyController</tt> will automatically
-
# include <tt>MyHelper</tt>. To return old behavior set +config.action_controller.include_all_helpers+ to +false+.
-
#
-
# Additional helpers can be specified using the +helper+ class method in ActionController::Base or any
-
# controller which inherits from it.
-
#
-
# ==== Examples
-
# The +to_s+ method from the \Time class can be wrapped in a helper method to display a custom message if
-
# a \Time object is blank:
-
#
-
# module FormattedTimeHelper
-
# def format_time(time, format=:long, blank_message=" ")
-
# time.blank? ? blank_message : time.to_s(format)
-
# end
-
# end
-
#
-
# FormattedTimeHelper can now be included in a controller, using the +helper+ class method:
-
#
-
# class EventsController < ActionController::Base
-
# helper FormattedTimeHelper
-
# def index
-
# @events = Event.all
-
# end
-
# end
-
#
-
# Then, in any view rendered by <tt>EventController</tt>, the <tt>format_time</tt> method can be called:
-
#
-
# <% @events.each do |event| -%>
-
# <p>
-
# <%= format_time(event.time, :short, "N/A") %> | <%= event.name %>
-
# </p>
-
# <% end -%>
-
#
-
# Finally, assuming we have two event instances, one which has a time and one which does not,
-
# the output might look like this:
-
#
-
# 23 Aug 11:30 | Carolina Railhawks Soccer Match
-
# N/A | Carolina Railhaws Training Workshop
-
#
-
2
module Helpers
-
2
extend ActiveSupport::Concern
-
-
2
include AbstractController::Helpers
-
-
2
included do
-
2
class_attribute :helpers_path, :include_all_helpers
-
2
self.helpers_path ||= []
-
2
self.include_all_helpers = true
-
end
-
-
2
module ClassMethods
-
# Declares helper accessors for controller attributes. For example, the
-
# following adds new +name+ and <tt>name=</tt> instance methods to a
-
# controller and makes them available to the view:
-
# attr_accessor :name
-
# helper_attr :name
-
#
-
# ==== Parameters
-
# * <tt>attrs</tt> - Names of attributes to be converted into helpers.
-
2
def helper_attr(*attrs)
-
attrs.flatten.each { |attr| helper_method(attr, "#{attr}=") }
-
end
-
-
# Provides a proxy to access helpers methods from outside the view.
-
2
def helpers
-
@helper_proxy ||= ActionView::Base.new.extend(_helpers)
-
end
-
-
# Overwrite modules_for_helpers to accept :all as argument, which loads
-
# all helpers in helpers_path.
-
#
-
# ==== Parameters
-
# * <tt>args</tt> - A list of helpers
-
#
-
# ==== Returns
-
# * <tt>array</tt> - A normalized list of modules for the list of helpers provided.
-
2
def modules_for_helpers(args)
-
40
args += all_application_helpers if args.delete(:all)
-
40
super(args)
-
end
-
-
2
def all_helpers_from_path(path)
-
3
helpers = []
-
3
Array.wrap(path).each do |_path|
-
6
extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/
-
72
helpers += Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
-
end
-
3
helpers.sort!
-
3
helpers.uniq!
-
3
helpers
-
end
-
-
2
private
-
# Extract helper names from files in <tt>app/helpers/**/*_helper.rb</tt>
-
2
def all_application_helpers
-
3
all_helpers_from_path(helpers_path)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
-
2
module ActionController
-
# Adds the ability to prevent public methods on a controller to be called as actions.
-
2
module HideActions
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :hidden_actions
-
2
self.hidden_actions = Set.new.freeze
-
end
-
-
2
private
-
-
# Overrides AbstractController::Base#action_method? to return false if the
-
# action name is in the list of hidden actions.
-
2
def method_for_action(action_name)
-
9
self.class.visible_action?(action_name) && super
-
end
-
-
2
module ClassMethods
-
# Sets all of the actions passed in as hidden actions.
-
#
-
# ==== Parameters
-
# * <tt>args</tt> - A list of actions
-
2
def hide_action(*args)
-
self.hidden_actions = hidden_actions.dup.merge(args.map(&:to_s)).freeze
-
end
-
-
2
def visible_action?(action_name)
-
9
not hidden_actions.include?(action_name)
-
end
-
-
# Overrides AbstractController::Base#action_methods to remove any methods
-
# that are listed as hidden methods.
-
2
def action_methods
-
1063
@action_methods ||= Set.new(super.reject { |name| hidden_actions.include?(name) }).freeze
-
end
-
end
-
end
-
end
-
2
require 'active_support/base64'
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActionController
-
2
module HttpAuthentication
-
# Makes it dead easy to do HTTP \Basic and \Digest authentication.
-
#
-
# === Simple \Basic example
-
#
-
# 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
-
#
-
# === Advanced \Basic example
-
#
-
# Here is a more advanced \Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
-
# the regular HTML interface is protected by a session approach:
-
#
-
# class ApplicationController < ActionController::Base
-
# before_filter :set_account, :authenticate
-
#
-
# protected
-
# def set_account
-
# @account = Account.find_by_url_name(request.subdomains.first)
-
# end
-
#
-
# def authenticate
-
# case request.format
-
# when Mime::XML, Mime::ATOM
-
# if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) }
-
# @current_user = user
-
# else
-
# request_http_basic_authentication
-
# end
-
# else
-
# if session_authenticated?
-
# @current_user = @account.users.find(session[:authenticated][:user_id])
-
# else
-
# redirect_to(login_url) and return false
-
# end
-
# end
-
# end
-
# end
-
#
-
# In your integration tests, you can do something like this:
-
#
-
# def test_access_granted_from_xml
-
# get(
-
# "/notes/1.xml", nil,
-
# 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
-
# )
-
#
-
# assert_equal 200, status
-
# end
-
#
-
# === Simple \Digest example
-
#
-
# require 'digest/md5'
-
# class PostsController < ApplicationController
-
# REALM = "SuperSecret"
-
# USERS = {"dhh" => "secret", #plain text password
-
# "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))} #ha1 digest password
-
#
-
# 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_digest(REALM) do |username|
-
# USERS[username]
-
# end
-
# end
-
# end
-
#
-
# === Notes
-
#
-
# The +authenticate_or_request_with_http_digest+ block must return the user's password
-
# or the ha1 digest hash so the framework can appropriately hash to check the user's
-
# credentials. Returning +nil+ will cause authentication to fail.
-
#
-
# Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If
-
# the password file or database is compromised, the attacker would be able to use the ha1 hash to
-
# authenticate as the user at this +realm+, but would not have the user's password to try using at
-
# other sites.
-
#
-
# In rare instances, web servers or front proxies strip authorization headers before
-
# they reach your application. You can debug this situation by logging all environment
-
# variables, and check for HTTP_AUTHORIZATION, amongst others.
-
2
module Basic
-
2
extend self
-
-
2
module ControllerMethods
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
2
def http_basic_authenticate_with(options = {})
-
before_filter(options.except(:name, :password, :realm)) do
-
authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password|
-
name == options[:name] && password == options[:password]
-
end
-
end
-
end
-
end
-
-
2
def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
-
authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
-
end
-
-
2
def authenticate_with_http_basic(&login_procedure)
-
HttpAuthentication::Basic.authenticate(request, &login_procedure)
-
end
-
-
2
def request_http_basic_authentication(realm = "Application")
-
HttpAuthentication::Basic.authentication_request(self, realm)
-
end
-
end
-
-
2
def authenticate(request, &login_procedure)
-
unless request.authorization.blank?
-
login_procedure.call(*user_name_and_password(request))
-
end
-
end
-
-
2
def user_name_and_password(request)
-
decode_credentials(request).split(/:/, 2)
-
end
-
-
2
def decode_credentials(request)
-
::Base64.decode64(request.authorization.split(' ', 2).last || '')
-
end
-
-
2
def encode_credentials(user_name, password)
-
"Basic #{::Base64.strict_encode64("#{user_name}:#{password}")}"
-
end
-
-
2
def authentication_request(controller, realm)
-
controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
-
controller.response_body = "HTTP Basic: Access denied.\n"
-
controller.status = 401
-
end
-
end
-
-
2
module Digest
-
2
extend self
-
-
2
module ControllerMethods
-
2
def authenticate_or_request_with_http_digest(realm = "Application", &password_procedure)
-
authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm)
-
end
-
-
# Authenticate with HTTP Digest, returns true or false
-
2
def authenticate_with_http_digest(realm = "Application", &password_procedure)
-
HttpAuthentication::Digest.authenticate(request, realm, &password_procedure)
-
end
-
-
# Render output including the HTTP Digest authentication header
-
2
def request_http_digest_authentication(realm = "Application", message = nil)
-
HttpAuthentication::Digest.authentication_request(self, realm, message)
-
end
-
end
-
-
# Returns false on a valid response, true otherwise
-
2
def authenticate(request, realm, &password_procedure)
-
request.authorization && validate_digest_response(request, realm, &password_procedure)
-
end
-
-
# Returns false unless the request credentials response value matches the expected value.
-
# First try the password as a ha1 digest password. If this fails, then try it as a plain
-
# text password.
-
2
def validate_digest_response(request, realm, &password_procedure)
-
secret_key = secret_token(request)
-
credentials = decode_credentials_header(request)
-
valid_nonce = validate_nonce(secret_key, request, credentials[:nonce])
-
-
if valid_nonce && realm == credentials[:realm] && opaque(secret_key) == credentials[:opaque]
-
password = password_procedure.call(credentials[:username])
-
return false unless password
-
-
method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
-
uri = credentials[:uri][0,1] == '/' ? request.original_fullpath : request.original_url
-
-
[true, false].any? do |trailing_question_mark|
-
[true, false].any? do |password_is_ha1|
-
_uri = trailing_question_mark ? uri + "?" : uri
-
expected = expected_response(method, _uri, credentials, password, password_is_ha1)
-
expected == credentials[:response]
-
end
-
end
-
end
-
end
-
-
# Returns the expected response for a request of +http_method+ to +uri+ with the decoded +credentials+ and the expected +password+
-
# Optional parameter +password_is_ha1+ is set to +true+ by default, since best practice is to store ha1 digest instead
-
# of a plain-text password.
-
2
def expected_response(http_method, uri, credentials, password, password_is_ha1=true)
-
ha1 = password_is_ha1 ? password : ha1(credentials, password)
-
ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase, uri].join(':'))
-
::Digest::MD5.hexdigest([ha1, credentials[:nonce], credentials[:nc], credentials[:cnonce], credentials[:qop], ha2].join(':'))
-
end
-
-
2
def ha1(credentials, password)
-
::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(':'))
-
end
-
-
2
def encode_credentials(http_method, credentials, password, password_is_ha1)
-
credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1)
-
"Digest " + credentials.sort_by {|x| x[0].to_s }.map {|v| "#{v[0]}='#{v[1]}'" }.join(', ')
-
end
-
-
2
def decode_credentials_header(request)
-
decode_credentials(request.authorization)
-
end
-
-
2
def decode_credentials(header)
-
HashWithIndifferentAccess[header.to_s.gsub(/^Digest\s+/,'').split(',').map do |pair|
-
key, value = pair.split('=', 2)
-
[key.strip, value.to_s.gsub(/^"|"$/,'').delete('\'')]
-
end]
-
end
-
-
2
def authentication_header(controller, realm)
-
secret_key = secret_token(controller.request)
-
nonce = self.nonce(secret_key)
-
opaque = opaque(secret_key)
-
controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}")
-
end
-
-
2
def authentication_request(controller, realm, message = nil)
-
message ||= "HTTP Digest: Access denied.\n"
-
authentication_header(controller, realm)
-
controller.response_body = message
-
controller.status = 401
-
end
-
-
2
def secret_token(request)
-
secret = request.env["action_dispatch.secret_token"]
-
raise "You must set config.secret_token in your app's config" if secret.blank?
-
secret
-
end
-
-
# Uses an MD5 digest based on time to generate a value to be used only once.
-
#
-
# A server-specified data string which should be uniquely generated each time a 401 response is made.
-
# It is recommended that this string be base64 or hexadecimal data.
-
# Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
-
#
-
# The contents of the nonce are implementation dependent.
-
# The quality of the implementation depends on a good choice.
-
# A nonce might, for example, be constructed as the base 64 encoding of
-
#
-
# => time-stamp H(time-stamp ":" ETag ":" private-key)
-
#
-
# where time-stamp is a server-generated time or other non-repeating value,
-
# ETag is the value of the HTTP ETag header associated with the requested entity,
-
# and private-key is data known only to the server.
-
# With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and
-
# reject the request if it did not match the nonce from that header or
-
# if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity.
-
# The inclusion of the ETag prevents a replay request for an updated version of the resource.
-
# (Note: including the IP address of the client in the nonce would appear to offer the server the ability
-
# to limit the reuse of the nonce to the same client that originally got it.
-
# However, that would break proxy farms, where requests from a single user often go through different proxies in the farm.
-
# Also, IP address spoofing is not that hard.)
-
#
-
# An implementation might choose not to accept a previously used nonce or a previously used digest, in order to
-
# protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for
-
# POST or PUT requests and a time-stamp for GET requests. For more details on the issues involved see Section 4
-
# of this document.
-
#
-
# The nonce is opaque to the client. Composed of Time, and hash of Time with secret
-
# key from the Rails session secret generated upon creation of project. Ensures
-
# the time cannot be modified by client.
-
2
def nonce(secret_key, time = Time.now)
-
t = time.to_i
-
hashed = [t, secret_key]
-
digest = ::Digest::MD5.hexdigest(hashed.join(":"))
-
::Base64.encode64("#{t}:#{digest}").gsub("\n", '')
-
end
-
-
# Might want a shorter timeout depending on whether the request
-
# is a PUT or POST, and if client is browser or web service.
-
# Can be much shorter if the Stale directive is implemented. This would
-
# allow a user to use new nonce without prompting user again for their
-
# username and password.
-
2
def validate_nonce(secret_key, request, value, seconds_to_timeout=5*60)
-
t = ::Base64.decode64(value).split(":").first.to_i
-
nonce(secret_key, t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout
-
end
-
-
# Opaque based on random generation - but changing each request?
-
2
def opaque(secret_key)
-
::Digest::MD5.hexdigest(secret_key)
-
end
-
-
end
-
-
# Makes it dead easy to do HTTP Token authentication.
-
#
-
# Simple Token example:
-
#
-
# class PostsController < ApplicationController
-
# TOKEN = "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_token do |token, options|
-
# token == TOKEN
-
# end
-
# end
-
# end
-
#
-
#
-
# Here is a more advanced Token example where only Atom feeds and the XML API is protected by HTTP token authentication,
-
# the regular HTML interface is protected by a session approach:
-
#
-
# class ApplicationController < ActionController::Base
-
# before_filter :set_account, :authenticate
-
#
-
# protected
-
# def set_account
-
# @account = Account.find_by_url_name(request.subdomains.first)
-
# end
-
#
-
# def authenticate
-
# case request.format
-
# when Mime::XML, Mime::ATOM
-
# if user = authenticate_with_http_token { |t, o| @account.users.authenticate(t, o) }
-
# @current_user = user
-
# else
-
# request_http_token_authentication
-
# end
-
# else
-
# if session_authenticated?
-
# @current_user = @account.users.find(session[:authenticated][:user_id])
-
# else
-
# redirect_to(login_url) and return false
-
# end
-
# end
-
# end
-
# end
-
#
-
#
-
# In your integration tests, you can do something like this:
-
#
-
# def test_access_granted_from_xml
-
# get(
-
# "/notes/1.xml", nil,
-
# :authorization => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
-
# )
-
#
-
# assert_equal 200, status
-
# end
-
#
-
#
-
# On shared hosts, Apache sometimes doesn't pass authentication headers to
-
# FCGI instances. If your environment matches this description and you cannot
-
# authenticate, try this rule in your Apache setup:
-
#
-
# RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
-
2
module Token
-
2
extend self
-
-
2
module ControllerMethods
-
2
def authenticate_or_request_with_http_token(realm = "Application", &login_procedure)
-
authenticate_with_http_token(&login_procedure) || request_http_token_authentication(realm)
-
end
-
-
2
def authenticate_with_http_token(&login_procedure)
-
Token.authenticate(self, &login_procedure)
-
end
-
-
2
def request_http_token_authentication(realm = "Application")
-
Token.authentication_request(self, realm)
-
end
-
end
-
-
# If token Authorization header is present, call the login procedure with
-
# the present token and options.
-
#
-
# controller - ActionController::Base instance for the current request.
-
# login_procedure - Proc to call if a token is present. The Proc should
-
# take 2 arguments:
-
# authenticate(controller) { |token, options| ... }
-
#
-
# Returns the return value of `&login_procedure` if a token is found.
-
# Returns nil if no token is found.
-
2
def authenticate(controller, &login_procedure)
-
token, options = token_and_options(controller.request)
-
unless token.blank?
-
login_procedure.call(token, options)
-
end
-
end
-
-
# Parses the token and options out of the token authorization header. If
-
# the header looks like this:
-
# Authorization: Token token="abc", nonce="def"
-
# Then the returned token is "abc", and the options is {:nonce => "def"}
-
#
-
# request - ActionDispatch::Request instance with the current headers.
-
#
-
# Returns an Array of [String, Hash] if a token is present.
-
# Returns nil if no token is found.
-
2
def token_and_options(request)
-
if request.authorization.to_s[/^Token (.*)/]
-
values = Hash[$1.split(',').map do |value|
-
value.strip! # remove any spaces between commas and values
-
key, value = value.split(/\=\"?/) # split key=value pairs
-
value.chomp!('"') # chomp trailing " in value
-
value.gsub!(/\\\"/, '"') # unescape remaining quotes
-
[key, value]
-
end]
-
[values.delete("token"), values.with_indifferent_access]
-
end
-
end
-
-
# Encodes the given token and options into an Authorization header value.
-
#
-
# token - String token.
-
# options - optional Hash of the options.
-
#
-
# Returns String.
-
2
def encode_credentials(token, options = {})
-
values = ["token=#{token.to_s.inspect}"] + options.map do |key, value|
-
"#{key}=#{value.to_s.inspect}"
-
end
-
"Token #{values * ", "}"
-
end
-
-
# Sets a WWW-Authenticate to let the client know a token is desired.
-
#
-
# controller - ActionController::Base instance for the outgoing response.
-
# realm - String realm to use in the header.
-
#
-
# Returns nothing.
-
2
def authentication_request(controller, realm)
-
controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
-
controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
-
end
-
end
-
end
-
end
-
2
module ActionController
-
2
module ImplicitRender
-
2
def send_action(method, *args)
-
ret = super
-
default_render unless response_body
-
ret
-
end
-
-
2
def default_render(*args)
-
render(*args)
-
end
-
-
2
def method_for_action(action_name)
-
super || if template_exists?(action_name.to_s, _prefixes)
-
"default_render"
-
9
end
-
end
-
end
-
end
-
2
require 'benchmark'
-
2
require 'abstract_controller/logger'
-
-
2
module ActionController
-
# Adds instrumentation to several ends in ActionController::Base. It also provides
-
# some hooks related with process_action, this allows an ORM like Active Record
-
# and/or DataMapper to plug in ActionController and show related information.
-
#
-
# Check ActiveRecord::Railties::ControllerRuntime for an example.
-
2
module Instrumentation
-
2
extend ActiveSupport::Concern
-
-
2
include AbstractController::Logger
-
-
2
attr_internal :view_runtime
-
-
2
def process_action(*args)
-
9
raw_payload = {
-
:controller => self.class.name,
-
:action => self.action_name,
-
:params => request.filtered_parameters,
-
:format => request.format.try(:ref),
-
:method => request.method,
-
9
:path => (request.fullpath rescue "unknown")
-
}
-
-
9
ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload.dup)
-
-
9
ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload|
-
9
result = super
-
9
payload[:status] = response.status
-
9
append_info_to_payload(payload)
-
9
result
-
end
-
end
-
-
2
def render(*args)
-
render_output = nil
-
self.view_runtime = cleanup_view_runtime do
-
Benchmark.ms { render_output = super }
-
end
-
render_output
-
end
-
-
2
def send_file(path, options={})
-
ActiveSupport::Notifications.instrument("send_file.action_controller",
-
options.merge(:path => path)) do
-
super
-
end
-
end
-
-
2
def send_data(data, options = {})
-
ActiveSupport::Notifications.instrument("send_data.action_controller", options) do
-
super
-
end
-
end
-
-
2
def redirect_to(*args)
-
9
ActiveSupport::Notifications.instrument("redirect_to.action_controller") do |payload|
-
9
result = super
-
9
payload[:status] = response.status
-
9
payload[:location] = response.location
-
9
result
-
end
-
end
-
-
2
private
-
-
# A hook invoked everytime a before callback is halted.
-
2
def halted_callback_hook(filter)
-
9
ActiveSupport::Notifications.instrument("halted_callback.action_controller", :filter => filter)
-
end
-
-
# A hook which allows you to clean up any time taken into account in
-
# views wrongly, like database querying time.
-
#
-
# def cleanup_view_runtime
-
# super - time_taken_in_something_expensive
-
# end
-
#
-
# :api: plugin
-
2
def cleanup_view_runtime #:nodoc:
-
yield
-
end
-
-
# Every time after an action is processed, this method is invoked
-
# with the payload, so you can add more information.
-
# :api: plugin
-
2
def append_info_to_payload(payload) #:nodoc:
-
9
payload[:view_runtime] = view_runtime
-
end
-
-
2
module ClassMethods
-
# A hook which allows other frameworks to log what happened during
-
# controller process action. This method should return an array
-
# with the messages to be added.
-
# :api: plugin
-
2
def log_process_action(payload) #:nodoc:
-
9
messages, view_runtime = [], payload[:view_runtime]
-
9
messages << ("Views: %.1fms" % view_runtime.to_f) if view_runtime
-
9
messages
-
end
-
end
-
end
-
end
-
2
require 'abstract_controller/collector'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/object/inclusion'
-
-
2
module ActionController #:nodoc:
-
2
module MimeResponds
-
2
extend ActiveSupport::Concern
-
-
2
include ActionController::ImplicitRender
-
-
2
included do
-
2
class_attribute :responder, :mimes_for_respond_to
-
2
self.responder = ActionController::Responder
-
2
clear_respond_to
-
end
-
-
2
module ClassMethods
-
# Defines mime types that are rendered by default when invoking
-
# <tt>respond_with</tt>.
-
#
-
# Examples:
-
#
-
# respond_to :html, :xml, :json
-
#
-
# Specifies that all actions in the controller respond to requests
-
# for <tt>:html</tt>, <tt>:xml</tt> and <tt>:json</tt>.
-
#
-
# To specify on per-action basis, use <tt>:only</tt> and
-
# <tt>:except</tt> with an array of actions or a single action:
-
#
-
# respond_to :html
-
# respond_to :xml, :json, :except => [ :edit ]
-
#
-
# This specifies that all actions respond to <tt>:html</tt>
-
# and all actions except <tt>:edit</tt> respond to <tt>:xml</tt> and
-
# <tt>:json</tt>.
-
#
-
# respond_to :json, :only => :create
-
#
-
# This specifies that the <tt>:create</tt> action and no other responds
-
# to <tt>:json</tt>.
-
2
def respond_to(*mimes)
-
options = mimes.extract_options!
-
-
only_actions = Array(options.delete(:only)).map(&:to_s)
-
except_actions = Array(options.delete(:except)).map(&:to_s)
-
-
new = mimes_for_respond_to.dup
-
mimes.each do |mime|
-
mime = mime.to_sym
-
new[mime] = {}
-
new[mime][:only] = only_actions unless only_actions.empty?
-
new[mime][:except] = except_actions unless except_actions.empty?
-
end
-
self.mimes_for_respond_to = new.freeze
-
end
-
-
# Clear all mime types in <tt>respond_to</tt>.
-
#
-
2
def clear_respond_to
-
2
self.mimes_for_respond_to = ActiveSupport::OrderedHash.new.freeze
-
end
-
end
-
-
# Without web-service support, an action which collects the data for displaying a list of people
-
# might look something like this:
-
#
-
# def index
-
# @people = Person.all
-
# end
-
#
-
# Here's the same action, with web-service support baked in:
-
#
-
# def index
-
# @people = Person.all
-
#
-
# respond_to do |format|
-
# format.html
-
# format.xml { render :xml => @people.to_xml }
-
# end
-
# end
-
#
-
# What that says is, "if the client wants HTML in response to this action, just respond as we
-
# would have before, but if the client wants XML, return them the list of people in XML format."
-
# (Rails determines the desired response format from the HTTP Accept header submitted by the client.)
-
#
-
# Supposing you have an action that adds a new person, optionally creating their company
-
# (by name) if it does not already exist, without web-services, it might look like this:
-
#
-
# def create
-
# @company = Company.find_or_create_by_name(params[:company][:name])
-
# @person = @company.people.create(params[:person])
-
#
-
# redirect_to(person_list_url)
-
# end
-
#
-
# Here's the same action, with web-service support baked in:
-
#
-
# def create
-
# company = params[:person].delete(:company)
-
# @company = Company.find_or_create_by_name(company[:name])
-
# @person = @company.people.create(params[:person])
-
#
-
# respond_to do |format|
-
# format.html { redirect_to(person_list_url) }
-
# format.js
-
# format.xml { render :xml => @person.to_xml(:include => @company) }
-
# end
-
# end
-
#
-
# If the client wants HTML, we just redirect them back to the person list. If they want JavaScript,
-
# then it is an Ajax request and we render the JavaScript template associated with this action.
-
# Lastly, if the client wants XML, we render the created person as XML, but with a twist: we also
-
# include the person's company in the rendered XML, so you get something like this:
-
#
-
# <person>
-
# <id>...</id>
-
# ...
-
# <company>
-
# <id>...</id>
-
# <name>...</name>
-
# ...
-
# </company>
-
# </person>
-
#
-
# Note, however, the extra bit at the top of that action:
-
#
-
# company = params[:person].delete(:company)
-
# @company = Company.find_or_create_by_name(company[:name])
-
#
-
# This is because the incoming XML document (if a web-service request is in process) can only contain a
-
# single root-node. So, we have to rearrange things so that the request looks like this (url-encoded):
-
#
-
# person[name]=...&person[company][name]=...&...
-
#
-
# And, like this (xml-encoded):
-
#
-
# <person>
-
# <name>...</name>
-
# <company>
-
# <name>...</name>
-
# </company>
-
# </person>
-
#
-
# In other words, we make the request so that it operates on a single entity's person. Then, in the action,
-
# we extract the company data from the request, find or create the company, and then create the new person
-
# with the remaining data.
-
#
-
# Note that you can define your own XML parameter parser which would allow you to describe multiple entities
-
# in a single request (i.e., by wrapping them all in a single root node), but if you just go with the flow
-
# and accept Rails' defaults, life will be much easier.
-
#
-
# If you need to use a MIME type which isn't supported by default, you can register your own handlers in
-
# config/initializers/mime_types.rb as follows.
-
#
-
# Mime::Type.register "image/jpg", :jpg
-
#
-
# Respond to also allows you to specify a common block for different formats by using any:
-
#
-
# def index
-
# @people = Person.all
-
#
-
# respond_to do |format|
-
# format.html
-
# format.any(:xml, :json) { render request.format.to_sym => @people }
-
# end
-
# end
-
#
-
# In the example above, if the format is xml, it will render:
-
#
-
# render :xml => @people
-
#
-
# Or if the format is json:
-
#
-
# render :json => @people
-
#
-
# Since this is a common pattern, you can use the class method respond_to
-
# with the respond_with method to have the same results:
-
#
-
# class PeopleController < ApplicationController
-
# respond_to :html, :xml, :json
-
#
-
# def index
-
# @people = Person.all
-
# respond_with(@people)
-
# end
-
# end
-
#
-
# Be sure to check respond_with and respond_to documentation for more examples.
-
#
-
2
def respond_to(*mimes, &block)
-
raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
-
-
if collector = retrieve_collector_from_mimes(mimes, &block)
-
response = collector.response
-
response ? response.call : default_render({})
-
end
-
end
-
-
# respond_with wraps a resource around a responder for default representation.
-
# First it invokes respond_to, if a response cannot be found (ie. no block
-
# for the request was given and template was not available), it instantiates
-
# an ActionController::Responder with the controller and resource.
-
#
-
# ==== Example
-
#
-
# def index
-
# @users = User.all
-
# respond_with(@users)
-
# end
-
#
-
# It also accepts a block to be given. It's used to overwrite a default
-
# response:
-
#
-
# def create
-
# @user = User.new(params[:user])
-
# flash[:notice] = "User was successfully created." if @user.save
-
#
-
# respond_with(@user) do |format|
-
# format.html { render }
-
# end
-
# end
-
#
-
# All options given to respond_with are sent to the underlying responder,
-
# except for the option :responder itself. Since the responder interface
-
# is quite simple (it just needs to respond to call), you can even give
-
# a proc to it.
-
#
-
# In order to use respond_with, first you need to declare the formats your
-
# controller responds to in the class level with a call to <tt>respond_to</tt>.
-
#
-
2
def respond_with(*resources, &block)
-
raise "In order to use respond_with, first you need to declare the formats your " <<
-
"controller responds to in the class level" if self.class.mimes_for_respond_to.empty?
-
-
if collector = retrieve_collector_from_mimes(&block)
-
options = resources.size == 1 ? {} : resources.extract_options!
-
options[:default_response] = collector.response
-
(options.delete(:responder) || self.class.responder).call(self, resources, options)
-
end
-
end
-
-
2
protected
-
-
# Collect mimes declared in the class method respond_to valid for the
-
# current action.
-
#
-
2
def collect_mimes_from_class_level #:nodoc:
-
action = action_name.to_s
-
-
self.class.mimes_for_respond_to.keys.select do |mime|
-
config = self.class.mimes_for_respond_to[mime]
-
-
if config[:except]
-
!action.in?(config[:except])
-
elsif config[:only]
-
action.in?(config[:only])
-
else
-
true
-
end
-
end
-
end
-
-
# Collects mimes and return the response for the negotiated format. Returns
-
# nil if :not_acceptable was sent to the client.
-
#
-
2
def retrieve_collector_from_mimes(mimes=nil, &block) #:nodoc:
-
mimes ||= collect_mimes_from_class_level
-
collector = Collector.new(mimes)
-
block.call(collector) if block_given?
-
format = collector.negotiate_format(request)
-
-
if format
-
self.content_type ||= format.to_s
-
lookup_context.formats = [format.to_sym]
-
lookup_context.rendered_format = lookup_context.formats.first
-
collector
-
else
-
head :not_acceptable
-
nil
-
end
-
end
-
-
2
class Collector #:nodoc:
-
2
include AbstractController::Collector
-
2
attr_accessor :order, :format
-
-
2
def initialize(mimes)
-
@order, @responses = [], {}
-
mimes.each { |mime| send(mime) }
-
end
-
-
2
def any(*args, &block)
-
if args.any?
-
args.each { |type| send(type, &block) }
-
else
-
custom(Mime::ALL, &block)
-
end
-
end
-
2
alias :all :any
-
-
2
def custom(mime_type, &block)
-
mime_type = Mime::Type.lookup(mime_type.to_s) unless mime_type.is_a?(Mime::Type)
-
@order << mime_type
-
@responses[mime_type] ||= block
-
end
-
-
2
def response
-
@responses[format] || @responses[Mime::ALL]
-
end
-
-
2
def negotiate_format(request)
-
@format = request.negotiate_mime(order)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'action_dispatch/http/mime_types'
-
-
2
module ActionController
-
# Wraps the parameters hash into a nested hash. This will allow clients to submit
-
# POST requests without having to specify any root elements.
-
#
-
# This functionality is enabled in +config/initializers/wrap_parameters.rb+
-
# and can be customized. If you are upgrading to \Rails 3.1, this file will
-
# need to be created for the functionality to be enabled.
-
#
-
# You could also turn it on per controller by setting the format array to
-
# a non-empty array:
-
#
-
# class UsersController < ApplicationController
-
# wrap_parameters :format => [:json, :xml]
-
# end
-
#
-
# If you enable +ParamsWrapper+ for +:json+ format, instead of having to
-
# send JSON parameters like this:
-
#
-
# {"user": {"name": "Konata"}}
-
#
-
# You can send parameters like this:
-
#
-
# {"name": "Konata"}
-
#
-
# And it will be wrapped into a nested hash with the key name matching the
-
# controller's name. For example, if you're posting to +UsersController+,
-
# your new +params+ hash will look like this:
-
#
-
# {"name" => "Konata", "user" => {"name" => "Konata"}}
-
#
-
# You can also specify the key in which the parameters should be wrapped to,
-
# and also the list of attributes it should wrap by using either +:include+ or
-
# +:exclude+ options like this:
-
#
-
# class UsersController < ApplicationController
-
# wrap_parameters :person, :include => [:username, :password]
-
# end
-
#
-
# On ActiveRecord models with no +:include+ or +:exclude+ option set,
-
# if attr_accessible is set on that model, it will only wrap the accessible
-
# parameters, else it will only wrap the parameters returned by the class
-
# method attribute_names.
-
#
-
# If you're going to pass the parameters to an +ActiveModel+ object (such as
-
# +User.new(params[:user])+), you might consider passing the model class to
-
# the method instead. The +ParamsWrapper+ will actually try to determine the
-
# list of attribute names from the model and only wrap those attributes:
-
#
-
# class UsersController < ApplicationController
-
# wrap_parameters Person
-
# end
-
#
-
# You still could pass +:include+ and +:exclude+ to set the list of attributes
-
# you want to wrap.
-
#
-
# By default, if you don't specify the key in which the parameters would be
-
# wrapped to, +ParamsWrapper+ will actually try to determine if there's
-
# a model related to it or not. This controller, for example:
-
#
-
# class Admin::UsersController < ApplicationController
-
# end
-
#
-
# will try to check if +Admin::User+ or +User+ model exists, and use it to
-
# determine the wrapper key respectively. If both models don't exist,
-
# it will then fallback to use +user+ as the key.
-
2
module ParamsWrapper
-
2
extend ActiveSupport::Concern
-
-
2
EXCLUDE_PARAMETERS = %w(authenticity_token _method utf8)
-
-
2
included do
-
2
class_attribute :_wrapper_options
-
2
self._wrapper_options = { :format => [] }
-
end
-
-
2
module ClassMethods
-
# Sets the name of the wrapper key, or the model which +ParamsWrapper+
-
# would use to determine the attribute names from.
-
#
-
# ==== Examples
-
# wrap_parameters :format => :xml
-
# # enables the parameter wrapper for XML format
-
#
-
# wrap_parameters :person
-
# # wraps parameters into +params[:person]+ hash
-
#
-
# wrap_parameters Person
-
# # wraps parameters by determining the wrapper key from Person class
-
# (+person+, in this case) and the list of attribute names
-
#
-
# wrap_parameters :include => [:username, :title]
-
# # wraps only +:username+ and +:title+ attributes from parameters.
-
#
-
# wrap_parameters false
-
# # disables parameters wrapping for this controller altogether.
-
#
-
# ==== Options
-
# * <tt>:format</tt> - The list of formats in which the parameters wrapper
-
# will be enabled.
-
# * <tt>:include</tt> - The list of attribute names which parameters wrapper
-
# will wrap into a nested hash.
-
# * <tt>:exclude</tt> - The list of attribute names which parameters wrapper
-
# will exclude from a nested hash.
-
2
def wrap_parameters(name_or_model_or_options, options = {})
-
2
model = nil
-
-
2
case name_or_model_or_options
-
when Hash
-
2
options = name_or_model_or_options
-
when false
-
options = options.merge(:format => [])
-
when Symbol, String
-
options = options.merge(:name => name_or_model_or_options)
-
else
-
model = name_or_model_or_options
-
end
-
-
2
_set_wrapper_defaults(_wrapper_options.slice(:format).merge(options), model)
-
end
-
-
# Sets the default wrapper key or model which will be used to determine
-
# wrapper key and attribute names. Will be called automatically when the
-
# module is inherited.
-
2
def inherited(klass)
-
29
if klass._wrapper_options[:format].present?
-
29
klass._set_wrapper_defaults(klass._wrapper_options.slice(:format))
-
end
-
29
super
-
end
-
-
2
protected
-
-
# Determine the wrapper model from the controller's name. By convention,
-
# this could be done by trying to find the defined model that has the
-
# same singularize name as the controller. For example, +UsersController+
-
# will try to find if the +User+ model exists.
-
#
-
# This method also does namespace lookup. Foo::Bar::UsersController will
-
# try to find Foo::Bar::User, Foo::User and finally User.
-
2
def _default_wrap_model #:nodoc:
-
43
return nil if self.anonymous?
-
43
model_name = self.name.sub(/Controller$/, '').classify
-
-
begin
-
45
if model_klass = model_name.safe_constantize
-
19
model_klass
-
else
-
26
namespaces = model_name.split("::")
-
26
namespaces.delete_at(-2)
-
26
break if namespaces.last == model_name
-
2
model_name = namespaces.join("::")
-
end
-
43
end until model_klass
-
-
43
model_klass
-
end
-
-
2
def _set_wrapper_defaults(options, model=nil)
-
31
options = options.dup
-
-
31
unless options[:include] || options[:exclude]
-
31
model ||= _default_wrap_model
-
31
role = options.has_key?(:as) ? options[:as] : :default
-
31
if model.respond_to?(:accessible_attributes) && model.accessible_attributes(role).present?
-
16
options[:include] = model.accessible_attributes(role).to_a
-
elsif model.respond_to?(:attribute_names) && model.attribute_names.present?
-
options[:include] = model.attribute_names
-
end
-
end
-
-
31
unless options[:name] || self.anonymous?
-
31
model ||= _default_wrap_model
-
31
options[:name] = model ? model.to_s.demodulize.underscore :
-
controller_name.singularize
-
end
-
-
31
options[:include] = Array.wrap(options[:include]).collect(&:to_s) if options[:include]
-
31
options[:exclude] = Array.wrap(options[:exclude]).collect(&:to_s) if options[:exclude]
-
31
options[:format] = Array.wrap(options[:format])
-
-
31
self._wrapper_options = options
-
end
-
end
-
-
# Performs parameters wrapping upon the request. Will be called automatically
-
# by the metal call stack.
-
2
def process_action(*args)
-
9
if _wrapper_enabled?
-
wrapped_hash = _wrap_parameters request.request_parameters
-
wrapped_keys = request.request_parameters.keys
-
wrapped_filtered_hash = _wrap_parameters request.filtered_parameters.slice(*wrapped_keys)
-
-
# This will make the wrapped hash accessible from controller and view
-
request.parameters.merge! wrapped_hash
-
request.request_parameters.merge! wrapped_hash
-
-
# This will make the wrapped hash displayed in the log file
-
request.filtered_parameters.merge! wrapped_filtered_hash
-
end
-
9
super
-
end
-
-
2
private
-
-
# Returns the wrapper key which will use to stored wrapped parameters.
-
2
def _wrapper_key
-
_wrapper_options[:name]
-
end
-
-
# Returns the list of enabled formats.
-
2
def _wrapper_formats
-
9
_wrapper_options[:format]
-
end
-
-
# Returns the list of parameters which will be selected for wrapped.
-
2
def _wrap_parameters(parameters)
-
value = if include_only = _wrapper_options[:include]
-
parameters.slice(*include_only)
-
else
-
exclude = _wrapper_options[:exclude] || []
-
parameters.except(*(exclude + EXCLUDE_PARAMETERS))
-
end
-
-
{ _wrapper_key => value }
-
end
-
-
# Checks if we should perform parameters wrapping.
-
2
def _wrapper_enabled?
-
9
ref = request.content_mime_type.try(:ref)
-
9
_wrapper_formats.include?(ref) && _wrapper_key && !request.request_parameters[_wrapper_key]
-
end
-
end
-
end
-
2
require 'action_dispatch/http/request'
-
2
require 'action_dispatch/http/response'
-
-
2
module ActionController
-
2
module RackDelegation
-
2
extend ActiveSupport::Concern
-
-
2
delegate :headers, :status=, :location=, :content_type=,
-
:status, :location, :content_type, :to => "@_response"
-
-
2
def dispatch(action, request, response = ActionDispatch::Response.new)
-
@_response ||= response
-
@_response.request ||= request
-
super(action, request)
-
end
-
-
2
def response_body=(body)
-
19
response.body = body if response
-
19
super
-
end
-
-
2
def reset_session
-
@_request.reset_session
-
end
-
end
-
end
-
2
module ActionController
-
2
class RedirectBackError < AbstractController::Error #:nodoc:
-
2
DEFAULT_MESSAGE = 'No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env["HTTP_REFERER"].'
-
-
2
def initialize(message = nil)
-
super(message || DEFAULT_MESSAGE)
-
end
-
end
-
-
2
module Redirecting
-
2
extend ActiveSupport::Concern
-
-
2
include AbstractController::Logger
-
2
include ActionController::RackDelegation
-
2
include ActionController::UrlFor
-
-
# Redirects the browser to the target specified in +options+. This parameter can take one of three forms:
-
#
-
# * <tt>Hash</tt> - The URL will be generated by calling url_for with the +options+.
-
# * <tt>Record</tt> - The URL will be generated by calling url_for with the +options+, which will reference a named URL for that record.
-
# * <tt>String</tt> starting with <tt>protocol://</tt> (like <tt>http://</tt>) or a protocol relative reference (like <tt>//</tt>) - Is passed straight through as the target for redirection.
-
# * <tt>String</tt> not containing a protocol - The current protocol and host is prepended to the string.
-
# * <tt>Proc</tt> - A block that will be executed in the controller's context. Should return any option accepted by +redirect_to+.
-
# * <tt>:back</tt> - Back to the page that issued the request. Useful for forms that are triggered from multiple places.
-
# Short-hand for <tt>redirect_to(request.env["HTTP_REFERER"])</tt>
-
#
-
# Examples:
-
# redirect_to :action => "show", :id => 5
-
# redirect_to post
-
# redirect_to "http://www.rubyonrails.org"
-
# redirect_to "/images/screenshot.jpg"
-
# redirect_to articles_url
-
# redirect_to :back
-
# redirect_to proc { edit_post_url(@post) }
-
#
-
# The redirection happens as a "302 Moved" header unless otherwise specified.
-
#
-
# Examples:
-
# redirect_to post_url(@post), :status => :found
-
# redirect_to :action=>'atom', :status => :moved_permanently
-
# redirect_to post_url(@post), :status => 301
-
# redirect_to :action=>'atom', :status => 302
-
#
-
# The status code can either be a standard {HTTP Status code}[http://www.iana.org/assignments/http-status-codes] as an
-
# integer, or a symbol representing the downcased, underscored and symbolized description.
-
# Note that the status code must be a 3xx HTTP code, or redirection will not occur.
-
#
-
# If you are using XHR requests other than GET or POST and redirecting after the
-
# request then some browsers will follow the redirect using the original request
-
# method. This may lead to undesirable behavior such as a double DELETE. To work
-
# around this you can return a <tt>303 See Other</tt> status code which will be
-
# followed using a GET request.
-
#
-
# Examples:
-
# redirect_to posts_url, :status => :see_other
-
# redirect_to :action => 'index', :status => 303
-
#
-
# It is also possible to assign a flash message as part of the redirection. There are two special accessors for the commonly used flash names
-
# +alert+ and +notice+ as well as a general purpose +flash+ bucket.
-
#
-
# Examples:
-
# redirect_to post_url(@post), :alert => "Watch it, mister!"
-
# redirect_to post_url(@post), :status=> :found, :notice => "Pay attention to the road"
-
# redirect_to post_url(@post), :status => 301, :flash => { :updated_post_id => @post.id }
-
# redirect_to { :action=>'atom' }, :alert => "Something serious happened"
-
#
-
# When using <tt>redirect_to :back</tt>, if there is no referrer, ActionController::RedirectBackError will be raised. You may specify some fallback
-
# behavior for this case by rescuing ActionController::RedirectBackError.
-
2
def redirect_to(options = {}, response_status = {}) #:doc:
-
9
raise ActionControllerError.new("Cannot redirect to nil!") unless options
-
9
raise AbstractController::DoubleRenderError if response_body
-
-
9
self.status = _extract_redirect_to_status(options, response_status)
-
9
self.location = _compute_redirect_to_location(options)
-
9
self.response_body = "<html><body>You are being <a href=\"#{ERB::Util.h(location)}\">redirected</a>.</body></html>"
-
end
-
-
2
private
-
2
def _extract_redirect_to_status(options, response_status)
-
9
if options.is_a?(Hash) && options.key?(:status)
-
Rack::Utils.status_code(options.delete(:status))
-
9
elsif response_status.key?(:status)
-
Rack::Utils.status_code(response_status[:status])
-
else
-
9
302
-
end
-
end
-
-
2
def _compute_redirect_to_location(options)
-
9
case options
-
# The scheme name consist of a letter followed by any combination of
-
# letters, digits, and the plus ("+"), period ("."), or hyphen ("-")
-
# characters; and is terminated by a colon (":").
-
# The protocol relative scheme starts with a double slash "//"
-
when %r{^(\w[\w+.-]*:|//).*}
-
9
options
-
when String
-
request.protocol + request.host_with_port + options
-
when :back
-
raise RedirectBackError unless refer = request.headers["Referer"]
-
refer
-
when Proc
-
_compute_redirect_to_location options.call
-
else
-
url_for(options)
-
end.gsub(/[\0\r\n]/, '')
-
end
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'set'
-
-
2
module ActionController
-
# See <tt>Renderers.add</tt>
-
2
def self.add_renderer(key, &block)
-
Renderers.add(key, &block)
-
end
-
-
2
module Renderers
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :_renderers
-
2
self._renderers = Set.new.freeze
-
end
-
-
2
module ClassMethods
-
2
def use_renderers(*args)
-
renderers = _renderers + args
-
self._renderers = renderers.freeze
-
end
-
2
alias use_renderer use_renderers
-
end
-
-
2
def render_to_body(options)
-
_handle_render_options(options) || super
-
end
-
-
2
def _handle_render_options(options)
-
_renderers.each do |name|
-
if options.key?(name)
-
_process_options(options)
-
return send("_render_option_#{name}", options.delete(name), options)
-
end
-
end
-
nil
-
end
-
-
# Hash of available renderers, mapping a renderer name to its proc.
-
# Default keys are :json, :js, :xml.
-
2
RENDERERS = Set.new
-
-
# Adds a new renderer to call within controller actions.
-
# A renderer is invoked by passing its name as an option to
-
# <tt>AbstractController::Rendering#render</tt>. To create a renderer
-
# pass it a name and a block. The block takes two arguments, the first
-
# is the value paired with its key and the second is the remaining
-
# hash of options passed to +render+.
-
#
-
# === Example
-
# Create a csv renderer:
-
#
-
# ActionController::Renderers.add :csv do |obj, options|
-
# filename = options[:filename] || 'data'
-
# str = obj.respond_to?(:to_csv) ? obj.to_csv : obj.to_s
-
# send_data str, :type => Mime::CSV,
-
# :disposition => "attachment; filename=#{filename}.csv"
-
# end
-
#
-
# Note that we used Mime::CSV for the csv mime type as it comes with Rails.
-
# For a custom renderer, you'll need to register a mime type with
-
# <tt>Mime::Type.register</tt>.
-
#
-
# To use the csv renderer in a controller action:
-
#
-
# def show
-
# @csvable = Csvable.find(params[:id])
-
# respond_to do |format|
-
# format.html
-
# format.csv { render :csv => @csvable, :filename => @csvable.name }
-
# }
-
# end
-
# To use renderers and their mime types in more concise ways, see
-
# <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt> and
-
# <tt>ActionController::MimeResponds#respond_with</tt>
-
2
def self.add(key, &block)
-
6
define_method("_render_option_#{key}", &block)
-
6
RENDERERS << key.to_sym
-
end
-
-
2
module All
-
2
extend ActiveSupport::Concern
-
2
include Renderers
-
-
2
included do
-
2
self._renderers = RENDERERS
-
end
-
end
-
-
2
add :json do |json, options|
-
json = json.to_json(options) unless json.kind_of?(String)
-
json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
-
self.content_type ||= Mime::JSON
-
json
-
end
-
-
2
add :js do |js, options|
-
self.content_type ||= Mime::JS
-
js.respond_to?(:to_js) ? js.to_js(options) : js
-
end
-
-
2
add :xml do |xml, options|
-
self.content_type ||= Mime::XML
-
xml.respond_to?(:to_xml) ? xml.to_xml(options) : xml
-
end
-
end
-
end
-
2
module ActionController
-
2
module Rendering
-
2
extend ActiveSupport::Concern
-
-
2
include AbstractController::Rendering
-
-
# Before processing, set the request formats in current controller formats.
-
2
def process_action(*) #:nodoc:
-
self.formats = request.formats.map { |x| x.ref }
-
super
-
end
-
-
# Check for double render errors and set the content_type after rendering.
-
2
def render(*args) #:nodoc:
-
raise ::AbstractController::DoubleRenderError if response_body
-
super
-
self.content_type ||= Mime[lookup_context.rendered_format].to_s
-
response_body
-
end
-
-
# Overwrite render_to_string because body can now be set to a rack body.
-
2
def render_to_string(*)
-
if self.response_body = super
-
string = ""
-
response_body.each { |r| string << r }
-
string
-
end
-
ensure
-
self.response_body = nil
-
end
-
-
2
private
-
-
# Normalize arguments by catching blocks and setting them on :update.
-
2
def _normalize_args(action=nil, options={}, &blk) #:nodoc:
-
options = super
-
options[:update] = blk if block_given?
-
options
-
end
-
-
# Normalize both text and status options.
-
2
def _normalize_options(options) #:nodoc:
-
if options.key?(:text) && options[:text].respond_to?(:to_text)
-
options[:text] = options[:text].to_text
-
end
-
-
if options[:status]
-
options[:status] = Rack::Utils.status_code(options[:status])
-
end
-
-
super
-
end
-
-
# Process controller specific options, as status, content-type and location.
-
2
def _process_options(options) #:nodoc:
-
status, content_type, location = options.values_at(:status, :content_type, :location)
-
-
self.status = status if status
-
self.content_type = content_type if content_type
-
self.headers["Location"] = url_for(location) if location
-
-
super
-
end
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'action_controller/metal/exceptions'
-
-
2
module ActionController #:nodoc:
-
2
class InvalidAuthenticityToken < ActionControllerError #:nodoc:
-
end
-
-
# Controller actions are protected from Cross-Site Request Forgery (CSRF) attacks
-
# by including a token in the rendered html for your application. This token is
-
# stored as a random string in the session, to which an attacker does not have
-
# access. When a request reaches your application, \Rails verifies the received
-
# token with the token in the session. Only HTML and JavaScript requests are checked,
-
# so this will not protect your XML API (presumably you'll have a different
-
# authentication scheme there anyway). Also, GET requests are not protected as these
-
# should be idempotent.
-
#
-
# CSRF protection is turned on with the <tt>protect_from_forgery</tt> method,
-
# which checks the token and resets the session if it doesn't match what was expected.
-
# A call to this method is generated for new \Rails applications by default.
-
# You can customize the error message by editing public/422.html.
-
#
-
# The token parameter is named <tt>authenticity_token</tt> by default. The name and
-
# value of this token must be added to every layout that renders forms by including
-
# <tt>csrf_meta_tags</tt> in the html +head+.
-
#
-
# Learn more about CSRF attacks and securing your application in the
-
# {Ruby on Rails Security Guide}[http://guides.rubyonrails.org/security.html].
-
2
module RequestForgeryProtection
-
2
extend ActiveSupport::Concern
-
-
2
include AbstractController::Helpers
-
2
include AbstractController::Callbacks
-
-
2
included do
-
# Sets the token parameter name for RequestForgery. Calling +protect_from_forgery+
-
# sets it to <tt>:authenticity_token</tt> by default.
-
2
config_accessor :request_forgery_protection_token
-
2
self.request_forgery_protection_token ||= :authenticity_token
-
-
# Controls whether request forgery protection is turned on or not. Turned off by default only in test mode.
-
2
config_accessor :allow_forgery_protection
-
2
self.allow_forgery_protection = true if allow_forgery_protection.nil?
-
-
2
helper_method :form_authenticity_token
-
2
helper_method :protect_against_forgery?
-
end
-
-
2
module ClassMethods
-
# Turn on request forgery protection. Bear in mind that only non-GET, HTML/JavaScript requests are checked.
-
#
-
# Example:
-
#
-
# class FooController < ApplicationController
-
# protect_from_forgery :except => :index
-
#
-
# You can disable csrf protection on controller-by-controller basis:
-
#
-
# skip_before_filter :verify_authenticity_token
-
#
-
# It can also be disabled for specific controller actions:
-
#
-
# skip_before_filter :verify_authenticity_token, :except => [:create]
-
#
-
# Valid Options:
-
#
-
# * <tt>:only/:except</tt> - Passed to the <tt>before_filter</tt> call. Set which actions are verified.
-
2
def protect_from_forgery(options = {})
-
2
self.request_forgery_protection_token ||= :authenticity_token
-
2
prepend_before_filter :verify_authenticity_token, options
-
end
-
end
-
-
2
protected
-
# The actual before_filter that is used. Modify this to change how you handle unverified requests.
-
2
def verify_authenticity_token
-
9
unless verified_request?
-
logger.warn "WARNING: Can't verify CSRF token authenticity" if logger
-
handle_unverified_request
-
end
-
end
-
-
# This is the method that defines the application behavior when a request is found to be unverified.
-
# By default, \Rails resets the session when it finds an unverified request.
-
2
def handle_unverified_request
-
reset_session
-
end
-
-
# Returns true or false if a request is verified. Checks:
-
#
-
# * is it a GET request? Gets should be safe and idempotent
-
# * Does the form_authenticity_token match the given token value from the params?
-
# * Does the X-CSRF-Token header match the form_authenticity_token
-
2
def verified_request?
-
9
!protect_against_forgery? || request.get? ||
-
form_authenticity_token == params[request_forgery_protection_token] ||
-
form_authenticity_token == request.headers['X-CSRF-Token']
-
end
-
-
# Sets the token value for the current session.
-
2
def form_authenticity_token
-
session[:_csrf_token] ||= SecureRandom.base64(32)
-
end
-
-
# The form's authenticity parameter. Override to provide your own.
-
2
def form_authenticity_param
-
params[request_forgery_protection_token]
-
end
-
-
2
def protect_against_forgery?
-
9
allow_forgery_protection
-
end
-
end
-
end
-
2
module ActionController #:nodoc:
-
# This module is responsible to provide `rescue_from` helpers
-
# to controllers and configure when detailed exceptions must be
-
# shown.
-
2
module Rescue
-
2
extend ActiveSupport::Concern
-
2
include ActiveSupport::Rescuable
-
-
2
def rescue_with_handler(exception)
-
if (exception.respond_to?(:original_exception) &&
-
(orig_exception = exception.original_exception) &&
-
handler_for_rescue(orig_exception))
-
exception = orig_exception
-
end
-
super(exception)
-
end
-
-
# Override this method if you want to customize when detailed
-
# exceptions must be shown. This method is only called when
-
# consider_all_requests_local is false. By default, it returns
-
# false, but someone may set it to `request.local?` so local
-
# requests in production still shows the detailed exception pages.
-
2
def show_detailed_exceptions?
-
false
-
end
-
-
2
private
-
2
def process_action(*args)
-
9
super
-
rescue Exception => exception
-
request.env['action_dispatch.show_detailed_exceptions'] ||= show_detailed_exceptions?
-
rescue_with_handler(exception) || raise(exception)
-
end
-
end
-
end
-
2
require 'active_support/json'
-
-
2
module ActionController #:nodoc:
-
# Responsible for exposing a resource to different mime requests,
-
# usually depending on the HTTP verb. The responder is triggered when
-
# <code>respond_with</code> is called. The simplest case to study is a GET request:
-
#
-
# class PeopleController < ApplicationController
-
# respond_to :html, :xml, :json
-
#
-
# def index
-
# @people = Person.all
-
# respond_with(@people)
-
# end
-
# end
-
#
-
# When a request comes in, for example for an XML response, three steps happen:
-
#
-
# 1) the responder searches for a template at people/index.xml;
-
#
-
# 2) if the template is not available, it will invoke <code>#to_xml</code> on the given resource;
-
#
-
# 3) if the responder does not <code>respond_to :to_xml</code>, call <code>#to_format</code> on it.
-
#
-
# === Builtin HTTP verb semantics
-
#
-
# The default \Rails responder holds semantics for each HTTP verb. Depending on the
-
# content type, verb and the resource status, it will behave differently.
-
#
-
# Using \Rails default responder, a POST request for creating an object could
-
# be written as:
-
#
-
# def create
-
# @user = User.new(params[:user])
-
# flash[:notice] = 'User was successfully created.' if @user.save
-
# respond_with(@user)
-
# end
-
#
-
# Which is exactly the same as:
-
#
-
# def create
-
# @user = User.new(params[:user])
-
#
-
# respond_to do |format|
-
# if @user.save
-
# flash[:notice] = 'User was successfully created.'
-
# format.html { redirect_to(@user) }
-
# format.xml { render :xml => @user, :status => :created, :location => @user }
-
# else
-
# format.html { render :action => "new" }
-
# format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
-
# end
-
# end
-
# end
-
#
-
# The same happens for PUT and DELETE requests.
-
#
-
# === Nested resources
-
#
-
# You can supply nested resources as you do in <code>form_for</code> and <code>polymorphic_url</code>.
-
# Consider the project has many tasks example. The create action for
-
# TasksController would be like:
-
#
-
# def create
-
# @project = Project.find(params[:project_id])
-
# @task = @project.comments.build(params[:task])
-
# flash[:notice] = 'Task was successfully created.' if @task.save
-
# respond_with(@project, @task)
-
# end
-
#
-
# Giving several resources ensures that the responder will redirect to
-
# <code>project_task_url</code> instead of <code>task_url</code>.
-
#
-
# Namespaced and singleton resources require a symbol to be given, as in
-
# polymorphic urls. If a project has one manager which has many tasks, it
-
# should be invoked as:
-
#
-
# respond_with(@project, :manager, @task)
-
#
-
# Note that if you give an array, it will be treated as a collection,
-
# so the following is not equivalent:
-
#
-
# respond_with [@project, :manager, @task]
-
#
-
# === Custom options
-
#
-
# <code>respond_with</code> also allows you to pass options that are forwarded
-
# to the underlying render call. Those options are only applied for success
-
# scenarios. For instance, you can do the following in the create method above:
-
#
-
# def create
-
# @project = Project.find(params[:project_id])
-
# @task = @project.comments.build(params[:task])
-
# flash[:notice] = 'Task was successfully created.' if @task.save
-
# respond_with(@project, @task, :status => 201)
-
# end
-
#
-
# This will return status 201 if the task was saved successfully. If not,
-
# it will simply ignore the given options and return status 422 and the
-
# resource errors. To customize the failure scenario, you can pass a
-
# a block to <code>respond_with</code>:
-
#
-
# def create
-
# @project = Project.find(params[:project_id])
-
# @task = @project.comments.build(params[:task])
-
# respond_with(@project, @task, :status => 201) do |format|
-
# if @task.save
-
# flash[:notice] = 'Task was successfully created.'
-
# else
-
# format.html { render "some_special_template" }
-
# end
-
# end
-
# end
-
#
-
# Using <code>respond_with</code> with a block follows the same syntax as <code>respond_to</code>.
-
2
class Responder
-
2
attr_reader :controller, :request, :format, :resource, :resources, :options
-
-
2
ACTIONS_FOR_VERBS = {
-
:post => :new,
-
:put => :edit
-
}
-
-
2
def initialize(controller, resources, options={})
-
@controller = controller
-
@request = @controller.request
-
@format = @controller.formats.first
-
@resource = resources.last
-
@resources = resources
-
@options = options
-
@action = options.delete(:action)
-
@default_response = options.delete(:default_response)
-
end
-
-
2
delegate :head, :render, :redirect_to, :to => :controller
-
2
delegate :get?, :post?, :put?, :delete?, :to => :request
-
-
# Undefine :to_json and :to_yaml since it's defined on Object
-
2
undef_method(:to_json) if method_defined?(:to_json)
-
2
undef_method(:to_yaml) if method_defined?(:to_yaml)
-
-
# Initializes a new responder an invoke the proper format. If the format is
-
# not defined, call to_format.
-
#
-
2
def self.call(*args)
-
new(*args).respond
-
end
-
-
# Main entry point for responder responsible to dispatch to the proper format.
-
#
-
2
def respond
-
method = "to_#{format}"
-
respond_to?(method) ? send(method) : to_format
-
end
-
-
# HTML format does not render the resource, it always attempt to render a
-
# template.
-
#
-
2
def to_html
-
default_render
-
rescue ActionView::MissingTemplate => e
-
navigation_behavior(e)
-
end
-
-
# to_js simply tries to render a template. If no template is found, raises the error.
-
2
def to_js
-
default_render
-
end
-
-
# All other formats follow the procedure below. First we try to render a
-
# template, if the template is not available, we verify if the resource
-
# responds to :to_format and display it.
-
#
-
2
def to_format
-
if get? || !has_errors? || response_overridden?
-
default_render
-
else
-
display_errors
-
end
-
rescue ActionView::MissingTemplate => e
-
api_behavior(e)
-
end
-
-
2
protected
-
-
# This is the common behavior for formats associated with browsing, like :html, :iphone and so forth.
-
2
def navigation_behavior(error)
-
if get?
-
raise error
-
elsif has_errors? && default_action
-
render :action => default_action
-
else
-
redirect_to navigation_location
-
end
-
end
-
-
# This is the common behavior for formats associated with APIs, such as :xml and :json.
-
2
def api_behavior(error)
-
raise error unless resourceful?
-
-
if get?
-
display resource
-
elsif post?
-
display resource, :status => :created, :location => api_location
-
else
-
head :no_content
-
end
-
end
-
-
# Checks whether the resource responds to the current format or not.
-
#
-
2
def resourceful?
-
resource.respond_to?("to_#{format}")
-
end
-
-
# Returns the resource location by retrieving it from the options or
-
# returning the resources array.
-
#
-
2
def resource_location
-
options[:location] || resources
-
end
-
2
alias :navigation_location :resource_location
-
2
alias :api_location :resource_location
-
-
# If a response block was given, use it, otherwise call render on
-
# controller.
-
#
-
2
def default_render
-
if @default_response
-
@default_response.call(options)
-
else
-
controller.default_render(options)
-
end
-
end
-
-
# Display is just a shortcut to render a resource with the current format.
-
#
-
# display @user, :status => :ok
-
#
-
# For XML requests it's equivalent to:
-
#
-
# render :xml => @user, :status => :ok
-
#
-
# Options sent by the user are also used:
-
#
-
# respond_with(@user, :status => :created)
-
# display(@user, :status => :ok)
-
#
-
# Results in:
-
#
-
# render :xml => @user, :status => :created
-
#
-
2
def display(resource, given_options={})
-
controller.render given_options.merge!(options).merge!(format => resource)
-
end
-
-
2
def display_errors
-
controller.render format => resource_errors, :status => :unprocessable_entity
-
end
-
-
# Check whether the resource has errors.
-
#
-
2
def has_errors?
-
resource.respond_to?(:errors) && !resource.errors.empty?
-
end
-
-
# By default, render the <code>:edit</code> action for HTML requests with failure, unless
-
# the verb is POST.
-
#
-
2
def default_action
-
@action ||= ACTIONS_FOR_VERBS[request.request_method_symbol]
-
end
-
-
2
def resource_errors
-
respond_to?("#{format}_resource_errors", true) ? send("#{format}_resource_errors") : resource.errors
-
end
-
-
2
def json_resource_errors
-
{:errors => resource.errors}
-
end
-
-
2
def response_overridden?
-
@default_response.present?
-
end
-
end
-
end
-
2
require 'active_support/core_ext/file/path'
-
2
require 'rack/chunked'
-
-
2
module ActionController #:nodoc:
-
# Allows views to be streamed back to the client as they are rendered.
-
#
-
# The default way Rails renders views is by first rendering the template
-
# and then the layout. The response is sent to the client after the whole
-
# template is rendered, all queries are made, and the layout is processed.
-
#
-
# Streaming inverts the rendering flow by rendering the layout first and
-
# streaming each part of the layout as they are processed. This allows the
-
# header of the HTML (which is usually in the layout) to be streamed back
-
# to client very quickly, allowing JavaScripts and stylesheets to be loaded
-
# earlier than usual.
-
#
-
# This approach was introduced in Rails 3.1 and is still improving. Several
-
# Rack middlewares may not work and you need to be careful when streaming.
-
# Those points are going to be addressed soon.
-
#
-
# In order to use streaming, you will need to use a Ruby version that
-
# supports fibers (fibers are supported since version 1.9.2 of the main
-
# Ruby implementation).
-
#
-
# == Examples
-
#
-
# Streaming can be added to a given template easily, all you need to do is
-
# to pass the :stream option.
-
#
-
# class PostsController
-
# def index
-
# @posts = Post.scoped
-
# render :stream => true
-
# end
-
# end
-
#
-
# == When to use streaming
-
#
-
# Streaming may be considered to be overkill for lightweight actions like
-
# +new+ or +edit+. The real benefit of streaming is on expensive actions
-
# that, for example, do a lot of queries on the database.
-
#
-
# In such actions, you want to delay queries execution as much as you can.
-
# For example, imagine the following +dashboard+ action:
-
#
-
# def dashboard
-
# @posts = Post.all
-
# @pages = Page.all
-
# @articles = Article.all
-
# end
-
#
-
# Most of the queries here are happening in the controller. In order to benefit
-
# from streaming you would want to rewrite it as:
-
#
-
# def dashboard
-
# # Allow lazy execution of the queries
-
# @posts = Post.scoped
-
# @pages = Page.scoped
-
# @articles = Article.scoped
-
# render :stream => true
-
# end
-
#
-
# Notice that :stream only works with templates. Rendering :json
-
# or :xml with :stream won't work.
-
#
-
# == Communication between layout and template
-
#
-
# When streaming, rendering happens top-down instead of inside-out.
-
# Rails starts with the layout, and the template is rendered later,
-
# when its +yield+ is reached.
-
#
-
# This means that, if your application currently relies on instance
-
# variables set in the template to be used in the layout, they won't
-
# work once you move to streaming. The proper way to communicate
-
# between layout and template, regardless of whether you use streaming
-
# or not, is by using +content_for+, +provide+ and +yield+.
-
#
-
# Take a simple example where the layout expects the template to tell
-
# which title to use:
-
#
-
# <html>
-
# <head><title><%= yield :title %></title></head>
-
# <body><%= yield %></body>
-
# </html>
-
#
-
# You would use +content_for+ in your template to specify the title:
-
#
-
# <%= content_for :title, "Main" %>
-
# Hello
-
#
-
# And the final result would be:
-
#
-
# <html>
-
# <head><title>Main</title></head>
-
# <body>Hello</body>
-
# </html>
-
#
-
# However, if +content_for+ is called several times, the final result
-
# would have all calls concatenated. For instance, if we have the following
-
# template:
-
#
-
# <%= content_for :title, "Main" %>
-
# Hello
-
# <%= content_for :title, " page" %>
-
#
-
# The final result would be:
-
#
-
# <html>
-
# <head><title>Main page</title></head>
-
# <body>Hello</body>
-
# </html>
-
#
-
# This means that, if you have <code>yield :title</code> in your layout
-
# and you want to use streaming, you would have to render the whole template
-
# (and eventually trigger all queries) before streaming the title and all
-
# assets, which kills the purpose of streaming. For this reason Rails 3.1
-
# introduces a new helper called +provide+ that does the same as +content_for+
-
# but tells the layout to stop searching for other entries and continue rendering.
-
#
-
# For instance, the template above using +provide+ would be:
-
#
-
# <%= provide :title, "Main" %>
-
# Hello
-
# <%= content_for :title, " page" %>
-
#
-
# Giving:
-
#
-
# <html>
-
# <head><title>Main</title></head>
-
# <body>Hello</body>
-
# </html>
-
#
-
# That said, when streaming, you need to properly check your templates
-
# and choose when to use +provide+ and +content_for+.
-
#
-
# == Headers, cookies, session and flash
-
#
-
# When streaming, the HTTP headers are sent to the client right before
-
# it renders the first line. This means that, modifying headers, cookies,
-
# session or flash after the template starts rendering will not propagate
-
# to the client.
-
#
-
# If you try to modify cookies, session or flash, an +ActionDispatch::ClosedError+
-
# will be raised, showing those objects are closed for modification.
-
#
-
# == Middlewares
-
#
-
# Middlewares that need to manipulate the body won't work with streaming.
-
# You should disable those middlewares whenever streaming in development
-
# or production. For instance, +Rack::Bug+ won't work when streaming as it
-
# needs to inject contents in the HTML body.
-
#
-
# Also +Rack::Cache+ won't work with streaming as it does not support
-
# streaming bodies yet. Whenever streaming Cache-Control is automatically
-
# set to "no-cache".
-
#
-
# == Errors
-
#
-
# When it comes to streaming, exceptions get a bit more complicated. This
-
# happens because part of the template was already rendered and streamed to
-
# the client, making it impossible to render a whole exception page.
-
#
-
# Currently, when an exception happens in development or production, Rails
-
# will automatically stream to the client:
-
#
-
# "><script type="text/javascript">window.location = "/500.html"</script></html>
-
#
-
# The first two characters (">) are required in case the exception happens
-
# while rendering attributes for a given tag. You can check the real cause
-
# for the exception in your logger.
-
#
-
# == Web server support
-
#
-
# Not all web servers support streaming out-of-the-box. You need to check
-
# the instructions for each of them.
-
#
-
# ==== Unicorn
-
#
-
# Unicorn supports streaming but it needs to be configured. For this, you
-
# need to create a config file as follow:
-
#
-
# # unicorn.config.rb
-
# listen 3000, :tcp_nopush => false
-
#
-
# And use it on initialization:
-
#
-
# unicorn_rails --config-file unicorn.config.rb
-
#
-
# You may also want to configure other parameters like <tt>:tcp_nodelay</tt>.
-
# Please check its documentation for more information: http://unicorn.bogomips.org/Unicorn/Configurator.html#method-i-listen
-
#
-
# If you are using Unicorn with Nginx, you may need to tweak Nginx.
-
# Streaming should work out of the box on Rainbows.
-
#
-
# ==== Passenger
-
#
-
# To be described.
-
#
-
2
module Streaming
-
2
extend ActiveSupport::Concern
-
-
2
include AbstractController::Rendering
-
-
2
protected
-
-
# Set proper cache control and transfer encoding when streaming
-
2
def _process_options(options) #:nodoc:
-
super
-
if options[:stream]
-
if env["HTTP_VERSION"] == "HTTP/1.0"
-
options.delete(:stream)
-
else
-
headers["Cache-Control"] ||= "no-cache"
-
headers["Transfer-Encoding"] = "chunked"
-
headers.delete("Content-Length")
-
end
-
end
-
end
-
-
# Call render_to_body if we are streaming instead of usual +render+.
-
2
def _render_template(options) #:nodoc:
-
if options.delete(:stream)
-
Rack::Chunked::Body.new view_renderer.render_body(view_context, options)
-
else
-
super
-
end
-
end
-
end
-
end
-
1
module ActionController
-
1
module Testing
-
1
extend ActiveSupport::Concern
-
-
1
include RackDelegation
-
-
1
def recycle!
-
9
@_url_options = nil
-
end
-
-
-
# TODO: Clean this up
-
1
def process_with_new_base_test(request, response)
-
9
@_request = request
-
9
@_response = response
-
9
@_response.request = request
-
9
ret = process(request.parameters[:action])
-
9
if cookies = @_request.env['action_dispatch.cookies']
-
9
cookies.write(@_response)
-
end
-
9
@_response.prepare!
-
9
ret
-
end
-
-
# TODO : Rewrite tests using controller.headers= to use Rack env
-
1
def headers=(new_headers)
-
@_response ||= ActionDispatch::Response.new
-
@_response.headers.replace(new_headers)
-
end
-
-
1
module ClassMethods
-
1
def before_filters
-
_process_action_callbacks.find_all{|x| x.kind == :before}.map{|x| x.name}
-
end
-
end
-
end
-
end
-
# Includes +url_for+ into the host class. The class has to provide a +RouteSet+ by implementing
-
# the <tt>_routes</tt> method. Otherwise, an exception will be raised.
-
#
-
# In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define
-
# url options like the +host+. In order to do so, this module requires the host class
-
# to implement +env+ and +request+, which need to be a Rack-compatible.
-
#
-
# Example:
-
#
-
# class RootUrl
-
# include ActionController::UrlFor
-
# include Rails.application.routes.url_helpers
-
#
-
# delegate :env, :request, :to => :controller
-
#
-
# def initialize(controller)
-
# @controller = controller
-
# @url = root_path # named route from the application.
-
# end
-
# end
-
#
-
2
module ActionController
-
2
module UrlFor
-
2
extend ActiveSupport::Concern
-
-
2
include AbstractController::UrlFor
-
-
2
def url_options
-
@_url_options ||= super.reverse_merge(
-
:host => request.host,
-
:port => request.optional_port,
-
:protocol => request.protocol,
-
:_path_segments => request.symbolized_path_parameters
-
19
).freeze
-
-
19
if _routes.equal?(env["action_dispatch.routes"])
-
@_url_options.dup.tap do |options|
-
options[:script_name] = request.script_name.dup
-
options.freeze
-
end
-
else
-
19
@_url_options
-
end
-
end
-
-
end
-
end
-
2
require "rails"
-
2
require "action_controller"
-
2
require "action_dispatch/railtie"
-
2
require "action_view/railtie"
-
2
require "abstract_controller/railties/routes_helpers"
-
2
require "action_controller/railties/paths"
-
-
2
module ActionController
-
2
class Railtie < Rails::Railtie
-
2
config.action_controller = ActiveSupport::OrderedOptions.new
-
-
2
initializer "action_controller.logger" do
-
4
ActiveSupport.on_load(:action_controller) { self.logger ||= Rails.logger }
-
end
-
-
2
initializer "action_controller.initialize_framework_caches" do
-
4
ActiveSupport.on_load(:action_controller) { self.cache_store ||= RAILS_CACHE }
-
end
-
-
2
initializer "action_controller.assets_config", :group => :all do |app|
-
2
app.config.action_controller.assets_dir ||= app.config.paths["public"].first
-
end
-
-
2
initializer "action_controller.set_configs" do |app|
-
2
paths = app.config.paths
-
2
options = app.config.action_controller
-
-
2
options.javascripts_dir ||= paths["public/javascripts"].first
-
2
options.stylesheets_dir ||= paths["public/stylesheets"].first
-
2
options.page_cache_directory ||= paths["public"].first
-
-
# make sure readers methods get compiled
-
2
options.asset_path ||= app.config.asset_path
-
2
options.asset_host ||= app.config.asset_host
-
2
options.relative_url_root ||= app.config.relative_url_root
-
-
2
ActiveSupport.on_load(:action_controller) do
-
2
include app.routes.mounted_helpers
-
2
extend ::AbstractController::Railties::RoutesHelpers.with(app.routes)
-
2
extend ::ActionController::Railties::Paths.with(app)
-
20
options.each { |k,v| send("#{k}=", v) }
-
end
-
end
-
-
2
initializer "action_controller.compile_config_methods" do
-
2
ActiveSupport.on_load(:action_controller) do
-
2
config.compile_methods! if config.respond_to?(:compile_methods!)
-
end
-
end
-
end
-
end
-
2
module ActionController
-
2
module Railties
-
2
module Paths
-
2
def self.with(app)
-
2
Module.new do
-
2
define_method(:inherited) do |klass|
-
29
super(klass)
-
-
60
if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_helpers_paths) }
-
paths = namespace.railtie_helpers_paths
-
else
-
29
paths = app.helpers_paths
-
end
-
-
29
klass.helpers_path = paths
-
-
29
if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers
-
3
klass.helper :all
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module'
-
-
2
module ActionController
-
# The record identifier encapsulates a number of naming conventions for dealing with records, like Active Records or
-
# Active Resources or pretty much any other model type that has an id. These patterns are then used to try elevate
-
# the view actions to a higher logical level. Example:
-
#
-
# # routes
-
# resources :posts
-
#
-
# # view
-
# <%= div_for(post) do %> <div id="post_45" class="post">
-
# <%= post.body %> What a wonderful world!
-
# <% end %> </div>
-
#
-
# # controller
-
# def update
-
# post = Post.find(params[:id])
-
# post.update_attributes(params[:post])
-
#
-
# redirect_to(post) # Calls polymorphic_url(post) which in turn calls post_url(post)
-
# end
-
#
-
# As the example above shows, you can stop caring to a large extent what the actual id of the post is.
-
# You just know that one is being assigned and that the subsequent calls in redirect_to expect that
-
# same naming convention and allows you to write less code if you follow it.
-
2
module RecordIdentifier
-
2
extend self
-
-
2
JOIN = '_'.freeze
-
2
NEW = 'new'.freeze
-
-
# The DOM class convention is to use the singular form of an object or class. Examples:
-
#
-
# dom_class(post) # => "post"
-
# dom_class(Person) # => "person"
-
#
-
# If you need to address multiple instances of the same class in the same view, you can prefix the dom_class:
-
#
-
# dom_class(post, :edit) # => "edit_post"
-
# dom_class(Person, :edit) # => "edit_person"
-
2
def dom_class(record_or_class, prefix = nil)
-
singular = ActiveModel::Naming.param_key(record_or_class)
-
prefix ? "#{prefix}#{JOIN}#{singular}" : singular
-
end
-
-
# The DOM id convention is to use the singular form of an object or class with the id following an underscore.
-
# If no id is found, prefix with "new_" instead. Examples:
-
#
-
# dom_id(Post.find(45)) # => "post_45"
-
# dom_id(Post.new) # => "new_post"
-
#
-
# If you need to address multiple instances of the same class in the same view, you can prefix the dom_id:
-
#
-
# dom_id(Post.find(45), :edit) # => "edit_post_45"
-
2
def dom_id(record, prefix = nil)
-
if record_id = record_key_for_dom_id(record)
-
"#{dom_class(record, prefix)}#{JOIN}#{record_id}"
-
else
-
dom_class(record, prefix || NEW)
-
end
-
end
-
-
2
protected
-
-
# Returns a string representation of the key attribute(s) that is suitable for use in an HTML DOM id.
-
# This can be overwritten to customize the default generated string representation if desired.
-
# If you need to read back a key from a dom_id in order to query for the underlying database record,
-
# you should write a helper like 'person_record_from_dom_id' that will extract the key either based
-
# on the default implementation (which just joins all key attributes with '_') or on your own
-
# overwritten version of the method. By default, this implementation passes the key string through a
-
# method that replaces all characters that are invalid inside DOM ids, with valid ones. You need to
-
# make sure yourself that your dom ids are valid, in case you overwrite this method.
-
2
def record_key_for_dom_id(record)
-
record = record.to_model if record.respond_to?(:to_model)
-
key = record.to_key
-
key ? sanitize_dom_id(key.join('_')) : key
-
end
-
-
# Replaces characters that are invalid in HTML DOM ids with valid ones.
-
2
def sanitize_dom_id(candidate_id)
-
candidate_id # TODO implement conversion to valid DOM id values
-
end
-
end
-
end
-
2
require 'rack/session/abstract/id'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/object/to_query'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/module/anonymous'
-
-
2
module ActionController
-
2
module TemplateAssertions
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
5
setup :setup_subscriptions
-
5
teardown :teardown_subscriptions
-
end
-
-
2
def setup_subscriptions
-
75
@partials = Hash.new(0)
-
75
@templates = Hash.new(0)
-
75
@layouts = Hash.new(0)
-
-
75
ActiveSupport::Notifications.subscribe("render_template.action_view") do |name, start, finish, id, payload|
-
path = payload[:layout]
-
if path
-
@layouts[path] += 1
-
if path =~ /^layouts\/(.*)/
-
@layouts[$1] += 1
-
end
-
end
-
end
-
-
75
ActiveSupport::Notifications.subscribe("!render_template.action_view") do |name, start, finish, id, payload|
-
path = payload[:virtual_path]
-
next unless path
-
partial = path =~ /^.*\/_[^\/]*$/
-
if partial
-
@partials[path] += 1
-
@partials[path.split("/").last] += 1
-
@templates[path] += 1
-
else
-
@templates[path] += 1
-
end
-
end
-
end
-
-
2
def teardown_subscriptions
-
75
ActiveSupport::Notifications.unsubscribe("render_template.action_view")
-
75
ActiveSupport::Notifications.unsubscribe("!render_template.action_view")
-
end
-
-
2
def process(*args)
-
26
@partials = Hash.new(0)
-
26
@templates = Hash.new(0)
-
26
@layouts = Hash.new(0)
-
26
super
-
end
-
-
# Asserts that the request was rendered with the appropriate template file or partials.
-
#
-
# ==== Examples
-
#
-
# # assert that the "new" view template was rendered
-
# assert_template "new"
-
#
-
# # assert that the layout 'admin' was rendered
-
# assert_template :layout => 'admin'
-
# assert_template :layout => 'layouts/admin'
-
# assert_template :layout => :admin
-
#
-
# # assert that no layout was rendered
-
# assert_template :layout => nil
-
# assert_template :layout => false
-
#
-
# # assert that the "_customer" partial was rendered twice
-
# assert_template :partial => '_customer', :count => 2
-
#
-
# # assert that no partials were rendered
-
# assert_template :partial => false
-
#
-
# In a view test case, you can also assert that specific locals are passed
-
# to partials:
-
#
-
# # assert that the "_customer" partial was rendered with a specific object
-
# assert_template :partial => '_customer', :locals => { :customer => @customer }
-
#
-
2
def assert_template(options = {}, message = nil)
-
validate_request!
-
# Force body to be read in case the template is being streamed
-
response.body
-
-
case options
-
when NilClass, String, Symbol
-
options = options.to_s if Symbol === options
-
rendered = @templates
-
msg = build_message(message,
-
"expecting <?> but rendering with <?>",
-
options, rendered.keys.join(', '))
-
assert_block(msg) do
-
if options
-
rendered.any? { |t,num| t.match(options) }
-
else
-
@templates.blank?
-
end
-
end
-
when Hash
-
if options.key?(:layout)
-
expected_layout = options[:layout]
-
msg = build_message(message,
-
"expecting layout <?> but action rendered <?>",
-
expected_layout, @layouts.keys)
-
-
case expected_layout
-
when String, Symbol
-
assert(@layouts.keys.include?(expected_layout.to_s), msg)
-
when Regexp
-
assert(@layouts.keys.any? {|l| l =~ expected_layout }, msg)
-
when nil, false
-
assert(@layouts.empty?, msg)
-
end
-
end
-
-
if expected_partial = options[:partial]
-
if expected_locals = options[:locals]
-
if defined?(@locals)
-
actual_locals = @locals[expected_partial.to_s.sub(/^_/,'')]
-
expected_locals.each_pair do |k,v|
-
assert_equal(v, actual_locals[k])
-
end
-
else
-
warn "the :locals option to #assert_template is only supported in a ActionView::TestCase"
-
end
-
elsif expected_count = options[:count]
-
actual_count = @partials[expected_partial]
-
msg = build_message(message,
-
"expecting ? to be rendered ? time(s) but rendered ? time(s)",
-
expected_partial, expected_count, actual_count)
-
assert(actual_count == expected_count.to_i, msg)
-
else
-
msg = build_message(message,
-
"expecting partial <?> but action rendered <?>",
-
options[:partial], @partials.keys)
-
assert(@partials.include?(expected_partial), msg)
-
end
-
elsif options.key?(:partial)
-
assert @partials.empty?,
-
"Expected no partials to be rendered"
-
end
-
end
-
end
-
end
-
-
2
class TestRequest < ActionDispatch::TestRequest #:nodoc:
-
2
def initialize(env = {})
-
75
super
-
-
75
self.session = TestSession.new
-
75
self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => SecureRandom.hex(16))
-
end
-
-
2
class Result < ::Array #:nodoc:
-
2
def to_s() join '/' end
-
2
def self.new_escaped(strings)
-
new strings.collect {|str| uri_parser.unescape str}
-
end
-
end
-
-
2
def assign_parameters(routes, controller_path, action, parameters = {})
-
10
parameters = parameters.symbolize_keys.merge(:controller => controller_path, :action => action)
-
10
extra_keys = routes.extra_keys(parameters)
-
9
non_path_parameters = get? ? query_parameters : request_parameters
-
9
parameters.each do |key, value|
-
24
if value.is_a?(Array) && (value.frozen? || value.any?(&:frozen?))
-
value = value.map{ |v| v.duplicable? ? v.dup : v }
-
elsif value.is_a?(Hash) && (value.frozen? || value.any?{ |k,v| v.frozen? })
-
value = Hash[value.map{ |k,v| [k, v.duplicable? ? v.dup : v] }]
-
elsif value.frozen? && value.duplicable?
-
value = value.dup
-
end
-
-
24
if extra_keys.include?(key.to_sym)
-
2
non_path_parameters[key] = value
-
else
-
22
if value.is_a?(Array)
-
value = Result.new(value.map(&:to_param))
-
else
-
22
value = value.to_param
-
end
-
-
22
path_parameters[key.to_s] = value
-
end
-
end
-
-
# Clear the combined params hash in case it was already referenced.
-
9
@env.delete("action_dispatch.request.parameters")
-
-
9
params = self.request_parameters.dup
-
9
%w(controller action only_path).each do |k|
-
27
params.delete(k)
-
27
params.delete(k.to_sym)
-
end
-
9
data = params.to_query
-
-
9
@env['CONTENT_LENGTH'] = data.length.to_s
-
9
@env['rack.input'] = StringIO.new(data)
-
end
-
-
2
def recycle!
-
10
@formats = nil
-
270
@env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
-
270
@env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
-
10
@symbolized_path_params = nil
-
10
@method = @request_method = nil
-
10
@fullpath = @ip = @remote_ip = @protocol = nil
-
10
@env['action_dispatch.request.query_parameters'] = {}
-
10
@set_cookies ||= {}
-
10
@set_cookies.update(Hash[cookie_jar.instance_variable_get("@set_cookies").map{ |k,o| [k,o[:value]] }])
-
10
deleted_cookies = cookie_jar.instance_variable_get("@delete_cookies")
-
10
@set_cookies.reject!{ |k,v| deleted_cookies.include?(k) }
-
10
cookie_jar.update(rack_cookies)
-
10
cookie_jar.update(cookies)
-
10
cookie_jar.update(@set_cookies)
-
10
cookie_jar.recycle!
-
end
-
end
-
-
2
class TestResponse < ActionDispatch::TestResponse
-
2
def recycle!
-
10
@status = 200
-
10
@header = {}
-
10
@writer = lambda { |x| @body << x }
-
10
@block = nil
-
10
@length = 0
-
10
@body = []
-
10
@charset = @content_type = nil
-
10
@request = @template = nil
-
end
-
end
-
-
2
class TestSession < Rack::Session::Abstract::SessionHash #:nodoc:
-
2
DEFAULT_OPTIONS = Rack::Session::Abstract::ID::DEFAULT_OPTIONS
-
-
2
def initialize(session = {})
-
75
super(nil, nil)
-
75
replace(session.stringify_keys)
-
75
@loaded = true
-
end
-
-
2
def exists?
-
true
-
end
-
end
-
-
# Superclass for ActionController functional tests. Functional tests allow you to
-
# test a single controller action per test method. This should not be confused with
-
# integration tests (see ActionDispatch::IntegrationTest), which are more like
-
# "stories" that can involve multiple controllers and multiple actions (i.e. multiple
-
# different HTTP requests).
-
#
-
# == Basic example
-
#
-
# Functional tests are written as follows:
-
# 1. First, one uses the +get+, +post+, +put+, +delete+ or +head+ method to simulate
-
# an HTTP request.
-
# 2. Then, one asserts whether the current state is as expected. "State" can be anything:
-
# the controller's HTTP response, the database contents, etc.
-
#
-
# For example:
-
#
-
# class BooksControllerTest < ActionController::TestCase
-
# def test_create
-
# # Simulate a POST response with the given HTTP parameters.
-
# post(:create, :book => { :title => "Love Hina" })
-
#
-
# # Assert that the controller tried to redirect us to
-
# # the created book's URI.
-
# assert_response :found
-
#
-
# # Assert that the controller really put the book in the database.
-
# assert_not_nil Book.find_by_title("Love Hina")
-
# end
-
# end
-
#
-
# == Special instance variables
-
#
-
# ActionController::TestCase will also automatically provide the following instance
-
# variables for use in the tests:
-
#
-
# <b>@controller</b>::
-
# The controller instance that will be tested.
-
# <b>@request</b>::
-
# An ActionController::TestRequest, representing the current HTTP
-
# request. You can modify this object before sending the HTTP request. For example,
-
# you might want to set some session properties before sending a GET request.
-
# <b>@response</b>::
-
# An ActionController::TestResponse object, representing the response
-
# of the last HTTP response. In the above example, <tt>@response</tt> becomes valid
-
# after calling +post+. If the various assert methods are not sufficient, then you
-
# may use this object to inspect the HTTP response in detail.
-
#
-
# (Earlier versions of \Rails required each functional test to subclass
-
# Test::Unit::TestCase and define @controller, @request, @response in +setup+.)
-
#
-
# == Controller is automatically inferred
-
#
-
# ActionController::TestCase will automatically infer the controller under test
-
# from the test class name. If the controller cannot be inferred from the test
-
# class name, you can explicitly set it with +tests+.
-
#
-
# class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
-
# tests WidgetController
-
# end
-
#
-
# == \Testing controller internals
-
#
-
# In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions
-
# can be used against. These collections are:
-
#
-
# * assigns: Instance variables assigned in the action that are available for the view.
-
# * session: Objects being saved in the session.
-
# * flash: The flash objects currently in the session.
-
# * cookies: \Cookies being sent to the user on this request.
-
#
-
# These collections can be used just like any other hash:
-
#
-
# assert_not_nil assigns(:person) # makes sure that a @person instance variable was set
-
# assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave"
-
# assert flash.empty? # makes sure that there's nothing in the flash
-
#
-
# For historic reasons, the assigns hash uses string-based keys. So <tt>assigns[:person]</tt> won't work, but <tt>assigns["person"]</tt> will. To
-
# appease our yearning for symbols, though, an alternative accessor has been devised using a method call instead of index referencing.
-
# So <tt>assigns(:person)</tt> will work just like <tt>assigns["person"]</tt>, but again, <tt>assigns[:person]</tt> will not work.
-
#
-
# On top of the collections, you have the complete url that a given action redirected to available in <tt>redirect_to_url</tt>.
-
#
-
# For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another
-
# action call which can then be asserted against.
-
#
-
# == Manipulating session and cookie variables
-
#
-
# Sometimes you need to set up the session and cookie variables for a test.
-
# To do this just assign a value to the session or cookie collection:
-
#
-
# session[:key] = "value"
-
# cookies[:key] = "value"
-
#
-
# To clear the cookies for a test just clear the cookie collection:
-
#
-
# cookies.clear
-
#
-
# == \Testing named routes
-
#
-
# If you're using named routes, they can be easily tested using the original named routes' methods straight in the test case.
-
# Example:
-
#
-
# assert_redirected_to page_url(:title => 'foo')
-
2
class TestCase < ActiveSupport::TestCase
-
2
module Behavior
-
2
extend ActiveSupport::Concern
-
2
include ActionDispatch::TestProcess
-
-
2
attr_reader :response, :request
-
-
2
module ClassMethods
-
-
# Sets the controller class name. Useful if the name can't be inferred from test class.
-
# Normalizes +controller_class+ before using. Examples:
-
#
-
# tests WidgetController
-
# tests :widget
-
# tests 'widget'
-
#
-
2
def tests(controller_class)
-
case controller_class
-
when String, Symbol
-
self.controller_class = "#{controller_class.to_s.underscore}_controller".camelize.constantize
-
when Class
-
self.controller_class = controller_class
-
else
-
raise ArgumentError, "controller class must be a String, Symbol, or Class"
-
end
-
end
-
-
2
def controller_class=(new_class)
-
32
prepare_controller_class(new_class) if new_class
-
32
self._controller_class = new_class
-
end
-
-
2
def controller_class
-
75
if current_controller_class = self._controller_class
-
43
current_controller_class
-
else
-
32
self.controller_class = determine_default_controller_class(name)
-
end
-
end
-
-
2
def determine_default_controller_class(name)
-
32
name.sub(/Test$/, '').safe_constantize
-
end
-
-
2
def prepare_controller_class(new_class)
-
9
new_class.send :include, ActionController::TestCase::RaiseActionExceptions
-
end
-
-
end
-
-
# Executes a request simulating GET HTTP method and set/volley the response
-
2
def get(action, parameters = nil, session = nil, flash = nil)
-
17
process(action, parameters, session, flash, "GET")
-
end
-
-
# Executes a request simulating POST HTTP method and set/volley the response
-
2
def post(action, parameters = nil, session = nil, flash = nil)
-
3
process(action, parameters, session, flash, "POST")
-
end
-
-
# Executes a request simulating PUT HTTP method and set/volley the response
-
2
def put(action, parameters = nil, session = nil, flash = nil)
-
3
process(action, parameters, session, flash, "PUT")
-
end
-
-
# Executes a request simulating DELETE HTTP method and set/volley the response
-
2
def delete(action, parameters = nil, session = nil, flash = nil)
-
3
process(action, parameters, session, flash, "DELETE")
-
end
-
-
# Executes a request simulating HEAD HTTP method and set/volley the response
-
2
def head(action, parameters = nil, session = nil, flash = nil)
-
process(action, parameters, session, flash, "HEAD")
-
end
-
-
2
def xml_http_request(request_method, action, parameters = nil, session = nil, flash = nil)
-
@request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
-
@request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
-
__send__(request_method, action, parameters, session, flash).tap do
-
@request.env.delete 'HTTP_X_REQUESTED_WITH'
-
@request.env.delete 'HTTP_ACCEPT'
-
end
-
end
-
2
alias xhr :xml_http_request
-
-
2
def paramify_values(hash_or_array_or_value)
-
66
case hash_or_array_or_value
-
when Hash
-
61
Hash[hash_or_array_or_value.map{|key, value| [key, paramify_values(value)] }]
-
when Array
-
hash_or_array_or_value.map {|i| paramify_values(i)}
-
when Rack::Test::UploadedFile, ActionDispatch::Http::UploadedFile
-
hash_or_array_or_value
-
else
-
45
hash_or_array_or_value.to_param
-
end
-
end
-
-
2
def process(action, parameters = nil, session = nil, flash = nil, http_method = 'GET')
-
# Ensure that numbers and symbols passed as params are converted to
-
# proper params, as is the case when engaging rack.
-
26
parameters = paramify_values(parameters) if html_format?(parameters)
-
-
# Sanity check for required instance variables so we can give an
-
# understandable error message.
-
26
%w(@routes @controller @request @response).each do |iv_name|
-
72
if !(instance_variable_names.include?(iv_name) || instance_variable_names.include?(iv_name.to_sym)) || instance_variable_get(iv_name).nil?
-
16
raise "#{iv_name} is nil: make sure you set it in your test's setup method."
-
end
-
end
-
-
10
@request.recycle!
-
10
@response.recycle!
-
10
@controller.response_body = nil
-
10
@controller.formats = nil
-
10
@controller.params = nil
-
-
10
@html_document = nil
-
10
@request.env['REQUEST_METHOD'] = http_method
-
-
10
parameters ||= {}
-
10
controller_class_name = @controller.class.anonymous? ?
-
"anonymous_controller" :
-
@controller.class.controller_path
-
-
10
@request.assign_parameters(@routes, controller_class_name, action.to_s, parameters)
-
-
9
@request.session = ActionController::TestSession.new(session) if session
-
9
@request.session["flash"] = @request.flash.update(flash || {})
-
9
@request.session["flash"].sweep
-
-
9
@controller.request = @request
-
9
build_request_uri(action, parameters)
-
18
@controller.class.class_eval { include Testing }
-
9
@controller.recycle!
-
9
@controller.process_with_new_base_test(@request, @response)
-
9
@assigns = @controller.respond_to?(:view_assigns) ? @controller.view_assigns : {}
-
9
@request.session.delete('flash') if @request.session['flash'].blank?
-
9
@response
-
end
-
-
2
def setup_controller_request_and_response
-
75
@request = TestRequest.new
-
75
@response = TestResponse.new
-
-
75
if klass = self.class.controller_class
-
52
@controller ||= klass.new rescue nil
-
end
-
-
75
@request.env.delete('PATH_INFO')
-
-
75
if defined?(@controller) && @controller
-
52
@controller.request = @request
-
52
@controller.params = {}
-
end
-
end
-
-
2
included do
-
2
include ActionController::TemplateAssertions
-
2
include ActionDispatch::Assertions
-
2
class_attribute :_controller_class
-
2
setup :setup_controller_request_and_response
-
end
-
-
2
private
-
-
2
def build_request_uri(action, parameters)
-
9
unless @request.env["PATH_INFO"]
-
9
options = @controller.respond_to?(:url_options) ? @controller.__send__(:url_options).merge(parameters) : parameters
-
9
options.update(
-
:only_path => true,
-
:action => action,
-
:relative_url_root => nil,
-
:_path_segments => @request.symbolized_path_parameters)
-
-
9
url, query_string = @routes.url_for(options).split("?", 2)
-
-
9
@request.env["SCRIPT_NAME"] = @controller.config.relative_url_root
-
9
@request.env["PATH_INFO"] = url
-
9
@request.env["QUERY_STRING"] = query_string || ""
-
end
-
end
-
-
2
def html_format?(parameters)
-
26
return true unless parameters.is_a?(Hash)
-
15
format = Mime[parameters[:format]]
-
15
format.nil? || format.html?
-
end
-
end
-
-
# When the request.remote_addr remains the default for testing, which is 0.0.0.0, the exception is simply raised inline
-
# (skipping the regular exception handling from rescue_action). If the request.remote_addr is anything else, the regular
-
# rescue_action process takes place. This means you can test your rescue_action code by setting remote_addr to something else
-
# than 0.0.0.0.
-
#
-
# The exception is stored in the exception accessor for further inspection.
-
2
module RaiseActionExceptions
-
2
def self.included(base)
-
9
unless base.method_defined?(:exception) && base.method_defined?(:exception=)
-
9
base.class_eval do
-
9
attr_accessor :exception
-
9
protected :exception, :exception=
-
end
-
end
-
end
-
-
2
protected
-
2
def rescue_action_without_handler(e)
-
self.exception = e
-
-
if request.remote_addr == "0.0.0.0"
-
raise(e)
-
else
-
super(e)
-
end
-
end
-
end
-
-
2
include Behavior
-
end
-
end
-
2
$LOAD_PATH << "#{File.dirname(__FILE__)}/html-scanner"
-
-
2
module HTML
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :CDATA, 'html/node'
-
2
autoload :Document, 'html/document'
-
2
autoload :FullSanitizer, 'html/sanitizer'
-
2
autoload :LinkSanitizer, 'html/sanitizer'
-
2
autoload :Node, 'html/node'
-
2
autoload :Sanitizer, 'html/sanitizer'
-
2
autoload :Selector, 'html/selector'
-
2
autoload :Tag, 'html/node'
-
2
autoload :Text, 'html/node'
-
2
autoload :Tokenizer, 'html/tokenizer'
-
2
autoload :Version, 'html/version'
-
2
autoload :WhiteListSanitizer, 'html/sanitizer'
-
end
-
end
-
#--
-
# Copyright (c) 2004-2011 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
-
2
$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-
-
2
activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
-
2
$:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
-
-
2
require 'active_support'
-
2
require 'active_support/dependencies/autoload'
-
-
2
require 'action_pack'
-
2
require 'active_model'
-
2
require 'rack'
-
-
2
module Rack
-
2
autoload :Test, 'rack/test'
-
end
-
-
2
module ActionDispatch
-
2
extend ActiveSupport::Autoload
-
-
2
autoload_under 'http' do
-
2
autoload :Request
-
2
autoload :Response
-
end
-
-
2
autoload_under 'middleware' do
-
2
autoload :RequestId
-
2
autoload :BestStandardsSupport
-
2
autoload :Callbacks
-
2
autoload :Cookies
-
2
autoload :DebugExceptions
-
2
autoload :ExceptionWrapper
-
2
autoload :Flash
-
2
autoload :Head
-
2
autoload :ParamsParser
-
2
autoload :PublicExceptions
-
2
autoload :Reloader
-
2
autoload :RemoteIp
-
2
autoload :Rescue
-
2
autoload :ShowExceptions
-
2
autoload :Static
-
end
-
-
2
autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
-
2
autoload :Routing
-
-
2
module Http
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Cache
-
2
autoload :Headers
-
2
autoload :MimeNegotiation
-
2
autoload :Parameters
-
2
autoload :ParameterFilter
-
2
autoload :FilterParameters
-
2
autoload :Upload
-
2
autoload :UploadedFile, 'action_dispatch/http/upload'
-
2
autoload :URL
-
end
-
-
2
module Session
-
2
autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
-
2
autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
-
2
autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
-
2
autoload :CacheStore, 'action_dispatch/middleware/session/cache_store'
-
end
-
-
2
autoload_under 'testing' do
-
2
autoload :Assertions
-
2
autoload :Integration
-
2
autoload :IntegrationTest, 'action_dispatch/testing/integration'
-
2
autoload :PerformanceTest
-
2
autoload :TestProcess
-
2
autoload :TestRequest
-
2
autoload :TestResponse
-
end
-
end
-
-
2
autoload :Mime, 'action_dispatch/http/mime_type'
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActionDispatch
-
2
module Http
-
2
module Cache
-
2
module Request
-
-
2
HTTP_IF_MODIFIED_SINCE = 'HTTP_IF_MODIFIED_SINCE'.freeze
-
2
HTTP_IF_NONE_MATCH = 'HTTP_IF_NONE_MATCH'.freeze
-
-
2
def if_modified_since
-
if since = env[HTTP_IF_MODIFIED_SINCE]
-
Time.rfc2822(since) rescue nil
-
end
-
end
-
-
2
def if_none_match
-
env[HTTP_IF_NONE_MATCH]
-
end
-
-
2
def not_modified?(modified_at)
-
if_modified_since && modified_at && if_modified_since >= modified_at
-
end
-
-
2
def etag_matches?(etag)
-
if_none_match && if_none_match == etag
-
end
-
-
# Check response freshness (Last-Modified and ETag) against request
-
# If-Modified-Since and If-None-Match conditions. If both headers are
-
# supplied, both must match, or the request is not considered fresh.
-
2
def fresh?(response)
-
last_modified = if_modified_since
-
etag = if_none_match
-
-
return false unless last_modified || etag
-
-
success = true
-
success &&= not_modified?(response.last_modified) if last_modified
-
success &&= etag_matches?(response.etag) if etag
-
success
-
end
-
end
-
-
2
module Response
-
2
attr_reader :cache_control, :etag
-
2
alias :etag? :etag
-
-
2
def last_modified
-
if last = headers[LAST_MODIFIED]
-
Time.httpdate(last)
-
end
-
end
-
-
2
def last_modified?
-
9
headers.include?(LAST_MODIFIED)
-
end
-
-
2
def last_modified=(utc_time)
-
headers[LAST_MODIFIED] = utc_time.httpdate
-
end
-
-
2
def etag=(etag)
-
key = ActiveSupport::Cache.expand_cache_key(etag)
-
@etag = self[ETAG] = %("#{Digest::MD5.hexdigest(key)}")
-
end
-
-
2
private
-
-
2
LAST_MODIFIED = "Last-Modified".freeze
-
2
ETAG = "ETag".freeze
-
2
CACHE_CONTROL = "Cache-Control".freeze
-
-
2
def prepare_cache_control!
-
75
@cache_control = {}
-
75
@etag = self[ETAG]
-
-
75
if cache_control = self[CACHE_CONTROL]
-
cache_control.split(/,\s*/).each do |segment|
-
first, last = segment.split("=")
-
@cache_control[first.to_sym] = last || true
-
end
-
end
-
end
-
-
2
def handle_conditional_get!
-
9
if etag? || last_modified? || !@cache_control.empty?
-
set_conditional_cache_control!
-
end
-
end
-
-
2
DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate".freeze
-
2
NO_CACHE = "no-cache".freeze
-
2
PUBLIC = "public".freeze
-
2
PRIVATE = "private".freeze
-
2
MUST_REVALIDATE = "must-revalidate".freeze
-
-
2
def set_conditional_cache_control!
-
return if self[CACHE_CONTROL].present?
-
-
control = @cache_control
-
-
if control.empty?
-
headers[CACHE_CONTROL] = DEFAULT_CACHE_CONTROL
-
elsif control[:no_cache]
-
headers[CACHE_CONTROL] = NO_CACHE
-
else
-
extras = control[:extras]
-
max_age = control[:max_age]
-
-
options = []
-
options << "max-age=#{max_age.to_i}" if max_age
-
options << (control[:public] ? PUBLIC : PRIVATE)
-
options << MUST_REVALIDATE if control[:must_revalidate]
-
options.concat(extras) if extras
-
-
headers[CACHE_CONTROL] = options.join(", ")
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/object/duplicable'
-
-
2
module ActionDispatch
-
2
module Http
-
# Allows you to specify sensitive parameters which will be replaced from
-
# the request log by looking in the query string of the request and all
-
# subhashes of the params hash to filter. If a block is given, each key and
-
# value of the params hash and all subhashes is passed to it, the value
-
# or key can be replaced using String#replace or similar method.
-
#
-
# Examples:
-
#
-
# env["action_dispatch.parameter_filter"] = [:password]
-
# => replaces the value to all keys matching /password/i with "[FILTERED]"
-
#
-
# env["action_dispatch.parameter_filter"] = [:foo, "bar"]
-
# => replaces the value to all keys matching /foo|bar/i with "[FILTERED]"
-
#
-
# env["action_dispatch.parameter_filter"] = lambda do |k,v|
-
# v.reverse! if k =~ /secret/i
-
# end
-
# => reverses the value to all keys matching /secret/i
-
#
-
2
module FilterParameters
-
2
extend ActiveSupport::Concern
-
-
# Return a hash of parameters with all sensitive data replaced.
-
2
def filtered_parameters
-
9
@filtered_parameters ||= parameter_filter.filter(parameters)
-
end
-
-
# Return a hash of request.env with all sensitive data replaced.
-
2
def filtered_env
-
@filtered_env ||= env_filter.filter(@env)
-
end
-
-
# Reconstructed a path with all sensitive GET parameters replaced.
-
2
def filtered_path
-
@filtered_path ||= query_string.empty? ? path : "#{path}?#{filtered_query_string}"
-
end
-
-
2
protected
-
-
2
def parameter_filter
-
9
parameter_filter_for(@env["action_dispatch.parameter_filter"])
-
end
-
-
2
def env_filter
-
parameter_filter_for(Array.wrap(@env["action_dispatch.parameter_filter"]) << /RAW_POST_DATA/)
-
end
-
-
2
def parameter_filter_for(filters)
-
9
ParameterFilter.new(filters)
-
end
-
-
2
KV_RE = '[^&;=]+'
-
2
PAIR_RE = %r{(#{KV_RE})=(#{KV_RE})}
-
2
def filtered_query_string
-
query_string.gsub(PAIR_RE) do |_|
-
parameter_filter.filter([[$1, $2]]).first.join("=")
-
end
-
end
-
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Http
-
2
class Headers < ::Hash
-
2
@@env_cache = Hash.new { |h,k| h[k] = "HTTP_#{k.upcase.gsub(/-/, '_')}" }
-
-
2
def initialize(*args)
-
-
if args.size == 1 && args[0].is_a?(Hash)
-
super()
-
update(args[0])
-
else
-
super
-
end
-
end
-
-
2
def [](header_name)
-
if include?(header_name)
-
super
-
else
-
super(env_name(header_name))
-
end
-
end
-
-
2
private
-
# Converts a HTTP header name to an environment variable name.
-
2
def env_name(header_name)
-
@@env_cache[header_name]
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Http
-
2
module MimeNegotiation
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
mattr_accessor :ignore_accept_header
-
2
self.ignore_accept_header = false
-
end
-
-
# The MIME type of the HTTP request, such as Mime::XML.
-
#
-
# For backward compatibility, the post \format is extracted from the
-
# X-Post-Data-Format HTTP header if present.
-
2
def content_mime_type
-
27
@env["action_dispatch.request.content_type"] ||= begin
-
27
if @env['CONTENT_TYPE'] =~ /^([^,\;]*)/
-
Mime::Type.lookup($1.strip.downcase)
-
else
-
27
nil
-
end
-
end
-
end
-
-
2
def content_type
-
content_mime_type && content_mime_type.to_s
-
end
-
-
# Returns the accepted MIME type for the request.
-
2
def accepts
-
@env["action_dispatch.request.accepts"] ||= begin
-
header = @env['HTTP_ACCEPT'].to_s.strip
-
-
if header.empty?
-
[content_mime_type]
-
else
-
Mime::Type.parse(header)
-
end
-
end
-
end
-
-
# Returns the MIME type for the \format used in the request.
-
#
-
# GET /posts/5.xml | request.format => Mime::XML
-
# GET /posts/5.xhtml | request.format => Mime::HTML
-
# GET /posts/5 | request.format => Mime::HTML or MIME::JS, or request.accepts.first
-
#
-
2
def format(view_path = [])
-
9
formats.first
-
end
-
-
2
def formats
-
9
@env["action_dispatch.request.formats"] ||=
-
if parameters[:format]
-
Array(Mime[parameters[:format]])
-
elsif use_accept_header && valid_accept_header
-
accepts
-
elsif xhr?
-
[Mime::JS]
-
else
-
9
[Mime::HTML]
-
end
-
end
-
-
# Sets the \format by string extension, which can be used to force custom formats
-
# that are not controlled by the extension.
-
#
-
# class ApplicationController < ActionController::Base
-
# before_filter :adjust_format_for_iphone
-
#
-
# private
-
# def adjust_format_for_iphone
-
# request.format = :iphone if request.env["HTTP_USER_AGENT"][/iPhone/]
-
# end
-
# end
-
2
def format=(extension)
-
parameters[:format] = extension.to_s
-
@env["action_dispatch.request.formats"] = [Mime::Type.lookup_by_extension(parameters[:format])]
-
end
-
-
# Receives an array of mimes and return the first user sent mime that
-
# matches the order array.
-
#
-
2
def negotiate_mime(order)
-
formats.each do |priority|
-
if priority == Mime::ALL
-
return order.first
-
elsif order.include?(priority)
-
return priority
-
end
-
end
-
-
order.include?(Mime::ALL) ? formats.first : nil
-
end
-
-
2
protected
-
-
2
BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/
-
-
2
def valid_accept_header
-
9
(xhr? && (accept.present? || content_mime_type)) ||
-
18
(accept.present? && accept !~ BROWSER_LIKE_ACCEPTS)
-
end
-
-
2
def use_accept_header
-
9
!self.class.ignore_accept_header
-
end
-
end
-
end
-
end
-
2
require 'set'
-
2
require 'active_support/core_ext/class/attribute_accessors'
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module Mime
-
2
class Mimes < Array
-
2
def symbols
-
74
@symbols ||= map {|m| m.to_sym }
-
end
-
-
2
%w(<< concat shift unshift push pop []= clear compact! collect!
-
delete delete_at delete_if flatten! map! insert reject! reverse!
-
replace slice! sort! uniq!).each do |method|
-
44
module_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{method}(*)
-
@symbols = nil
-
super
-
end
-
CODE
-
end
-
end
-
-
2
SET = Mimes.new
-
2
EXTENSION_LOOKUP = {}
-
2
LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k.blank? }
-
-
2
def self.[](type)
-
16
return type if type.is_a?(Type)
-
16
Type.lookup_by_extension(type.to_s)
-
end
-
-
# Encapsulates the notion of a mime type. Can be used at render time, for example, with:
-
#
-
# class PostsController < ActionController::Base
-
# def show
-
# @post = Post.find(params[:id])
-
#
-
# respond_to do |format|
-
# format.html
-
# format.ics { render :text => post.to_ics, :mime_type => Mime::Type["text/calendar"] }
-
# format.xml { render :xml => @people.to_xml }
-
# end
-
# end
-
# end
-
2
class Type
-
2
@@html_types = Set.new [:html, :all]
-
2
cattr_reader :html_types
-
-
# These are the content types which browsers can generate without using ajax, flash, etc
-
# i.e. following a link, getting an image or posting a form. CSRF protection
-
# only needs to protect against these types.
-
2
@@browser_generated_types = Set.new [:html, :url_encoded_form, :multipart_form, :text]
-
2
cattr_reader :browser_generated_types
-
2
attr_reader :symbol
-
-
# A simple helper class used in parsing the accept header
-
2
class AcceptItem #:nodoc:
-
2
attr_accessor :order, :name, :q
-
-
2
def initialize(order, name, q=nil)
-
@order = order
-
@name = name.strip
-
q ||= 0.0 if @name == Mime::ALL # default wildcard match to end of list
-
@q = ((q || 1.0).to_f * 100).to_i
-
end
-
-
2
def to_s
-
@name
-
end
-
-
2
def <=>(item)
-
result = item.q <=> q
-
result = order <=> item.order if result == 0
-
result
-
end
-
-
2
def ==(item)
-
name == (item.respond_to?(:name) ? item.name : item)
-
end
-
end
-
-
2
class << self
-
-
2
TRAILING_STAR_REGEXP = /(text|application)\/\*/
-
2
Q_SEPARATOR_REGEXP = /;\s*q=/
-
-
2
def lookup(string)
-
LOOKUP[string]
-
end
-
-
2
def lookup_by_extension(extension)
-
17
EXTENSION_LOOKUP[extension.to_s]
-
end
-
-
# Registers an alias that's not used on mime type lookup, but can be referenced directly. Especially useful for
-
# rendering different HTML versions depending on the user agent, like an iPhone.
-
2
def register_alias(string, symbol, extension_synonyms = [])
-
register(string, symbol, [], extension_synonyms, true)
-
end
-
-
2
def register(string, symbol, mime_type_synonyms = [], extension_synonyms = [], skip_lookup = false)
-
42
Mime.const_set(symbol.to_s.upcase, Type.new(string, symbol, mime_type_synonyms))
-
-
42
SET << Mime.const_get(symbol.to_s.upcase)
-
-
100
([string] + mime_type_synonyms).each { |str| LOOKUP[str] = SET.last } unless skip_lookup
-
114
([symbol] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext.to_s] = SET.last }
-
end
-
-
2
def parse(accept_header)
-
if accept_header !~ /,/
-
accept_header = accept_header.split(Q_SEPARATOR_REGEXP).first
-
if accept_header =~ TRAILING_STAR_REGEXP
-
parse_data_with_trailing_star($1)
-
else
-
[Mime::Type.lookup(accept_header)]
-
end
-
else
-
# keep track of creation order to keep the subsequent sort stable
-
list, index = [], 0
-
accept_header.split(/,/).each do |header|
-
params, q = header.split(Q_SEPARATOR_REGEXP)
-
if params.present?
-
params.strip!
-
-
if params =~ TRAILING_STAR_REGEXP
-
parse_data_with_trailing_star($1).each do |m|
-
list << AcceptItem.new(index, m.to_s, q)
-
index += 1
-
end
-
else
-
list << AcceptItem.new(index, params, q)
-
index += 1
-
end
-
end
-
end
-
list.sort!
-
-
# Take care of the broken text/xml entry by renaming or deleting it
-
text_xml = list.index("text/xml")
-
app_xml = list.index(Mime::XML.to_s)
-
-
if text_xml && app_xml
-
# set the q value to the max of the two
-
list[app_xml].q = [list[text_xml].q, list[app_xml].q].max
-
-
# make sure app_xml is ahead of text_xml in the list
-
if app_xml > text_xml
-
list[app_xml], list[text_xml] = list[text_xml], list[app_xml]
-
app_xml, text_xml = text_xml, app_xml
-
end
-
-
# delete text_xml from the list
-
list.delete_at(text_xml)
-
-
elsif text_xml
-
list[text_xml].name = Mime::XML.to_s
-
end
-
-
# Look for more specific XML-based types and sort them ahead of app/xml
-
-
if app_xml
-
idx = app_xml
-
app_xml_type = list[app_xml]
-
-
while(idx < list.length)
-
type = list[idx]
-
break if type.q < app_xml_type.q
-
if type.name =~ /\+xml$/
-
list[app_xml], list[idx] = list[idx], list[app_xml]
-
app_xml = idx
-
end
-
idx += 1
-
end
-
end
-
-
list.map! { |i| Mime::Type.lookup(i.name) }.uniq!
-
list
-
end
-
end
-
-
# input: 'text'
-
# returned value: [Mime::JSON, Mime::XML, Mime::ICS, Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT]
-
#
-
# input: 'application'
-
# returned value: [Mime::HTML, Mime::JS, Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM]
-
2
def parse_data_with_trailing_star(input)
-
Mime::SET.select { |m| m =~ input }
-
end
-
-
# This method is opposite of register method.
-
#
-
# Usage:
-
#
-
# Mime::Type.unregister(:mobile)
-
2
def unregister(symbol)
-
symbol = symbol.to_s.upcase
-
mime = Mime.const_get(symbol)
-
Mime.instance_eval { remove_const(symbol) }
-
-
SET.delete_if { |v| v.eql?(mime) }
-
LOOKUP.delete_if { |k,v| v.eql?(mime) }
-
EXTENSION_LOOKUP.delete_if { |k,v| v.eql?(mime) }
-
end
-
end
-
-
2
def initialize(string, symbol = nil, synonyms = [])
-
44
@symbol, @synonyms = symbol, synonyms
-
44
@string = string
-
end
-
-
2
def to_s
-
14
@string
-
end
-
-
2
def to_str
-
to_s
-
end
-
-
2
def to_sym
-
95
@symbol
-
end
-
-
2
def ref
-
10
to_sym || to_s
-
end
-
-
2
def ===(list)
-
if list.is_a?(Array)
-
(@synonyms + [ self ]).any? { |synonym| list.include?(synonym) }
-
else
-
super
-
end
-
end
-
-
2
def ==(mime_type)
-
1
return false if mime_type.blank?
-
1
(@synonyms + [ self ]).any? do |synonym|
-
2
synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym
-
end
-
end
-
-
2
def =~(mime_type)
-
return false if mime_type.blank?
-
regexp = Regexp.new(Regexp.quote(mime_type.to_s))
-
(@synonyms + [ self ]).any? do |synonym|
-
synonym.to_s =~ regexp
-
end
-
end
-
-
# Returns true if Action Pack should check requests using this Mime Type for possible request forgery. See
-
# ActionController::RequestForgeryProtection.
-
2
def verify_request?
-
@@browser_generated_types.include?(to_sym)
-
end
-
-
2
def html?
-
@@html_types.include?(to_sym) || @string =~ /html/
-
end
-
-
2
def respond_to?(method, include_private = false) #:nodoc:
-
2
super || method.to_s =~ /(\w+)\?$/
-
end
-
-
2
private
-
2
def method_missing(method, *args)
-
if method.to_s =~ /(\w+)\?$/
-
$1.downcase.to_sym == to_sym
-
else
-
super
-
end
-
end
-
end
-
end
-
-
2
require 'action_dispatch/http/mime_types'
-
# Build list of Mime types for HTTP responses
-
# http://www.iana.org/assignments/media-types/
-
-
2
Mime::Type.register "text/html", :html, %w( application/xhtml+xml ), %w( xhtml )
-
2
Mime::Type.register "text/plain", :text, [], %w(txt)
-
2
Mime::Type.register "text/javascript", :js, %w( application/javascript application/x-javascript )
-
2
Mime::Type.register "text/css", :css
-
2
Mime::Type.register "text/calendar", :ics
-
2
Mime::Type.register "text/csv", :csv
-
-
2
Mime::Type.register "image/png", :png, [], %w(png)
-
2
Mime::Type.register "image/jpeg", :jpeg, [], %w(jpg jpeg jpe)
-
2
Mime::Type.register "image/gif", :gif, [], %w(gif)
-
2
Mime::Type.register "image/bmp", :bmp, [], %w(bmp)
-
2
Mime::Type.register "image/tiff", :tiff, [], %w(tif tiff)
-
-
2
Mime::Type.register "video/mpeg", :mpeg, [], %w(mpg mpeg mpe)
-
-
2
Mime::Type.register "application/xml", :xml, %w( text/xml application/x-xml )
-
2
Mime::Type.register "application/rss+xml", :rss
-
2
Mime::Type.register "application/atom+xml", :atom
-
2
Mime::Type.register "application/x-yaml", :yaml, %w( text/yaml )
-
-
2
Mime::Type.register "multipart/form-data", :multipart_form
-
2
Mime::Type.register "application/x-www-form-urlencoded", :url_encoded_form
-
-
# http://www.ietf.org/rfc/rfc4627.txt
-
# http://www.json.org/JSONRequest.html
-
2
Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest )
-
-
2
Mime::Type.register "application/pdf", :pdf, [], %w(pdf)
-
2
Mime::Type.register "application/zip", :zip, [], %w(zip)
-
-
# Create Mime::ALL but do not add it to the SET.
-
2
Mime::ALL = Mime::Type.new("*/*", :all, [])
-
1
module ActionDispatch
-
1
module Http
-
1
class ParameterFilter
-
-
1
def initialize(filters)
-
9
@filters = filters
-
end
-
-
1
def filter(params)
-
11
if enabled?
-
11
compiled_filter.call(params)
-
else
-
params.dup
-
end
-
end
-
-
1
private
-
-
1
def enabled?
-
11
@filters.present?
-
end
-
-
1
FILTERED = '[FILTERED]'.freeze
-
-
1
def compiled_filter
-
@compiled_filter ||= begin
-
9
regexps, blocks = compile_filter
-
-
9
lambda do |original_params|
-
11
filtered_params = {}
-
-
11
original_params.each do |key, value|
-
48
if regexps.find { |r| key =~ r }
-
value = FILTERED
-
elsif value.is_a?(Hash)
-
2
value = filter(value)
-
elsif value.is_a?(Array)
-
value = value.map { |v| v.is_a?(Hash) ? filter(v) : v }
-
elsif blocks.present?
-
key = key.dup
-
value = value.dup if value.duplicable?
-
blocks.each { |b| b.call(key, value) }
-
end
-
-
24
filtered_params[key] = value
-
end
-
-
11
filtered_params
-
end
-
11
end
-
end
-
-
1
def compile_filter
-
9
strings, regexps, blocks = [], [], []
-
-
9
@filters.each do |item|
-
9
case item
-
when NilClass
-
when Proc
-
blocks << item
-
when Regexp
-
regexps << item
-
else
-
9
strings << item.to_s
-
end
-
end
-
-
9
regexps << Regexp.new(strings.join('|'), true) unless strings.empty?
-
9
[regexps, blocks]
-
end
-
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
-
2
module ActionDispatch
-
2
module Http
-
2
module Parameters
-
# Returns both GET and POST \parameters in a single hash.
-
2
def parameters
-
27
@env["action_dispatch.request.parameters"] ||= begin
-
9
params = request_parameters.merge(query_parameters)
-
9
params.merge!(path_parameters)
-
9
encode_params(params).with_indifferent_access
-
end
-
end
-
2
alias :params :parameters
-
-
2
def path_parameters=(parameters) #:nodoc:
-
@symbolized_path_params = nil
-
@env.delete("action_dispatch.request.parameters")
-
@env["action_dispatch.request.path_parameters"] = parameters
-
end
-
-
# The same as <tt>path_parameters</tt> with explicitly symbolized keys.
-
2
def symbolized_path_parameters
-
27
@symbolized_path_params ||= path_parameters.symbolize_keys
-
end
-
-
# Returns a hash with the \parameters used to form the \path of the request.
-
# Returned hash keys are strings:
-
#
-
# {'action' => 'my_action', 'controller' => 'my_controller'}
-
#
-
# See <tt>symbolized_path_parameters</tt> for symbolized keys.
-
2
def path_parameters
-
40
@env["action_dispatch.request.path_parameters"] ||= {}
-
end
-
-
2
def reset_parameters #:nodoc:
-
@env.delete("action_dispatch.request.parameters")
-
end
-
-
2
private
-
-
# TODO: Validate that the characters are UTF-8. If they aren't,
-
# you'll get a weird error down the road, but our form handling
-
# should really prevent that from happening
-
2
def encode_params(params)
-
33
return params unless "ruby".encoding_aware?
-
-
33
if params.is_a?(String)
-
22
return params.force_encoding("UTF-8").encode!
-
elsif !params.is_a?(Hash)
-
return params
-
end
-
-
11
params.each do |k, v|
-
24
case v
-
when Hash
-
2
encode_params(v)
-
when Array
-
v.map! {|el| encode_params(el) }
-
else
-
22
encode_params(v)
-
end
-
end
-
end
-
-
# Convert nested Hash to HashWithIndifferentAccess
-
2
def normalize_parameters(value)
-
9
case value
-
when Hash
-
9
h = {}
-
9
value.each { |k, v| h[k] = normalize_parameters(v) }
-
9
h.with_indifferent_access
-
when Array
-
value.map { |e| normalize_parameters(e) }
-
else
-
value
-
end
-
end
-
end
-
end
-
end
-
2
require 'tempfile'
-
2
require 'stringio'
-
2
require 'strscan'
-
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
2
require 'active_support/core_ext/string/access'
-
2
require 'active_support/inflector'
-
2
require 'action_dispatch/http/headers'
-
2
require 'action_controller/metal/exceptions'
-
-
2
module ActionDispatch
-
2
class Request < Rack::Request
-
2
include ActionDispatch::Http::Cache::Request
-
2
include ActionDispatch::Http::MimeNegotiation
-
2
include ActionDispatch::Http::Parameters
-
2
include ActionDispatch::Http::FilterParameters
-
2
include ActionDispatch::Http::Upload
-
2
include ActionDispatch::Http::URL
-
-
2
LOCALHOST = [/^127\.0\.0\.\d{1,3}$/, "::1", /^0:0:0:0:0:0:0:1(%.*)?$/].freeze
-
2
ENV_METHODS = %w[ AUTH_TYPE GATEWAY_INTERFACE
-
PATH_TRANSLATED REMOTE_HOST
-
REMOTE_IDENT REMOTE_USER REMOTE_ADDR
-
SERVER_NAME SERVER_PROTOCOL
-
-
HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
-
HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM
-
HTTP_NEGOTIATE HTTP_PRAGMA ].freeze
-
-
2
ENV_METHODS.each do |env|
-
34
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{env.sub(/^HTTP_/n, '').downcase} # def accept_charset
-
@env["#{env}"] # @env["HTTP_ACCEPT_CHARSET"]
-
end # end
-
METHOD
-
end
-
-
2
def key?(key)
-
@env.key?(key)
-
end
-
-
# List of HTTP request methods from the following RFCs:
-
# Hypertext Transfer Protocol -- HTTP/1.1 (http://www.ietf.org/rfc/rfc2616.txt)
-
# HTTP Extensions for Distributed Authoring -- WEBDAV (http://www.ietf.org/rfc/rfc2518.txt)
-
# Versioning Extensions to WebDAV (http://www.ietf.org/rfc/rfc3253.txt)
-
# Ordered Collections Protocol (WebDAV) (http://www.ietf.org/rfc/rfc3648.txt)
-
# Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol (http://www.ietf.org/rfc/rfc3744.txt)
-
# Web Distributed Authoring and Versioning (WebDAV) SEARCH (http://www.ietf.org/rfc/rfc5323.txt)
-
# PATCH Method for HTTP (http://www.ietf.org/rfc/rfc5789.txt)
-
2
RFC2616 = %w(OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT)
-
2
RFC2518 = %w(PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK)
-
2
RFC3253 = %w(VERSION-CONTROL REPORT CHECKOUT CHECKIN UNCHECKOUT MKWORKSPACE UPDATE LABEL MERGE BASELINE-CONTROL MKACTIVITY)
-
2
RFC3648 = %w(ORDERPATCH)
-
2
RFC3744 = %w(ACL)
-
2
RFC5323 = %w(SEARCH)
-
2
RFC5789 = %w(PATCH)
-
-
2
HTTP_METHODS = RFC2616 + RFC2518 + RFC3253 + RFC3648 + RFC3744 + RFC5323 + RFC5789
-
2
HTTP_METHOD_LOOKUP = {}
-
-
# Populate the HTTP method lookup cache
-
2
HTTP_METHODS.each do |method|
-
60
HTTP_METHOD_LOOKUP[method] = method.underscore.to_sym
-
end
-
-
# Returns the HTTP \method that the application should see.
-
# In the case where the \method was overridden by a middleware
-
# (for instance, if a HEAD request was converted to a GET,
-
# or if a _method parameter was used to determine the \method
-
# the application should use), this \method returns the overridden
-
# value, not the original.
-
2
def request_method
-
9
@request_method ||= check_method(env["REQUEST_METHOD"])
-
end
-
-
# Returns a symbol form of the #request_method
-
2
def request_method_symbol
-
HTTP_METHOD_LOOKUP[request_method]
-
end
-
-
# Returns the original value of the environment's REQUEST_METHOD,
-
# even if it was overridden by middleware. See #request_method for
-
# more information.
-
2
def method
-
9
@method ||= check_method(env["rack.methodoverride.original_method"] || env['REQUEST_METHOD'])
-
end
-
-
# Returns a symbol form of the #method
-
2
def method_symbol
-
HTTP_METHOD_LOOKUP[method]
-
end
-
-
# Is this a GET (or HEAD) request?
-
# Equivalent to <tt>request.request_method_symbol == :get</tt>.
-
2
def get?
-
9
HTTP_METHOD_LOOKUP[request_method] == :get
-
end
-
-
# Is this a POST request?
-
# Equivalent to <tt>request.request_method_symbol == :post</tt>.
-
2
def post?
-
HTTP_METHOD_LOOKUP[request_method] == :post
-
end
-
-
# Is this a PUT request?
-
# Equivalent to <tt>request.request_method_symbol == :put</tt>.
-
2
def put?
-
HTTP_METHOD_LOOKUP[request_method] == :put
-
end
-
-
# Is this a DELETE request?
-
# Equivalent to <tt>request.request_method_symbol == :delete</tt>.
-
2
def delete?
-
HTTP_METHOD_LOOKUP[request_method] == :delete
-
end
-
-
# Is this a HEAD request?
-
# Equivalent to <tt>request.method_symbol == :head</tt>.
-
2
def head?
-
HTTP_METHOD_LOOKUP[method] == :head
-
end
-
-
# Provides access to the request's HTTP headers, for example:
-
#
-
# request.headers["Content-Type"] # => "text/plain"
-
2
def headers
-
Http::Headers.new(@env)
-
end
-
-
2
def original_fullpath
-
@original_fullpath ||= (env["ORIGINAL_FULLPATH"] || fullpath)
-
end
-
-
2
def fullpath
-
9
@fullpath ||= super
-
end
-
-
2
def original_url
-
base_url + original_fullpath
-
end
-
-
2
def media_type
-
9
content_mime_type.to_s
-
end
-
-
# Returns the content length of the request as an integer.
-
2
def content_length
-
super.to_i
-
end
-
-
# Returns true if the "X-Requested-With" header contains "XMLHttpRequest"
-
# (case-insensitive). All major JavaScript libraries send this header with
-
# every Ajax request.
-
2
def xml_http_request?
-
18
@env['HTTP_X_REQUESTED_WITH'] =~ /XMLHttpRequest/i
-
end
-
2
alias :xhr? :xml_http_request?
-
-
2
def ip
-
@ip ||= super
-
end
-
-
# Originating IP address, usually set by the RemoteIp middleware.
-
2
def remote_ip
-
@remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s
-
end
-
-
# Returns the unique request id, which is based off either the X-Request-Id header that can
-
# be generated by a firewall, load balancer, or web server or by the RequestId middleware
-
# (which sets the action_dispatch.request_id environment variable).
-
#
-
# This unique ID is useful for tracing a request from end-to-end as part of logging or debugging.
-
# This relies on the rack variable set by the ActionDispatch::RequestId middleware.
-
2
def uuid
-
@uuid ||= env["action_dispatch.request_id"]
-
end
-
-
# Returns the lowercase name of the HTTP server software.
-
2
def server_software
-
(@env['SERVER_SOFTWARE'] && /^([a-zA-Z]+)/ =~ @env['SERVER_SOFTWARE']) ? $1.downcase : nil
-
end
-
-
# Read the request \body. This is useful for web services that need to
-
# work with raw requests directly.
-
2
def raw_post
-
unless @env.include? 'RAW_POST_DATA'
-
raw_post_body = body
-
@env['RAW_POST_DATA'] = raw_post_body.read(@env['CONTENT_LENGTH'].to_i)
-
raw_post_body.rewind if raw_post_body.respond_to?(:rewind)
-
end
-
@env['RAW_POST_DATA']
-
end
-
-
# The request body is an IO input stream. If the RAW_POST_DATA environment
-
# variable is already set, wrap it in a StringIO.
-
2
def body
-
if raw_post = @env['RAW_POST_DATA']
-
raw_post.force_encoding(Encoding::BINARY) if raw_post.respond_to?(:force_encoding)
-
StringIO.new(raw_post)
-
else
-
@env['rack.input']
-
end
-
end
-
-
2
def form_data?
-
9
FORM_DATA_MEDIA_TYPES.include?(content_mime_type.to_s)
-
end
-
-
2
def body_stream #:nodoc:
-
@env['rack.input']
-
end
-
-
# TODO This should be broken apart into AD::Request::Session and probably
-
# be included by the session middleware.
-
2
def reset_session
-
session.destroy if session && session.respond_to?(:destroy)
-
self.session = {}
-
@env['action_dispatch.request.flash_hash'] = nil
-
end
-
-
2
def session=(session) #:nodoc:
-
75
@env['rack.session'] = session
-
end
-
-
2
def session_options=(options)
-
75
@env['rack.session.options'] = options
-
end
-
-
# Override Rack's GET method to support indifferent access
-
2
def GET
-
15
@env["action_dispatch.request.query_parameters"] ||= deep_munge(normalize_parameters(super) || {})
-
end
-
2
alias :query_parameters :GET
-
-
# Override Rack's POST method to support indifferent access
-
2
def POST
-
21
@env["action_dispatch.request.request_parameters"] ||= deep_munge(normalize_parameters(super) || {})
-
end
-
2
alias :request_parameters :POST
-
-
-
# Returns the authorization header regardless of whether it was specified directly or through one of the
-
# proxy alternatives.
-
2
def authorization
-
@env['HTTP_AUTHORIZATION'] ||
-
@env['X-HTTP_AUTHORIZATION'] ||
-
@env['X_HTTP_AUTHORIZATION'] ||
-
@env['REDIRECT_X_HTTP_AUTHORIZATION']
-
end
-
-
# True if the request came from localhost, 127.0.0.1.
-
2
def local?
-
LOCALHOST.any? { |local_ip| local_ip === remote_addr && local_ip === remote_ip }
-
end
-
-
# Remove nils from the params hash
-
2
def deep_munge(hash)
-
9
hash.each do |k, v|
-
case v
-
when Array
-
v.grep(Hash) { |x| deep_munge(x) }
-
v.compact!
-
hash[k] = nil if v.empty?
-
when Hash
-
deep_munge(v)
-
end
-
end
-
-
9
hash
-
end
-
-
2
protected
-
-
2
def parse_query(qs)
-
deep_munge(super)
-
end
-
-
2
private
-
-
2
def check_method(name)
-
18
HTTP_METHOD_LOOKUP[name] || raise(ActionController::UnknownHttpMethod, "#{name}, accepted HTTP methods are #{HTTP_METHODS.to_sentence(:locale => :en)}")
-
18
name
-
end
-
end
-
end
-
2
require 'digest/md5'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/class/attribute_accessors'
-
-
2
module ActionDispatch # :nodoc:
-
# Represents an HTTP response generated by a controller action. Use it to
-
# retrieve the current state of the response, or customize the response. It can
-
# either represent a real HTTP response (i.e. one that is meant to be sent
-
# back to the web browser) or a TestResponse (i.e. one that is generated
-
# from integration tests).
-
#
-
# \Response is mostly a Ruby on \Rails framework implementation detail, and
-
# should never be used directly in controllers. Controllers should use the
-
# methods defined in ActionController::Base instead. For example, if you want
-
# to set the HTTP response's content MIME type, then use
-
# ActionControllerBase#headers instead of Response#headers.
-
#
-
# Nevertheless, integration tests may want to inspect controller responses in
-
# more detail, and that's when \Response can be useful for application
-
# developers. Integration test methods such as
-
# ActionDispatch::Integration::Session#get and
-
# ActionDispatch::Integration::Session#post return objects of type
-
# TestResponse (which are of course also of type \Response).
-
#
-
# For example, the following demo integration test prints the body of the
-
# controller response to the console:
-
#
-
# class DemoControllerTest < ActionDispatch::IntegrationTest
-
# def test_print_root_path_to_console
-
# get('/')
-
# puts @response.body
-
# end
-
# end
-
2
class Response
-
2
attr_accessor :request, :header
-
2
attr_reader :status
-
2
attr_writer :sending_file
-
-
2
alias_method :headers=, :header=
-
2
alias_method :headers, :header
-
-
2
delegate :[], :[]=, :to => :@header
-
2
delegate :each, :to => :@body
-
-
# Sets the HTTP response's content MIME type. For example, in the controller
-
# you could write this:
-
#
-
# response.content_type = "text/plain"
-
#
-
# If a character set has been defined for this response (see charset=) then
-
# the character set information will also be included in the content type
-
# information.
-
2
attr_accessor :charset, :content_type
-
-
2
CONTENT_TYPE = "Content-Type".freeze
-
2
SET_COOKIE = "Set-Cookie".freeze
-
2
LOCATION = "Location".freeze
-
-
4
cattr_accessor(:default_charset) { "utf-8" }
-
-
2
include Rack::Response::Helpers
-
2
include ActionDispatch::Http::Cache::Response
-
-
2
def initialize(status = 200, header = {}, body = [])
-
75
self.body, self.header, self.status = body, header, status
-
-
75
@sending_file = false
-
75
@blank = false
-
-
75
if content_type = self[CONTENT_TYPE]
-
type, charset = content_type.split(/;\s*charset=/)
-
@content_type = Mime::Type.lookup(type)
-
@charset = charset || self.class.default_charset
-
end
-
-
75
prepare_cache_control!
-
-
75
yield self if block_given?
-
end
-
-
2
def status=(status)
-
84
@status = Rack::Utils.status_code(status)
-
end
-
-
# The response code of the request
-
2
def response_code
-
12
@status
-
end
-
-
# Returns a String to ensure compatibility with Net::HTTPResponse
-
2
def code
-
@status.to_s
-
end
-
-
2
def message
-
Rack::Utils::HTTP_STATUS_CODES[@status]
-
end
-
2
alias_method :status_message, :message
-
-
2
def respond_to?(method)
-
if method.to_sym == :to_path
-
@body.respond_to?(:to_path)
-
else
-
super
-
end
-
end
-
-
2
def to_path
-
@body.to_path
-
end
-
-
2
def body
-
strings = []
-
each { |part| strings << part.to_s }
-
strings.join
-
end
-
-
2
EMPTY = " "
-
-
2
def body=(body)
-
84
@blank = true if body == EMPTY
-
-
# Explicitly check for strings. This is *wrong* theoretically
-
# but if we don't check this, the performance on string bodies
-
# is bad on Ruby 1.8 (because strings responds to each then).
-
84
@body = if body.respond_to?(:to_str) || !body.respond_to?(:each)
-
9
[body]
-
else
-
75
body
-
end
-
end
-
-
2
def body_parts
-
@body
-
end
-
-
2
def set_cookie(key, value)
-
::Rack::Utils.set_cookie_header!(header, key, value)
-
end
-
-
2
def delete_cookie(key, value={})
-
::Rack::Utils.delete_cookie_header!(header, key, value)
-
end
-
-
2
def location
-
18
headers[LOCATION]
-
end
-
2
alias_method :redirect_url, :location
-
-
2
def location=(url)
-
9
headers[LOCATION] = url
-
end
-
-
2
def close
-
@body.close if @body.respond_to?(:close)
-
end
-
-
2
def to_a
-
9
assign_default_content_type_and_charset!
-
9
handle_conditional_get!
-
-
9
@header[SET_COOKIE] = @header[SET_COOKIE].join("\n") if @header[SET_COOKIE].respond_to?(:join)
-
-
9
if [204, 304].include?(@status)
-
@header.delete CONTENT_TYPE
-
[@status, @header, []]
-
else
-
9
[@status, @header, self]
-
end
-
end
-
2
alias prepare! to_a
-
2
alias to_ary to_a # For implicit splat on 1.9.2
-
-
# Returns the response cookies, converted to a Hash of (name => value) pairs
-
#
-
# assert_equal 'AuthorOfNewPage', r.cookies['author']
-
2
def cookies
-
cookies = {}
-
if header = self[SET_COOKIE]
-
header = header.split("\n") if header.respond_to?(:to_str)
-
header.each do |cookie|
-
if pair = cookie.split(';').first
-
key, value = pair.split("=").map { |v| Rack::Utils.unescape(v) }
-
cookies[key] = value
-
end
-
end
-
end
-
cookies
-
end
-
-
2
private
-
-
2
def assign_default_content_type_and_charset!
-
9
return if headers[CONTENT_TYPE].present?
-
-
9
@content_type ||= Mime::HTML
-
9
@charset ||= self.class.default_charset
-
-
9
type = @content_type.to_s.dup
-
9
type << "; charset=#{@charset}" unless @sending_file
-
-
9
headers[CONTENT_TYPE] = type
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Http
-
2
class UploadedFile
-
2
attr_accessor :original_filename, :content_type, :tempfile, :headers
-
-
2
def initialize(hash)
-
@original_filename = encode_filename(hash[:filename])
-
@content_type = hash[:type]
-
@headers = hash[:head]
-
@tempfile = hash[:tempfile]
-
raise(ArgumentError, ':tempfile is required') unless @tempfile
-
end
-
-
2
def read(*args)
-
@tempfile.read(*args)
-
end
-
-
# Delegate these methods to the tempfile.
-
2
[:open, :path, :rewind, :size].each do |method|
-
8
class_eval "def #{method}; @tempfile.#{method}; end"
-
end
-
-
2
private
-
2
def encode_filename(filename)
-
# Encode the filename in the utf8 encoding, unless it is nil or we're in 1.8
-
if "ruby".encoding_aware? && filename
-
filename.force_encoding("UTF-8").encode!
-
else
-
filename
-
end
-
end
-
end
-
-
2
module Upload
-
# Convert nested Hash to HashWithIndifferentAccess and replace
-
# file upload hash with UploadedFile objects
-
2
def normalize_parameters(value)
-
9
if Hash === value && value.has_key?(:tempfile)
-
UploadedFile.new(value)
-
else
-
9
super
-
end
-
end
-
2
private :normalize_parameters
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Http
-
2
module URL
-
2
mattr_accessor :tld_length
-
2
self.tld_length = 1
-
-
2
class << self
-
2
def extract_domain(host, tld_length = @@tld_length)
-
return nil unless named_host?(host)
-
host.split('.').last(1 + tld_length).join('.')
-
end
-
-
2
def extract_subdomains(host, tld_length = @@tld_length)
-
return [] unless named_host?(host)
-
parts = host.split('.')
-
parts[0..-(tld_length+2)]
-
end
-
-
2
def extract_subdomain(host, tld_length = @@tld_length)
-
extract_subdomains(host, tld_length).join('.')
-
end
-
-
2
def url_for(options = {})
-
18
unless options[:host].present? || options[:only_path].present?
-
raise ArgumentError, 'Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true'
-
end
-
-
18
rewritten_url = ""
-
-
18
unless options[:only_path]
-
9
unless options[:protocol] == false
-
9
rewritten_url << (options[:protocol] || "http")
-
9
rewritten_url << ":" unless rewritten_url.match(%r{:|//})
-
end
-
9
rewritten_url << "//" unless rewritten_url.match("//")
-
9
rewritten_url << rewrite_authentication(options)
-
9
rewritten_url << host_or_subdomain_and_domain(options)
-
9
rewritten_url << ":#{options.delete(:port)}" if options[:port]
-
end
-
-
18
path = options.delete(:path) || ''
-
-
18
params = options[:params] || {}
-
29
params.reject! {|k,v| v.to_param.nil? }
-
-
18
if options[:trailing_slash] && !path.ends_with?('/')
-
rewritten_url << path.sub(/(\?|\z)/) { "/" + $& }
-
else
-
18
rewritten_url << path
-
end
-
18
rewritten_url << "?#{params.to_query}" unless params.empty?
-
18
rewritten_url << "##{Journey::Router::Utils.escape_fragment(options[:anchor].to_param.to_s)}" if options[:anchor]
-
18
rewritten_url
-
end
-
-
2
private
-
-
2
def named_host?(host)
-
9
!(host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host))
-
end
-
-
2
def rewrite_authentication(options)
-
9
if options[:user] && options[:password]
-
"#{Rack::Utils.escape(options[:user])}:#{Rack::Utils.escape(options[:password])}@"
-
else
-
9
""
-
end
-
end
-
-
2
def host_or_subdomain_and_domain(options)
-
9
return options[:host] if !named_host?(options[:host]) || (options[:subdomain].nil? && options[:domain].nil?)
-
-
tld_length = options[:tld_length] || @@tld_length
-
-
host = ""
-
unless options[:subdomain] == false
-
host << (options[:subdomain] || extract_subdomain(options[:host], tld_length)).to_param
-
host << "."
-
end
-
host << (options[:domain] || extract_domain(options[:host], tld_length))
-
host
-
end
-
end
-
-
# Returns the complete URL used for this request.
-
2
def url
-
protocol + host_with_port + fullpath
-
end
-
-
# Returns 'https://' if this is an SSL request and 'http://' otherwise.
-
2
def protocol
-
45
@protocol ||= ssl? ? 'https://' : 'http://'
-
end
-
-
# Returns the \host for this request, such as "example.com".
-
2
def raw_host_with_port
-
37
if forwarded = env["HTTP_X_FORWARDED_HOST"]
-
forwarded.split(/,\s?/).last
-
else
-
37
env['HTTP_HOST'] || "#{env['SERVER_NAME'] || env['SERVER_ADDR']}:#{env['SERVER_PORT']}"
-
end
-
end
-
-
# Returns the host for this request, such as example.com.
-
2
def host
-
28
raw_host_with_port.sub(/:\d+$/, '')
-
end
-
-
# Returns a \host:\port string for this request, such as "example.com" or
-
# "example.com:8080".
-
2
def host_with_port
-
"#{host}#{port_string}"
-
end
-
-
# Returns the port number of this request as an integer.
-
2
def port
-
@port ||= begin
-
9
if raw_host_with_port =~ /:(\d+)$/
-
$1.to_i
-
else
-
9
standard_port
-
end
-
18
end
-
end
-
-
# Returns the standard \port number for this request's protocol.
-
2
def standard_port
-
27
case protocol
-
when 'https://' then 443
-
27
else 80
-
end
-
end
-
-
# Returns whether this request is using the standard port
-
2
def standard_port?
-
18
port == standard_port
-
end
-
-
# Returns a number \port suffix like 8080 if the \port number of this request
-
# is not the default HTTP \port 80 or HTTPS \port 443.
-
2
def optional_port
-
18
standard_port? ? nil : port
-
end
-
-
# Returns a string \port suffix, including colon, like ":8080" if the \port
-
# number of this request is not the default HTTP \port 80 or HTTPS \port 443.
-
2
def port_string
-
standard_port? ? '' : ":#{port}"
-
end
-
-
2
def server_port
-
@env['SERVER_PORT'].to_i
-
end
-
-
# Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org". You can specify
-
# a different <tt>tld_length</tt>, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk".
-
2
def domain(tld_length = @@tld_length)
-
ActionDispatch::Http::URL.extract_domain(host, tld_length)
-
end
-
-
# Returns all the \subdomains as an array, so <tt>["dev", "www"]</tt> would be
-
# returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
-
# such as 2 to catch <tt>["www"]</tt> instead of <tt>["www", "rubyonrails"]</tt>
-
# in "www.rubyonrails.co.uk".
-
2
def subdomains(tld_length = @@tld_length)
-
ActionDispatch::Http::URL.extract_subdomains(host, tld_length)
-
end
-
-
# Returns all the \subdomains as a string, so <tt>"dev.www"</tt> would be
-
# returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
-
# such as 2 to catch <tt>"www"</tt> instead of <tt>"www.rubyonrails"</tt>
-
# in "www.rubyonrails.co.uk".
-
2
def subdomain(tld_length = @@tld_length)
-
subdomains(tld_length).join(".")
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
class BestStandardsSupport
-
2
def initialize(app, type = true)
-
2
@app = app
-
-
2
@header = case type
-
when true
-
2
"IE=Edge,chrome=1"
-
when :builtin
-
"IE=Edge"
-
when false
-
nil
-
end
-
end
-
-
2
def call(env)
-
status, headers, body = @app.call(env)
-
-
if headers["X-UA-Compatible"] && @header
-
unless headers["X-UA-Compatible"][@header]
-
headers["X-UA-Compatible"] << "," << @header.to_s
-
end
-
else
-
headers["X-UA-Compatible"] = @header
-
end
-
-
[status, headers, body]
-
end
-
end
-
end
-
# Keep this file meanwhile https://github.com/rack/rack/pull/313 is not released
-
2
module ActionDispatch
-
2
class BodyProxy
-
2
def initialize(body, &block)
-
@body, @block, @closed = body, block, false
-
end
-
-
2
def respond_to?(*args)
-
super or @body.respond_to?(*args)
-
end
-
-
2
def close
-
return if @closed
-
@closed = true
-
begin
-
@body.close if @body.respond_to? :close
-
ensure
-
@block.call
-
end
-
end
-
-
2
def closed?
-
@closed
-
end
-
-
2
def method_missing(*args, &block)
-
@body.__send__(*args, &block)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/delegation'
-
-
2
module ActionDispatch
-
# Provide callbacks to be executed before and after the request dispatch.
-
2
class Callbacks
-
2
include ActiveSupport::Callbacks
-
-
2
define_callbacks :call, :rescuable => true
-
-
2
class << self
-
2
delegate :to_prepare, :to_cleanup, :to => "ActionDispatch::Reloader"
-
end
-
-
2
def self.before(*args, &block)
-
set_callback(:call, :before, *args, &block)
-
end
-
-
2
def self.after(*args, &block)
-
set_callback(:call, :after, *args, &block)
-
end
-
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
run_callbacks :call do
-
@app.call(env)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
-
2
module ActionDispatch
-
2
class Request
-
2
def cookie_jar
-
60
env['action_dispatch.cookies'] ||= Cookies::CookieJar.build(self)
-
end
-
end
-
-
# \Cookies are read and written through ActionController#cookies.
-
#
-
# The cookies being read are the ones received along with the request, the cookies
-
# being written will be sent out with the response. Reading a cookie does not get
-
# the cookie object itself back, just the value it holds.
-
#
-
# Examples for writing:
-
#
-
# # Sets a simple session cookie.
-
# # This cookie will be deleted when the user's browser is closed.
-
# cookies[:user_name] = "david"
-
#
-
# # Assign an array of values to a cookie.
-
# cookies[:lat_lon] = [47.68, -122.37]
-
#
-
# # Sets a cookie that expires in 1 hour.
-
# cookies[:login] = { :value => "XJ-122", :expires => 1.hour.from_now }
-
#
-
# # Sets a signed cookie, which prevents a user from tampering with its value.
-
# # The cookie is signed by your app's <tt>config.secret_token</tt> value.
-
# # Rails generates this value by default when you create a new Rails app.
-
# cookies.signed[:user_id] = current_user.id
-
#
-
# # Sets a "permanent" cookie (which expires in 20 years from now).
-
# cookies.permanent[:login] = "XJ-122"
-
#
-
# # You can also chain these methods:
-
# cookies.permanent.signed[:login] = "XJ-122"
-
#
-
# Examples for reading:
-
#
-
# cookies[:user_name] # => "david"
-
# cookies.size # => 2
-
# cookies[:lat_lon] # => [47.68, -122.37]
-
#
-
# Example for deleting:
-
#
-
# cookies.delete :user_name
-
#
-
# Please note that if you specify a :domain when setting a cookie, you must also specify the domain when deleting the cookie:
-
#
-
# cookies[:key] = {
-
# :value => 'a yummy cookie',
-
# :expires => 1.year.from_now,
-
# :domain => 'domain.com'
-
# }
-
#
-
# cookies.delete(:key, :domain => 'domain.com')
-
#
-
# The option symbols for setting cookies are:
-
#
-
# * <tt>:value</tt> - The cookie's value or list of values (as an array).
-
# * <tt>:path</tt> - The path for which this cookie applies. Defaults to the root
-
# of the application.
-
# * <tt>:domain</tt> - The domain for which this cookie applies so you can
-
# restrict to the domain level. If you use a schema like www.example.com
-
# and want to share session with user.example.com set <tt>:domain</tt>
-
# to <tt>:all</tt>. Make sure to specify the <tt>:domain</tt> option with
-
# <tt>:all</tt> again when deleting keys.
-
#
-
# :domain => nil # Does not sets cookie domain. (default)
-
# :domain => :all # Allow the cookie for the top most level
-
# domain and subdomains.
-
#
-
# * <tt>:expires</tt> - The time at which this cookie expires, as a \Time object.
-
# * <tt>:secure</tt> - Whether this cookie is a only transmitted to HTTPS servers.
-
# Default is +false+.
-
# * <tt>:httponly</tt> - Whether this cookie is accessible via scripting or
-
# only HTTP. Defaults to +false+.
-
2
class Cookies
-
2
HTTP_HEADER = "Set-Cookie".freeze
-
2
TOKEN_KEY = "action_dispatch.secret_token".freeze
-
-
# Raised when storing more than 4K of session data.
-
2
class CookieOverflow < StandardError; end
-
-
2
class CookieJar #:nodoc:
-
2
include Enumerable
-
-
# This regular expression is used to split the levels of a domain.
-
# The top level domain can be any string without a period or
-
# **.**, ***.** style TLDs like co.uk or com.au
-
#
-
# www.example.co.uk gives:
-
# $& => example.co.uk
-
#
-
# example.com gives:
-
# $& => example.com
-
#
-
# lots.of.subdomains.example.local gives:
-
# $& => example.local
-
2
DOMAIN_REGEXP = /[^.]*\.([^.]*|..\...|...\...)$/
-
-
2
def self.build(request)
-
10
secret = request.env[TOKEN_KEY]
-
10
host = request.host
-
10
secure = request.ssl?
-
-
10
new(secret, host, secure).tap do |hash|
-
10
hash.update(request.cookies)
-
end
-
end
-
-
2
def initialize(secret = nil, host = nil, secure = false)
-
10
@secret = secret
-
10
@set_cookies = {}
-
10
@delete_cookies = {}
-
10
@host = host
-
10
@secure = secure
-
10
@closed = false
-
10
@cookies = {}
-
end
-
-
2
def each(&block)
-
@cookies.each(&block)
-
end
-
-
# Returns the value of the cookie by +name+, or +nil+ if no such cookie exists.
-
2
def [](name)
-
@cookies[name.to_s]
-
end
-
-
2
def key?(name)
-
@cookies.key?(name.to_s)
-
end
-
2
alias :has_key? :key?
-
-
2
def update(other_hash)
-
40
@cookies.update other_hash.stringify_keys
-
40
self
-
end
-
-
2
def handle_options(options) #:nodoc:
-
options[:path] ||= "/"
-
-
if options[:domain] == :all
-
# if there is a provided tld length then we use it otherwise default domain regexp
-
domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP
-
-
# if host is not ip and matches domain regexp
-
# (ip confirms to domain regexp so we explicitly check for ip)
-
options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp)
-
".#{$&}"
-
end
-
elsif options[:domain].is_a? Array
-
# if host matches one of the supplied domains without a dot in front of it
-
options[:domain] = options[:domain].find {|domain| @host.include? domain[/^\.?(.*)$/, 1] }
-
end
-
end
-
-
# Sets the cookie named +name+. The second argument may be the very cookie
-
# value, or a hash of options as documented above.
-
2
def []=(key, options)
-
if options.is_a?(Hash)
-
options.symbolize_keys!
-
value = options[:value]
-
else
-
value = options
-
options = { :value => value }
-
end
-
-
handle_options(options)
-
-
if @cookies[key.to_s] != value or options[:expires]
-
@cookies[key.to_s] = value
-
@set_cookies[key.to_s] = options
-
@delete_cookies.delete(key.to_s)
-
end
-
-
value
-
end
-
-
# Removes the cookie on the client machine by setting the value to an empty string
-
# and setting its expiration date into the past. Like <tt>[]=</tt>, you can pass in
-
# an options hash to delete cookies with extra data such as a <tt>:path</tt>.
-
2
def delete(key, options = {})
-
options.symbolize_keys!
-
-
handle_options(options)
-
-
value = @cookies.delete(key.to_s)
-
@delete_cookies[key.to_s] = options
-
value
-
end
-
-
# Removes all cookies on the client machine by calling <tt>delete</tt> for each cookie
-
2
def clear(options = {})
-
@cookies.each_key{ |k| delete(k, options) }
-
end
-
-
# Returns a jar that'll automatically set the assigned cookies to have an expiration date 20 years from now. Example:
-
#
-
# cookies.permanent[:prefers_open_id] = true
-
# # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
#
-
# This jar is only meant for writing. You'll read permanent cookies through the regular accessor.
-
#
-
# This jar allows chaining with the signed jar as well, so you can set permanent, signed cookies. Examples:
-
#
-
# cookies.permanent.signed[:remember_me] = current_user.id
-
# # => Set-Cookie: remember_me=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
2
def permanent
-
@permanent ||= PermanentCookieJar.new(self, @secret)
-
end
-
-
# Returns a jar that'll automatically generate a signed representation of cookie value and verify it when reading from
-
# the cookie again. This is useful for creating cookies with values that the user is not supposed to change. If a signed
-
# cookie was tampered with by the user (or a 3rd party), an ActiveSupport::MessageVerifier::InvalidSignature exception will
-
# be raised.
-
#
-
# This jar requires that you set a suitable secret for the verification on your app's config.secret_token.
-
#
-
# Example:
-
#
-
# cookies.signed[:discount] = 45
-
# # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/
-
#
-
# cookies.signed[:discount] # => 45
-
2
def signed
-
@signed ||= SignedCookieJar.new(self, @secret)
-
end
-
-
2
def write(headers)
-
9
@set_cookies.each { |k, v| ::Rack::Utils.set_cookie_header!(headers, k, v) if write_cookie?(v) }
-
9
@delete_cookies.each { |k, v| ::Rack::Utils.delete_cookie_header!(headers, k, v) }
-
end
-
-
2
def recycle! #:nodoc:
-
10
@set_cookies.clear
-
10
@delete_cookies.clear
-
end
-
-
2
mattr_accessor :always_write_cookie
-
2
self.always_write_cookie = false
-
-
2
private
-
-
2
def write_cookie?(cookie)
-
@secure || !cookie[:secure] || always_write_cookie
-
end
-
end
-
-
2
class PermanentCookieJar < CookieJar #:nodoc:
-
2
def initialize(parent_jar, secret)
-
@parent_jar, @secret = parent_jar, secret
-
end
-
-
2
def []=(key, options)
-
if options.is_a?(Hash)
-
options.symbolize_keys!
-
else
-
options = { :value => options }
-
end
-
-
options[:expires] = 20.years.from_now
-
@parent_jar[key] = options
-
end
-
-
2
def signed
-
@signed ||= SignedCookieJar.new(self, @secret)
-
end
-
-
2
def method_missing(method, *arguments, &block)
-
@parent_jar.send(method, *arguments, &block)
-
end
-
end
-
-
2
class SignedCookieJar < CookieJar #:nodoc:
-
2
MAX_COOKIE_SIZE = 4096 # Cookies can typically store 4096 bytes.
-
2
SECRET_MIN_LENGTH = 30 # Characters
-
-
2
def initialize(parent_jar, secret)
-
ensure_secret_secure(secret)
-
@parent_jar = parent_jar
-
@verifier = ActiveSupport::MessageVerifier.new(secret)
-
end
-
-
2
def [](name)
-
if signed_message = @parent_jar[name]
-
@verifier.verify(signed_message)
-
end
-
rescue ActiveSupport::MessageVerifier::InvalidSignature
-
nil
-
end
-
-
2
def []=(key, options)
-
if options.is_a?(Hash)
-
options.symbolize_keys!
-
options[:value] = @verifier.generate(options[:value])
-
else
-
options = { :value => @verifier.generate(options) }
-
end
-
-
raise CookieOverflow if options[:value].size > MAX_COOKIE_SIZE
-
@parent_jar[key] = options
-
end
-
-
2
def method_missing(method, *arguments, &block)
-
@parent_jar.send(method, *arguments, &block)
-
end
-
-
2
protected
-
-
# To prevent users from using something insecure like "Password" we make sure that the
-
# secret they've provided is at least 30 characters in length.
-
2
def ensure_secret_secure(secret)
-
if secret.blank?
-
raise ArgumentError, "A secret is required to generate an " +
-
"integrity hash for cookie session data. Use " +
-
"config.secret_token = \"some secret phrase of at " +
-
"least #{SECRET_MIN_LENGTH} characters\"" +
-
"in config/initializers/secret_token.rb"
-
end
-
-
if secret.length < SECRET_MIN_LENGTH
-
raise ArgumentError, "Secret should be something secure, " +
-
"like \"#{SecureRandom.hex(16)}\". The value you " +
-
"provided, \"#{secret}\", is shorter than the minimum length " +
-
"of #{SECRET_MIN_LENGTH} characters"
-
end
-
end
-
end
-
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
cookie_jar = nil
-
status, headers, body = @app.call(env)
-
-
if cookie_jar = env['action_dispatch.cookies']
-
cookie_jar.write(headers)
-
if headers[HTTP_HEADER].respond_to?(:join)
-
headers[HTTP_HEADER] = headers[HTTP_HEADER].join("\n")
-
end
-
end
-
-
[status, headers, body]
-
end
-
end
-
end
-
2
require 'action_dispatch/http/request'
-
2
require 'action_dispatch/middleware/exception_wrapper'
-
-
2
module ActionDispatch
-
# This middleware is responsible for logging exceptions and
-
# showing a debugging page in case the request is local.
-
2
class DebugExceptions
-
2
RESCUES_TEMPLATE_PATH = File.join(File.dirname(__FILE__), 'templates')
-
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
begin
-
response = @app.call(env)
-
-
if response[1]['X-Cascade'] == 'pass'
-
body = response[2]
-
body.close if body.respond_to?(:close)
-
raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
-
end
-
rescue Exception => exception
-
raise exception if env['action_dispatch.show_exceptions'] == false
-
end
-
-
exception ? render_exception(env, exception) : response
-
end
-
-
2
private
-
-
2
def render_exception(env, exception)
-
wrapper = ExceptionWrapper.new(env, exception)
-
log_error(env, wrapper)
-
-
if env['action_dispatch.show_detailed_exceptions']
-
template = ActionView::Base.new([RESCUES_TEMPLATE_PATH],
-
:request => Request.new(env),
-
:exception => wrapper.exception,
-
:application_trace => wrapper.application_trace,
-
:framework_trace => wrapper.framework_trace,
-
:full_trace => wrapper.full_trace
-
)
-
-
file = "rescues/#{wrapper.rescue_template}"
-
body = template.render(:template => file, :layout => 'rescues/layout')
-
render(wrapper.status_code, body)
-
else
-
raise exception
-
end
-
end
-
-
2
def render(status, body)
-
[status, {'Content-Type' => "text/html; charset=#{Response.default_charset}", 'Content-Length' => body.bytesize.to_s}, [body]]
-
end
-
-
2
def log_error(env, wrapper)
-
logger = logger(env)
-
return unless logger
-
-
exception = wrapper.exception
-
-
trace = wrapper.application_trace
-
trace = wrapper.framework_trace if trace.empty?
-
-
ActiveSupport::Deprecation.silence do
-
message = "\n#{exception.class} (#{exception.message}):\n"
-
message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
-
message << " " << trace.join("\n ")
-
logger.fatal("#{message}\n\n")
-
end
-
end
-
-
2
def logger(env)
-
env['action_dispatch.logger'] || stderr_logger
-
end
-
-
2
def stderr_logger
-
@stderr_logger ||= Logger.new($stderr)
-
end
-
end
-
end
-
2
require 'action_controller/metal/exceptions'
-
2
require 'active_support/core_ext/exception'
-
-
2
module ActionDispatch
-
2
class ExceptionWrapper
-
2
cattr_accessor :rescue_responses
-
2
@@rescue_responses = Hash.new(:internal_server_error)
-
2
@@rescue_responses.merge!(
-
'ActionController::RoutingError' => :not_found,
-
'AbstractController::ActionNotFound' => :not_found,
-
'ActionController::MethodNotAllowed' => :method_not_allowed,
-
'ActionController::NotImplemented' => :not_implemented,
-
'ActionController::InvalidAuthenticityToken' => :unprocessable_entity
-
)
-
-
2
cattr_accessor :rescue_templates
-
2
@@rescue_templates = Hash.new('diagnostics')
-
2
@@rescue_templates.merge!(
-
'ActionView::MissingTemplate' => 'missing_template',
-
'ActionController::RoutingError' => 'routing_error',
-
'AbstractController::ActionNotFound' => 'unknown_action',
-
'ActionView::Template::Error' => 'template_error'
-
)
-
-
2
attr_reader :env, :exception
-
-
2
def initialize(env, exception)
-
@env = env
-
@exception = original_exception(exception)
-
end
-
-
2
def rescue_template
-
@@rescue_templates[@exception.class.name]
-
end
-
-
2
def status_code
-
self.class.status_code_for_exception(@exception.class.name)
-
end
-
-
2
def application_trace
-
clean_backtrace(:silent)
-
end
-
-
2
def framework_trace
-
clean_backtrace(:noise)
-
end
-
-
2
def full_trace
-
clean_backtrace(:all)
-
end
-
-
2
def self.status_code_for_exception(class_name)
-
Rack::Utils.status_code(@@rescue_responses[class_name])
-
end
-
-
2
private
-
-
2
def original_exception(exception)
-
if registered_original_exception?(exception)
-
exception.original_exception
-
else
-
exception
-
end
-
end
-
-
2
def registered_original_exception?(exception)
-
exception.respond_to?(:original_exception) && @@rescue_responses.has_key?(exception.original_exception.class.name)
-
end
-
-
2
def clean_backtrace(*args)
-
if backtrace_cleaner
-
backtrace_cleaner.clean(@exception.backtrace, *args)
-
else
-
@exception.backtrace
-
end
-
end
-
-
2
def backtrace_cleaner
-
@backtrace_cleaner ||= @env['action_dispatch.backtrace_cleaner']
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
class Request
-
# Access the contents of the flash. Use <tt>flash["notice"]</tt> to
-
# read a notice you put there or <tt>flash["notice"] = "hello"</tt>
-
# to put a new one.
-
2
def flash
-
18
@env[Flash::KEY] ||= (session["flash"] || Flash::FlashHash.new)
-
end
-
end
-
-
# The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed
-
# to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create
-
# action that sets <tt>flash[:notice] = "Post successfully created"</tt> before redirecting to a display action that can
-
# then expose the flash to its template. Actually, that exposure is automatically done. Example:
-
#
-
# class PostsController < ActionController::Base
-
# def create
-
# # save post
-
# flash[:notice] = "Post successfully created"
-
# redirect_to posts_path(@post)
-
# end
-
#
-
# def show
-
# # doesn't need to assign the flash notice to the template, that's done automatically
-
# end
-
# end
-
#
-
# show.html.erb
-
# <% if flash[:notice] %>
-
# <div class="notice"><%= flash[:notice] %></div>
-
# <% end %>
-
#
-
# Since the +notice+ and +alert+ keys are a common idiom, convenience accessors are available:
-
#
-
# flash.alert = "You must be logged in"
-
# flash.notice = "Post successfully created"
-
#
-
# This example just places a string in the flash, but you can put any object in there. And of course, you can put as
-
# many as you like at a time too. Just remember: They'll be gone by the time the next action has been performed.
-
#
-
# See docs on the FlashHash class for more details about the flash.
-
2
class Flash
-
2
KEY = 'action_dispatch.request.flash_hash'.freeze
-
-
2
class FlashNow #:nodoc:
-
2
attr_accessor :flash
-
-
2
def initialize(flash)
-
@flash = flash
-
end
-
-
2
def []=(k, v)
-
@flash[k] = v
-
@flash.discard(k)
-
v
-
end
-
-
2
def [](k)
-
@flash[k]
-
end
-
-
# Convenience accessor for flash.now[:alert]=
-
2
def alert=(message)
-
self[:alert] = message
-
end
-
-
# Convenience accessor for flash.now[:notice]=
-
2
def notice=(message)
-
self[:notice] = message
-
end
-
end
-
-
# Implementation detail: please do not change the signature of the
-
# FlashHash class. Doing that will likely affect all Rails apps in
-
# production as the FlashHash currently stored in their sessions will
-
# become invalid.
-
2
class FlashHash
-
2
include Enumerable
-
-
2
def initialize #:nodoc:
-
9
@used = Set.new
-
9
@closed = false
-
9
@flashes = {}
-
9
@now = nil
-
end
-
-
2
def initialize_copy(other)
-
if other.now_is_loaded?
-
@now = other.now.dup
-
@now.flash = self
-
end
-
super
-
end
-
-
2
def []=(k, v) #:nodoc:
-
9
keep(k)
-
9
@flashes[k] = v
-
end
-
-
2
def [](k)
-
9
@flashes[k]
-
end
-
-
2
def update(h) #:nodoc:
-
9
h.keys.each { |k| keep(k) }
-
9
@flashes.update h
-
9
self
-
end
-
-
2
def keys
-
18
@flashes.keys
-
end
-
-
2
def key?(name)
-
@flashes.key? name
-
end
-
-
2
def delete(key)
-
@flashes.delete key
-
self
-
end
-
-
2
def to_hash
-
@flashes.dup
-
end
-
-
2
def empty?
-
9
@flashes.empty?
-
end
-
-
2
def clear
-
@flashes.clear
-
end
-
-
2
def each(&block)
-
@flashes.each(&block)
-
end
-
-
2
alias :merge! :update
-
-
2
def replace(h) #:nodoc:
-
@used = Set.new
-
@flashes.replace h
-
self
-
end
-
-
# Sets a flash that will not be available to the next action, only to the current.
-
#
-
# flash.now[:message] = "Hello current action"
-
#
-
# This method enables you to use the flash as a central messaging system in your app.
-
# When you need to pass an object to the next action, you use the standard flash assign (<tt>[]=</tt>).
-
# When you need to pass an object to the current action, you use <tt>now</tt>, and your object will
-
# vanish when the current action is done.
-
#
-
# Entries set via <tt>now</tt> are accessed the same way as standard entries: <tt>flash['my-key']</tt>.
-
2
def now
-
@now ||= FlashNow.new(self)
-
end
-
-
# Keeps either the entire current flash or a specific flash entry available for the next action:
-
#
-
# flash.keep # keeps the entire flash
-
# flash.keep(:notice) # keeps only the "notice" entry, the rest of the flash is discarded
-
2
def keep(k = nil)
-
9
use(k, false)
-
end
-
-
# Marks the entire flash or a single flash entry to be discarded by the end of the current action:
-
#
-
# flash.discard # discard the entire flash at the end of the current action
-
# flash.discard(:warning) # discard only the "warning" entry at the end of the current action
-
2
def discard(k = nil)
-
use(k)
-
end
-
-
# Mark for removal entries that were kept, and delete unkept ones.
-
#
-
# This method is called automatically by filters, so you generally don't need to care about it.
-
2
def sweep #:nodoc:
-
9
keys.each do |k|
-
unless @used.include?(k)
-
@used << k
-
else
-
delete(k)
-
@used.delete(k)
-
end
-
end
-
-
# clean up after keys that could have been left over by calling reject! or shift on the flash
-
9
(@used - keys).each{ |k| @used.delete(k) }
-
end
-
-
# Convenience accessor for flash[:alert]
-
2
def alert
-
self[:alert]
-
end
-
-
# Convenience accessor for flash[:alert]=
-
2
def alert=(message)
-
self[:alert] = message
-
end
-
-
# Convenience accessor for flash[:notice]
-
2
def notice
-
self[:notice]
-
end
-
-
# Convenience accessor for flash[:notice]=
-
2
def notice=(message)
-
self[:notice] = message
-
end
-
-
2
protected
-
-
2
def now_is_loaded?
-
!!@now
-
end
-
-
# Used internally by the <tt>keep</tt> and <tt>discard</tt> methods
-
# use() # marks the entire flash as used
-
# use('msg') # marks the "msg" entry as used
-
# use(nil, false) # marks the entire flash as unused (keeps it around for one more action)
-
# use('msg', false) # marks the "msg" entry as unused (keeps it around for one more action)
-
# Returns the single value for the key you asked to be marked (un)used or the FlashHash itself
-
# if no key is passed.
-
2
def use(key = nil, used = true)
-
18
Array(key || keys).each { |k| used ? @used << k : @used.delete(k) }
-
9
return key ? self[key] : self
-
end
-
end
-
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
if (session = env['rack.session']) && (flash = session['flash'])
-
flash.sweep
-
end
-
-
@app.call(env)
-
ensure
-
session = env['rack.session'] || {}
-
flash_hash = env[KEY]
-
-
if flash_hash
-
if !flash_hash.empty? || session.key?('flash')
-
session["flash"] = flash_hash
-
new_hash = flash_hash.dup
-
else
-
new_hash = flash_hash
-
end
-
-
env[KEY] = new_hash
-
end
-
-
if session.key?('flash') && session['flash'].empty?
-
session.delete('flash')
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
class Head
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
if env["REQUEST_METHOD"] == "HEAD"
-
env["REQUEST_METHOD"] = "GET"
-
env["rack.methodoverride.original_method"] = "HEAD"
-
status, headers, _ = @app.call(env)
-
[status, headers, []]
-
else
-
@app.call(env)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/conversions'
-
2
require 'action_dispatch/http/request'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
-
2
module ActionDispatch
-
2
class ParamsParser
-
2
DEFAULT_PARSERS = {
-
Mime::XML => :xml_simple,
-
Mime::JSON => :json
-
}
-
-
2
def initialize(app, parsers = {})
-
2
@app, @parsers = app, DEFAULT_PARSERS.merge(parsers)
-
end
-
-
2
def call(env)
-
if params = parse_formatted_parameters(env)
-
env["action_dispatch.request.request_parameters"] = params
-
end
-
-
@app.call(env)
-
end
-
-
2
private
-
2
def parse_formatted_parameters(env)
-
request = Request.new(env)
-
-
return false if request.content_length.zero?
-
-
mime_type = content_type_from_legacy_post_data_format_header(env) ||
-
request.content_mime_type
-
-
strategy = @parsers[mime_type]
-
-
return false unless strategy
-
-
case strategy
-
when Proc
-
strategy.call(request.raw_post)
-
when :xml_simple, :xml_node
-
data = request.deep_munge(Hash.from_xml(request.body.read) || {})
-
request.body.rewind if request.body.respond_to?(:rewind)
-
data.with_indifferent_access
-
when :yaml
-
YAML.load(request.raw_post)
-
when :json
-
data = ActiveSupport::JSON.decode(request.body)
-
request.body.rewind if request.body.respond_to?(:rewind)
-
data = {:_json => data} unless data.is_a?(Hash)
-
request.deep_munge(data).with_indifferent_access
-
else
-
false
-
end
-
rescue Exception => e # YAML, XML or Ruby code block errors
-
logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
-
-
raise e
-
end
-
-
2
def content_type_from_legacy_post_data_format_header(env)
-
if x_post_format = env['HTTP_X_POST_DATA_FORMAT']
-
case x_post_format.to_s.downcase
-
when 'yaml' then return Mime::YAML
-
when 'xml' then return Mime::XML
-
end
-
end
-
-
nil
-
end
-
-
2
def logger(env)
-
env['action_dispatch.logger'] || Logger.new($stderr)
-
end
-
end
-
end
-
2
module ActionDispatch
-
# A simple Rack application that renders exceptions in the given public path.
-
2
class PublicExceptions
-
2
attr_accessor :public_path
-
-
2
def initialize(public_path)
-
2
@public_path = public_path
-
end
-
-
2
def call(env)
-
status = env["PATH_INFO"][1..-1]
-
locale_path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
-
path = "#{public_path}/#{status}.html"
-
-
if locale_path && File.exist?(locale_path)
-
render(status, File.read(locale_path))
-
elsif File.exist?(path)
-
render(status, File.read(path))
-
else
-
[404, { "X-Cascade" => "pass" }, []]
-
end
-
end
-
-
2
private
-
-
2
def render(status, body)
-
[status, {'Content-Type' => "text/html; charset=#{Response.default_charset}", 'Content-Length' => body.bytesize.to_s}, [body]]
-
end
-
end
-
end
-
2
require 'action_dispatch/middleware/body_proxy'
-
-
2
module ActionDispatch
-
# ActionDispatch::Reloader provides prepare and cleanup callbacks,
-
# intended to assist with code reloading during development.
-
#
-
# Prepare callbacks are run before each request, and cleanup callbacks
-
# after each request. In this respect they are analogs of ActionDispatch::Callback's
-
# before and after callbacks. However, cleanup callbacks are not called until the
-
# request is fully complete -- that is, after #close has been called on
-
# the response body. This is important for streaming responses such as the
-
# following:
-
#
-
# self.response_body = lambda { |response, output|
-
# # code here which refers to application models
-
# }
-
#
-
# Cleanup callbacks will not be called until after the response_body lambda
-
# is evaluated, ensuring that it can refer to application models and other
-
# classes before they are unloaded.
-
#
-
# By default, ActionDispatch::Reloader is included in the middleware stack
-
# only in the development environment; specifically, when config.cache_classes
-
# is false. Callbacks may be registered even when it is not included in the
-
# middleware stack, but are executed only when +ActionDispatch::Reloader.prepare!+
-
# or +ActionDispatch::Reloader.cleanup!+ are called manually.
-
#
-
2
class Reloader
-
2
include ActiveSupport::Callbacks
-
-
2
define_callbacks :prepare, :scope => :name
-
2
define_callbacks :cleanup, :scope => :name
-
-
# Add a prepare callback. Prepare callbacks are run before each request, prior
-
# to ActionDispatch::Callback's before callbacks.
-
2
def self.to_prepare(*args, &block)
-
12
set_callback(:prepare, *args, &block)
-
end
-
-
# Add a cleanup callback. Cleanup callbacks are run after each request is
-
# complete (after #close is called on the response body).
-
2
def self.to_cleanup(*args, &block)
-
set_callback(:cleanup, *args, &block)
-
end
-
-
# Execute all prepare callbacks.
-
2
def self.prepare!
-
2
new(nil).prepare!
-
end
-
-
# Execute all cleanup callbacks.
-
2
def self.cleanup!
-
new(nil).cleanup!
-
end
-
-
2
def initialize(app, condition=nil)
-
2
@app = app
-
2
@condition = condition || lambda { true }
-
2
@validated = true
-
end
-
-
2
def call(env)
-
@validated = @condition.call
-
prepare!
-
response = @app.call(env)
-
response[2] = ActionDispatch::BodyProxy.new(response[2]) { cleanup! }
-
response
-
rescue Exception
-
cleanup!
-
raise
-
end
-
-
2
def prepare! #:nodoc:
-
2
run_callbacks :prepare if validated?
-
end
-
-
2
def cleanup! #:nodoc:
-
run_callbacks :cleanup if validated?
-
ensure
-
@validated = true
-
end
-
-
2
private
-
-
2
def validated? #:nodoc:
-
2
@validated
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
class RemoteIp
-
2
class IpSpoofAttackError < StandardError ; end
-
-
# IP addresses that are "trusted proxies" that can be stripped from
-
# the comma-delimited list in the X-Forwarded-For header. See also:
-
# http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
-
2
TRUSTED_PROXIES = %r{
-
^127\.0\.0\.1$ | # localhost
-
^(10 | # private IP 10.x.x.x
-
172\.(1[6-9]|2[0-9]|3[0-1]) | # private IP in the range 172.16.0.0 .. 172.31.255.255
-
192\.168 # private IP 192.168.x.x
-
)\.
-
}x
-
-
2
attr_reader :check_ip, :proxies
-
-
2
def initialize(app, check_ip_spoofing = true, custom_proxies = nil)
-
2
@app = app
-
2
@check_ip = check_ip_spoofing
-
2
if custom_proxies
-
custom_regexp = Regexp.new(custom_proxies)
-
@proxies = Regexp.union(TRUSTED_PROXIES, custom_regexp)
-
else
-
2
@proxies = TRUSTED_PROXIES
-
end
-
end
-
-
2
def call(env)
-
env["action_dispatch.remote_ip"] = GetIp.new(env, self)
-
@app.call(env)
-
end
-
-
2
class GetIp
-
2
def initialize(env, middleware)
-
@env = env
-
@middleware = middleware
-
@calculated_ip = false
-
end
-
-
# Determines originating IP address. REMOTE_ADDR is the standard
-
# but will be wrong if the user is behind a proxy. Proxies will set
-
# HTTP_CLIENT_IP and/or HTTP_X_FORWARDED_FOR, so we prioritize those.
-
# HTTP_X_FORWARDED_FOR may be a comma-delimited list in the case of
-
# multiple chained proxies. The last address which is not a known proxy
-
# will be the originating IP.
-
2
def calculate_ip
-
client_ip = @env['HTTP_CLIENT_IP']
-
forwarded_ips = ips_from('HTTP_X_FORWARDED_FOR')
-
remote_addrs = ips_from('REMOTE_ADDR')
-
-
check_ip = client_ip && forwarded_ips.present? && @middleware.check_ip
-
if check_ip && !forwarded_ips.include?(client_ip)
-
# We don't know which came from the proxy, and which from the user
-
raise IpSpoofAttackError, "IP spoofing attack?!" \
-
"HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect}" \
-
"HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}"
-
end
-
-
not_proxy = client_ip || forwarded_ips.last || remote_addrs.first
-
-
# Return first REMOTE_ADDR if there are no other options
-
not_proxy || ips_from('REMOTE_ADDR', :allow_proxies).first
-
end
-
-
2
def to_s
-
return @ip if @calculated_ip
-
@calculated_ip = true
-
@ip = calculate_ip
-
end
-
-
2
protected
-
-
2
def ips_from(header, allow_proxies = false)
-
ips = @env[header] ? @env[header].strip.split(/[,\s]+/) : []
-
allow_proxies ? ips : ips.reject{|ip| ip =~ @middleware.proxies }
-
end
-
end
-
-
end
-
end
-
2
require 'securerandom'
-
2
require 'active_support/core_ext/string/access'
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActionDispatch
-
# Makes a unique request id available to the action_dispatch.request_id env variable (which is then accessible through
-
# ActionDispatch::Request#uuid) and sends the same id to the client via the X-Request-Id header.
-
#
-
# The unique request id is either based off the X-Request-Id header in the request, which would typically be generated
-
# by a firewall, load balancer, or the web server, or, if this header is not available, a random uuid. If the
-
# header is accepted from the outside world, we sanitize it to a max of 255 chars and alphanumeric and dashes only.
-
#
-
# The unique request id can be used to trace a request end-to-end and would typically end up being part of log files
-
# from multiple pieces of the stack.
-
2
class RequestId
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
env["action_dispatch.request_id"] = external_request_id(env) || internal_request_id
-
status, headers, body = @app.call(env)
-
-
headers["X-Request-Id"] = env["action_dispatch.request_id"]
-
[ status, headers, body ]
-
end
-
-
2
private
-
2
def external_request_id(env)
-
if request_id = env["HTTP_X_REQUEST_ID"].presence
-
request_id.gsub(/[^\w\-]/, "").first(255)
-
end
-
end
-
-
2
def internal_request_id
-
SecureRandom.hex(16)
-
end
-
end
-
end
-
2
require 'rack/utils'
-
2
require 'rack/request'
-
2
require 'rack/session/abstract/id'
-
2
require 'action_dispatch/middleware/cookies'
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActionDispatch
-
2
module Session
-
2
class SessionRestoreError < StandardError #:nodoc:
-
end
-
-
2
module DestroyableSession
-
2
def destroy
-
clear
-
options = @env[Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY] if @env
-
options ||= {}
-
@by.send(:destroy_session, @env, options[:id], options) if @by
-
options[:id] = nil
-
@loaded = false
-
end
-
end
-
-
2
::Rack::Session::Abstract::SessionHash.send :include, DestroyableSession
-
-
2
module Compatibility
-
2
def initialize(app, options = {})
-
2
options[:key] ||= '_session_id'
-
# FIXME Rack's secret is not being used
-
2
options[:secret] ||= SecureRandom.hex(30)
-
2
super
-
end
-
-
2
def generate_sid
-
sid = SecureRandom.hex(16)
-
sid.encode!('UTF-8') if sid.respond_to?(:encode!)
-
sid
-
end
-
-
2
protected
-
-
2
def initialize_sid
-
2
@default_options.delete(:sidbits)
-
2
@default_options.delete(:secure_random)
-
end
-
end
-
-
2
module StaleSessionCheck
-
2
def load_session(env)
-
stale_session_check! { super }
-
end
-
-
2
def extract_session_id(env)
-
stale_session_check! { super }
-
end
-
-
2
def stale_session_check!
-
yield
-
rescue ArgumentError => argument_error
-
if argument_error.message =~ %r{undefined class/module ([\w:]*\w)}
-
begin
-
# Note that the regexp does not allow $1 to end with a ':'
-
$1.constantize
-
rescue LoadError, NameError => const_error
-
raise ActionDispatch::Session::SessionRestoreError,
-
"Session contains objects whose class definition isn't available.\n" +
-
"Remember to require the classes for all objects kept in the session.\n" +
-
"(Original exception: #{const_error.message} [#{const_error.class}])\n"
-
end
-
retry
-
else
-
raise
-
end
-
end
-
end
-
-
2
class AbstractStore < Rack::Session::Abstract::ID
-
2
include Compatibility
-
2
include StaleSessionCheck
-
-
2
private
-
-
2
def set_cookie(env, session_id, cookie)
-
request = ActionDispatch::Request.new(env)
-
request.cookie_jar[key] = cookie
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'action_dispatch/middleware/session/abstract_store'
-
2
require 'rack/session/cookie'
-
-
2
module ActionDispatch
-
2
module Session
-
# This cookie-based session store is the Rails default. Sessions typically
-
# contain at most a user_id and flash message; both fit within the 4K cookie
-
# size limit. Cookie-based sessions are dramatically faster than the
-
# alternatives.
-
#
-
# If you have more than 4K of session data or don't want your data to be
-
# visible to the user, pick another session store.
-
#
-
# CookieOverflow is raised if you attempt to store more than 4K of data.
-
#
-
# A message digest is included with the cookie to ensure data integrity:
-
# a user cannot alter his +user_id+ without knowing the secret key
-
# included in the hash. New apps are generated with a pregenerated secret
-
# in config/environment.rb. Set your own for old apps you're upgrading.
-
#
-
# Session options:
-
#
-
# * <tt>:secret</tt>: An application-wide key string. It's important that
-
# the secret is not vulnerable to a dictionary attack. Therefore, you
-
# should choose a secret consisting of random numbers and letters and
-
# more than 30 characters.
-
#
-
# :secret => '449fe2e7daee471bffae2fd8dc02313d'
-
#
-
# * <tt>:digest</tt>: The message digest algorithm used to verify session
-
# integrity defaults to 'SHA1' but may be any digest provided by OpenSSL,
-
# such as 'MD5', 'RIPEMD160', 'SHA256', etc.
-
#
-
# To generate a secret key for an existing application, run
-
# "rake secret" and set the key in config/initializers/secret_token.rb.
-
#
-
# Note that changing digest or secret invalidates all existing sessions!
-
2
class CookieStore < Rack::Session::Cookie
-
2
include Compatibility
-
2
include StaleSessionCheck
-
-
2
private
-
-
2
def unpacked_cookie_data(env)
-
env["action_dispatch.request.unsigned_session_cookie"] ||= begin
-
stale_session_check! do
-
request = ActionDispatch::Request.new(env)
-
if data = request.cookie_jar.signed[@key]
-
data.stringify_keys!
-
end
-
data || {}
-
end
-
end
-
end
-
-
2
def set_session(env, sid, session_data, options)
-
session_data.merge!("session_id" => sid)
-
end
-
-
2
def set_cookie(env, session_id, cookie)
-
request = ActionDispatch::Request.new(env)
-
request.cookie_jar.signed[@key] = cookie
-
end
-
end
-
end
-
end
-
2
require 'action_dispatch/http/request'
-
2
require 'action_dispatch/middleware/exception_wrapper'
-
2
require 'active_support/deprecation'
-
-
2
module ActionDispatch
-
# This middleware rescues any exception returned by the application
-
# and calls an exceptions app that will wrap it in a format for the end user.
-
#
-
# The exceptions app should be passed as parameter on initialization
-
# of ShowExceptions. Everytime there is an exception, ShowExceptions will
-
# store the exception in env["action_dispatch.exception"], rewrite the
-
# PATH_INFO to the exception status code and call the rack app.
-
#
-
# If the application returns a "X-Cascade" pass response, this middleware
-
# will send an empty response as result with the correct status code.
-
# If any exception happens inside the exceptions app, this middleware
-
# catches the exceptions and returns a FAILSAFE_RESPONSE.
-
2
class ShowExceptions
-
2
FAILSAFE_RESPONSE = [500, {'Content-Type' => 'text/html'},
-
["<html><body><h1>500 Internal Server Error</h1>" <<
-
"If you are the administrator of this website, then please read this web " <<
-
"application's log file and/or the web server's log file to find out what " <<
-
"went wrong.</body></html>"]]
-
-
2
class << self
-
2
def rescue_responses
-
ActiveSupport::Deprecation.warn "ActionDispatch::ShowExceptions.rescue_responses is deprecated. " \
-
"Please configure your exceptions using a railtie or in your application config instead."
-
ExceptionWrapper.rescue_responses
-
end
-
-
2
def rescue_templates
-
ActiveSupport::Deprecation.warn "ActionDispatch::ShowExceptions.rescue_templates is deprecated. " \
-
"Please configure your exceptions using a railtie or in your application config instead."
-
ExceptionWrapper.rescue_templates
-
end
-
end
-
-
2
def initialize(app, exceptions_app = nil)
-
2
if [true, false].include?(exceptions_app)
-
ActiveSupport::Deprecation.warn "Passing consider_all_requests_local option to ActionDispatch::ShowExceptions middleware no longer works"
-
exceptions_app = nil
-
end
-
-
2
if exceptions_app.nil?
-
raise ArgumentError, "You need to pass an exceptions_app when initializing ActionDispatch::ShowExceptions. " \
-
"In case you want to render pages from a public path, you can use ActionDispatch::PublicExceptions.new('path/to/public')"
-
end
-
-
2
@app = app
-
2
@exceptions_app = exceptions_app
-
end
-
-
2
def call(env)
-
begin
-
response = @app.call(env)
-
rescue Exception => exception
-
raise exception if env['action_dispatch.show_exceptions'] == false
-
end
-
-
response || render_exception(env, exception)
-
end
-
-
2
private
-
-
# Define this method because some plugins were monkey patching it.
-
# Remove this after 3.2 is out with the other deprecations in this class.
-
2
def status_code(*)
-
end
-
-
2
def render_exception(env, exception)
-
wrapper = ExceptionWrapper.new(env, exception)
-
status = wrapper.status_code
-
env["action_dispatch.exception"] = wrapper.exception
-
env["PATH_INFO"] = "/#{status}"
-
response = @exceptions_app.call(env)
-
response[1]['X-Cascade'] == 'pass' ? pass_response(status) : response
-
rescue Exception => failsafe_error
-
$stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}"
-
FAILSAFE_RESPONSE
-
end
-
-
2
def pass_response(status)
-
[status, {"Content-Type" => "text/html; charset=#{Response.default_charset}", "Content-Length" => "0"}, []]
-
end
-
end
-
end
-
2
require "active_support/inflector/methods"
-
2
require "active_support/dependencies"
-
-
2
module ActionDispatch
-
2
class MiddlewareStack
-
2
class Middleware
-
2
attr_reader :args, :block, :name, :classcache
-
-
2
def initialize(klass_or_name, *args, &block)
-
42
@klass = nil
-
-
42
if klass_or_name.respond_to?(:name)
-
38
@klass = klass_or_name
-
38
@name = @klass.name
-
else
-
4
@name = klass_or_name.to_s
-
end
-
-
42
@classcache = ActiveSupport::Dependencies::Reference
-
42
@args, @block = args, block
-
end
-
-
2
def klass
-
42
@klass || classcache[@name]
-
end
-
-
2
def ==(middleware)
-
46
case middleware
-
when Middleware
-
klass == middleware.klass
-
when Class
-
klass == middleware
-
else
-
46
normalize(@name) == normalize(middleware)
-
end
-
end
-
-
2
def inspect
-
klass.to_s
-
end
-
-
2
def build(app)
-
42
klass.new(app, *args, &block)
-
end
-
-
2
private
-
-
2
def normalize(object)
-
92
object.to_s.strip.sub(/^::/, '')
-
end
-
end
-
-
2
include Enumerable
-
-
2
attr_accessor :middlewares
-
-
2
def initialize(*args)
-
4
@middlewares = []
-
4
yield(self) if block_given?
-
end
-
-
2
def each
-
@middlewares.each { |x| yield x }
-
end
-
-
2
def size
-
middlewares.size
-
end
-
-
2
def last
-
middlewares.last
-
end
-
-
2
def [](i)
-
middlewares[i]
-
end
-
-
2
def initialize_copy(other)
-
31
self.middlewares = other.middlewares.dup
-
end
-
-
2
def insert(index, *args, &block)
-
6
index = assert_index(index, :before)
-
6
middleware = self.class::Middleware.new(*args, &block)
-
6
middlewares.insert(index, middleware)
-
end
-
-
2
alias_method :insert_before, :insert
-
-
2
def insert_after(index, *args, &block)
-
4
index = assert_index(index, :after)
-
4
insert(index + 1, *args, &block)
-
end
-
-
2
def swap(target, *args, &block)
-
index = assert_index(target, :before)
-
insert(index, *args, &block)
-
middlewares.delete_at(index + 1)
-
end
-
-
2
def delete(target)
-
middlewares.delete target
-
end
-
-
2
def use(*args, &block)
-
36
middleware = self.class::Middleware.new(*args, &block)
-
36
middlewares.push(middleware)
-
end
-
-
2
def build(app = nil, &block)
-
2
app ||= block
-
2
raise "MiddlewareStack#build requires an app" unless app
-
44
middlewares.reverse.inject(app) { |a, e| e.build(a) }
-
end
-
-
2
protected
-
-
2
def assert_index(index, where)
-
10
i = index.is_a?(Integer) ? index : middlewares.index(index)
-
10
raise "No such middleware to insert #{where}: #{index.inspect}" unless i
-
10
i
-
end
-
end
-
end
-
2
require 'rack/utils'
-
-
2
module ActionDispatch
-
2
class FileHandler
-
2
def initialize(root, cache_control)
-
2
@root = root.chomp('/')
-
2
@compiled_root = /^#{Regexp.escape(root)}/
-
2
headers = cache_control && { 'Cache-Control' => cache_control }
-
2
@file_server = ::Rack::File.new(@root, headers)
-
end
-
-
2
def match?(path)
-
path = path.dup
-
-
full_path = path.empty? ? @root : File.join(@root, escape_glob_chars(unescape_path(path)))
-
paths = "#{full_path}#{ext}"
-
-
matches = Dir[paths]
-
match = matches.detect { |m| File.file?(m) }
-
if match
-
match.sub!(@compiled_root, '')
-
::Rack::Utils.escape(match)
-
end
-
end
-
-
2
def call(env)
-
@file_server.call(env)
-
end
-
-
2
def ext
-
@ext ||= begin
-
ext = ::ActionController::Base.page_cache_extension
-
"{,#{ext},/index#{ext}}"
-
end
-
end
-
-
2
def unescape_path(path)
-
URI.parser.unescape(path)
-
end
-
-
2
def escape_glob_chars(path)
-
path.force_encoding('binary') if path.respond_to? :force_encoding
-
path.gsub(/[*?{}\[\]]/, "\\\\\\&")
-
end
-
end
-
-
2
class Static
-
2
def initialize(app, path, cache_control=nil)
-
2
@app = app
-
2
@file_handler = FileHandler.new(path, cache_control)
-
end
-
-
2
def call(env)
-
case env['REQUEST_METHOD']
-
when 'GET', 'HEAD'
-
path = env['PATH_INFO'].chomp('/')
-
if match = @file_handler.match?(path)
-
env["PATH_INFO"] = match
-
return @file_handler.call(env)
-
end
-
end
-
-
@app.call(env)
-
end
-
end
-
end
-
2
require "action_dispatch"
-
-
2
module ActionDispatch
-
2
class Railtie < Rails::Railtie
-
2
config.action_dispatch = ActiveSupport::OrderedOptions.new
-
2
config.action_dispatch.x_sendfile_header = nil
-
2
config.action_dispatch.ip_spoofing_check = true
-
2
config.action_dispatch.show_exceptions = true
-
2
config.action_dispatch.best_standards_support = true
-
2
config.action_dispatch.tld_length = 1
-
2
config.action_dispatch.ignore_accept_header = false
-
2
config.action_dispatch.rescue_templates = { }
-
2
config.action_dispatch.rescue_responses = { }
-
2
config.action_dispatch.default_charset = nil
-
-
2
config.action_dispatch.rack_cache = {
-
:metastore => "rails:/",
-
:entitystore => "rails:/",
-
:verbose => false
-
}
-
-
2
initializer "action_dispatch.configure" do |app|
-
2
ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length
-
2
ActionDispatch::Request.ignore_accept_header = app.config.action_dispatch.ignore_accept_header
-
2
ActionDispatch::Response.default_charset = app.config.action_dispatch.default_charset || app.config.encoding
-
-
2
ActionDispatch::ExceptionWrapper.rescue_responses.merge!(config.action_dispatch.rescue_responses)
-
2
ActionDispatch::ExceptionWrapper.rescue_templates.merge!(config.action_dispatch.rescue_templates)
-
-
2
config.action_dispatch.always_write_cookie = Rails.env.development? if config.action_dispatch.always_write_cookie.nil?
-
2
ActionDispatch::Cookies::CookieJar.always_write_cookie = config.action_dispatch.always_write_cookie
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/to_param'
-
2
require 'active_support/core_ext/regexp'
-
-
2
module ActionDispatch
-
# The routing module provides URL rewriting in native Ruby. It's a way to
-
# redirect incoming requests to controllers and actions. This replaces
-
# mod_rewrite rules. Best of all, Rails' \Routing works with any web server.
-
# Routes are defined in <tt>config/routes.rb</tt>.
-
#
-
# Think of creating routes as drawing a map for your requests. The map tells
-
# them where to go based on some predefined pattern:
-
#
-
# AppName::Application.routes.draw do
-
# Pattern 1 tells some request to go to one place
-
# Pattern 2 tell them to go to another
-
# ...
-
# end
-
#
-
# The following symbols are special:
-
#
-
# :controller maps to your controller name
-
# :action maps to an action with your controllers
-
#
-
# Other names simply map to a parameter as in the case of <tt>:id</tt>.
-
#
-
# == Resources
-
#
-
# Resource routing allows you to quickly declare all of the common routes
-
# for a given resourceful controller. Instead of declaring separate routes
-
# for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+
-
# actions, a resourceful route declares them in a single line of code:
-
#
-
# resources :photos
-
#
-
# Sometimes, you have a resource that clients always look up without
-
# referencing an ID. A common example, /profile always shows the profile of
-
# the currently logged in user. In this case, you can use a singular resource
-
# to map /profile (rather than /profile/:id) to the show action.
-
#
-
# resource :profile
-
#
-
# It's common to have resources that are logically children of other
-
# resources:
-
#
-
# resources :magazines do
-
# resources :ads
-
# end
-
#
-
# You may wish to organize groups of controllers under a namespace. Most
-
# commonly, you might group a number of administrative controllers under
-
# an +admin+ namespace. You would place these controllers under the
-
# <tt>app/controllers/admin</tt> directory, and you can group them together
-
# in your router:
-
#
-
# namespace "admin" do
-
# resources :posts, :comments
-
# end
-
#
-
# Alternately, you can add prefixes to your path without using a separate
-
# directory by using +scope+. +scope+ takes additional options which
-
# apply to all enclosed routes.
-
#
-
# scope :path => "/cpanel", :as => 'admin' do
-
# resources :posts, :comments
-
# end
-
#
-
# For more, see <tt>Routing::Mapper::Resources#resources</tt>,
-
# <tt>Routing::Mapper::Scoping#namespace</tt>, and
-
# <tt>Routing::Mapper::Scoping#scope</tt>.
-
#
-
# == Named routes
-
#
-
# Routes can be named by passing an <tt>:as</tt> option,
-
# allowing for easy reference within your source as +name_of_route_url+
-
# for the full URL and +name_of_route_path+ for the URI path.
-
#
-
# Example:
-
#
-
# # In routes.rb
-
# match '/login' => 'accounts#login', :as => 'login'
-
#
-
# # With render, redirect_to, tests, etc.
-
# redirect_to login_url
-
#
-
# Arguments can be passed as well.
-
#
-
# redirect_to show_item_path(:id => 25)
-
#
-
# Use <tt>root</tt> as a shorthand to name a route for the root path "/".
-
#
-
# # In routes.rb
-
# root :to => 'blogs#index'
-
#
-
# # would recognize http://www.example.com/ as
-
# params = { :controller => 'blogs', :action => 'index' }
-
#
-
# # and provide these named routes
-
# root_url # => 'http://www.example.com/'
-
# root_path # => '/'
-
#
-
# Note: when using +controller+, the route is simply named after the
-
# method you call on the block parameter rather than map.
-
#
-
# # In routes.rb
-
# controller :blog do
-
# match 'blog/show' => :list
-
# match 'blog/delete' => :delete
-
# match 'blog/edit/:id' => :edit
-
# end
-
#
-
# # provides named routes for show, delete, and edit
-
# link_to @article.title, show_path(:id => @article.id)
-
#
-
# == Pretty URLs
-
#
-
# Routes can generate pretty URLs. For example:
-
#
-
# match '/articles/:year/:month/:day' => 'articles#find_by_id', :constraints => {
-
# :year => /\d{4}/,
-
# :month => /\d{1,2}/,
-
# :day => /\d{1,2}/
-
# }
-
#
-
# Using the route above, the URL "http://localhost:3000/articles/2005/11/06"
-
# maps to
-
#
-
# params = {:year => '2005', :month => '11', :day => '06'}
-
#
-
# == Regular Expressions and parameters
-
# You can specify a regular expression to define a format for a parameter.
-
#
-
# controller 'geocode' do
-
# match 'geocode/:postalcode' => :show, :constraints => {
-
# :postalcode => /\d{5}(-\d{4})?/
-
# }
-
#
-
# Constraints can include the 'ignorecase' and 'extended syntax' regular
-
# expression modifiers:
-
#
-
# controller 'geocode' do
-
# match 'geocode/:postalcode' => :show, :constraints => {
-
# :postalcode => /hx\d\d\s\d[a-z]{2}/i
-
# }
-
# end
-
#
-
# controller 'geocode' do
-
# match 'geocode/:postalcode' => :show, :constraints => {
-
# :postalcode => /# Postcode format
-
# \d{5} #Prefix
-
# (-\d{4})? #Suffix
-
# /x
-
# }
-
# end
-
#
-
# Using the multiline match modifier will raise an +ArgumentError+.
-
# Encoding regular expression modifiers are silently ignored. The
-
# match will always use the default encoding or ASCII.
-
#
-
# == Default route
-
#
-
# Consider the following route, which you will find commented out at the
-
# bottom of your generated <tt>config/routes.rb</tt>:
-
#
-
# match ':controller(/:action(/:id))(.:format)'
-
#
-
# This route states that it expects requests to consist of a
-
# <tt>:controller</tt> followed optionally by an <tt>:action</tt> that in
-
# turn is followed optionally by an <tt>:id</tt>, which in turn is followed
-
# optionally by a <tt>:format</tt>.
-
#
-
# Suppose you get an incoming request for <tt>/blog/edit/22</tt>, you'll end
-
# up with:
-
#
-
# params = { :controller => 'blog',
-
# :action => 'edit',
-
# :id => '22'
-
# }
-
#
-
# By not relying on default routes, you improve the security of your
-
# application since not all controller actions, which includes actions you
-
# might add at a later time, are exposed by default.
-
#
-
# == HTTP Methods
-
#
-
# Using the <tt>:via</tt> option when specifying a route allows you to restrict it to a specific HTTP method.
-
# Possible values are <tt>:post</tt>, <tt>:get</tt>, <tt>:put</tt>, <tt>:delete</tt> and <tt>:any</tt>.
-
# If your route needs to respond to more than one method you can use an array, e.g. <tt>[ :get, :post ]</tt>.
-
# The default value is <tt>:any</tt> which means that the route will respond to any of the HTTP methods.
-
#
-
# Examples:
-
#
-
# match 'post/:id' => 'posts#show', :via => :get
-
# match 'post/:id' => "posts#create_comment', :via => :post
-
#
-
# Now, if you POST to <tt>/posts/:id</tt>, it will route to the <tt>create_comment</tt> action. A GET on the same
-
# URL will route to the <tt>show</tt> action.
-
#
-
# === HTTP helper methods
-
#
-
# An alternative method of specifying which HTTP method a route should respond to is to use the helper
-
# methods <tt>get</tt>, <tt>post</tt>, <tt>put</tt> and <tt>delete</tt>.
-
#
-
# Examples:
-
#
-
# get 'post/:id' => 'posts#show'
-
# post 'post/:id' => "posts#create_comment'
-
#
-
# This syntax is less verbose and the intention is more apparent to someone else reading your code,
-
# however if your route needs to respond to more than one HTTP method (or all methods) then using the
-
# <tt>:via</tt> option on <tt>match</tt> is preferable.
-
#
-
# == External redirects
-
#
-
# You can redirect any path to another path using the redirect helper in your router:
-
#
-
# match "/stories" => redirect("/posts")
-
#
-
# == Routing to Rack Applications
-
#
-
# Instead of a String, like <tt>posts#index</tt>, which corresponds to the
-
# index action in the PostsController, you can specify any Rack application
-
# as the endpoint for a matcher:
-
#
-
# match "/application.js" => Sprockets
-
#
-
# == Reloading routes
-
#
-
# You can reload routes if you feel you must:
-
#
-
# Rails.application.reload_routes!
-
#
-
# This will clear all named routes and reload routes.rb if the file has been modified from
-
# last load. To absolutely force reloading, use <tt>reload!</tt>.
-
#
-
# == Testing Routes
-
#
-
# The two main methods for testing your routes:
-
#
-
# === +assert_routing+
-
#
-
# def test_movie_route_properly_splits
-
# opts = {:controller => "plugin", :action => "checkout", :id => "2"}
-
# assert_routing "plugin/checkout/2", opts
-
# end
-
#
-
# +assert_routing+ lets you test whether or not the route properly resolves into options.
-
#
-
# === +assert_recognizes+
-
#
-
# def test_route_has_options
-
# opts = {:controller => "plugin", :action => "show", :id => "12"}
-
# assert_recognizes opts, "/plugins/show/12"
-
# end
-
#
-
# Note the subtle difference between the two: +assert_routing+ tests that
-
# a URL fits options while +assert_recognizes+ tests that a URL
-
# breaks into parameters properly.
-
#
-
# In tests you can simply pass the URL or named route to +get+ or +post+.
-
#
-
# def send_to_jail
-
# get '/jail'
-
# assert_response :success
-
# assert_template "jail/front"
-
# end
-
#
-
# def goes_to_login
-
# get login_url
-
# #...
-
# end
-
#
-
# == View a list of all your routes
-
#
-
# rake routes
-
#
-
# Target specific controllers by prefixing the command with <tt>CONTROLLER=x</tt>.
-
#
-
2
module Routing
-
2
autoload :Mapper, 'action_dispatch/routing/mapper'
-
2
autoload :RouteSet, 'action_dispatch/routing/route_set'
-
2
autoload :RoutesProxy, 'action_dispatch/routing/routes_proxy'
-
2
autoload :UrlFor, 'action_dispatch/routing/url_for'
-
2
autoload :PolymorphicRoutes, 'action_dispatch/routing/polymorphic_routes'
-
-
2
SEPARATORS = %w( / . ? ) #:nodoc:
-
2
HTTP_METHODS = [:get, :head, :post, :put, :delete, :options] #:nodoc:
-
-
# A helper module to hold URL related helpers.
-
2
module Helpers #:nodoc:
-
2
include PolymorphicRoutes
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/object/inclusion'
-
2
require 'active_support/core_ext/enumerable'
-
2
require 'active_support/inflector'
-
2
require 'action_dispatch/routing/redirection'
-
-
2
module ActionDispatch
-
2
module Routing
-
2
class Mapper
-
2
class Constraints #:nodoc:
-
2
def self.new(app, constraints, request = Rack::Request)
-
164
if constraints.any?
-
super(app, constraints, request)
-
else
-
164
app
-
end
-
end
-
-
2
attr_reader :app, :constraints
-
-
2
def initialize(app, constraints, request)
-
@app, @constraints, @request = app, constraints, request
-
end
-
-
2
def matches?(env)
-
req = @request.new(env)
-
-
@constraints.each { |constraint|
-
if constraint.respond_to?(:matches?) && !constraint.matches?(req)
-
return false
-
elsif constraint.respond_to?(:call) && !constraint.call(*constraint_args(constraint, req))
-
return false
-
end
-
}
-
-
return true
-
ensure
-
req.reset_parameters
-
end
-
-
2
def call(env)
-
matches?(env) ? @app.call(env) : [ 404, {'X-Cascade' => 'pass'}, [] ]
-
end
-
-
2
private
-
2
def constraint_args(constraint, request)
-
constraint.arity == 1 ? [request] : [request.symbolized_path_parameters, request]
-
end
-
end
-
-
2
class Mapping #:nodoc:
-
2
IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix]
-
2
ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
-
2
WILDCARD_PATH = %r{\*([^/\)]+)\)?$}
-
-
2
def initialize(set, scope, path, options)
-
164
@set, @scope = set, scope
-
164
@options = (@scope[:options] || {}).merge(options)
-
164
@path = normalize_path(path)
-
164
normalize_options!
-
end
-
-
2
def to_route
-
164
[ app, conditions, requirements, defaults, @options[:as], @options[:anchor] ]
-
end
-
-
2
private
-
-
2
def normalize_options!
-
164
@options.merge!(default_controller_and_action)
-
-
164
requirements.each do |name, requirement|
-
# segment_keys.include?(k.to_s) || k == :controller
-
next unless Regexp === requirement && !constraints[name]
-
-
if requirement.source =~ ANCHOR_CHARACTERS_REGEX
-
raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
-
end
-
if requirement.multiline?
-
raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
-
end
-
end
-
end
-
-
# match "account/overview"
-
2
def using_match_shorthand?(path, options)
-
path && (options[:to] || options[:action]).nil? && path =~ SHORTHAND_REGEX
-
end
-
-
2
def normalize_path(path)
-
164
raise ArgumentError, "path is required" if path.blank?
-
164
path = Mapper.normalize_path(path)
-
-
164
if path.match(':controller')
-
raise ArgumentError, ":controller segment is not allowed within a namespace block" if @scope[:module]
-
-
# Add a default constraint for :controller path segments that matches namespaced
-
# controllers with default routes like :controller/:action/:id(.:format), e.g:
-
# GET /admin/products/show/1
-
# => { :controller => 'admin/products', :action => 'show', :id => '1' }
-
@options[:controller] ||= /.+?/
-
end
-
-
# Add a constraint for wildcard route to make it non-greedy and match the
-
# optional format part of the route by default
-
164
if path.match(WILDCARD_PATH) && @options[:format] != false
-
@options[$1.to_sym] ||= /.+?/
-
end
-
-
164
if @options[:format] == false
-
2
@options.delete(:format)
-
2
path
-
162
elsif path.include?(":format") || path.end_with?('/')
-
2
path
-
160
elsif @options[:format] == true
-
"#{path}.:format"
-
else
-
160
"#{path}(.:format)"
-
end
-
end
-
-
2
def app
-
164
Constraints.new(
-
to.respond_to?(:call) ? to : Routing::RouteSet::Dispatcher.new(:defaults => defaults),
-
blocks,
-
@set.request_class
-
)
-
end
-
-
2
def conditions
-
164
{ :path_info => @path }.merge(constraints).merge(request_method_condition)
-
end
-
-
2
def requirements
-
164
@requirements ||= (@options[:constraints].is_a?(Hash) ? @options[:constraints] : {}).tap do |requirements|
-
164
requirements.reverse_merge!(@scope[:constraints]) if @scope[:constraints]
-
990
@options.each { |k, v| requirements[k] = v if v.is_a?(Regexp) }
-
492
end
-
end
-
-
2
def defaults
-
164
@defaults ||= (@options[:defaults] || {}).tap do |defaults|
-
164
defaults.reverse_merge!(@scope[:defaults]) if @scope[:defaults]
-
990
@options.each { |k, v| defaults[k] = v unless v.is_a?(Regexp) || IGNORE_OPTIONS.include?(k.to_sym) }
-
326
end
-
end
-
-
2
def default_controller_and_action
-
164
if to.respond_to?(:call)
-
2
{ }
-
else
-
162
if to.is_a?(String)
-
22
controller, action = to.split('#')
-
elsif to.is_a?(Symbol)
-
action = to.to_s
-
end
-
-
162
controller ||= default_controller
-
162
action ||= default_action
-
-
162
unless controller.is_a?(Regexp)
-
162
controller = [@scope[:module], controller].compact.join("/").presence
-
end
-
-
162
if controller.is_a?(String) && controller =~ %r{\A/}
-
raise ArgumentError, "controller name should not start with a slash"
-
end
-
-
162
controller = controller.to_s unless controller.is_a?(Regexp)
-
162
action = action.to_s unless action.is_a?(Regexp)
-
-
162
if controller.blank? && segment_keys.exclude?("controller")
-
raise ArgumentError, "missing :controller"
-
end
-
-
162
if action.blank? && segment_keys.exclude?("action")
-
raise ArgumentError, "missing :action"
-
end
-
-
162
hash = {}
-
162
hash[:controller] = controller unless controller.blank?
-
162
hash[:action] = action unless action.blank?
-
162
hash
-
end
-
end
-
-
2
def blocks
-
164
constraints = @options[:constraints]
-
164
if constraints.present? && !constraints.is_a?(Hash)
-
[constraints]
-
else
-
164
@scope[:blocks] || []
-
end
-
end
-
-
2
def constraints
-
164
@constraints ||= requirements.reject { |k, v| segment_keys.include?(k.to_s) || k == :controller }
-
end
-
-
2
def request_method_condition
-
164
if via = @options[:via]
-
304
list = Array(via).map { |m| m.to_s.dasherize.upcase }
-
152
{ :request_method => list }
-
else
-
12
{ }
-
end
-
end
-
-
2
def segment_keys
-
@segment_keys ||= Journey::Path::Pattern.new(
-
Journey::Router::Strexp.compile(@path, requirements, SEPARATORS)
-
).names
-
end
-
-
2
def to
-
654
@options[:to]
-
end
-
-
2
def default_controller
-
140
@options[:controller] || @scope[:controller]
-
end
-
-
2
def default_action
-
140
@options[:action] || @scope[:action]
-
end
-
end
-
-
# Invokes Rack::Mount::Utils.normalize path and ensure that
-
# (:locale) becomes (/:locale) instead of /(:locale). Except
-
# for root cases, where the latter is the correct one.
-
2
def self.normalize_path(path)
-
282
path = Journey::Router::Utils.normalize_path(path)
-
282
path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^)]+\)$}
-
282
path
-
end
-
-
2
def self.normalize_name(name)
-
52
normalize_path(name)[1..-1].gsub("/", "_")
-
end
-
-
2
module Base
-
# You can specify what Rails should route "/" to with the root method:
-
#
-
# root :to => 'pages#main'
-
#
-
# For options, see +match+, as +root+ uses it internally.
-
#
-
# You should put the root route at the top of <tt>config/routes.rb</tt>,
-
# because this means it will be matched first. As this is the most popular route
-
# of most Rails applications, this is beneficial.
-
2
def root(options = {})
-
2
match '/', { :as => :root }.merge(options)
-
end
-
-
# Matches a url pattern to one or more routes. Any symbols in a pattern
-
# are interpreted as url query parameters and thus available as +params+
-
# in an action:
-
#
-
# # sets :controller, :action and :id in params
-
# match ':controller/:action/:id'
-
#
-
# Two of these symbols are special, +:controller+ maps to the controller
-
# and +:action+ to the controller's action. A pattern can also map
-
# wildcard segments (globs) to params:
-
#
-
# match 'songs/*category/:title' => 'songs#show'
-
#
-
# # 'songs/rock/classic/stairway-to-heaven' sets
-
# # params[:category] = 'rock/classic'
-
# # params[:title] = 'stairway-to-heaven'
-
#
-
# When a pattern points to an internal route, the route's +:action+ and
-
# +:controller+ should be set in options or hash shorthand. Examples:
-
#
-
# match 'photos/:id' => 'photos#show'
-
# match 'photos/:id', :to => 'photos#show'
-
# match 'photos/:id', :controller => 'photos', :action => 'show'
-
#
-
# A pattern can also point to a +Rack+ endpoint i.e. anything that
-
# responds to +call+:
-
#
-
# match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon"] }
-
# match 'photos/:id' => PhotoRackApp
-
# # Yes, controller actions are just rack endpoints
-
# match 'photos/:id' => PhotosController.action(:show)
-
#
-
# === Options
-
#
-
# Any options not seen here are passed on as params with the url.
-
#
-
# [:controller]
-
# The route's controller.
-
#
-
# [:action]
-
# The route's action.
-
#
-
# [:path]
-
# The path prefix for the routes.
-
#
-
# [:module]
-
# The namespace for :controller.
-
#
-
# match 'path' => 'c#a', :module => 'sekret', :controller => 'posts'
-
# #=> Sekret::PostsController
-
#
-
# See <tt>Scoping#namespace</tt> for its scope equivalent.
-
#
-
# [:as]
-
# The name used to generate routing helpers.
-
#
-
# [:via]
-
# Allowed HTTP verb(s) for route.
-
#
-
# match 'path' => 'c#a', :via => :get
-
# match 'path' => 'c#a', :via => [:get, :post]
-
#
-
# [:to]
-
# Points to a +Rack+ endpoint. Can be an object that responds to
-
# +call+ or a string representing a controller's action.
-
#
-
# match 'path', :to => 'controller#action'
-
# match 'path', :to => lambda { |env| [200, {}, "Success!"] }
-
# match 'path', :to => RackApp
-
#
-
# [:on]
-
# Shorthand for wrapping routes in a specific RESTful context. Valid
-
# values are +:member+, +:collection+, and +:new+. Only use within
-
# <tt>resource(s)</tt> block. For example:
-
#
-
# resource :bar do
-
# match 'foo' => 'c#a', :on => :member, :via => [:get, :post]
-
# end
-
#
-
# Is equivalent to:
-
#
-
# resource :bar do
-
# member do
-
# match 'foo' => 'c#a', :via => [:get, :post]
-
# end
-
# end
-
#
-
# [:constraints]
-
# Constrains parameters with a hash of regular expressions or an
-
# object that responds to <tt>matches?</tt>
-
#
-
# match 'path/:id', :constraints => { :id => /[A-Z]\d{5}/ }
-
#
-
# class Blacklist
-
# def matches?(request) request.remote_ip == '1.2.3.4' end
-
# end
-
# match 'path' => 'c#a', :constraints => Blacklist.new
-
#
-
# See <tt>Scoping#constraints</tt> for more examples with its scope
-
# equivalent.
-
#
-
# [:defaults]
-
# Sets defaults for parameters
-
#
-
# # Sets params[:format] to 'jpg' by default
-
# match 'path' => 'c#a', :defaults => { :format => 'jpg' }
-
#
-
# See <tt>Scoping#defaults</tt> for its scope equivalent.
-
#
-
# [:anchor]
-
# Boolean to anchor a <tt>match</tt> pattern. Default is true. When set to
-
# false, the pattern matches any request prefixed with the given path.
-
#
-
# # Matches any request starting with 'path'
-
# match 'path' => 'c#a', :anchor => false
-
2
def match(path, options=nil)
-
end
-
-
# Mount a Rack-based application to be used within the application.
-
#
-
# mount SomeRackApp, :at => "some_route"
-
#
-
# Alternatively:
-
#
-
# mount(SomeRackApp => "some_route")
-
#
-
# For options, see +match+, as +mount+ uses it internally.
-
#
-
# All mounted applications come with routing helpers to access them.
-
# These are named after the class specified, so for the above example
-
# the helper is either +some_rack_app_path+ or +some_rack_app_url+.
-
# To customize this helper's name, use the +:as+ option:
-
#
-
# mount(SomeRackApp => "some_route", :as => "exciting")
-
#
-
# This will generate the +exciting_path+ and +exciting_url+ helpers
-
# which can be used to navigate to this mounted app.
-
2
def mount(app, options = nil)
-
2
if options
-
path = options.delete(:at)
-
else
-
2
options = app
-
4
app, path = options.find { |k, v| k.respond_to?(:call) }
-
2
options.delete(app) if app
-
end
-
-
2
raise "A rack application must be specified" unless path
-
-
2
options[:as] ||= app_name(app)
-
-
2
match(path, options.merge(:to => app, :anchor => false, :format => false))
-
-
2
define_generate_prefix(app, options[:as])
-
2
self
-
end
-
-
2
def default_url_options=(options)
-
@set.default_url_options = options
-
end
-
2
alias_method :default_url_options, :default_url_options=
-
-
2
def with_default_scope(scope, &block)
-
scope(scope) do
-
instance_exec(&block)
-
end
-
end
-
-
2
private
-
2
def app_name(app)
-
2
return unless app.respond_to?(:routes)
-
-
if app.respond_to?(:railtie_name)
-
app.railtie_name
-
else
-
class_name = app.class.is_a?(Class) ? app.name : app.class.name
-
ActiveSupport::Inflector.underscore(class_name).gsub("/", "_")
-
end
-
end
-
-
2
def define_generate_prefix(app, name)
-
2
return unless app.respond_to?(:routes) && app.routes.respond_to?(:define_mounted_helper)
-
-
_route = @set.named_routes.routes[name.to_sym]
-
_routes = @set
-
app.routes.define_mounted_helper(name)
-
app.routes.class_eval do
-
define_method :_generate_prefix do |options|
-
prefix_options = options.slice(*_route.segment_keys)
-
# we must actually delete prefix segment keys to avoid passing them to next url_for
-
_route.segment_keys.each { |k| options.delete(k) }
-
prefix = _routes.url_helpers.send("#{name}_path", prefix_options)
-
prefix = prefix.gsub(%r{/\z}, '')
-
prefix
-
end
-
end
-
end
-
end
-
-
2
module HttpHelpers
-
# Define a route that only recognizes HTTP GET.
-
# For supported arguments, see <tt>Base#match</tt>.
-
#
-
# Example:
-
#
-
# get 'bacon', :to => 'food#bacon'
-
2
def get(*args, &block)
-
90
map_method(:get, *args, &block)
-
end
-
-
# Define a route that only recognizes HTTP POST.
-
# For supported arguments, see <tt>Base#match</tt>.
-
#
-
# Example:
-
#
-
# post 'bacon', :to => 'food#bacon'
-
2
def post(*args, &block)
-
24
map_method(:post, *args, &block)
-
end
-
-
# Define a route that only recognizes HTTP PUT.
-
# For supported arguments, see <tt>Base#match</tt>.
-
#
-
# Example:
-
#
-
# put 'bacon', :to => 'food#bacon'
-
2
def put(*args, &block)
-
20
map_method(:put, *args, &block)
-
end
-
-
# Define a route that only recognizes HTTP PUT.
-
# For supported arguments, see <tt>Base#match</tt>.
-
#
-
# Example:
-
#
-
# delete 'broccoli', :to => 'food#broccoli'
-
2
def delete(*args, &block)
-
18
map_method(:delete, *args, &block)
-
end
-
-
2
private
-
2
def map_method(method, *args, &block)
-
152
options = args.extract_options!
-
152
options[:via] = method
-
152
args.push(options)
-
152
match(*args, &block)
-
152
self
-
end
-
end
-
-
# You may wish to organize groups of controllers under a namespace.
-
# Most commonly, you might group a number of administrative controllers
-
# under an +admin+ namespace. You would place these controllers under
-
# the <tt>app/controllers/admin</tt> directory, and you can group them
-
# together in your router:
-
#
-
# namespace "admin" do
-
# resources :posts, :comments
-
# end
-
#
-
# This will create a number of routes for each of the posts and comments
-
# controller. For <tt>Admin::PostsController</tt>, Rails will create:
-
#
-
# GET /admin/posts
-
# GET /admin/posts/new
-
# POST /admin/posts
-
# GET /admin/posts/1
-
# GET /admin/posts/1/edit
-
# PUT /admin/posts/1
-
# DELETE /admin/posts/1
-
#
-
# If you want to route /posts (without the prefix /admin) to
-
# <tt>Admin::PostsController</tt>, you could use
-
#
-
# scope :module => "admin" do
-
# resources :posts
-
# end
-
#
-
# or, for a single case
-
#
-
# resources :posts, :module => "admin"
-
#
-
# If you want to route /admin/posts to +PostsController+
-
# (without the Admin:: module prefix), you could use
-
#
-
# scope "/admin" do
-
# resources :posts
-
# end
-
#
-
# or, for a single case
-
#
-
# resources :posts, :path => "/admin/posts"
-
#
-
# In each of these cases, the named routes remain the same as if you did
-
# not use scope. In the last case, the following paths map to
-
# +PostsController+:
-
#
-
# GET /admin/posts
-
# GET /admin/posts/new
-
# POST /admin/posts
-
# GET /admin/posts/1
-
# GET /admin/posts/1/edit
-
# PUT /admin/posts/1
-
# DELETE /admin/posts/1
-
2
module Scoping
-
# Scopes a set of routes to the given default options.
-
#
-
# Take the following route definition as an example:
-
#
-
# scope :path => ":account_id", :as => "account" do
-
# resources :projects
-
# end
-
#
-
# This generates helpers such as +account_projects_path+, just like +resources+ does.
-
# The difference here being that the routes generated are like /:account_id/projects,
-
# rather than /accounts/:account_id/projects.
-
#
-
# === Options
-
#
-
# Takes same options as <tt>Base#match</tt> and <tt>Resources#resources</tt>.
-
#
-
# === Examples
-
#
-
# # route /posts (without the prefix /admin) to <tt>Admin::PostsController</tt>
-
# scope :module => "admin" do
-
# resources :posts
-
# end
-
#
-
# # prefix the posts resource's requests with '/admin'
-
# scope :path => "/admin" do
-
# resources :posts
-
# end
-
#
-
# # prefix the routing helper name: +sekret_posts_path+ instead of +posts_path+
-
# scope :as => "sekret" do
-
# resources :posts
-
# end
-
2
def scope(*args)
-
86
options = args.extract_options!
-
86
options = options.dup
-
-
86
options[:path] = args.first if args.first.is_a?(String)
-
86
recover = {}
-
-
86
options[:constraints] ||= {}
-
86
unless options[:constraints].is_a?(Hash)
-
block, options[:constraints] = options[:constraints], {}
-
end
-
-
86
scope_options.each do |option|
-
1118
if value = options.delete(option)
-
172
recover[option] = @scope[option]
-
172
@scope[option] = send("merge_#{option}_scope", @scope[option], value)
-
end
-
end
-
-
86
recover[:block] = @scope[:blocks]
-
86
@scope[:blocks] = merge_blocks_scope(@scope[:blocks], block)
-
-
86
recover[:options] = @scope[:options]
-
86
@scope[:options] = merge_options_scope(@scope[:options], options)
-
-
86
yield
-
86
self
-
ensure
-
86
scope_options.each do |option|
-
1118
@scope[option] = recover[option] if recover.has_key?(option)
-
end
-
-
86
@scope[:options] = recover[:options]
-
86
@scope[:blocks] = recover[:block]
-
end
-
-
# Scopes routes to a specific controller
-
#
-
# Example:
-
# controller "food" do
-
# match "bacon", :action => "bacon"
-
# end
-
2
def controller(controller, options={})
-
options[:controller] = controller
-
scope(options) { yield }
-
end
-
-
# Scopes routes to a specific namespace. For example:
-
#
-
# namespace :admin do
-
# resources :posts
-
# end
-
#
-
# This generates the following routes:
-
#
-
# admin_posts GET /admin/posts(.:format) admin/posts#index
-
# admin_posts POST /admin/posts(.:format) admin/posts#create
-
# new_admin_post GET /admin/posts/new(.:format) admin/posts#new
-
# edit_admin_post GET /admin/posts/:id/edit(.:format) admin/posts#edit
-
# admin_post GET /admin/posts/:id(.:format) admin/posts#show
-
# admin_post PUT /admin/posts/:id(.:format) admin/posts#update
-
# admin_post DELETE /admin/posts/:id(.:format) admin/posts#destroy
-
#
-
# === Options
-
#
-
# The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+
-
# options all default to the name of the namespace.
-
#
-
# For options, see <tt>Base#match</tt>. For +:shallow_path+ option, see
-
# <tt>Resources#resources</tt>.
-
#
-
# === Examples
-
#
-
# # accessible through /sekret/posts rather than /admin/posts
-
# namespace :admin, :path => "sekret" do
-
# resources :posts
-
# end
-
#
-
# # maps to <tt>Sekret::PostsController</tt> rather than <tt>Admin::PostsController</tt>
-
# namespace :admin, :module => "sekret" do
-
# resources :posts
-
# end
-
#
-
# # generates +sekret_posts_path+ rather than +admin_posts_path+
-
# namespace :admin, :as => "sekret" do
-
# resources :posts
-
# end
-
2
def namespace(path, options = {})
-
path = path.to_s
-
options = { :path => path, :as => path, :module => path,
-
:shallow_path => path, :shallow_prefix => path }.merge!(options)
-
scope(options) { yield }
-
end
-
-
# === Parameter Restriction
-
# Allows you to constrain the nested routes based on a set of rules.
-
# For instance, in order to change the routes to allow for a dot character in the +id+ parameter:
-
#
-
# constraints(:id => /\d+\.\d+/) do
-
# resources :posts
-
# end
-
#
-
# Now routes such as +/posts/1+ will no longer be valid, but +/posts/1.1+ will be.
-
# The +id+ parameter must match the constraint passed in for this example.
-
#
-
# You may use this to also restrict other parameters:
-
#
-
# resources :posts do
-
# constraints(:post_id => /\d+\.\d+/) do
-
# resources :comments
-
# end
-
# end
-
#
-
# === Restricting based on IP
-
#
-
# Routes can also be constrained to an IP or a certain range of IP addresses:
-
#
-
# constraints(:ip => /192.168.\d+.\d+/) do
-
# resources :posts
-
# end
-
#
-
# Any user connecting from the 192.168.* range will be able to see this resource,
-
# where as any user connecting outside of this range will be told there is no such route.
-
#
-
# === Dynamic request matching
-
#
-
# Requests to routes can be constrained based on specific criteria:
-
#
-
# constraints(lambda { |req| req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do
-
# resources :iphones
-
# end
-
#
-
# You are able to move this logic out into a class if it is too complex for routes.
-
# This class must have a +matches?+ method defined on it which either returns +true+
-
# if the user should be given access to that route, or +false+ if the user should not.
-
#
-
# class Iphone
-
# def self.matches?(request)
-
# request.env["HTTP_USER_AGENT"] =~ /iPhone/
-
# end
-
# end
-
#
-
# An expected place for this code would be +lib/constraints+.
-
#
-
# This class is then used like this:
-
#
-
# constraints(Iphone) do
-
# resources :iphones
-
# end
-
2
def constraints(constraints = {})
-
scope(:constraints => constraints) { yield }
-
end
-
-
# Allows you to set default parameters for a route, such as this:
-
# defaults :id => 'home' do
-
# match 'scoped_pages/(:id)', :to => 'pages#show'
-
# end
-
# Using this, the +:id+ parameter here will default to 'home'.
-
2
def defaults(defaults = {})
-
scope(:defaults => defaults) { yield }
-
end
-
-
2
private
-
2
def scope_options #:nodoc:
-
198
@scope_options ||= private_methods.grep(/^merge_(.+)_scope$/) { $1.to_sym }
-
end
-
-
2
def merge_path_scope(parent, child) #:nodoc:
-
66
Mapper.normalize_path("#{parent}/#{child}")
-
end
-
-
2
def merge_shallow_path_scope(parent, child) #:nodoc:
-
Mapper.normalize_path("#{parent}/#{child}")
-
end
-
-
2
def merge_as_scope(parent, child) #:nodoc:
-
parent ? "#{parent}_#{child}" : child
-
end
-
-
2
def merge_shallow_prefix_scope(parent, child) #:nodoc:
-
parent ? "#{parent}_#{child}" : child
-
end
-
-
2
def merge_module_scope(parent, child) #:nodoc:
-
parent ? "#{parent}/#{child}" : child
-
end
-
-
2
def merge_controller_scope(parent, child) #:nodoc:
-
20
child
-
end
-
-
2
def merge_action_scope(parent, child) #:nodoc:
-
child
-
end
-
-
2
def merge_path_names_scope(parent, child) #:nodoc:
-
merge_options_scope(parent, child)
-
end
-
-
2
def merge_constraints_scope(parent, child) #:nodoc:
-
86
merge_options_scope(parent, child)
-
end
-
-
2
def merge_defaults_scope(parent, child) #:nodoc:
-
merge_options_scope(parent, child)
-
end
-
-
2
def merge_blocks_scope(parent, child) #:nodoc:
-
86
merged = parent ? parent.dup : []
-
86
merged << child if child
-
86
merged
-
end
-
-
2
def merge_options_scope(parent, child) #:nodoc:
-
172
(parent || {}).except(*override_keys(child)).merge(child)
-
end
-
-
2
def merge_shallow_scope(parent, child) #:nodoc:
-
child ? true : false
-
end
-
-
2
def override_keys(child) #:nodoc:
-
172
child.key?(:only) || child.key?(:except) ? [:only, :except] : []
-
end
-
end
-
-
# Resource routing allows you to quickly declare all of the common routes
-
# for a given resourceful controller. Instead of declaring separate routes
-
# for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+
-
# actions, a resourceful route declares them in a single line of code:
-
#
-
# resources :photos
-
#
-
# Sometimes, you have a resource that clients always look up without
-
# referencing an ID. A common example, /profile always shows the profile of
-
# the currently logged in user. In this case, you can use a singular resource
-
# to map /profile (rather than /profile/:id) to the show action.
-
#
-
# resource :profile
-
#
-
# It's common to have resources that are logically children of other
-
# resources:
-
#
-
# resources :magazines do
-
# resources :ads
-
# end
-
#
-
# You may wish to organize groups of controllers under a namespace. Most
-
# commonly, you might group a number of administrative controllers under
-
# an +admin+ namespace. You would place these controllers under the
-
# <tt>app/controllers/admin</tt> directory, and you can group them together
-
# in your router:
-
#
-
# namespace "admin" do
-
# resources :posts, :comments
-
# end
-
#
-
# By default the +:id+ parameter doesn't accept dots. If you need to
-
# use dots as part of the +:id+ parameter add a constraint which
-
# overrides this restriction, e.g:
-
#
-
# resources :articles, :id => /[^\/]+/
-
#
-
# This allows any character other than a slash as part of your +:id+.
-
#
-
2
module Resources
-
# CANONICAL_ACTIONS holds all actions that does not need a prefix or
-
# a path appended since they fit properly in their scope level.
-
2
VALID_ON_OPTIONS = [:new, :collection, :member]
-
2
RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except]
-
2
CANONICAL_ACTIONS = %w(index create new show update destroy)
-
-
2
class Resource #:nodoc:
-
2
attr_reader :controller, :path, :options
-
-
2
def initialize(entities, options = {})
-
20
@name = entities.to_s
-
20
@path = (options[:path] || @name).to_s
-
20
@controller = (options[:controller] || @name).to_s
-
20
@as = options[:as]
-
20
@options = options
-
end
-
-
2
def default_actions
-
126
[:index, :create, :new, :show, :update, :destroy, :edit]
-
end
-
-
2
def actions
-
140
if only = @options[:only]
-
14
Array(only).map(&:to_sym)
-
126
elsif except = @options[:except]
-
default_actions - Array(except).map(&:to_sym)
-
else
-
126
default_actions
-
end
-
end
-
-
2
def name
-
40
@as || @name
-
end
-
-
2
def plural
-
280
@plural ||= name.to_s
-
end
-
-
2
def singular
-
280
@singular ||= name.to_s.singularize
-
end
-
-
2
alias :member_name :singular
-
-
# Checks for uncountable plurals, and appends "_index" if the plural
-
# and singular form are the same.
-
2
def collection_name
-
140
singular == plural ? "#{plural}_index" : plural
-
end
-
-
2
def resource_scope
-
20
{ :controller => controller }
-
end
-
-
2
alias :collection_scope :path
-
-
2
def member_scope
-
24
"#{path}/:id"
-
end
-
-
2
def new_scope(new_path)
-
18
"#{path}/#{new_path}"
-
end
-
-
2
def nested_scope
-
"#{path}/:#{singular}_id"
-
end
-
-
end
-
-
2
class SingletonResource < Resource #:nodoc:
-
2
def initialize(entities, options)
-
super
-
@as = nil
-
@controller = (options[:controller] || plural).to_s
-
@as = options[:as]
-
end
-
-
2
def default_actions
-
[:show, :create, :update, :destroy, :new, :edit]
-
end
-
-
2
def plural
-
@plural ||= name.to_s.pluralize
-
end
-
-
2
def singular
-
@singular ||= name.to_s
-
end
-
-
2
alias :member_name :singular
-
2
alias :collection_name :singular
-
-
2
alias :member_scope :path
-
2
alias :nested_scope :path
-
end
-
-
2
def resources_path_names(options)
-
@scope[:path_names].merge!(options)
-
end
-
-
# Sometimes, you have a resource that clients always look up without
-
# referencing an ID. A common example, /profile always shows the
-
# profile of the currently logged in user. In this case, you can use
-
# a singular resource to map /profile (rather than /profile/:id) to
-
# the show action:
-
#
-
# resource :geocoder
-
#
-
# creates six different routes in your application, all mapping to
-
# the +GeoCoders+ controller (note that the controller is named after
-
# the plural):
-
#
-
# GET /geocoder/new
-
# POST /geocoder
-
# GET /geocoder
-
# GET /geocoder/edit
-
# PUT /geocoder
-
# DELETE /geocoder
-
#
-
# === Options
-
# Takes same options as +resources+.
-
2
def resource(*resources, &block)
-
options = resources.extract_options!.dup
-
-
if apply_common_behavior_for(:resource, resources, options, &block)
-
return self
-
end
-
-
resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
-
yield if block_given?
-
-
collection do
-
post :create
-
end if parent_resource.actions.include?(:create)
-
-
new do
-
get :new
-
end if parent_resource.actions.include?(:new)
-
-
member do
-
get :edit if parent_resource.actions.include?(:edit)
-
get :show if parent_resource.actions.include?(:show)
-
put :update if parent_resource.actions.include?(:update)
-
delete :destroy if parent_resource.actions.include?(:destroy)
-
end
-
end
-
-
self
-
end
-
-
# In Rails, a resourceful route provides a mapping between HTTP verbs
-
# and URLs and controller actions. By convention, each action also maps
-
# to particular CRUD operations in a database. A single entry in the
-
# routing file, such as
-
#
-
# resources :photos
-
#
-
# creates seven different routes in your application, all mapping to
-
# the +Photos+ controller:
-
#
-
# GET /photos
-
# GET /photos/new
-
# POST /photos
-
# GET /photos/:id
-
# GET /photos/:id/edit
-
# PUT /photos/:id
-
# DELETE /photos/:id
-
#
-
# Resources can also be nested infinitely by using this block syntax:
-
#
-
# resources :photos do
-
# resources :comments
-
# end
-
#
-
# This generates the following comments routes:
-
#
-
# GET /photos/:photo_id/comments
-
# GET /photos/:photo_id/comments/new
-
# POST /photos/:photo_id/comments
-
# GET /photos/:photo_id/comments/:id
-
# GET /photos/:photo_id/comments/:id/edit
-
# PUT /photos/:photo_id/comments/:id
-
# DELETE /photos/:photo_id/comments/:id
-
#
-
# === Options
-
# Takes same options as <tt>Base#match</tt> as well as:
-
#
-
# [:path_names]
-
# Allows you to change the segment component of the +edit+ and +new+ actions.
-
# Actions not specified are not changed.
-
#
-
# resources :posts, :path_names => { :new => "brand_new" }
-
#
-
# The above example will now change /posts/new to /posts/brand_new
-
#
-
# [:path]
-
# Allows you to change the path prefix for the resource.
-
#
-
# resources :posts, :path => 'postings'
-
#
-
# The resource and all segments will now route to /postings instead of /posts
-
#
-
# [:only]
-
# Only generate routes for the given actions.
-
#
-
# resources :cows, :only => :show
-
# resources :cows, :only => [:show, :index]
-
#
-
# [:except]
-
# Generate all routes except for the given actions.
-
#
-
# resources :cows, :except => :show
-
# resources :cows, :except => [:show, :index]
-
#
-
# [:shallow]
-
# Generates shallow routes for nested resource(s). When placed on a parent resource,
-
# generates shallow routes for all nested resources.
-
#
-
# resources :posts, :shallow => true do
-
# resources :comments
-
# end
-
#
-
# Is the same as:
-
#
-
# resources :posts do
-
# resources :comments, :except => [:show, :edit, :update, :destroy]
-
# end
-
# resources :comments, :only => [:show, :edit, :update, :destroy]
-
#
-
# This allows URLs for resources that otherwise would be deeply nested such
-
# as a comment on a blog post like <tt>/posts/a-long-permalink/comments/1234</tt>
-
# to be shortened to just <tt>/comments/1234</tt>.
-
#
-
# [:shallow_path]
-
# Prefixes nested shallow routes with the specified path.
-
#
-
# scope :shallow_path => "sekret" do
-
# resources :posts do
-
# resources :comments, :shallow => true
-
# end
-
# end
-
#
-
# The +comments+ resource here will have the following routes generated for it:
-
#
-
# post_comments GET /posts/:post_id/comments(.:format)
-
# post_comments POST /posts/:post_id/comments(.:format)
-
# new_post_comment GET /posts/:post_id/comments/new(.:format)
-
# edit_comment GET /sekret/comments/:id/edit(.:format)
-
# comment GET /sekret/comments/:id(.:format)
-
# comment PUT /sekret/comments/:id(.:format)
-
# comment DELETE /sekret/comments/:id(.:format)
-
#
-
# === Examples
-
#
-
# # routes call <tt>Admin::PostsController</tt>
-
# resources :posts, :module => "admin"
-
#
-
# # resource actions are at /admin/posts.
-
# resources :posts, :path => "admin/posts"
-
2
def resources(*resources, &block)
-
20
options = resources.extract_options!.dup
-
-
20
if apply_common_behavior_for(:resources, resources, options, &block)
-
return self
-
end
-
-
20
resource_scope(:resources, Resource.new(resources.pop, options)) do
-
20
yield if block_given?
-
-
20
collection do
-
20
get :index if parent_resource.actions.include?(:index)
-
20
post :create if parent_resource.actions.include?(:create)
-
end
-
-
new do
-
18
get :new
-
20
end if parent_resource.actions.include?(:new)
-
-
20
member do
-
20
get :edit if parent_resource.actions.include?(:edit)
-
20
get :show if parent_resource.actions.include?(:show)
-
20
put :update if parent_resource.actions.include?(:update)
-
20
delete :destroy if parent_resource.actions.include?(:destroy)
-
end
-
end
-
-
20
self
-
end
-
-
# To add a route to the collection:
-
#
-
# resources :photos do
-
# collection do
-
# get 'search'
-
# end
-
# end
-
#
-
# This will enable Rails to recognize paths such as <tt>/photos/search</tt>
-
# with GET, and route to the search action of +PhotosController+. It will also
-
# create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt>
-
# route helpers.
-
2
def collection
-
24
unless resource_scope?
-
raise ArgumentError, "can't use collection outside resource(s) scope"
-
end
-
-
24
with_scope_level(:collection) do
-
24
scope(parent_resource.collection_scope) do
-
24
yield
-
end
-
end
-
end
-
-
# To add a member route, add a member block into the resource block:
-
#
-
# resources :photos do
-
# member do
-
# get 'preview'
-
# end
-
# end
-
#
-
# This will recognize <tt>/photos/1/preview</tt> with GET, and route to the
-
# preview action of +PhotosController+. It will also create the
-
# <tt>preview_photo_url</tt> and <tt>preview_photo_path</tt> helpers.
-
2
def member
-
24
unless resource_scope?
-
raise ArgumentError, "can't use member outside resource(s) scope"
-
end
-
-
24
with_scope_level(:member) do
-
24
scope(parent_resource.member_scope) do
-
24
yield
-
end
-
end
-
end
-
-
2
def new
-
18
unless resource_scope?
-
raise ArgumentError, "can't use new outside resource(s) scope"
-
end
-
-
18
with_scope_level(:new) do
-
18
scope(parent_resource.new_scope(action_path(:new))) do
-
18
yield
-
end
-
end
-
end
-
-
2
def nested
-
unless resource_scope?
-
raise ArgumentError, "can't use nested outside resource(s) scope"
-
end
-
-
with_scope_level(:nested) do
-
if shallow?
-
with_exclusive_scope do
-
if @scope[:shallow_path].blank?
-
scope(parent_resource.nested_scope, nested_options) { yield }
-
else
-
scope(@scope[:shallow_path], :as => @scope[:shallow_prefix]) do
-
scope(parent_resource.nested_scope, nested_options) { yield }
-
end
-
end
-
end
-
else
-
scope(parent_resource.nested_scope, nested_options) { yield }
-
end
-
end
-
end
-
-
# See ActionDispatch::Routing::Mapper::Scoping#namespace
-
2
def namespace(path, options = {})
-
if resource_scope?
-
nested { super }
-
else
-
super
-
end
-
end
-
-
2
def shallow
-
scope(:shallow => true, :shallow_path => @scope[:path]) do
-
yield
-
end
-
end
-
-
2
def shallow?
-
242
parent_resource.instance_of?(Resource) && @scope[:shallow]
-
end
-
-
2
def match(path, *rest)
-
164
if rest.empty? && Hash === path
-
10
options = path
-
20
path, to = options.find { |name, value| name.is_a?(String) }
-
10
options[:to] = to
-
10
options.delete(path)
-
10
paths = [path]
-
else
-
154
options = rest.pop || {}
-
154
paths = [path] + rest
-
end
-
-
164
if @scope[:controller] && @scope[:action]
-
options[:to] ||= "#{@scope[:controller]}##{@scope[:action]}"
-
end
-
-
164
path_without_format = path.to_s.sub(/\(\.:format\)$/, '')
-
164
if using_match_shorthand?(path_without_format, options)
-
6
options[:to] ||= path_without_format.gsub(%r{^/}, "").sub(%r{/([^/]*)$}, '#\1')
-
end
-
-
164
options[:anchor] = true unless options.key?(:anchor)
-
-
164
if options[:on] && !VALID_ON_OPTIONS.include?(options[:on])
-
raise ArgumentError, "Unknown scope #{on.inspect} given to :on"
-
end
-
-
328
paths.each { |_path| decomposed_match(_path, options.dup) }
-
164
self
-
end
-
-
2
def using_match_shorthand?(path, options)
-
164
path && (options[:to] || options[:action]).nil? && path =~ %r{/[\w/]+$}
-
end
-
-
2
def decomposed_match(path, options) # :nodoc:
-
164
if on = options.delete(:on)
-
send(on) { decomposed_match(path, options) }
-
else
-
164
case @scope[:scope_level]
-
when :resources
-
nested { decomposed_match(path, options) }
-
when :resource
-
member { decomposed_match(path, options) }
-
else
-
164
add_route(path, options)
-
end
-
end
-
end
-
-
2
def add_route(action, options) # :nodoc:
-
164
path = path_for_action(action, options.delete(:path))
-
164
action = action.to_s.dup
-
-
164
if action =~ /^[\w\/]+$/
-
162
options[:action] ||= action unless action.include?("/")
-
else
-
2
action = nil
-
end
-
-
164
if !options.fetch(:as, true)
-
2
options.delete(:as)
-
else
-
162
options[:as] = name_for_action(options[:as], action)
-
end
-
-
164
mapping = Mapping.new(@set, @scope, path, options)
-
164
app, conditions, requirements, defaults, as, anchor = mapping.to_route
-
164
@set.add_route(app, conditions, requirements, defaults, as, anchor)
-
end
-
-
2
def root(options={})
-
2
if @scope[:scope_level] == :resources
-
with_scope_level(:root) do
-
scope(parent_resource.path) do
-
super(options)
-
end
-
end
-
else
-
2
super(options)
-
end
-
end
-
-
2
protected
-
-
2
def parent_resource #:nodoc:
-
976
@scope[:scope_level_resource]
-
end
-
-
2
def apply_common_behavior_for(method, resources, options, &block) #:nodoc:
-
20
if resources.length > 1
-
resources.each { |r| send(method, r, options, &block) }
-
return true
-
end
-
-
20
if resource_scope?
-
nested { send(method, resources.pop, options, &block) }
-
return true
-
end
-
-
20
options.keys.each do |k|
-
2
(options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp)
-
end
-
-
20
scope_options = options.slice!(*RESOURCE_OPTIONS)
-
20
unless scope_options.empty?
-
scope(scope_options) do
-
send(method, resources.pop, options, &block)
-
end
-
return true
-
end
-
-
20
unless action_options?(options)
-
18
options.merge!(scope_action_options) if scope_action_options?
-
end
-
-
20
false
-
end
-
-
2
def action_options?(options) #:nodoc:
-
20
options[:only] || options[:except]
-
end
-
-
2
def scope_action_options? #:nodoc:
-
18
@scope[:options] && (@scope[:options][:only] || @scope[:options][:except])
-
end
-
-
2
def scope_action_options #:nodoc:
-
@scope[:options].slice(:only, :except)
-
end
-
-
2
def resource_scope? #:nodoc:
-
86
[:resource, :resources].include? @scope[:scope_level]
-
end
-
-
2
def resource_method_scope? #:nodoc:
-
304
[:collection, :member, :new].include? @scope[:scope_level]
-
end
-
-
2
def with_exclusive_scope
-
begin
-
old_name_prefix, old_path = @scope[:as], @scope[:path]
-
@scope[:as], @scope[:path] = nil, nil
-
-
with_scope_level(:exclusive) do
-
yield
-
end
-
ensure
-
@scope[:as], @scope[:path] = old_name_prefix, old_path
-
end
-
end
-
-
2
def with_scope_level(kind, resource = parent_resource)
-
86
old, @scope[:scope_level] = @scope[:scope_level], kind
-
86
old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
-
86
yield
-
ensure
-
86
@scope[:scope_level] = old
-
86
@scope[:scope_level_resource] = old_resource
-
end
-
-
2
def resource_scope(kind, resource) #:nodoc:
-
20
with_scope_level(kind, resource) do
-
20
scope(parent_resource.resource_scope) do
-
20
yield
-
end
-
end
-
end
-
-
2
def nested_options #:nodoc:
-
options = { :as => parent_resource.member_name }
-
options[:constraints] = {
-
:"#{parent_resource.singular}_id" => id_constraint
-
} if id_constraint?
-
-
options
-
end
-
-
2
def id_constraint? #:nodoc:
-
@scope[:constraints] && @scope[:constraints][:id].is_a?(Regexp)
-
end
-
-
2
def id_constraint #:nodoc:
-
@scope[:constraints][:id]
-
end
-
-
2
def canonical_action?(action, flag) #:nodoc:
-
314
flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
-
end
-
-
2
def shallow_scoping? #:nodoc:
-
242
shallow? && @scope[:scope_level] == :member
-
end
-
-
2
def path_for_action(action, path) #:nodoc:
-
164
prefix = shallow_scoping? ?
-
"#{@scope[:shallow_path]}/#{parent_resource.path}/:id" : @scope[:path]
-
-
164
path = if canonical_action?(action, path.blank?)
-
110
prefix.to_s
-
else
-
54
"#{prefix}/#{action_path(action, path)}"
-
end
-
end
-
-
2
def action_path(name, path = nil) #:nodoc:
-
# Ruby 1.8 can't transform empty strings to symbols
-
72
name = name.to_sym if name.is_a?(String) && !name.empty?
-
72
path || @scope[:path_names][name] || name.to_s
-
end
-
-
2
def prefix_name_for_action(as, action) #:nodoc:
-
162
if as
-
12
as.to_s
-
150
elsif !canonical_action?(action, @scope[:scope_level])
-
40
action.to_s
-
end
-
end
-
-
2
def name_for_action(as, action) #:nodoc:
-
162
prefix = prefix_name_for_action(as, action)
-
162
prefix = Mapper.normalize_name(prefix) if prefix
-
162
name_prefix = @scope[:as]
-
-
162
if parent_resource
-
140
return nil unless as || action
-
-
140
collection_name = parent_resource.collection_name
-
140
member_name = parent_resource.member_name
-
end
-
-
162
name = case @scope[:scope_level]
-
when :nested
-
[name_prefix, prefix]
-
when :collection
-
44
[prefix, name_prefix, collection_name]
-
when :new
-
18
[prefix, :new, name_prefix, member_name]
-
when :member
-
78
[prefix, shallow_scoping? ? @scope[:shallow_prefix] : name_prefix, member_name]
-
when :root
-
[name_prefix, collection_name, prefix]
-
else
-
22
[name_prefix, member_name, prefix]
-
end
-
-
162
if candidate = name.select(&:present?).join("_").presence
-
# If a name was not explicitly given, we check if it is valid
-
# and return nil in case it isn't. Otherwise, we pass the invalid name
-
# forward so the underlying router engine treats it and raises an exception.
-
162
if as.nil?
-
6150
candidate unless @set.routes.find { |r| r.name == candidate } || candidate !~ /\A[_a-z]/i
-
else
-
12
candidate
-
end
-
end
-
end
-
end
-
-
2
def initialize(set) #:nodoc:
-
4
@set = set
-
4
@scope = { :path_names => @set.resources_path_names }
-
end
-
-
2
include Base
-
2
include HttpHelpers
-
2
include Redirection
-
2
include Scoping
-
2
include Resources
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Routing
-
# Polymorphic URL helpers are methods for smart resolution to a named route call when
-
# given an Active Record model instance. They are to be used in combination with
-
# ActionController::Resources.
-
#
-
# These methods are useful when you want to generate correct URL or path to a RESTful
-
# resource without having to know the exact type of the record in question.
-
#
-
# Nested resources and/or namespaces are also supported, as illustrated in the example:
-
#
-
# polymorphic_url([:admin, @article, @comment])
-
#
-
# results in:
-
#
-
# admin_article_comment_url(@article, @comment)
-
#
-
# == Usage within the framework
-
#
-
# Polymorphic URL helpers are used in a number of places throughout the \Rails framework:
-
#
-
# * <tt>url_for</tt>, so you can use it with a record as the argument, e.g.
-
# <tt>url_for(@article)</tt>;
-
# * ActionView::Helpers::FormHelper uses <tt>polymorphic_path</tt>, so you can write
-
# <tt>form_for(@article)</tt> without having to specify <tt>:url</tt> parameter for the form
-
# action;
-
# * <tt>redirect_to</tt> (which, in fact, uses <tt>url_for</tt>) so you can write
-
# <tt>redirect_to(post)</tt> in your controllers;
-
# * ActionView::Helpers::AtomFeedHelper, so you don't have to explicitly specify URLs
-
# for feed entries.
-
#
-
# == Prefixed polymorphic helpers
-
#
-
# In addition to <tt>polymorphic_url</tt> and <tt>polymorphic_path</tt> methods, a
-
# number of prefixed helpers are available as a shorthand to <tt>:action => "..."</tt>
-
# in options. Those are:
-
#
-
# * <tt>edit_polymorphic_url</tt>, <tt>edit_polymorphic_path</tt>
-
# * <tt>new_polymorphic_url</tt>, <tt>new_polymorphic_path</tt>
-
#
-
# Example usage:
-
#
-
# edit_polymorphic_path(@post) # => "/posts/1/edit"
-
# polymorphic_path(@post, :format => :pdf) # => "/posts/1.pdf"
-
#
-
# == Using with mounted engines
-
#
-
# If you use mounted engine, there is a possibility that you will need to use
-
# polymorphic_url pointing at engine's routes. To do that, just pass proxy used
-
# to reach engine's routes as a first argument:
-
#
-
# For example:
-
#
-
# polymorphic_url([blog, @post]) # it will call blog.post_path(@post)
-
# form_for([blog, @post]) # => "/blog/posts/1
-
#
-
2
module PolymorphicRoutes
-
# Constructs a call to a named RESTful route for the given record and returns the
-
# resulting URL string. For example:
-
#
-
# # calls post_url(post)
-
# polymorphic_url(post) # => "http://example.com/posts/1"
-
# polymorphic_url([blog, post]) # => "http://example.com/blogs/1/posts/1"
-
# polymorphic_url([:admin, blog, post]) # => "http://example.com/admin/blogs/1/posts/1"
-
# polymorphic_url([user, :blog, post]) # => "http://example.com/users/1/blog/posts/1"
-
# polymorphic_url(Comment) # => "http://example.com/comments"
-
#
-
# ==== Options
-
#
-
# * <tt>:action</tt> - Specifies the action prefix for the named route:
-
# <tt>:new</tt> or <tt>:edit</tt>. Default is no prefix.
-
# * <tt>:routing_type</tt> - Allowed values are <tt>:path</tt> or <tt>:url</tt>.
-
# Default is <tt>:url</tt>.
-
#
-
# ==== Examples
-
#
-
# # an Article record
-
# polymorphic_url(record) # same as article_url(record)
-
#
-
# # a Comment record
-
# polymorphic_url(record) # same as comment_url(record)
-
#
-
# # it recognizes new records and maps to the collection
-
# record = Comment.new
-
# polymorphic_url(record) # same as comments_url()
-
#
-
# # the class of a record will also map to the collection
-
# polymorphic_url(Comment) # same as comments_url()
-
#
-
2
def polymorphic_url(record_or_hash_or_array, options = {})
-
if record_or_hash_or_array.kind_of?(Array)
-
record_or_hash_or_array = record_or_hash_or_array.compact
-
if record_or_hash_or_array.first.is_a?(ActionDispatch::Routing::RoutesProxy)
-
proxy = record_or_hash_or_array.shift
-
end
-
record_or_hash_or_array = record_or_hash_or_array[0] if record_or_hash_or_array.size == 1
-
end
-
-
record = extract_record(record_or_hash_or_array)
-
record = convert_to_model(record)
-
-
args = Array === record_or_hash_or_array ?
-
record_or_hash_or_array.dup :
-
[ record_or_hash_or_array ]
-
-
inflection = if options[:action] && options[:action].to_s == "new"
-
args.pop
-
:singular
-
elsif (record.respond_to?(:persisted?) && !record.persisted?)
-
args.pop
-
:plural
-
elsif record.is_a?(Class)
-
args.pop
-
:plural
-
else
-
:singular
-
end
-
-
args.delete_if {|arg| arg.is_a?(Symbol) || arg.is_a?(String)}
-
named_route = build_named_route_call(record_or_hash_or_array, inflection, options)
-
-
url_options = options.except(:action, :routing_type)
-
unless url_options.empty?
-
args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options
-
end
-
-
args.collect! { |a| convert_to_model(a) }
-
-
(proxy || self).send(named_route, *args)
-
end
-
-
# Returns the path component of a URL for the given record. It uses
-
# <tt>polymorphic_url</tt> with <tt>:routing_type => :path</tt>.
-
2
def polymorphic_path(record_or_hash_or_array, options = {})
-
polymorphic_url(record_or_hash_or_array, options.merge(:routing_type => :path))
-
end
-
-
2
%w(edit new).each do |action|
-
4
module_eval <<-EOT, __FILE__, __LINE__ + 1
-
def #{action}_polymorphic_url(record_or_hash, options = {}) # def edit_polymorphic_url(record_or_hash, options = {})
-
polymorphic_url( # polymorphic_url(
-
record_or_hash, # record_or_hash,
-
options.merge(:action => "#{action}")) # options.merge(:action => "edit"))
-
end # end
-
#
-
def #{action}_polymorphic_path(record_or_hash, options = {}) # def edit_polymorphic_path(record_or_hash, options = {})
-
polymorphic_url( # polymorphic_url(
-
record_or_hash, # record_or_hash,
-
options.merge(:action => "#{action}", :routing_type => :path)) # options.merge(:action => "edit", :routing_type => :path))
-
end # end
-
EOT
-
end
-
-
2
private
-
2
def action_prefix(options)
-
options[:action] ? "#{options[:action]}_" : ''
-
end
-
-
2
def convert_to_model(object)
-
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
-
2
def routing_type(options)
-
options[:routing_type] || :url
-
end
-
-
2
def build_named_route_call(records, inflection, options = {})
-
if records.is_a?(Array)
-
record = records.pop
-
route = records.map do |parent|
-
if parent.is_a?(Symbol) || parent.is_a?(String)
-
parent
-
else
-
ActiveModel::Naming.singular_route_key(parent)
-
end
-
end
-
else
-
record = extract_record(records)
-
route = []
-
end
-
-
if record.is_a?(Symbol) || record.is_a?(String)
-
route << record
-
elsif record
-
if inflection == :singular
-
route << ActiveModel::Naming.singular_route_key(record)
-
else
-
route << ActiveModel::Naming.route_key(record)
-
end
-
else
-
raise ArgumentError, "Nil location provided. Can't build URI."
-
end
-
-
route << routing_type(options)
-
-
action_prefix(options) + route.join("_")
-
end
-
-
2
def extract_record(record_or_hash_or_array)
-
case record_or_hash_or_array
-
when Array; record_or_hash_or_array.last
-
when Hash; record_or_hash_or_array[:id]
-
else record_or_hash_or_array
-
end
-
end
-
end
-
end
-
end
-
-
2
require 'action_dispatch/http/request'
-
2
require 'active_support/core_ext/uri'
-
2
require 'rack/utils'
-
-
2
module ActionDispatch
-
2
module Routing
-
2
class Redirect # :nodoc:
-
2
attr_reader :status, :block
-
-
2
def initialize(status, block)
-
@status = status
-
@block = block
-
end
-
-
2
def call(env)
-
req = Request.new(env)
-
-
uri = URI.parse(path(req.symbolized_path_parameters, req))
-
uri.scheme ||= req.scheme
-
uri.host ||= req.host
-
uri.port ||= req.port unless req.standard_port?
-
-
body = %(<html><body>You are being <a href="#{ERB::Util.h(uri.to_s)}">redirected</a>.</body></html>)
-
-
headers = {
-
'Location' => uri.to_s,
-
'Content-Type' => 'text/html',
-
'Content-Length' => body.length.to_s
-
}
-
-
[ status, headers, [body] ]
-
end
-
-
2
def path(params, request)
-
block.call params, request
-
end
-
end
-
-
2
class OptionRedirect < Redirect # :nodoc:
-
2
alias :options :block
-
-
2
def path(params, request)
-
url_options = {
-
:protocol => request.protocol,
-
:host => request.host,
-
:port => request.optional_port,
-
:path => request.path,
-
:params => request.query_parameters
-
}.merge options
-
-
if !params.empty? && url_options[:path].match(/%\{\w*\}/)
-
url_options[:path] = (url_options[:path] % escape_path(params))
-
end
-
-
ActionDispatch::Http::URL.url_for url_options
-
end
-
-
2
private
-
2
def escape_path(params)
-
Hash[params.map{ |k,v| [k, URI.parser.escape(v)] }]
-
end
-
end
-
-
2
module Redirection
-
-
# Redirect any path to another path:
-
#
-
# match "/stories" => redirect("/posts")
-
#
-
# You can also use interpolation in the supplied redirect argument:
-
#
-
# match 'docs/:article', :to => redirect('/wiki/%{article}')
-
#
-
# Alternatively you can use one of the other syntaxes:
-
#
-
# The block version of redirect allows for the easy encapsulation of any logic associated with
-
# the redirect in question. Either the params and request are supplied as arguments, or just
-
# params, depending of how many arguments your block accepts. A string is required as a
-
# return value.
-
#
-
# match 'jokes/:number', :to => redirect { |params, request|
-
# path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp")
-
# "http://#{request.host_with_port}/#{path}"
-
# }
-
#
-
# The options version of redirect allows you to supply only the parts of the url which need
-
# to change, it also supports interpolation of the path similar to the first example.
-
#
-
# match 'stores/:name', :to => redirect(:subdomain => 'stores', :path => '/%{name}')
-
# match 'stores/:name(*all)', :to => redirect(:subdomain => 'stores', :path => '/%{name}%{all}')
-
#
-
# Finally, an object which responds to call can be supplied to redirect, allowing you to reuse
-
# common redirect routes. The call method must accept two arguments, params and request, and return
-
# a string.
-
#
-
# match 'accounts/:name' => redirect(SubdomainRedirector.new('api'))
-
#
-
2
def redirect(*args, &block)
-
options = args.last.is_a?(Hash) ? args.pop : {}
-
status = options.delete(:status) || 301
-
-
return OptionRedirect.new(status, options) if options.any?
-
-
path = args.shift
-
-
block = lambda { |params, request|
-
(params.empty? || !path.match(/%\{\w*\}/)) ? path : (path % escape(params))
-
} if String === path
-
-
block = path if path.respond_to? :call
-
-
# :FIXME: remove in Rails 4.0
-
if block && block.respond_to?(:arity) && block.arity < 2
-
msg = "redirect blocks with arity of #{block.arity} are deprecated. Your block must take 2 parameters: the environment, and a request object"
-
ActiveSupport::Deprecation.warn msg
-
deprecated_block = block
-
block = lambda { |params, _| deprecated_block.call(params) }
-
end
-
-
raise ArgumentError, "redirection argument not supported" unless block
-
-
Redirect.new status, block
-
end
-
-
2
private
-
2
def escape(params)
-
Hash[params.map{ |k,v| [k, Rack::Utils.escape(v)] }]
-
end
-
end
-
end
-
end
-
2
require 'journey'
-
2
require 'forwardable'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/object/to_query'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/module/remove_method'
-
2
require 'action_controller/metal/exceptions'
-
-
2
module ActionDispatch
-
2
module Routing
-
2
class RouteSet #:nodoc:
-
# Since the router holds references to many parts of the system
-
# like engines, controllers and the application itself, inspecting
-
# the route set can actually be really slow, therefore we default
-
# alias inspect to to_s.
-
2
alias inspect to_s
-
-
2
PARAMETERS_KEY = 'action_dispatch.request.path_parameters'
-
-
2
class Dispatcher #:nodoc:
-
2
def initialize(options={})
-
162
@defaults = options[:defaults]
-
162
@glob_param = options.delete(:glob)
-
162
@controllers = {}
-
end
-
-
2
def call(env)
-
params = env[PARAMETERS_KEY]
-
prepare_params!(params)
-
-
# Just raise undefined constant errors if a controller was specified as default.
-
unless controller = controller(params, @defaults.key?(:controller))
-
return [404, {'X-Cascade' => 'pass'}, []]
-
end
-
-
dispatch(controller, params[:action], env)
-
end
-
-
2
def prepare_params!(params)
-
normalize_controller!(params)
-
merge_default_action!(params)
-
split_glob_param!(params) if @glob_param
-
end
-
-
# If this is a default_controller (i.e. a controller specified by the user)
-
# we should raise an error in case it's not found, because it usually means
-
# a user error. However, if the controller was retrieved through a dynamic
-
# segment, as in :controller(/:action), we should simply return nil and
-
# delegate the control back to Rack cascade. Besides, if this is not a default
-
# controller, it means we should respect the @scope[:module] parameter.
-
2
def controller(params, default_controller=true)
-
if params && params.key?(:controller)
-
controller_param = params[:controller]
-
controller_reference(controller_param)
-
end
-
rescue NameError => e
-
raise ActionController::RoutingError, e.message, e.backtrace if default_controller
-
end
-
-
2
private
-
-
2
def controller_reference(controller_param)
-
controller_name = "#{controller_param.camelize}Controller"
-
-
unless controller = @controllers[controller_param]
-
controller = @controllers[controller_param] =
-
ActiveSupport::Dependencies.reference(controller_name)
-
end
-
controller.get(controller_name)
-
end
-
-
2
def dispatch(controller, action, env)
-
controller.action(action).call(env)
-
end
-
-
2
def normalize_controller!(params)
-
params[:controller] = params[:controller].underscore if params.key?(:controller)
-
end
-
-
2
def merge_default_action!(params)
-
params[:action] ||= 'index'
-
end
-
-
2
def split_glob_param!(params)
-
params[@glob_param] = params[@glob_param].split('/').map { |v| URI.parser.unescape(v) }
-
end
-
end
-
-
# A NamedRouteCollection instance is a collection of named routes, and also
-
# maintains an anonymous module that can be used to install helpers for the
-
# named routes.
-
2
class NamedRouteCollection #:nodoc:
-
2
include Enumerable
-
2
attr_reader :routes, :helpers, :module
-
-
2
def initialize
-
2
@routes = {}
-
2
@helpers = []
-
-
2
@module = Module.new
-
end
-
-
2
def helper_names
-
10
self.module.instance_methods.map(&:to_s)
-
end
-
-
2
def clear!
-
2
@helpers.each do |helper|
-
@module.remove_possible_method helper
-
end
-
-
2
@routes.clear
-
2
@helpers.clear
-
end
-
-
2
def add(name, route)
-
106
routes[name.to_sym] = route
-
106
define_named_route_methods(name, route)
-
end
-
-
2
def get(name)
-
2
routes[name.to_sym]
-
end
-
-
2
alias []= add
-
2
alias [] get
-
2
alias clear clear!
-
-
2
def each
-
routes.each { |name, route| yield name, route }
-
self
-
end
-
-
2
def names
-
routes.keys
-
end
-
-
2
def length
-
routes.length
-
end
-
-
2
def reset!
-
old_routes = routes.dup
-
clear!
-
old_routes.each do |name, route|
-
add(name, route)
-
end
-
end
-
-
2
def install(destinations = [ActionController::Base, ActionView::Base], regenerate = false)
-
10
reset! if regenerate
-
10
Array(destinations).each do |dest|
-
10
dest.__send__(:include, @module)
-
end
-
end
-
-
2
private
-
2
def url_helper_name(name, kind = :url)
-
212
:"#{name}_#{kind}"
-
end
-
-
2
def hash_access_name(name, kind = :url)
-
424
:"hash_for_#{name}_#{kind}"
-
end
-
-
2
def define_named_route_methods(name, route)
-
106
{:url => {:only_path => false}, :path => {:only_path => true}}.each do |kind, opts|
-
212
hash = route.defaults.merge(:use_route => name).merge(opts)
-
212
define_hash_access route, name, kind, hash
-
212
define_url_helper route, name, kind, hash
-
end
-
end
-
-
2
def define_hash_access(route, name, kind, options)
-
212
selector = hash_access_name(name, kind)
-
-
# We use module_eval to avoid leaks
-
212
@module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1
-
remove_possible_method :#{selector}
-
def #{selector}(*args)
-
options = args.extract_options!
-
result = #{options.inspect}
-
-
if args.size > 0
-
result[:_positional_args] = args
-
result[:_positional_keys] = #{route.segment_keys.inspect}
-
end
-
-
result.merge(options)
-
end
-
protected :#{selector}
-
END_EVAL
-
212
helpers << selector
-
end
-
-
# Create a url helper allowing ordered parameters to be associated
-
# with corresponding dynamic segments, so you can do:
-
#
-
# foo_url(bar, baz, bang)
-
#
-
# Instead of:
-
#
-
# foo_url(:bar => bar, :baz => baz, :bang => bang)
-
#
-
# Also allow options hash, so you can do:
-
#
-
# foo_url(bar, baz, bang, :sort_by => 'baz')
-
#
-
2
def define_url_helper(route, name, kind, options)
-
212
selector = url_helper_name(name, kind)
-
212
hash_access_method = hash_access_name(name, kind)
-
-
212
@module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1
-
remove_possible_method :#{selector}
-
def #{selector}(*args)
-
url_for(#{hash_access_method}(*args))
-
end
-
END_EVAL
-
212
helpers << selector
-
end
-
end
-
-
2
attr_accessor :formatter, :set, :named_routes, :default_scope, :router
-
2
attr_accessor :disable_clear_and_finalize, :resources_path_names
-
2
attr_accessor :default_url_options, :request_class, :valid_conditions
-
-
2
alias :routes :set
-
-
2
def self.default_resources_path_names
-
2
{ :new => 'new', :edit => 'edit' }
-
end
-
-
2
def initialize(request_class = ActionDispatch::Request)
-
2
self.named_routes = NamedRouteCollection.new
-
2
self.resources_path_names = self.class.default_resources_path_names.dup
-
2
self.default_url_options = {}
-
-
2
self.request_class = request_class
-
2
@valid_conditions = {}
-
-
2
request_class.public_instance_methods.each { |m|
-
440
@valid_conditions[m.to_sym] = true
-
}
-
2
@valid_conditions[:controller] = true
-
2
@valid_conditions[:action] = true
-
-
2
self.valid_conditions.delete(:id)
-
-
2
@append = []
-
2
@prepend = []
-
2
@disable_clear_and_finalize = false
-
2
@finalized = false
-
-
2
@set = Journey::Routes.new
-
2
@router = Journey::Router.new(@set, {
-
:parameters_key => PARAMETERS_KEY,
-
:request_class => request_class})
-
2
@formatter = Journey::Formatter.new @set
-
end
-
-
2
def draw(&block)
-
2
clear! unless @disable_clear_and_finalize
-
2
eval_block(block)
-
2
finalize! unless @disable_clear_and_finalize
-
nil
-
end
-
-
2
def append(&block)
-
@append << block
-
end
-
-
2
def prepend(&block)
-
2
@prepend << block
-
end
-
-
2
def eval_block(block)
-
4
if block.arity == 1
-
raise "You are using the old router DSL which has been removed in Rails 3.1. " <<
-
"Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/"
-
end
-
4
mapper = Mapper.new(self)
-
4
if default_scope
-
mapper.with_default_scope(default_scope, &block)
-
else
-
4
mapper.instance_exec(&block)
-
end
-
end
-
-
2
def finalize!
-
21
return if @finalized
-
2
@append.each { |blk| eval_block(blk) }
-
2
@finalized = true
-
end
-
-
2
def clear!
-
2
@finalized = false
-
2
named_routes.clear
-
2
set.clear
-
2
formatter.clear
-
4
@prepend.each { |blk| eval_block(blk) }
-
end
-
-
2
def install_helpers(destinations = [ActionController::Base, ActionView::Base], regenerate_code = false)
-
30
Array(destinations).each { |d| d.module_eval { include Helpers } }
-
10
named_routes.install(destinations, regenerate_code)
-
end
-
-
2
module MountedHelpers
-
end
-
-
2
def mounted_helpers
-
5
MountedHelpers
-
end
-
-
2
def define_mounted_helper(name)
-
2
return if MountedHelpers.method_defined?(name)
-
-
2
routes = self
-
2
MountedHelpers.class_eval do
-
2
define_method "_#{name}" do
-
RoutesProxy.new(routes, self._routes_context)
-
end
-
end
-
-
2
MountedHelpers.class_eval <<-RUBY
-
def #{name}
-
@#{name} ||= _#{name}
-
end
-
RUBY
-
end
-
-
2
def url_helpers
-
@url_helpers ||= begin
-
2
routes = self
-
-
2
helpers = Module.new do
-
2
extend ActiveSupport::Concern
-
2
include UrlFor
-
-
2
@_routes = routes
-
2
class << self
-
2
delegate :url_for, :to => '@_routes'
-
end
-
2
extend routes.named_routes.module
-
-
# ROUTES TODO: install_helpers isn't great... can we make a module with the stuff that
-
# we can include?
-
# Yes plz - JP
-
2
included do
-
10
routes.install_helpers(self)
-
31
singleton_class.send(:redefine_method, :_routes) { routes }
-
end
-
-
31
define_method(:_routes) { @_routes || routes }
-
end
-
-
2
helpers
-
36
end
-
end
-
-
2
def empty?
-
routes.empty?
-
end
-
-
2
def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true)
-
164
raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
-
-
164
path = build_path(conditions.delete(:path_info), requirements, SEPARATORS, anchor)
-
404
conditions = build_conditions(conditions, valid_conditions, path.names.map { |x| x.to_sym })
-
-
164
route = @set.add_route(app, path, conditions, defaults, name)
-
164
named_routes[name] = route if name
-
164
route
-
end
-
-
2
def build_path(path, requirements, separators, anchor)
-
164
strexp = Journey::Router::Strexp.new(
-
path,
-
requirements,
-
SEPARATORS,
-
anchor)
-
-
164
pattern = Journey::Path::Pattern.new(strexp)
-
-
164
builder = Journey::GTG::Builder.new pattern.spec
-
-
# Get all the symbol nodes followed by literals that are not the
-
# dummy node.
-
164
symbols = pattern.spec.grep(Journey::Nodes::Symbol).find_all { |n|
-
240
builder.followpos(n).first.literal?
-
}
-
-
# Get all the symbol nodes preceded by literals.
-
164
symbols.concat pattern.spec.find_all(&:literal?).map { |n|
-
218
builder.followpos(n).first
-
}.find_all(&:symbol?)
-
-
164
symbols.each { |x|
-
x.regexp = /(?:#{Regexp.union(x.regexp, '-')})+/
-
}
-
-
164
pattern
-
end
-
2
private :build_path
-
-
2
def build_conditions(current_conditions, req_predicates, path_values)
-
164
conditions = current_conditions.dup
-
-
164
verbs = conditions[:request_method] || []
-
-
# Rack-Mount requires that :request_method be a regular expression.
-
# :request_method represents the HTTP verb that matches this route.
-
#
-
# Here we munge values before they get sent on to rack-mount.
-
164
unless verbs.empty?
-
152
conditions[:request_method] = %r[^#{verbs.join('|')}$]
-
end
-
316
conditions.delete_if { |k,v| !(req_predicates.include?(k) || path_values.include?(k)) }
-
-
164
conditions
-
end
-
2
private :build_conditions
-
-
2
class Generator #:nodoc:
-
2
PARAMETERIZE = lambda do |name, value|
-
9
if name == :controller
-
value
-
elsif value.is_a?(Array)
-
value.map { |v| v.to_param }.join('/')
-
elsif param = value.to_param
-
8
param
-
end
-
end
-
-
2
attr_reader :options, :recall, :set, :named_route
-
-
2
def initialize(options, recall, set, extras = false)
-
29
@named_route = options.delete(:use_route)
-
29
@options = options.dup
-
29
@recall = recall.dup
-
29
@set = set
-
29
@extras = extras
-
-
29
normalize_options!
-
29
normalize_controller_action_id!
-
29
use_relative_controller!
-
29
normalize_controller!
-
29
handle_nil_action!
-
end
-
-
2
def controller
-
58
@options[:controller]
-
end
-
-
2
def current_controller
-
48
@recall[:controller]
-
end
-
-
2
def use_recall_for(key)
-
47
if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
-
23
if named_route_exists?
-
1
@options[key] = @recall.delete(key) if segment_keys.include?(key)
-
else
-
22
@options[key] = @recall.delete(key)
-
end
-
end
-
end
-
-
2
def normalize_options!
-
# If an explicit :controller was given, always make :action explicit
-
# too, so that action expiry works as expected for things like
-
#
-
# generate({:controller => 'content'}, {:controller => 'content', :action => 'show'})
-
#
-
# (the above is from the unit tests). In the above case, because the
-
# controller was explicitly given, but no action, the action is implied to
-
# be "index", not the recalled action of "show".
-
-
29
if options[:controller]
-
20
options[:action] ||= 'index'
-
20
options[:controller] = options[:controller].to_s
-
end
-
-
29
if options[:action]
-
29
options[:action] = options[:action].to_s
-
end
-
end
-
-
# This pulls :controller, :action, and :id out of the recall.
-
# The recall key is only used if there is no key in the options
-
# or if the key in the options is identical. If any of
-
# :controller, :action or :id is not found, don't pull any
-
# more keys from the recall.
-
2
def normalize_controller_action_id!
-
29
@recall[:action] ||= 'index' if current_controller
-
-
29
use_recall_for(:controller) or return
-
9
use_recall_for(:action) or return
-
9
use_recall_for(:id)
-
end
-
-
# if the current controller is "foo/bar/baz" and :controller => "baz/bat"
-
# is specified, the controller becomes "foo/baz/bat"
-
2
def use_relative_controller!
-
29
if !named_route && different_controller? && !controller.start_with?("/")
-
old_parts = current_controller.split('/')
-
size = controller.count("/") + 1
-
parts = old_parts[0...-size] << controller
-
@options[:controller] = parts.join("/")
-
end
-
end
-
-
# Remove leading slashes from controllers
-
2
def normalize_controller!
-
29
@options[:controller] = controller.sub(%r{^/}, '') if controller
-
end
-
-
# This handles the case of :action => nil being explicitly passed.
-
# It is identical to :action => "index"
-
2
def handle_nil_action!
-
29
if options.has_key?(:action) && options[:action].nil?
-
options[:action] = 'index'
-
end
-
29
recall[:action] = options.delete(:action) if options[:action] == 'index'
-
end
-
-
2
def generate
-
29
path, params = @set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE)
-
-
27
raise_routing_error unless path
-
-
27
return [path, params.keys] if @extras
-
-
18
[path, params]
-
rescue Journey::Router::RoutingError
-
2
raise_routing_error
-
end
-
-
2
def raise_routing_error
-
2
raise ActionController::RoutingError, "No route matches #{options.inspect}"
-
end
-
-
2
def different_controller?
-
19
return false unless current_controller
-
controller.to_param != current_controller.to_param
-
end
-
-
2
private
-
2
def named_route_exists?
-
23
named_route && set.named_routes[named_route]
-
end
-
-
2
def segment_keys
-
1
set.named_routes[named_route].segment_keys
-
end
-
end
-
-
# Generate the path indicated by the arguments, and return an array of
-
# the keys that were not used to generate it.
-
2
def extra_keys(options, recall={})
-
10
generate_extras(options, recall).last
-
end
-
-
2
def generate_extras(options, recall={})
-
10
generate(options, recall, true)
-
end
-
-
2
def generate(options, recall = {}, extras = false)
-
29
Generator.new(options, recall, self, extras).generate
-
end
-
-
2
RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
-
:trailing_slash, :anchor, :params, :only_path, :script_name]
-
-
2
def _generate_prefix(options = {})
-
nil
-
end
-
-
2
def url_for(options)
-
19
finalize!
-
19
options = (options || {}).reverse_merge!(default_url_options)
-
-
19
handle_positional_args(options)
-
-
19
user, password = extract_authentication(options)
-
19
path_segments = options.delete(:_path_segments)
-
19
script_name = options.delete(:script_name)
-
-
19
path = (script_name.blank? ? _generate_prefix(options) : script_name.chomp('/')).to_s
-
-
19
path_options = options.except(*RESERVED_OPTIONS)
-
19
path_options = yield(path_options) if block_given?
-
-
19
path_addition, params = generate(path_options, path_segments || {})
-
18
path << path_addition
-
18
params.merge!(options[:params] || {})
-
-
18
ActionDispatch::Http::URL.url_for(options.merge!({
-
:path => path,
-
:params => params,
-
:user => user,
-
:password => password
-
}))
-
end
-
-
2
def call(env)
-
finalize!
-
@router.call(env)
-
end
-
-
2
def recognize_path(path, environment = {})
-
method = (environment[:method] || "GET").to_s.upcase
-
path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://}
-
extras = environment[:extras] || {}
-
-
begin
-
env = Rack::MockRequest.env_for(path, {:method => method, :params => extras})
-
rescue URI::InvalidURIError => e
-
raise ActionController::RoutingError, e.message
-
end
-
-
req = @request_class.new(env)
-
@router.recognize(req) do |route, matches, params|
-
params.each do |key, value|
-
if value.is_a?(String)
-
value = value.dup.force_encoding(Encoding::BINARY) if value.encoding_aware?
-
params[key] = URI.parser.unescape(value)
-
end
-
end
-
-
dispatcher = route.app
-
while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do
-
dispatcher = dispatcher.app
-
end
-
-
if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params, false)
-
dispatcher.prepare_params!(params)
-
return params
-
end
-
end
-
-
raise ActionController::RoutingError, "No route matches #{path.inspect}"
-
end
-
-
2
private
-
-
2
def extract_authentication(options)
-
19
if options[:user] && options[:password]
-
[options.delete(:user), options.delete(:password)]
-
else
-
nil
-
end
-
end
-
-
2
def handle_positional_args(options)
-
19
return unless args = options.delete(:_positional_args)
-
-
1
keys = options.delete(:_positional_keys)
-
1
keys -= options.keys if args.size < keys.size - 1 # take format into account
-
-
# Tell url_for to skip default_url_options
-
2
options.merge!(Hash[args.zip(keys).map { |v, k| [k, v] }])
-
end
-
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Routing
-
# In <tt>config/routes.rb</tt> you define URL-to-controller mappings, but the reverse
-
# is also possible: an URL can be generated from one of your routing definitions.
-
# URL generation functionality is centralized in this module.
-
#
-
# See ActionDispatch::Routing for general information about routing and routes.rb.
-
#
-
# <b>Tip:</b> If you need to generate URLs from your models or some other place,
-
# then ActionController::UrlFor is what you're looking for. Read on for
-
# an introduction.
-
#
-
# == URL generation from parameters
-
#
-
# As you may know, some functions, such as ActionController::Base#url_for
-
# and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set
-
# of parameters. For example, you've probably had the chance to write code
-
# like this in one of your views:
-
#
-
# <%= link_to('Click here', :controller => 'users',
-
# :action => 'new', :message => 'Welcome!') %>
-
# # => "/users/new?message=Welcome%21"
-
#
-
# link_to, and all other functions that require URL generation functionality,
-
# actually use ActionController::UrlFor under the hood. And in particular,
-
# they use the ActionController::UrlFor#url_for method. One can generate
-
# the same path as the above example by using the following code:
-
#
-
# include UrlFor
-
# url_for(:controller => 'users',
-
# :action => 'new',
-
# :message => 'Welcome!',
-
# :only_path => true)
-
# # => "/users/new?message=Welcome%21"
-
#
-
# Notice the <tt>:only_path => true</tt> part. This is because UrlFor has no
-
# information about the website hostname that your Rails app is serving. So if you
-
# want to include the hostname as well, then you must also pass the <tt>:host</tt>
-
# argument:
-
#
-
# include UrlFor
-
# url_for(:controller => 'users',
-
# :action => 'new',
-
# :message => 'Welcome!',
-
# :host => 'www.example.com')
-
# # => "http://www.example.com/users/new?message=Welcome%21"
-
#
-
# By default, all controllers and views have access to a special version of url_for,
-
# that already knows what the current hostname is. So if you use url_for in your
-
# controllers or your views, then you don't need to explicitly pass the <tt>:host</tt>
-
# argument.
-
#
-
# For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for.
-
# So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlFor#url_for'
-
# in full. However, mailers don't have hostname information, and that's why you'll still
-
# have to specify the <tt>:host</tt> argument when generating URLs in mailers.
-
#
-
#
-
# == URL generation for named routes
-
#
-
# UrlFor also allows one to access methods that have been auto-generated from
-
# named routes. For example, suppose that you have a 'users' resource in your
-
# <tt>config/routes.rb</tt>:
-
#
-
# resources :users
-
#
-
# This generates, among other things, the method <tt>users_path</tt>. By default,
-
# this method is accessible from your controllers, views and mailers. If you need
-
# to access this auto-generated method from other places (such as a model), then
-
# you can do that by including ActionController::UrlFor in your class:
-
#
-
# class User < ActiveRecord::Base
-
# include Rails.application.routes.url_helpers
-
#
-
# def base_uri
-
# user_path(self)
-
# end
-
# end
-
#
-
# User.find(1).base_uri # => "/users/1"
-
#
-
2
module UrlFor
-
2
extend ActiveSupport::Concern
-
2
include PolymorphicRoutes
-
-
2
included do
-
# TODO: with_routing extends @controller with url_helpers, trickling down to including this module which overrides its default_url_options
-
13
unless method_defined?(:default_url_options)
-
# Including in a class uses an inheritable hash. Modules get a plain hash.
-
11
if respond_to?(:class_attribute)
-
11
class_attribute :default_url_options
-
else
-
mattr_accessor :default_url_options
-
remove_method :default_url_options
-
end
-
-
11
self.default_url_options = {}
-
end
-
end
-
-
2
def initialize(*)
-
56
@_routes = nil
-
56
super
-
end
-
-
2
def url_options
-
18
default_url_options
-
end
-
-
# Generate a url based on the options provided, default_url_options and the
-
# routes defined in routes.rb. The following options are supported:
-
#
-
# * <tt>:only_path</tt> - If true, the relative url is returned. Defaults to +false+.
-
# * <tt>:protocol</tt> - The protocol to connect to. Defaults to 'http'.
-
# * <tt>:host</tt> - Specifies the host the link should be targeted at.
-
# If <tt>:only_path</tt> is false, this option must be
-
# provided either explicitly, or via +default_url_options+.
-
# * <tt>:subdomain</tt> - Specifies the subdomain of the link, using the +tld_length+
-
# to split the subdomain from the host.
-
# If false, removes all subdomains from the host part of the link.
-
# * <tt>:domain</tt> - Specifies the domain of the link, using the +tld_length+
-
# to split the domain from the host.
-
# * <tt>:tld_length</tt> - Number of labels the TLD id composed of, only used if
-
# <tt>:subdomain</tt> or <tt>:domain</tt> are supplied. Defaults to
-
# <tt>ActionDispatch::Http::URL.tld_length</tt>, which in turn defaults to 1.
-
# * <tt>:port</tt> - Optionally specify the port to connect to.
-
# * <tt>:anchor</tt> - An anchor name to be appended to the path.
-
# * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2009/"
-
#
-
# Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to
-
# +url_for+ is forwarded to the Routes module.
-
#
-
# Examples:
-
#
-
# url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :port => '8080'
-
# # => 'http://somehost.org:8080/tasks/testing'
-
# url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :anchor => 'ok', :only_path => true
-
# # => '/tasks/testing#ok'
-
# url_for :controller => 'tasks', :action => 'testing', :trailing_slash => true
-
# # => 'http://somehost.org/tasks/testing/'
-
# url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :number => '33'
-
# # => 'http://somehost.org/tasks/testing?number=33'
-
2
def url_for(options = nil)
-
10
case options
-
when String
-
options
-
when nil, Hash
-
10
_routes.url_for((options || {}).symbolize_keys.reverse_merge!(url_options))
-
else
-
polymorphic_url(options)
-
end
-
end
-
-
2
protected
-
2
def _with_routes(routes)
-
old_routes, @_routes = @_routes, routes
-
yield
-
ensure
-
@_routes = old_routes
-
end
-
-
2
def _routes_context
-
self
-
end
-
end
-
end
-
end
-
2
module ActionDispatch
-
2
module Assertions
-
2
autoload :DomAssertions, 'action_dispatch/testing/assertions/dom'
-
2
autoload :ResponseAssertions, 'action_dispatch/testing/assertions/response'
-
2
autoload :RoutingAssertions, 'action_dispatch/testing/assertions/routing'
-
2
autoload :SelectorAssertions, 'action_dispatch/testing/assertions/selector'
-
2
autoload :TagAssertions, 'action_dispatch/testing/assertions/tag'
-
-
2
extend ActiveSupport::Concern
-
-
2
include DomAssertions
-
2
include ResponseAssertions
-
2
include RoutingAssertions
-
2
include SelectorAssertions
-
2
include TagAssertions
-
end
-
end
-
-
2
require 'action_controller/vendor/html-scanner'
-
-
2
module ActionDispatch
-
2
module Assertions
-
2
module DomAssertions
-
# \Test two HTML strings for equivalency (e.g., identical up to reordering of attributes)
-
#
-
# ==== Examples
-
#
-
# # assert that the referenced method generates the appropriate HTML string
-
# assert_dom_equal '<a href="http://www.example.com">Apples</a>', link_to("Apples", "http://www.example.com")
-
#
-
2
def assert_dom_equal(expected, actual, message = "")
-
expected_dom = HTML::Document.new(expected).root
-
actual_dom = HTML::Document.new(actual).root
-
full_message = build_message(message, "<?> expected to be == to\n<?>.", expected_dom.to_s, actual_dom.to_s)
-
-
assert_block(full_message) { expected_dom == actual_dom }
-
end
-
-
# The negated form of +assert_dom_equivalent+.
-
#
-
# ==== Examples
-
#
-
# # assert that the referenced method does not generate the specified HTML string
-
# assert_dom_not_equal '<a href="http://www.example.com">Apples</a>', link_to("Oranges", "http://www.example.com")
-
#
-
2
def assert_dom_not_equal(expected, actual, message = "")
-
expected_dom = HTML::Document.new(expected).root
-
actual_dom = HTML::Document.new(actual).root
-
full_message = build_message(message, "<?> expected to be != to\n<?>.", expected_dom.to_s, actual_dom.to_s)
-
-
assert_block(full_message) { expected_dom != actual_dom }
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/inclusion'
-
-
2
module ActionDispatch
-
2
module Assertions
-
# A small suite of assertions that test responses from \Rails applications.
-
2
module ResponseAssertions
-
2
extend ActiveSupport::Concern
-
-
# Asserts that the response is one of the following types:
-
#
-
# * <tt>:success</tt> - Status code was 200
-
# * <tt>:redirect</tt> - Status code was in the 300-399 range
-
# * <tt>:missing</tt> - Status code was 404
-
# * <tt>:error</tt> - Status code was in the 500-599 range
-
#
-
# You can also pass an explicit status number like <tt>assert_response(501)</tt>
-
# or its symbolic equivalent <tt>assert_response(:not_implemented)</tt>.
-
# See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list.
-
#
-
# ==== Examples
-
#
-
# # assert that the response was a redirection
-
# assert_response :redirect
-
#
-
# # assert that the response code was status code 401 (unauthorized)
-
# assert_response 401
-
#
-
2
def assert_response(type, message = nil)
-
6
validate_request!
-
-
6
if type.in?([:success, :missing, :redirect, :error]) && @response.send("#{type}?")
-
assert_block("") { true } # to count the assertion
-
6
elsif type.is_a?(Fixnum) && @response.response_code == type
-
assert_block("") { true } # to count the assertion
-
6
elsif type.is_a?(Symbol) && @response.response_code == Rack::Utils::SYMBOL_TO_STATUS_CODE[type]
-
assert_block("") { true } # to count the assertion
-
else
-
6
flunk(build_message(message, "Expected response to be a <?>, but was <?>", type, @response.response_code))
-
end
-
end
-
-
# Assert that the redirection options passed in match those of the redirect called in the latest action.
-
# This match can be partial, such that <tt>assert_redirected_to(:controller => "weblog")</tt> will also
-
# match the redirection of <tt>redirect_to(:controller => "weblog", :action => "show")</tt> and so on.
-
#
-
# ==== Examples
-
#
-
# # assert that the redirection was to the "index" action on the WeblogController
-
# assert_redirected_to :controller => "weblog", :action => "index"
-
#
-
# # assert that the redirection was to the named route login_url
-
# assert_redirected_to login_url
-
#
-
# # assert that the redirection was to the url for @customer
-
# assert_redirected_to @customer
-
#
-
2
def assert_redirected_to(options = {}, message=nil)
-
assert_response(:redirect, message)
-
return true if options == @response.location
-
-
redirect_is = normalize_argument_to_redirection(@response.location)
-
redirect_expected = normalize_argument_to_redirection(options)
-
-
if redirect_is != redirect_expected
-
flunk(build_message(message, "Expected response to be a redirect to <?> but was a redirect to <?>", redirect_expected, redirect_is))
-
end
-
end
-
-
2
private
-
# Proxy to to_param if the object will respond to it.
-
2
def parameterize(value)
-
value.respond_to?(:to_param) ? value.to_param : value
-
end
-
-
2
def normalize_argument_to_redirection(fragment)
-
case fragment
-
when %r{^\w[A-Za-z\d+.-]*:.*}
-
fragment
-
when String
-
@request.protocol + @request.host_with_port + fragment
-
when :back
-
raise RedirectBackError unless refer = @request.headers["Referer"]
-
refer
-
else
-
@controller.url_for(fragment)
-
end.gsub(/[\0\r\n]/, '')
-
end
-
-
2
def validate_request!
-
6
unless @request.is_a?(ActionDispatch::Request)
-
raise ArgumentError, "@request must be an ActionDispatch::Request"
-
end
-
end
-
end
-
end
-
end
-
2
require 'uri'
-
2
require 'active_support/core_ext/hash/diff'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
2
require 'action_controller/metal/exceptions'
-
-
2
module ActionDispatch
-
2
module Assertions
-
# Suite of assertions to test routes generated by \Rails and the handling of requests made to them.
-
2
module RoutingAssertions
-
# Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash)
-
# match +path+. Basically, it asserts that \Rails recognizes the route given by +expected_options+.
-
#
-
# Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes
-
# requiring a specific HTTP method. The hash should contain a :path with the incoming request path
-
# and a :method containing the required HTTP verb.
-
#
-
# # assert that POSTing to /items will call the create action on ItemsController
-
# assert_recognizes({:controller => 'items', :action => 'create'}, {:path => 'items', :method => :post})
-
#
-
# You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
-
# to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the
-
# extras argument, appending the query string on the path directly will not work. For example:
-
#
-
# # assert that a path of '/items/list/1?view=print' returns the correct options
-
# assert_recognizes({:controller => 'items', :action => 'list', :id => '1', :view => 'print'}, 'items/list/1', { :view => "print" })
-
#
-
# The +message+ parameter allows you to pass in an error message that is displayed upon failure.
-
#
-
# ==== Examples
-
# # Check the default route (i.e., the index action)
-
# assert_recognizes({:controller => 'items', :action => 'index'}, 'items')
-
#
-
# # Test a specific action
-
# assert_recognizes({:controller => 'items', :action => 'list'}, 'items/list')
-
#
-
# # Test an action with a parameter
-
# assert_recognizes({:controller => 'items', :action => 'destroy', :id => '1'}, 'items/destroy/1')
-
#
-
# # Test a custom route
-
# assert_recognizes({:controller => 'items', :action => 'show', :id => '1'}, 'view/item1')
-
2
def assert_recognizes(expected_options, path, extras={}, message=nil)
-
request = recognized_request_for(path, extras)
-
-
expected_options = expected_options.clone
-
extras.each_key { |key| expected_options.delete key } unless extras.nil?
-
-
expected_options.stringify_keys!
-
msg = build_message(message, "The recognized options <?> did not match <?>, difference: <?>",
-
request.path_parameters, expected_options, expected_options.diff(request.path_parameters))
-
assert_equal(expected_options, request.path_parameters, msg)
-
end
-
-
# Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+.
-
# The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in
-
# a query string. The +message+ parameter allows you to specify a custom error message for assertion failures.
-
#
-
# The +defaults+ parameter is unused.
-
#
-
# ==== Examples
-
# # Asserts that the default action is generated for a route with no action
-
# assert_generates "/items", :controller => "items", :action => "index"
-
#
-
# # Tests that the list action is properly routed
-
# assert_generates "/items/list", :controller => "items", :action => "list"
-
#
-
# # Tests the generation of a route with a parameter
-
# assert_generates "/items/list/1", { :controller => "items", :action => "list", :id => "1" }
-
#
-
# # Asserts that the generated route gives us our custom route
-
# assert_generates "changesets/12", { :controller => 'scm', :action => 'show_diff', :revision => "12" }
-
2
def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
-
if expected_path =~ %r{://}
-
begin
-
uri = URI.parse(expected_path)
-
expected_path = uri.path.to_s.empty? ? "/" : uri.path
-
rescue URI::InvalidURIError => e
-
raise ActionController::RoutingError, e.message
-
end
-
else
-
expected_path = "/#{expected_path}" unless expected_path.first == '/'
-
end
-
# Load routes.rb if it hasn't been loaded.
-
-
generated_path, extra_keys = @routes.generate_extras(options, defaults)
-
found_extras = options.reject {|k, v| ! extra_keys.include? k}
-
-
msg = build_message(message, "found extras <?>, not <?>", found_extras, extras)
-
assert_equal(extras, found_extras, msg)
-
-
msg = build_message(message, "The generated path <?> did not match <?>", generated_path,
-
expected_path)
-
assert_equal(expected_path, generated_path, msg)
-
end
-
-
# Asserts that path and options match both ways; in other words, it verifies that <tt>path</tt> generates
-
# <tt>options</tt> and then that <tt>options</tt> generates <tt>path</tt>. This essentially combines +assert_recognizes+
-
# and +assert_generates+ into one step.
-
#
-
# The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The
-
# +message+ parameter allows you to specify a custom error message to display upon failure.
-
#
-
# ==== Examples
-
# # Assert a basic route: a controller with the default action (index)
-
# assert_routing '/home', :controller => 'home', :action => 'index'
-
#
-
# # Test a route generated with a specific controller, action, and parameter (id)
-
# assert_routing '/entries/show/23', :controller => 'entries', :action => 'show', :id => 23
-
#
-
# # Assert a basic route (controller + default action), with an error message if it fails
-
# assert_routing '/store', { :controller => 'store', :action => 'index' }, {}, {}, 'Route for store index not generated properly'
-
#
-
# # Tests a route, providing a defaults hash
-
# assert_routing 'controller/action/9', {:id => "9", :item => "square"}, {:controller => "controller", :action => "action"}, {}, {:item => "square"}
-
#
-
# # Tests a route with a HTTP method
-
# assert_routing({ :method => 'put', :path => '/product/321' }, { :controller => "product", :action => "update", :id => "321" })
-
2
def assert_routing(path, options, defaults={}, extras={}, message=nil)
-
assert_recognizes(options, path, extras, message)
-
-
controller, default_controller = options[:controller], defaults[:controller]
-
if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
-
options[:controller] = "/#{controller}"
-
end
-
-
generate_options = options.dup.delete_if{ |k,v| defaults.key?(k) }
-
assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
-
end
-
-
# A helper to make it easier to test different route configurations.
-
# This method temporarily replaces @routes
-
# with a new RouteSet instance.
-
#
-
# The new instance is yielded to the passed block. Typically the block
-
# will create some routes using <tt>map.draw { map.connect ... }</tt>:
-
#
-
# with_routing do |set|
-
# set.draw do |map|
-
# map.connect ':controller/:action/:id'
-
# assert_equal(
-
# ['/content/10/show', {}],
-
# map.generate(:controller => 'content', :id => 10, :action => 'show')
-
# end
-
# end
-
# end
-
#
-
2
def with_routing
-
old_routes, @routes = @routes, ActionDispatch::Routing::RouteSet.new
-
if defined?(@controller) && @controller
-
old_controller, @controller = @controller, @controller.clone
-
_routes = @routes
-
-
# Unfortunately, there is currently an abstraction leak between AC::Base
-
# and AV::Base which requires having the URL helpers in both AC and AV.
-
# To do this safely at runtime for tests, we need to bump up the helper serial
-
# to that the old AV subclass isn't cached.
-
#
-
# TODO: Make this unnecessary
-
@controller.singleton_class.send(:include, _routes.url_helpers)
-
@controller.view_context_class = Class.new(@controller.view_context_class) do
-
include _routes.url_helpers
-
end
-
end
-
yield @routes
-
ensure
-
@routes = old_routes
-
if defined?(@controller) && @controller
-
@controller = old_controller
-
end
-
end
-
-
# ROUTES TODO: These assertions should really work in an integration context
-
2
def method_missing(selector, *args, &block)
-
1
if defined?(@controller) && @controller && @routes && @routes.named_routes.helpers.include?(selector)
-
1
@controller.send(selector, *args, &block)
-
else
-
super
-
end
-
end
-
-
2
private
-
# Recognizes the route for a given path.
-
2
def recognized_request_for(path, extras = {})
-
if path.is_a?(Hash)
-
method = path[:method]
-
path = path[:path]
-
else
-
method = :get
-
end
-
-
# Assume given controller
-
request = ActionController::TestRequest.new
-
-
if path =~ %r{://}
-
begin
-
uri = URI.parse(path)
-
request.env["rack.url_scheme"] = uri.scheme || "http"
-
request.host = uri.host if uri.host
-
request.port = uri.port if uri.port
-
request.path = uri.path.to_s.empty? ? "/" : uri.path
-
rescue URI::InvalidURIError => e
-
raise ActionController::RoutingError, e.message
-
end
-
else
-
path = "/#{path}" unless path.first == "/"
-
request.path = path
-
end
-
-
request.request_method = method if method
-
-
params = @routes.recognize_path(path, { :method => method, :extras => extras })
-
request.path_parameters = params.with_indifferent_access
-
-
request
-
end
-
end
-
end
-
end
-
2
require 'action_controller/vendor/html-scanner'
-
2
require 'active_support/core_ext/object/inclusion'
-
-
#--
-
# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
-
# Under MIT and/or CC By license.
-
#++
-
-
2
module ActionDispatch
-
2
module Assertions
-
2
NO_STRIP = %w{pre script style textarea}
-
-
# Adds the +assert_select+ method for use in Rails functional
-
# test cases, which can be used to make assertions on the response HTML of a controller
-
# action. You can also call +assert_select+ within another +assert_select+ to
-
# make assertions on elements selected by the enclosing assertion.
-
#
-
# Use +css_select+ to select elements without making an assertions, either
-
# from the response HTML or elements selected by the enclosing assertion.
-
#
-
# In addition to HTML responses, you can make the following assertions:
-
#
-
# * +assert_select_encoded+ - Assertions on HTML encoded inside XML, for example for dealing with feed item descriptions.
-
# * +assert_select_email+ - Assertions on the HTML body of an e-mail.
-
#
-
# Also see HTML::Selector to learn how to use selectors.
-
2
module SelectorAssertions
-
# Select and return all matching elements.
-
#
-
# If called with a single argument, uses that argument as a selector
-
# to match all elements of the current page. Returns an empty array
-
# if no match is found.
-
#
-
# If called with two arguments, uses the first argument as the base
-
# element and the second argument as the selector. Attempts to match the
-
# base element and any of its children. Returns an empty array if no
-
# match is found.
-
#
-
# The selector may be a CSS selector expression (String), an expression
-
# with substitution values (Array) or an HTML::Selector object.
-
#
-
# ==== Examples
-
# # Selects all div tags
-
# divs = css_select("div")
-
#
-
# # Selects all paragraph tags and does something interesting
-
# pars = css_select("p")
-
# pars.each do |par|
-
# # Do something fun with paragraphs here...
-
# end
-
#
-
# # Selects all list items in unordered lists
-
# items = css_select("ul>li")
-
#
-
# # Selects all form tags and then all inputs inside the form
-
# forms = css_select("form")
-
# forms.each do |form|
-
# inputs = css_select(form, "input")
-
# ...
-
# end
-
#
-
2
def css_select(*args)
-
# See assert_select to understand what's going on here.
-
arg = args.shift
-
-
if arg.is_a?(HTML::Node)
-
root = arg
-
arg = args.shift
-
elsif arg == nil
-
raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
-
elsif defined?(@selected) && @selected
-
matches = []
-
-
@selected.each do |selected|
-
subset = css_select(selected, HTML::Selector.new(arg.dup, args.dup))
-
subset.each do |match|
-
matches << match unless matches.any? { |m| m.equal?(match) }
-
end
-
end
-
-
return matches
-
else
-
root = response_from_page
-
end
-
-
case arg
-
when String
-
selector = HTML::Selector.new(arg, args)
-
when Array
-
selector = HTML::Selector.new(*arg)
-
when HTML::Selector
-
selector = arg
-
else raise ArgumentError, "Expecting a selector as the first argument"
-
end
-
-
selector.select(root)
-
end
-
-
# An assertion that selects elements and makes one or more equality tests.
-
#
-
# If the first argument is an element, selects all matching elements
-
# starting from (and including) that element and all its children in
-
# depth-first order.
-
#
-
# If no element if specified, calling +assert_select+ selects from the
-
# response HTML unless +assert_select+ is called from within an +assert_select+ block.
-
#
-
# When called with a block +assert_select+ passes an array of selected elements
-
# to the block. Calling +assert_select+ from the block, with no element specified,
-
# runs the assertion on the complete set of elements selected by the enclosing assertion.
-
# Alternatively the array may be iterated through so that +assert_select+ can be called
-
# separately for each element.
-
#
-
#
-
# ==== Example
-
# If the response contains two ordered lists, each with four list elements then:
-
# assert_select "ol" do |elements|
-
# elements.each do |element|
-
# assert_select element, "li", 4
-
# end
-
# end
-
#
-
# will pass, as will:
-
# assert_select "ol" do
-
# assert_select "li", 8
-
# end
-
#
-
# The selector may be a CSS selector expression (String), an expression
-
# with substitution values, or an HTML::Selector object.
-
#
-
# === Equality Tests
-
#
-
# The equality test may be one of the following:
-
# * <tt>true</tt> - Assertion is true if at least one element selected.
-
# * <tt>false</tt> - Assertion is true if no element selected.
-
# * <tt>String/Regexp</tt> - Assertion is true if the text value of at least
-
# one element matches the string or regular expression.
-
# * <tt>Integer</tt> - Assertion is true if exactly that number of
-
# elements are selected.
-
# * <tt>Range</tt> - Assertion is true if the number of selected
-
# elements fit the range.
-
# If no equality test specified, the assertion is true if at least one
-
# element selected.
-
#
-
# To perform more than one equality tests, use a hash with the following keys:
-
# * <tt>:text</tt> - Narrow the selection to elements that have this text
-
# value (string or regexp).
-
# * <tt>:html</tt> - Narrow the selection to elements that have this HTML
-
# content (string or regexp).
-
# * <tt>:count</tt> - Assertion is true if the number of selected elements
-
# is equal to this value.
-
# * <tt>:minimum</tt> - Assertion is true if the number of selected
-
# elements is at least this value.
-
# * <tt>:maximum</tt> - Assertion is true if the number of selected
-
# elements is at most this value.
-
#
-
# If the method is called with a block, once all equality tests are
-
# evaluated the block is called with an array of all matched elements.
-
#
-
# ==== Examples
-
#
-
# # At least one form element
-
# assert_select "form"
-
#
-
# # Form element includes four input fields
-
# assert_select "form input", 4
-
#
-
# # Page title is "Welcome"
-
# assert_select "title", "Welcome"
-
#
-
# # Page title is "Welcome" and there is only one title element
-
# assert_select "title", {:count => 1, :text => "Welcome"},
-
# "Wrong title or more than one title element"
-
#
-
# # Page contains no forms
-
# assert_select "form", false, "This page must contain no forms"
-
#
-
# # Test the content and style
-
# assert_select "body div.header ul.menu"
-
#
-
# # Use substitution values
-
# assert_select "ol>li#?", /item-\d+/
-
#
-
# # All input fields in the form have a name
-
# assert_select "form input" do
-
# assert_select "[name=?]", /.+/ # Not empty
-
# end
-
2
def assert_select(*args, &block)
-
# Start with optional element followed by mandatory selector.
-
arg = args.shift
-
@selected ||= nil
-
-
if arg.is_a?(HTML::Node)
-
# First argument is a node (tag or text, but also HTML root),
-
# so we know what we're selecting from.
-
root = arg
-
arg = args.shift
-
elsif arg == nil
-
# This usually happens when passing a node/element that
-
# happens to be nil.
-
raise ArgumentError, "First argument is either selector or element to select, but nil found. Perhaps you called assert_select with an element that does not exist?"
-
elsif @selected
-
root = HTML::Node.new(nil)
-
root.children.concat @selected
-
else
-
# Otherwise just operate on the response document.
-
root = response_from_page
-
end
-
-
# First or second argument is the selector: string and we pass
-
# all remaining arguments. Array and we pass the argument. Also
-
# accepts selector itself.
-
case arg
-
when String
-
selector = HTML::Selector.new(arg, args)
-
when Array
-
selector = HTML::Selector.new(*arg)
-
when HTML::Selector
-
selector = arg
-
else raise ArgumentError, "Expecting a selector as the first argument"
-
end
-
-
# Next argument is used for equality tests.
-
equals = {}
-
case arg = args.shift
-
when Hash
-
equals = arg
-
when String, Regexp
-
equals[:text] = arg
-
when Integer
-
equals[:count] = arg
-
when Range
-
equals[:minimum] = arg.begin
-
equals[:maximum] = arg.end
-
when FalseClass
-
equals[:count] = 0
-
when NilClass, TrueClass
-
equals[:minimum] = 1
-
else raise ArgumentError, "I don't understand what you're trying to match"
-
end
-
-
# By default we're looking for at least one match.
-
if equals[:count]
-
equals[:minimum] = equals[:maximum] = equals[:count]
-
else
-
equals[:minimum] = 1 unless equals[:minimum]
-
end
-
-
# Last argument is the message we use if the assertion fails.
-
message = args.shift
-
#- message = "No match made with selector #{selector.inspect}" unless message
-
if args.shift
-
raise ArgumentError, "Not expecting that last argument, you either have too many arguments, or they're the wrong type"
-
end
-
-
matches = selector.select(root)
-
# If text/html, narrow down to those elements that match it.
-
content_mismatch = nil
-
if match_with = equals[:text]
-
matches.delete_if do |match|
-
text = ""
-
stack = match.children.reverse
-
while node = stack.pop
-
if node.tag?
-
stack.concat node.children.reverse
-
else
-
content = node.content
-
text << content
-
end
-
end
-
text.strip! unless NO_STRIP.include?(match.name)
-
text.sub!(/\A\n/, '') if match.name == "textarea"
-
unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s)
-
content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, text)
-
true
-
end
-
end
-
elsif match_with = equals[:html]
-
matches.delete_if do |match|
-
html = match.children.map(&:to_s).join
-
html.strip! unless NO_STRIP.include?(match.name)
-
unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s)
-
content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, html)
-
true
-
end
-
end
-
end
-
# Expecting foo found bar element only if found zero, not if
-
# found one but expecting two.
-
message ||= content_mismatch if matches.empty?
-
# Test minimum/maximum occurrence.
-
min, max, count = equals[:minimum], equals[:maximum], equals[:count]
-
message = message || %(Expected #{count_description(min, max, count)} matching "#{selector.to_s}", found #{matches.size}.)
-
if count
-
assert matches.size == count, message
-
else
-
assert matches.size >= min, message if min
-
assert matches.size <= max, message if max
-
end
-
-
# If a block is given call that block. Set @selected to allow
-
# nested assert_select, which can be nested several levels deep.
-
if block_given? && !matches.empty?
-
begin
-
in_scope, @selected = @selected, matches
-
yield matches
-
ensure
-
@selected = in_scope
-
end
-
end
-
-
# Returns all matches elements.
-
matches
-
end
-
-
2
def count_description(min, max, count) #:nodoc:
-
pluralize = lambda {|word, quantity| word << (quantity == 1 ? '' : 's')}
-
-
if min && max && (max != min)
-
"between #{min} and #{max} elements"
-
elsif min && max && max == min && count
-
"exactly #{count} #{pluralize['element', min]}"
-
elsif min && !(min == 1 && max == 1)
-
"at least #{min} #{pluralize['element', min]}"
-
elsif max
-
"at most #{max} #{pluralize['element', max]}"
-
end
-
end
-
-
# Extracts the content of an element, treats it as encoded HTML and runs
-
# nested assertion on it.
-
#
-
# You typically call this method within another assertion to operate on
-
# all currently selected elements. You can also pass an element or array
-
# of elements.
-
#
-
# The content of each element is un-encoded, and wrapped in the root
-
# element +encoded+. It then calls the block with all un-encoded elements.
-
#
-
# ==== Examples
-
# # Selects all bold tags from within the title of an ATOM feed's entries (perhaps to nab a section name prefix)
-
# assert_select_feed :atom, 1.0 do
-
# # Select each entry item and then the title item
-
# assert_select "entry>title" do
-
# # Run assertions on the encoded title elements
-
# assert_select_encoded do
-
# assert_select "b"
-
# end
-
# end
-
# end
-
#
-
#
-
# # Selects all paragraph tags from within the description of an RSS feed
-
# assert_select_feed :rss, 2.0 do
-
# # Select description element of each feed item.
-
# assert_select "channel>item>description" do
-
# # Run assertions on the encoded elements.
-
# assert_select_encoded do
-
# assert_select "p"
-
# end
-
# end
-
# end
-
2
def assert_select_encoded(element = nil, &block)
-
case element
-
when Array
-
elements = element
-
when HTML::Node
-
elements = [element]
-
when nil
-
unless elements = @selected
-
raise ArgumentError, "First argument is optional, but must be called from a nested assert_select"
-
end
-
else
-
raise ArgumentError, "Argument is optional, and may be node or array of nodes"
-
end
-
-
fix_content = lambda do |node|
-
# Gets around a bug in the Rails 1.1 HTML parser.
-
node.content.gsub(/<!\[CDATA\[(.*)(\]\]>)?/m) { Rack::Utils.escapeHTML($1) }
-
end
-
-
selected = elements.map do |_element|
-
text = _element.children.select{ |c| not c.tag? }.map{ |c| fix_content[c] }.join
-
root = HTML::Document.new(CGI.unescapeHTML("<encoded>#{text}</encoded>")).root
-
css_select(root, "encoded:root", &block)[0]
-
end
-
-
begin
-
old_selected, @selected = @selected, selected
-
assert_select ":root", &block
-
ensure
-
@selected = old_selected
-
end
-
end
-
-
# Extracts the body of an email and runs nested assertions on it.
-
#
-
# You must enable deliveries for this assertion to work, use:
-
# ActionMailer::Base.perform_deliveries = true
-
#
-
# ==== Examples
-
#
-
# assert_select_email do
-
# assert_select "h1", "Email alert"
-
# end
-
#
-
# assert_select_email do
-
# items = assert_select "ol>li"
-
# items.each do
-
# # Work with items here...
-
# end
-
# end
-
#
-
2
def assert_select_email(&block)
-
deliveries = ActionMailer::Base.deliveries
-
assert !deliveries.empty?, "No e-mail in delivery list"
-
-
for delivery in deliveries
-
for part in (delivery.parts.empty? ? [delivery] : delivery.parts)
-
if part["Content-Type"].to_s =~ /^text\/html\W/
-
root = HTML::Document.new(part.body.to_s).root
-
assert_select root, ":root", &block
-
end
-
end
-
end
-
end
-
-
2
protected
-
# +assert_select+ and +css_select+ call this to obtain the content in the HTML page.
-
2
def response_from_page
-
html_document.root
-
end
-
end
-
end
-
end
-
2
require 'action_controller/vendor/html-scanner'
-
-
2
module ActionDispatch
-
2
module Assertions
-
# Pair of assertions to testing elements in the HTML output of the response.
-
2
module TagAssertions
-
# Asserts that there is a tag/node/element in the body of the response
-
# that meets all of the given conditions. The +conditions+ parameter must
-
# be a hash of any of the following keys (all are optional):
-
#
-
# * <tt>:tag</tt>: the node type must match the corresponding value
-
# * <tt>:attributes</tt>: a hash. The node's attributes must match the
-
# corresponding values in the hash.
-
# * <tt>:parent</tt>: a hash. The node's parent must match the
-
# corresponding hash.
-
# * <tt>:child</tt>: a hash. At least one of the node's immediate children
-
# must meet the criteria described by the hash.
-
# * <tt>:ancestor</tt>: a hash. At least one of the node's ancestors must
-
# meet the criteria described by the hash.
-
# * <tt>:descendant</tt>: a hash. At least one of the node's descendants
-
# must meet the criteria described by the hash.
-
# * <tt>:sibling</tt>: a hash. At least one of the node's siblings must
-
# meet the criteria described by the hash.
-
# * <tt>:after</tt>: a hash. The node must be after any sibling meeting
-
# the criteria described by the hash, and at least one sibling must match.
-
# * <tt>:before</tt>: a hash. The node must be before any sibling meeting
-
# the criteria described by the hash, and at least one sibling must match.
-
# * <tt>:children</tt>: a hash, for counting children of a node. Accepts
-
# the keys:
-
# * <tt>:count</tt>: either a number or a range which must equal (or
-
# include) the number of children that match.
-
# * <tt>:less_than</tt>: the number of matching children must be less
-
# than this number.
-
# * <tt>:greater_than</tt>: the number of matching children must be
-
# greater than this number.
-
# * <tt>:only</tt>: another hash consisting of the keys to use
-
# to match on the children, and only matching children will be
-
# counted.
-
# * <tt>:content</tt>: the textual content of the node must match the
-
# given value. This will not match HTML tags in the body of a
-
# tag--only text.
-
#
-
# Conditions are matched using the following algorithm:
-
#
-
# * if the condition is a string, it must be a substring of the value.
-
# * if the condition is a regexp, it must match the value.
-
# * if the condition is a number, the value must match number.to_s.
-
# * if the condition is +true+, the value must not be +nil+.
-
# * if the condition is +false+ or +nil+, the value must be +nil+.
-
#
-
# === Examples
-
#
-
# # Assert that there is a "span" tag
-
# assert_tag :tag => "span"
-
#
-
# # Assert that there is a "span" tag with id="x"
-
# assert_tag :tag => "span", :attributes => { :id => "x" }
-
#
-
# # Assert that there is a "span" tag using the short-hand
-
# assert_tag :span
-
#
-
# # Assert that there is a "span" tag with id="x" using the short-hand
-
# assert_tag :span, :attributes => { :id => "x" }
-
#
-
# # Assert that there is a "span" inside of a "div"
-
# assert_tag :tag => "span", :parent => { :tag => "div" }
-
#
-
# # Assert that there is a "span" somewhere inside a table
-
# assert_tag :tag => "span", :ancestor => { :tag => "table" }
-
#
-
# # Assert that there is a "span" with at least one "em" child
-
# assert_tag :tag => "span", :child => { :tag => "em" }
-
#
-
# # Assert that there is a "span" containing a (possibly nested)
-
# # "strong" tag.
-
# assert_tag :tag => "span", :descendant => { :tag => "strong" }
-
#
-
# # Assert that there is a "span" containing between 2 and 4 "em" tags
-
# # as immediate children
-
# assert_tag :tag => "span",
-
# :children => { :count => 2..4, :only => { :tag => "em" } }
-
#
-
# # Get funky: assert that there is a "div", with an "ul" ancestor
-
# # and an "li" parent (with "class" = "enum"), and containing a
-
# # "span" descendant that contains text matching /hello world/
-
# assert_tag :tag => "div",
-
# :ancestor => { :tag => "ul" },
-
# :parent => { :tag => "li",
-
# :attributes => { :class => "enum" } },
-
# :descendant => { :tag => "span",
-
# :child => /hello world/ }
-
#
-
# <b>Please note</b>: +assert_tag+ and +assert_no_tag+ only work
-
# with well-formed XHTML. They recognize a few tags as implicitly self-closing
-
# (like br and hr and such) but will not work correctly with tags
-
# that allow optional closing tags (p, li, td). <em>You must explicitly
-
# close all of your tags to use these assertions.</em>
-
2
def assert_tag(*opts)
-
opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
-
tag = find_tag(opts)
-
assert tag, "expected tag, but no tag found matching #{opts.inspect} in:\n#{@response.body.inspect}"
-
end
-
-
# Identical to +assert_tag+, but asserts that a matching tag does _not_
-
# exist. (See +assert_tag+ for a full discussion of the syntax.)
-
#
-
# === Examples
-
# # Assert that there is not a "div" containing a "p"
-
# assert_no_tag :tag => "div", :descendant => { :tag => "p" }
-
#
-
# # Assert that an unordered list is empty
-
# assert_no_tag :tag => "ul", :descendant => { :tag => "li" }
-
#
-
# # Assert that there is not a "p" tag with between 1 to 3 "img" tags
-
# # as immediate children
-
# assert_no_tag :tag => "p",
-
# :children => { :count => 1..3, :only => { :tag => "img" } }
-
2
def assert_no_tag(*opts)
-
opts = opts.size > 1 ? opts.last.merge({ :tag => opts.first.to_s }) : opts.first
-
tag = find_tag(opts)
-
assert !tag, "expected no tag, but found tag matching #{opts.inspect} in:\n#{@response.body.inspect}"
-
end
-
-
2
def find_tag(conditions)
-
html_document.find(conditions)
-
end
-
-
2
def find_all_tag(conditions)
-
html_document.find_all(conditions)
-
end
-
-
2
def html_document
-
xml = @response.content_type =~ /xml$/
-
@html_document ||= HTML::Document.new(@response.body, false, xml)
-
end
-
end
-
end
-
end
-
2
require 'stringio'
-
2
require 'uri'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'active_support/core_ext/object/inclusion'
-
2
require 'active_support/core_ext/object/try'
-
2
require 'rack/test'
-
2
require 'test/unit/assertions'
-
-
2
module ActionDispatch
-
2
module Integration #:nodoc:
-
2
module RequestHelpers
-
# Performs a GET request with the given parameters.
-
#
-
# - +path+: The URI (as a String) on which you want to perform a GET
-
# request.
-
# - +parameters+: The HTTP parameters that you want to pass. This may
-
# be +nil+,
-
# a Hash, or a String that is appropriately encoded
-
# (<tt>application/x-www-form-urlencoded</tt> or
-
# <tt>multipart/form-data</tt>).
-
# - +headers+: Additional headers to pass, as a Hash. The headers will be
-
# merged into the Rack env hash.
-
#
-
# This method returns an Response object, which one can use to
-
# inspect the details of the response. Furthermore, if this method was
-
# called from an ActionDispatch::IntegrationTest object, then that
-
# object's <tt>@response</tt> instance variable will point to the same
-
# response object.
-
#
-
# You can also perform POST, PUT, DELETE, and HEAD requests with +#post+,
-
# +#put+, +#delete+, and +#head+.
-
2
def get(path, parameters = nil, headers = nil)
-
process :get, path, parameters, headers
-
end
-
-
# Performs a POST request with the given parameters. See +#get+ for more
-
# details.
-
2
def post(path, parameters = nil, headers = nil)
-
process :post, path, parameters, headers
-
end
-
-
# Performs a PUT request with the given parameters. See +#get+ for more
-
# details.
-
2
def put(path, parameters = nil, headers = nil)
-
process :put, path, parameters, headers
-
end
-
-
# Performs a DELETE request with the given parameters. See +#get+ for
-
# more details.
-
2
def delete(path, parameters = nil, headers = nil)
-
process :delete, path, parameters, headers
-
end
-
-
# Performs a HEAD request with the given parameters. See +#get+ for more
-
# details.
-
2
def head(path, parameters = nil, headers = nil)
-
process :head, path, parameters, headers
-
end
-
-
# Performs an XMLHttpRequest request with the given parameters, mirroring
-
# a request from the Prototype library.
-
#
-
# The request_method is +:get+, +:post+, +:put+, +:delete+ or +:head+; the
-
# parameters are +nil+, a hash, or a url-encoded or multipart string;
-
# the headers are a hash.
-
2
def xml_http_request(request_method, path, parameters = nil, headers = nil)
-
headers ||= {}
-
headers['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
-
headers['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
-
process(request_method, path, parameters, headers)
-
end
-
2
alias xhr :xml_http_request
-
-
# Follow a single redirect response. If the last response was not a
-
# redirect, an exception will be raised. Otherwise, the redirect is
-
# performed on the location header.
-
2
def follow_redirect!
-
raise "not a redirect! #{status} #{status_message}" unless redirect?
-
get(response.location)
-
status
-
end
-
-
# Performs a request using the specified method, following any subsequent
-
# redirect. Note that the redirects are followed until the response is
-
# not a redirect--this means you may run into an infinite loop if your
-
# redirect loops back to itself.
-
2
def request_via_redirect(http_method, path, parameters = nil, headers = nil)
-
process(http_method, path, parameters, headers)
-
follow_redirect! while redirect?
-
status
-
end
-
-
# Performs a GET request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
2
def get_via_redirect(path, parameters = nil, headers = nil)
-
request_via_redirect(:get, path, parameters, headers)
-
end
-
-
# Performs a POST request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
2
def post_via_redirect(path, parameters = nil, headers = nil)
-
request_via_redirect(:post, path, parameters, headers)
-
end
-
-
# Performs a PUT request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
2
def put_via_redirect(path, parameters = nil, headers = nil)
-
request_via_redirect(:put, path, parameters, headers)
-
end
-
-
# Performs a DELETE request, following any subsequent redirect.
-
# See +request_via_redirect+ for more information.
-
2
def delete_via_redirect(path, parameters = nil, headers = nil)
-
request_via_redirect(:delete, path, parameters, headers)
-
end
-
end
-
-
# An instance of this class represents a set of requests and responses
-
# performed sequentially by a test process. Because you can instantiate
-
# multiple sessions and run them side-by-side, you can also mimic (to some
-
# limited extent) multiple simultaneous users interacting with your system.
-
#
-
# Typically, you will instantiate a new session using
-
# IntegrationTest#open_session, rather than instantiating
-
# Integration::Session directly.
-
2
class Session
-
2
DEFAULT_HOST = "www.example.com"
-
-
2
include Test::Unit::Assertions
-
2
include TestProcess, RequestHelpers, Assertions
-
-
2
%w( status status_message headers body redirect? ).each do |method|
-
10
delegate method, :to => :response, :allow_nil => true
-
end
-
-
2
%w( path ).each do |method|
-
2
delegate method, :to => :request, :allow_nil => true
-
end
-
-
# The hostname used in the last request.
-
2
def host
-
@host || DEFAULT_HOST
-
end
-
2
attr_writer :host
-
-
# The remote_addr used in the last request.
-
2
attr_accessor :remote_addr
-
-
# The Accept header to send.
-
2
attr_accessor :accept
-
-
# A map of the cookies returned by the last response, and which will be
-
# sent with the next request.
-
2
def cookies
-
_mock_session.cookie_jar
-
end
-
-
# A reference to the controller instance used by the last request.
-
2
attr_reader :controller
-
-
# A reference to the request instance used by the last request.
-
2
attr_reader :request
-
-
# A reference to the response instance used by the last request.
-
2
attr_reader :response
-
-
# A running counter of the number of requests processed.
-
2
attr_accessor :request_count
-
-
2
include ActionDispatch::Routing::UrlFor
-
-
# Create and initialize a new Session instance.
-
2
def initialize(app)
-
super()
-
@app = app
-
-
# If the app is a Rails app, make url_helpers available on the session
-
# This makes app.url_for and app.foo_path available in the console
-
if app.respond_to?(:routes)
-
singleton_class.class_eval do
-
include app.routes.url_helpers if app.routes.respond_to?(:url_helpers)
-
include app.routes.mounted_helpers if app.routes.respond_to?(:mounted_helpers)
-
end
-
end
-
-
reset!
-
end
-
-
2
def url_options
-
@url_options ||= default_url_options.dup.tap do |url_options|
-
url_options.reverse_merge!(controller.url_options) if controller
-
-
if @app.respond_to?(:routes) && @app.routes.respond_to?(:default_url_options)
-
url_options.reverse_merge!(@app.routes.default_url_options)
-
end
-
-
url_options.reverse_merge!(:host => host, :protocol => https? ? "https" : "http")
-
end
-
end
-
-
# Resets the instance. This can be used to reset the state information
-
# in an existing session instance, so it can be used from a clean-slate
-
# condition.
-
#
-
# session.reset!
-
2
def reset!
-
@https = false
-
@controller = @request = @response = nil
-
@_mock_session = nil
-
@request_count = 0
-
@url_options = nil
-
-
self.host = DEFAULT_HOST
-
self.remote_addr = "127.0.0.1"
-
self.accept = "text/xml,application/xml,application/xhtml+xml," +
-
"text/html;q=0.9,text/plain;q=0.8,image/png," +
-
"*/*;q=0.5"
-
-
unless defined? @named_routes_configured
-
# the helpers are made protected by default--we make them public for
-
# easier access during testing and troubleshooting.
-
@named_routes_configured = true
-
end
-
end
-
-
# Specify whether or not the session should mimic a secure HTTPS request.
-
#
-
# session.https!
-
# session.https!(false)
-
2
def https!(flag = true)
-
@https = flag
-
end
-
-
# Return +true+ if the session is mimicking a secure HTTPS request.
-
#
-
# if session.https?
-
# ...
-
# end
-
2
def https?
-
@https
-
end
-
-
# Set the host name to use in the next request.
-
#
-
# session.host! "www.example.com"
-
2
alias :host! :host=
-
-
2
private
-
2
def _mock_session
-
@_mock_session ||= Rack::MockSession.new(@app, host)
-
end
-
-
# Performs the actual request.
-
2
def process(method, path, parameters = nil, rack_env = nil)
-
rack_env ||= {}
-
if path =~ %r{://}
-
location = URI.parse(path)
-
https! URI::HTTPS === location if location.scheme
-
host! location.host if location.host
-
path = location.query ? "#{location.path}?#{location.query}" : location.path
-
end
-
-
unless ActionController::Base < ActionController::Testing
-
ActionController::Base.class_eval do
-
include ActionController::Testing
-
end
-
end
-
-
hostname, port = host.split(':')
-
-
env = {
-
:method => method,
-
:params => parameters,
-
-
"SERVER_NAME" => hostname,
-
"SERVER_PORT" => port || (https? ? "443" : "80"),
-
"HTTPS" => https? ? "on" : "off",
-
"rack.url_scheme" => https? ? "https" : "http",
-
-
"REQUEST_URI" => path,
-
"HTTP_HOST" => host,
-
"REMOTE_ADDR" => remote_addr,
-
"CONTENT_TYPE" => "application/x-www-form-urlencoded",
-
"HTTP_ACCEPT" => accept
-
}
-
-
session = Rack::Test::Session.new(_mock_session)
-
-
env.merge!(rack_env)
-
-
# NOTE: rack-test v0.5 doesn't build a default uri correctly
-
# Make sure requested path is always a full uri
-
uri = URI.parse('/')
-
uri.scheme ||= env['rack.url_scheme']
-
uri.host ||= env['SERVER_NAME']
-
uri.port ||= env['SERVER_PORT'].try(:to_i)
-
uri += path
-
-
session.request(uri.to_s, env)
-
-
@request_count += 1
-
@request = ActionDispatch::Request.new(session.last_request.env)
-
response = _mock_session.last_response
-
@response = ActionDispatch::TestResponse.new(response.status, response.headers, response.body)
-
@html_document = nil
-
@url_options = nil
-
-
@controller = session.last_request.env['action_controller.instance']
-
-
return response.status
-
end
-
end
-
-
2
module Runner
-
2
include ActionDispatch::Assertions
-
-
2
def app
-
@app ||= nil
-
end
-
-
# Reset the current session. This is useful for testing multiple sessions
-
# in a single test case.
-
2
def reset!
-
@integration_session = Integration::Session.new(app)
-
end
-
-
2
%w(get post put head delete cookies assigns
-
xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
-
22
define_method(method) do |*args|
-
reset! unless integration_session
-
# reset the html_document variable, but only for new get/post calls
-
@html_document = nil unless method.in?(["cookies", "assigns"])
-
integration_session.__send__(method, *args).tap do
-
copy_session_variables!
-
end
-
end
-
end
-
-
# Open a new session instance. If a block is given, the new session is
-
# yielded to the block before being returned.
-
#
-
# session = open_session do |sess|
-
# sess.extend(CustomAssertions)
-
# end
-
#
-
# By default, a single session is automatically created for you, but you
-
# can use this method to open multiple sessions that ought to be tested
-
# simultaneously.
-
2
def open_session(app = nil)
-
dup.tap do |session|
-
yield session if block_given?
-
end
-
end
-
-
# Copy the instance variables from the current session instance into the
-
# test instance.
-
2
def copy_session_variables! #:nodoc:
-
return unless integration_session
-
%w(controller response request).each do |var|
-
instance_variable_set("@#{var}", @integration_session.__send__(var))
-
end
-
end
-
-
2
def default_url_options
-
reset! unless integration_session
-
integration_session.default_url_options
-
end
-
-
2
def default_url_options=(options)
-
integration_session.url_options
-
integration_session.default_url_options = options
-
end
-
-
2
def respond_to?(method, include_private = false)
-
integration_session.respond_to?(method, include_private) || super
-
end
-
-
# Delegate unhandled messages to the current session instance.
-
2
def method_missing(sym, *args, &block)
-
reset! unless integration_session
-
if integration_session.respond_to?(sym)
-
integration_session.__send__(sym, *args, &block).tap do
-
copy_session_variables!
-
end
-
else
-
super
-
end
-
end
-
-
2
private
-
2
def integration_session
-
@integration_session ||= nil
-
end
-
end
-
end
-
-
# An integration test spans multiple controllers and actions,
-
# tying them all together to ensure they work together as expected. It tests
-
# more completely than either unit or functional tests do, exercising the
-
# entire stack, from the dispatcher to the database.
-
#
-
# At its simplest, you simply extend <tt>IntegrationTest</tt> and write your tests
-
# using the get/post methods:
-
#
-
# require "test_helper"
-
#
-
# class ExampleTest < ActionDispatch::IntegrationTest
-
# fixtures :people
-
#
-
# def test_login
-
# # get the login page
-
# get "/login"
-
# assert_equal 200, status
-
#
-
# # post the login and follow through to the home page
-
# post "/login", :username => people(:jamis).username,
-
# :password => people(:jamis).password
-
# follow_redirect!
-
# assert_equal 200, status
-
# assert_equal "/home", path
-
# end
-
# end
-
#
-
# However, you can also have multiple session instances open per test, and
-
# even extend those instances with assertions and methods to create a very
-
# powerful testing DSL that is specific for your application. You can even
-
# reference any named routes you happen to have defined.
-
#
-
# require "test_helper"
-
#
-
# class AdvancedTest < ActionDispatch::IntegrationTest
-
# fixtures :people, :rooms
-
#
-
# def test_login_and_speak
-
# jamis, david = login(:jamis), login(:david)
-
# room = rooms(:office)
-
#
-
# jamis.enter(room)
-
# jamis.speak(room, "anybody home?")
-
#
-
# david.enter(room)
-
# david.speak(room, "hello!")
-
# end
-
#
-
# private
-
#
-
# module CustomAssertions
-
# def enter(room)
-
# # reference a named route, for maximum internal consistency!
-
# get(room_url(:id => room.id))
-
# assert(...)
-
# ...
-
# end
-
#
-
# def speak(room, message)
-
# xml_http_request "/say/#{room.id}", :message => message
-
# assert(...)
-
# ...
-
# end
-
# end
-
#
-
# def login(who)
-
# open_session do |sess|
-
# sess.extend(CustomAssertions)
-
# who = people(who)
-
# sess.post "/login", :username => who.username,
-
# :password => who.password
-
# assert(...)
-
# end
-
# end
-
# end
-
2
class IntegrationTest < ActiveSupport::TestCase
-
2
include Integration::Runner
-
2
include ActionController::TemplateAssertions
-
2
include ActionDispatch::Routing::UrlFor
-
-
2
@@app = nil
-
-
2
def self.app
-
# DEPRECATE Rails application fallback
-
# This should be set by the initializer
-
@@app || (defined?(Rails.application) && Rails.application) || nil
-
end
-
-
2
def self.app=(app)
-
@@app = app
-
end
-
-
2
def app
-
super || self.class.app
-
end
-
-
2
def url_options
-
reset! unless integration_session
-
integration_session.url_options
-
end
-
end
-
end
-
2
require 'action_dispatch/middleware/cookies'
-
2
require 'action_dispatch/middleware/flash'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
-
2
module ActionDispatch
-
2
module TestProcess
-
2
def assigns(key = nil)
-
1
assigns = @controller.view_assigns.with_indifferent_access
-
1
key.nil? ? assigns : assigns[key]
-
end
-
-
2
def session
-
@request.session
-
end
-
-
2
def flash
-
@request.flash
-
end
-
-
2
def cookies
-
@request.cookie_jar
-
end
-
-
2
def redirect_to_url
-
@response.redirect_url
-
end
-
-
# Shortcut for <tt>Rack::Test::UploadedFile.new(ActionController::TestCase.fixture_path + path, type)</tt>:
-
#
-
# post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png')
-
#
-
# To upload binary files on Windows, pass <tt>:binary</tt> as the last parameter.
-
# This will not affect other platforms:
-
#
-
# post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png', :binary)
-
2
def fixture_file_upload(path, mime_type = nil, binary = false)
-
fixture_path = self.class.fixture_path if self.class.respond_to?(:fixture_path)
-
Rack::Test::UploadedFile.new("#{fixture_path}#{path}", mime_type, binary)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
2
require 'rack/utils'
-
-
2
module ActionDispatch
-
2
class TestRequest < Request
-
2
DEFAULT_ENV = Rack::MockRequest.env_for('/')
-
-
2
def self.new(env = {})
-
75
super
-
end
-
-
2
def initialize(env = {})
-
75
env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
-
75
super(DEFAULT_ENV.merge(env))
-
-
75
self.host = 'test.host'
-
75
self.remote_addr = '0.0.0.0'
-
75
self.user_agent = 'Rails Testing'
-
end
-
-
2
def request_method=(method)
-
@env['REQUEST_METHOD'] = method.to_s.upcase
-
end
-
-
2
def host=(host)
-
75
@env['HTTP_HOST'] = host
-
end
-
-
2
def port=(number)
-
@env['SERVER_PORT'] = number.to_i
-
end
-
-
2
def request_uri=(uri)
-
@env['REQUEST_URI'] = uri
-
end
-
-
2
def path=(path)
-
@env['PATH_INFO'] = path
-
end
-
-
2
def action=(action_name)
-
path_parameters["action"] = action_name.to_s
-
end
-
-
2
def if_modified_since=(last_modified)
-
@env['HTTP_IF_MODIFIED_SINCE'] = last_modified
-
end
-
-
2
def if_none_match=(etag)
-
@env['HTTP_IF_NONE_MATCH'] = etag
-
end
-
-
2
def remote_addr=(addr)
-
75
@env['REMOTE_ADDR'] = addr
-
end
-
-
2
def user_agent=(user_agent)
-
75
@env['HTTP_USER_AGENT'] = user_agent
-
end
-
-
2
def accept=(mime_types)
-
@env.delete('action_dispatch.request.accepts')
-
@env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_type| mime_type.to_s }.join(",")
-
end
-
-
2
alias :rack_cookies :cookies
-
-
2
def cookies
-
20
@cookies ||= {}.with_indifferent_access
-
end
-
end
-
end
-
2
module ActionDispatch
-
# Integration test methods such as ActionDispatch::Integration::Session#get
-
# and ActionDispatch::Integration::Session#post return objects of class
-
# TestResponse, which represent the HTTP response results of the requested
-
# controller actions.
-
#
-
# See Response for more information on controller response objects.
-
2
class TestResponse < Response
-
2
def self.from_response(response)
-
new.tap do |resp|
-
resp.status = response.status
-
resp.headers = response.headers
-
resp.body = response.body
-
end
-
end
-
-
# Was the response successful?
-
2
alias_method :success?, :successful?
-
-
# Was the URL not found?
-
2
alias_method :missing?, :not_found?
-
-
# Were we redirected?
-
2
alias_method :redirect?, :redirection?
-
-
# Was there a server-side error?
-
2
alias_method :error?, :server_error?
-
end
-
end
-
#--
-
# Copyright (c) 2004-2011 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
require 'action_pack/version'
-
2
module ActionPack
-
2
module VERSION #:nodoc:
-
2
MAJOR = 3
-
2
MINOR = 2
-
2
TINY = 16
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
-
end
-
end
-
#--
-
# Copyright (c) 2004-2011 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
require 'active_support/ruby/shim'
-
2
require 'active_support/core_ext/class/attribute_accessors'
-
-
2
require 'action_pack'
-
-
2
module ActionView
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :AssetPaths
-
2
autoload :Base
-
2
autoload :Context
-
2
autoload :CompiledTemplates, "action_view/context"
-
2
autoload :Helpers
-
2
autoload :LookupContext
-
2
autoload :PathSet
-
2
autoload :Template
-
2
autoload :TestCase
-
-
2
autoload_under "renderer" do
-
2
autoload :Renderer
-
2
autoload :AbstractRenderer
-
2
autoload :PartialRenderer
-
2
autoload :TemplateRenderer
-
2
autoload :StreamingTemplateRenderer
-
end
-
-
2
autoload_at "action_view/template/resolver" do
-
2
autoload :Resolver
-
2
autoload :PathResolver
-
2
autoload :FileSystemResolver
-
2
autoload :OptimizedFileSystemResolver
-
2
autoload :FallbackFileSystemResolver
-
end
-
-
2
autoload_at "action_view/buffers" do
-
2
autoload :OutputBuffer
-
2
autoload :StreamingBuffer
-
end
-
-
2
autoload_at "action_view/flows" do
-
2
autoload :OutputFlow
-
2
autoload :StreamingFlow
-
end
-
-
2
autoload_at "action_view/template/error" do
-
2
autoload :MissingTemplate
-
2
autoload :ActionViewError
-
2
autoload :EncodingError
-
2
autoload :TemplateError
-
2
autoload :WrongEncodingError
-
end
-
end
-
-
2
ENCODING_FLAG = '#.*coding[:=]\s*(\S+)[ \t]*'
-
end
-
-
2
require 'active_support/i18n'
-
2
require 'active_support/core_ext/string/output_safety'
-
-
2
I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en.yml"
-
2
require 'zlib'
-
2
require 'active_support/core_ext/file'
-
2
require 'action_controller/metal/exceptions'
-
-
2
module ActionView
-
2
class AssetPaths #:nodoc:
-
2
attr_reader :config, :controller
-
-
2
def initialize(config, controller = nil)
-
@config = config
-
@controller = controller
-
end
-
-
# Add the extension +ext+ if not present. Return full or scheme-relative URLs otherwise untouched.
-
# Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL
-
# roots. Rewrite the asset path for cache-busting asset ids. Include
-
# asset host, if configured, with the correct request protocol.
-
#
-
# When :relative (default), the protocol will be determined by the client using current protocol
-
# When :request, the protocol will be the request protocol
-
# Otherwise, the protocol is used (E.g. :http, :https, etc)
-
2
def compute_public_path(source, dir, options = {})
-
source = source.to_s
-
return source if is_uri?(source)
-
-
source = rewrite_extension(source, dir, options[:ext]) if options[:ext]
-
source = rewrite_asset_path(source, dir, options)
-
source = rewrite_relative_url_root(source, relative_url_root)
-
source = rewrite_host_and_protocol(source, options[:protocol])
-
source
-
end
-
-
# Return the filesystem path for the source
-
2
def compute_source_path(source, dir, ext)
-
source = rewrite_extension(source, dir, ext) if ext
-
-
sources = []
-
sources << config.assets_dir
-
sources << dir unless source[0] == ?/
-
sources << source
-
-
File.join(sources)
-
end
-
-
2
def is_uri?(path)
-
path =~ %r{^[-a-z]+://|^(?:cid|data):|^//}i
-
end
-
-
2
private
-
-
2
def rewrite_extension(source, dir, ext)
-
raise NotImplementedError
-
end
-
-
2
def rewrite_asset_path(source, path = nil)
-
raise NotImplementedError
-
end
-
-
2
def rewrite_relative_url_root(source, relative_url_root)
-
relative_url_root && !source.starts_with?("#{relative_url_root}/") ? "#{relative_url_root}#{source}" : source
-
end
-
-
2
def has_request?
-
controller.respond_to?(:request)
-
end
-
-
2
def rewrite_host_and_protocol(source, protocol = nil)
-
host = compute_asset_host(source)
-
if host && !is_uri?(host)
-
if (protocol || default_protocol) == :request && !has_request?
-
host = nil
-
else
-
host = "#{compute_protocol(protocol)}#{host}"
-
end
-
end
-
host ? "#{host}#{source}" : source
-
end
-
-
2
def compute_protocol(protocol)
-
protocol ||= default_protocol
-
case protocol
-
when :relative
-
"//"
-
when :request
-
unless @controller
-
invalid_asset_host!("The protocol requested was :request. Consider using :relative instead.")
-
end
-
@controller.request.protocol
-
else
-
"#{protocol}://"
-
end
-
end
-
-
2
def default_protocol
-
@config.default_asset_host_protocol || (has_request? ? :request : :relative)
-
end
-
-
2
def invalid_asset_host!(help_message)
-
raise ActionController::RoutingError, "This asset host cannot be computed without a request in scope. #{help_message}"
-
end
-
-
# Pick an asset host for this source. Returns +nil+ if no host is set,
-
# the host if no wildcard is set, the host interpolated with the
-
# numbers 0-3 if it contains <tt>%d</tt> (the number is the source hash mod 4),
-
# or the value returned from invoking call on an object responding to call
-
# (proc or otherwise).
-
2
def compute_asset_host(source)
-
if host = asset_host_config
-
if host.respond_to?(:call)
-
args = [source]
-
arity = arity_of(host)
-
if (arity > 1 || arity < -2) && !has_request?
-
invalid_asset_host!("Remove the second argument to your asset_host Proc if you do not need the request, or make it optional.")
-
end
-
args << current_request if (arity > 1 || arity < 0) && has_request?
-
host.call(*args)
-
else
-
(host =~ /%d/) ? host % (Zlib.crc32(source) % 4) : host
-
end
-
end
-
end
-
-
2
def relative_url_root
-
config.relative_url_root
-
end
-
-
2
def asset_host_config
-
config.asset_host
-
end
-
-
# Returns the current request if one exists.
-
2
def current_request
-
controller.request if has_request?
-
end
-
-
# Returns the arity of a callable
-
2
def arity_of(callable)
-
callable.respond_to?(:arity) ? callable.arity : callable.method(:call).arity
-
end
-
-
end
-
end
-
2
require 'active_support/core_ext/module/attr_internal'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/ordered_options'
-
2
require 'action_view/log_subscriber'
-
2
require 'active_support/core_ext/module/deprecation'
-
-
2
module ActionView #:nodoc:
-
# = Action View Base
-
#
-
# Action View templates can be written in several ways. If the template file has a <tt>.erb</tt> extension then it uses a mixture of ERb
-
# (included in Ruby) and HTML. If the template file has a <tt>.builder</tt> extension then Jim Weirich's Builder::XmlMarkup library is used.
-
#
-
# == ERB
-
#
-
# You trigger ERB by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the
-
# following loop for names:
-
#
-
# <b>Names of all the people</b>
-
# <% @people.each do |person| %>
-
# Name: <%= person.name %><br/>
-
# <% end %>
-
#
-
# The loop is setup in regular embedding tags <% %> and the name is written using the output embedding tag <%= %>. Note that this
-
# is not just a usage suggestion. Regular output functions like print or puts won't work with ERB templates. So this would be wrong:
-
#
-
# <%# WRONG %>
-
# Hi, Mr. <% puts "Frodo" %>
-
#
-
# If you absolutely must write from within a function use +concat+.
-
#
-
# <%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>.
-
#
-
# === Using sub templates
-
#
-
# Using sub templates allows you to sidestep tedious replication and extract common display structures in shared templates. The
-
# classic example is the use of a header and footer (even though the Action Pack-way would be to use Layouts):
-
#
-
# <%= render "shared/header" %>
-
# Something really specific and terrific
-
# <%= render "shared/footer" %>
-
#
-
# As you see, we use the output embeddings for the render methods. The render call itself will just return a string holding the
-
# result of the rendering. The output embedding writes it to the current template.
-
#
-
# But you don't have to restrict yourself to static includes. Templates can share variables amongst themselves by using instance
-
# variables defined using the regular embedding tags. Like this:
-
#
-
# <% @page_title = "A Wonderful Hello" %>
-
# <%= render "shared/header" %>
-
#
-
# Now the header can pick up on the <tt>@page_title</tt> variable and use it for outputting a title tag:
-
#
-
# <title><%= @page_title %></title>
-
#
-
# === Passing local variables to sub templates
-
#
-
# You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:
-
#
-
# <%= render "shared/header", { :headline => "Welcome", :person => person } %>
-
#
-
# These can now be accessed in <tt>shared/header</tt> with:
-
#
-
# Headline: <%= headline %>
-
# First name: <%= person.first_name %>
-
#
-
# If you need to find out whether a certain local variable has been assigned a value in a particular render call,
-
# you need to use the following pattern:
-
#
-
# <% if local_assigns.has_key? :headline %>
-
# Headline: <%= headline %>
-
# <% end %>
-
#
-
# Testing using <tt>defined? headline</tt> will not work. This is an implementation restriction.
-
#
-
# === Template caching
-
#
-
# By default, Rails will compile each template to a method in order to render it. When you alter a template,
-
# Rails will check the file's modification time and recompile it in development mode.
-
#
-
# == Builder
-
#
-
# Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object
-
# named +xml+ is automatically made available to templates with a <tt>.builder</tt> extension.
-
#
-
# Here are some basic examples:
-
#
-
# xml.em("emphasized") # => <em>emphasized</em>
-
# xml.em { xml.b("emph & bold") } # => <em><b>emph & bold</b></em>
-
# xml.a("A Link", "href" => "http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
-
# xml.target("name" => "compile", "option" => "fast") # => <target option="fast" name="compile"\>
-
# # NOTE: order of attributes is not specified.
-
#
-
# Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
-
#
-
# xml.div do
-
# xml.h1(@person.name)
-
# xml.p(@person.bio)
-
# end
-
#
-
# would produce something like:
-
#
-
# <div>
-
# <h1>David Heinemeier Hansson</h1>
-
# <p>A product of Danish Design during the Winter of '79...</p>
-
# </div>
-
#
-
# A full-length RSS example actually used on Basecamp:
-
#
-
# xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
-
# xml.channel do
-
# xml.title(@feed_title)
-
# xml.link(@url)
-
# xml.description "Basecamp: Recent items"
-
# xml.language "en-us"
-
# xml.ttl "40"
-
#
-
# @recent_items.each do |item|
-
# xml.item do
-
# xml.title(item_title(item))
-
# xml.description(item_description(item)) if item_description(item)
-
# xml.pubDate(item_pubDate(item))
-
# xml.guid(@person.firm.account.url + @recent_items.url(item))
-
# xml.link(@person.firm.account.url + @recent_items.url(item))
-
#
-
# xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
-
# end
-
# end
-
# end
-
# end
-
#
-
# More builder documentation can be found at http://builder.rubyforge.org.
-
2
class Base
-
2
include Helpers, ::ERB::Util, Context
-
-
# Specify the proc used to decorate input tags that refer to attributes with errors.
-
2
cattr_accessor :field_error_proc
-
2
@@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
-
-
# How to complete the streaming when an exception occurs.
-
# This is our best guess: first try to close the attribute, then the tag.
-
2
cattr_accessor :streaming_completion_on_exception
-
2
@@streaming_completion_on_exception = %("><script type="text/javascript">window.location = "/500.html"</script></html>)
-
-
2
class_attribute :helpers
-
2
class_attribute :_routes
-
-
2
class << self
-
2
delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB'
-
2
delegate :logger, :to => 'ActionController::Base', :allow_nil => true
-
-
2
def cache_template_loading
-
ActionView::Resolver.caching?
-
end
-
-
2
def cache_template_loading=(value)
-
ActionView::Resolver.caching = value
-
end
-
-
2
def process_view_paths(value)
-
value.is_a?(PathSet) ?
-
value.dup : ActionView::PathSet.new(Array.wrap(value))
-
end
-
2
deprecate :process_view_paths
-
-
2
def xss_safe? #:nodoc:
-
true
-
end
-
-
# This method receives routes and helpers from the controller
-
# and return a subclass ready to be used as view context.
-
2
def prepare(routes, helpers) #:nodoc:
-
1
Class.new(self) do
-
1
if routes
-
1
include routes.url_helpers
-
1
include routes.mounted_helpers
-
end
-
-
1
if helpers
-
1
include helpers
-
1
self.helpers = helpers
-
end
-
end
-
end
-
end
-
-
2
attr_accessor :view_renderer
-
2
attr_internal :config, :assigns
-
-
2
delegate :lookup_context, :to => :view_renderer
-
2
delegate :formats, :formats=, :locale, :locale=, :view_paths, :view_paths=, :to => :lookup_context
-
-
2
def assign(new_assigns) # :nodoc:
-
20
@_assigns = new_assigns.each { |key, value| instance_variable_set("@#{key}", value) }
-
end
-
-
2
def initialize(context = nil, assigns = {}, controller = nil, formats = nil) #:nodoc:
-
4
@_config = ActiveSupport::InheritableOptions.new
-
-
# Handle all these for backwards compatibility.
-
# TODO Provide a new API for AV::Base and deprecate this one.
-
4
if context.is_a?(ActionView::Renderer)
-
4
@view_renderer = context
-
elsif
-
lookup_context = context.is_a?(ActionView::LookupContext) ?
-
context : ActionView::LookupContext.new(context)
-
lookup_context.formats = formats if formats
-
lookup_context.prefixes = controller._prefixes if controller
-
@view_renderer = ActionView::Renderer.new(lookup_context)
-
end
-
-
4
assign(assigns)
-
4
assign_controller(controller)
-
4
_prepare_context
-
end
-
-
2
ActiveSupport.run_load_hooks(:action_view, self)
-
end
-
end
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
module ActionView
-
1
class OutputBuffer < ActiveSupport::SafeBuffer #:nodoc:
-
1
def initialize(*)
-
4
super
-
4
encode! if encoding_aware?
-
end
-
-
1
def <<(value)
-
12
super(value.to_s)
-
end
-
1
alias :append= :<<
-
1
alias :safe_append= :safe_concat
-
end
-
-
1
class StreamingBuffer #:nodoc:
-
1
def initialize(block)
-
@block = block
-
end
-
-
1
def <<(value)
-
value = value.to_s
-
value = ERB::Util.h(value) unless value.html_safe?
-
@block.call(value)
-
end
-
1
alias :concat :<<
-
1
alias :append= :<<
-
-
1
def safe_concat(value)
-
@block.call(value.to_s)
-
end
-
1
alias :safe_append= :safe_concat
-
-
1
def html_safe?
-
true
-
end
-
-
1
def html_safe
-
self
-
end
-
end
-
end
-
2
module ActionView
-
2
module CompiledTemplates #:nodoc:
-
# holds compiled template code
-
end
-
-
# = Action View Context
-
#
-
# Action View contexts are supplied to Action Controller to render template.
-
# The default Action View context is ActionView::Base.
-
#
-
# In order to work with ActionController, a Context must just include this module.
-
# The initialization of the variables used by the context (@output_buffer, @view_flow,
-
# and @virtual_path) is responsibility of the object that includes this module
-
# (although you can call _prepare_context defined below).
-
2
module Context
-
2
include CompiledTemplates
-
2
attr_accessor :output_buffer, :view_flow
-
-
# Prepares the context by setting the appropriate instance variables.
-
# :api: plugin
-
2
def _prepare_context
-
4
@view_flow = OutputFlow.new
-
4
@output_buffer = nil
-
4
@virtual_path = nil
-
end
-
-
# Encapsulates the interaction with the view flow so it
-
# returns the correct buffer on yield. This is usually
-
# overwriten by helpers to add more behavior.
-
# :api: plugin
-
2
def _layout_for(name=nil)
-
name ||= :layout
-
view_flow.get(name).html_safe
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/output_safety'
-
-
1
module ActionView
-
1
class OutputFlow #:nodoc:
-
1
attr_reader :content
-
-
1
def initialize
-
4
@content = Hash.new { |h,k| h[k] = ActiveSupport::SafeBuffer.new }
-
end
-
-
# Called by _layout_for to read stored values.
-
1
def get(key)
-
@content[key]
-
end
-
-
# Called by each renderer object to set the layout contents.
-
1
def set(key, value)
-
@content[key] = value
-
end
-
-
# Called by content_for
-
1
def append(key, value)
-
@content[key] << value
-
end
-
-
# Called by provide
-
1
def append!(key, value)
-
@content[key] << value
-
end
-
end
-
-
1
class StreamingFlow < OutputFlow #:nodoc:
-
1
def initialize(view, fiber)
-
@view = view
-
@parent = nil
-
@child = view.output_buffer
-
@content = view.view_flow.content
-
@fiber = fiber
-
@root = Fiber.current.object_id
-
end
-
-
# Try to get an stored content. If the content
-
# is not available and we are inside the layout
-
# fiber, we set that we are waiting for the given
-
# key and yield.
-
1
def get(key)
-
return super if @content.key?(key)
-
-
if inside_fiber?
-
view = @view
-
-
begin
-
@waiting_for = key
-
view.output_buffer, @parent = @child, view.output_buffer
-
Fiber.yield
-
ensure
-
@waiting_for = nil
-
view.output_buffer, @child = @parent, view.output_buffer
-
end
-
end
-
-
super
-
end
-
-
# Appends the contents for the given key. This is called
-
# by provides and resumes back to the fiber if it is
-
# the key it is waiting for.
-
1
def append!(key, value)
-
super
-
@fiber.resume if @waiting_for == key
-
end
-
-
1
private
-
-
1
def inside_fiber?
-
Fiber.current.object_id != @root
-
end
-
end
-
end
-
2
require 'active_support/benchmarkable'
-
-
2
module ActionView #:nodoc:
-
2
module Helpers #:nodoc:
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :ActiveModelHelper
-
2
autoload :AssetTagHelper
-
2
autoload :AtomFeedHelper
-
2
autoload :CacheHelper
-
2
autoload :CaptureHelper
-
2
autoload :ControllerHelper
-
2
autoload :CsrfHelper
-
2
autoload :DateHelper
-
2
autoload :DebugHelper
-
2
autoload :FormHelper
-
2
autoload :FormOptionsHelper
-
2
autoload :FormTagHelper
-
2
autoload :JavaScriptHelper, "action_view/helpers/javascript_helper"
-
2
autoload :NumberHelper
-
2
autoload :OutputSafetyHelper
-
2
autoload :RecordTagHelper
-
2
autoload :RenderingHelper
-
2
autoload :SanitizeHelper
-
2
autoload :TagHelper
-
2
autoload :TextHelper
-
2
autoload :TranslationHelper
-
2
autoload :UrlHelper
-
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
3
extend SanitizeHelper::ClassMethods
-
end
-
-
2
include ActiveSupport::Benchmarkable
-
2
include ActiveModelHelper
-
2
include AssetTagHelper
-
2
include AtomFeedHelper
-
2
include CacheHelper
-
2
include CaptureHelper
-
2
include ControllerHelper
-
2
include CsrfHelper
-
2
include DateHelper
-
2
include DebugHelper
-
2
include FormHelper
-
2
include FormOptionsHelper
-
2
include FormTagHelper
-
2
include JavaScriptHelper
-
2
include NumberHelper
-
2
include OutputSafetyHelper
-
2
include RecordTagHelper
-
2
include RenderingHelper
-
2
include SanitizeHelper
-
2
include TagHelper
-
2
include TextHelper
-
2
include TranslationHelper
-
2
include UrlHelper
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute_accessors'
-
2
require 'active_support/core_ext/enumerable'
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActionView
-
# = Active Model Helpers
-
2
module Helpers
-
2
module ActiveModelHelper
-
end
-
-
2
module ActiveModelInstanceTag
-
2
def object
-
@active_model_object ||= begin
-
object = super
-
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
end
-
-
2
%w(content_tag to_date_select_tag to_datetime_select_tag to_time_select_tag).each do |meth|
-
8
module_eval "def #{meth}(*) error_wrapping(super) end", __FILE__, __LINE__
-
end
-
-
2
def tag(type, options, *)
-
tag_generate_errors?(options) ? error_wrapping(super) : super
-
end
-
-
2
def error_wrapping(html_tag)
-
if object_has_errors?
-
Base.field_error_proc.call(html_tag, self)
-
else
-
html_tag
-
end
-
end
-
-
2
def error_message
-
object.errors[@method_name]
-
end
-
-
2
private
-
-
2
def object_has_errors?
-
object.respond_to?(:errors) && object.errors.respond_to?(:full_messages) && error_message.any?
-
end
-
-
2
def tag_generate_errors?(options)
-
options['type'] != 'hidden'
-
end
-
end
-
end
-
end
-
2
require 'action_view/helpers/asset_tag_helpers/javascript_tag_helpers'
-
2
require 'action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers'
-
2
require 'action_view/helpers/asset_tag_helpers/asset_paths'
-
2
require 'action_view/helpers/tag_helper'
-
-
2
module ActionView
-
# = Action View Asset Tag Helpers
-
2
module Helpers #:nodoc:
-
# This module provides methods for generating HTML that links views to assets such
-
# as images, javascripts, stylesheets, and feeds. These methods do not verify
-
# the assets exist before linking to them:
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="/images/rails.png?1230601161" />
-
# stylesheet_link_tag("application")
-
# # => <link href="/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# === Using asset hosts
-
#
-
# By default, Rails links to these assets on the current host in the public
-
# folder, but you can direct Rails to link to assets from a dedicated asset
-
# server by setting ActionController::Base.asset_host in the application
-
# configuration, typically in <tt>config/environments/production.rb</tt>.
-
# For example, you'd define <tt>assets.example.com</tt> to be your asset
-
# host this way:
-
#
-
# ActionController::Base.asset_host = "assets.example.com"
-
#
-
# Helpers take that into account:
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets.example.com/images/rails.png?1230601161" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# Browsers typically open at most two simultaneous connections to a single
-
# host, which means your assets often have to wait for other assets to finish
-
# downloading. You can alleviate this by using a <tt>%d</tt> wildcard in the
-
# +asset_host+. For example, "assets%d.example.com". If that wildcard is
-
# present Rails distributes asset requests among the corresponding four hosts
-
# "assets0.example.com", ..., "assets3.example.com". With this trick browsers
-
# will open eight simultaneous connections rather than two.
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets0.example.com/images/rails.png?1230601161" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets2.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# To do this, you can either setup four actual hosts, or you can use wildcard
-
# DNS to CNAME the wildcard to a single asset host. You can read more about
-
# setting up your DNS CNAME records from your ISP.
-
#
-
# Note: This is purely a browser performance optimization and is not meant
-
# for server load balancing. See http://www.die.net/musings/page_load_time/
-
# for background.
-
#
-
# Alternatively, you can exert more control over the asset host by setting
-
# +asset_host+ to a proc like this:
-
#
-
# ActionController::Base.asset_host = Proc.new { |source|
-
# "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com"
-
# }
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://assets1.example.com/images/rails.png?1230601161" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets2.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# The example above generates "http://assets1.example.com" and
-
# "http://assets2.example.com". This option is useful for example if
-
# you need fewer/more than four hosts, custom host names, etc.
-
#
-
# As you see the proc takes a +source+ parameter. That's a string with the
-
# absolute path of the asset with any extensions and timestamps in place,
-
# for example "/images/rails.png?1230601161".
-
#
-
# ActionController::Base.asset_host = Proc.new { |source|
-
# if source.starts_with?('/images')
-
# "http://images.example.com"
-
# else
-
# "http://assets.example.com"
-
# end
-
# }
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="http://images.example.com/images/rails.png?1230601161" />
-
# stylesheet_link_tag("application")
-
# # => <link href="http://assets.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# Alternatively you may ask for a second parameter +request+. That one is
-
# particularly useful for serving assets from an SSL-protected page. The
-
# example proc below disables asset hosting for HTTPS connections, while
-
# still sending assets for plain HTTP requests from asset hosts. If you don't
-
# have SSL certificates for each of the asset hosts this technique allows you
-
# to avoid warnings in the client about mixed media.
-
#
-
# ActionController::Base.asset_host = Proc.new { |source, request|
-
# if request.ssl?
-
# "#{request.protocol}#{request.host_with_port}"
-
# else
-
# "#{request.protocol}assets.example.com"
-
# end
-
# }
-
#
-
# You can also implement a custom asset host object that responds to +call+
-
# and takes either one or two parameters just like the proc.
-
#
-
# config.action_controller.asset_host = AssetHostingWithMinimumSsl.new(
-
# "http://asset%d.example.com", "https://asset1.example.com"
-
# )
-
#
-
# === Customizing the asset path
-
#
-
# By default, Rails appends asset's timestamps to all asset paths. This allows
-
# you to set a cache-expiration date for the asset far into the future, but
-
# still be able to instantly invalidate it by simply updating the file (and
-
# hence updating the timestamp, which then updates the URL as the timestamp
-
# is part of that, which in turn busts the cache).
-
#
-
# It's the responsibility of the web server you use to set the far-future
-
# expiration date on cache assets that you need to take advantage of this
-
# feature. Here's an example for Apache:
-
#
-
# # Asset Expiration
-
# ExpiresActive On
-
# <FilesMatch "\.(ico|gif|jpe?g|png|js|css)$">
-
# ExpiresDefault "access plus 1 year"
-
# </FilesMatch>
-
#
-
# Also note that in order for this to work, all your application servers must
-
# return the same timestamps. This means that they must have their clocks
-
# synchronized. If one of them drifts out of sync, you'll see different
-
# timestamps at random and the cache won't work. In that case the browser
-
# will request the same assets over and over again even thought they didn't
-
# change. You can use something like Live HTTP Headers for Firefox to verify
-
# that the cache is indeed working.
-
#
-
# This strategy works well enough for most server setups and requires the
-
# least configuration, but if you deploy several application servers at
-
# different times - say to handle a temporary spike in load - then the
-
# asset time stamps will be out of sync. In a setup like this you may want
-
# to set the way that asset paths are generated yourself.
-
#
-
# Altering the asset paths that Rails generates can be done in two ways.
-
# The easiest is to define the RAILS_ASSET_ID environment variable. The
-
# contents of this variable will always be used in preference to
-
# calculated timestamps. A more complex but flexible way is to set
-
# <tt>ActionController::Base.config.asset_path</tt> to a proc
-
# that takes the unmodified asset path and returns the path needed for
-
# your asset caching to work. Typically you'd do something like this in
-
# <tt>config/environments/production.rb</tt>:
-
#
-
# # Normally you'd calculate RELEASE_NUMBER at startup.
-
# RELEASE_NUMBER = 12345
-
# config.action_controller.asset_path = proc { |asset_path|
-
# "/release-#{RELEASE_NUMBER}#{asset_path}"
-
# }
-
#
-
# This example would cause the following behavior on all servers no
-
# matter when they were deployed:
-
#
-
# image_tag("rails.png")
-
# # => <img alt="Rails" src="/release-12345/images/rails.png" />
-
# stylesheet_link_tag("application")
-
# # => <link href="/release-12345/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# Changing the asset_path does require that your web servers have
-
# knowledge of the asset template paths that you rewrite to so it's not
-
# suitable for out-of-the-box use. To use the example given above you
-
# could use something like this in your Apache VirtualHost configuration:
-
#
-
# <LocationMatch "^/release-\d+/(images|javascripts|stylesheets)/.*$">
-
# # Some browsers still send conditional-GET requests if there's a
-
# # Last-Modified header or an ETag header even if they haven't
-
# # reached the expiry date sent in the Expires header.
-
# Header unset Last-Modified
-
# Header unset ETag
-
# FileETag None
-
#
-
# # Assets requested using a cache-busting filename should be served
-
# # only once and then cached for a really long time. The HTTP/1.1
-
# # spec frowns on hugely-long expiration times though and suggests
-
# # that assets which never expire be served with an expiration date
-
# # 1 year from access.
-
# ExpiresActive On
-
# ExpiresDefault "access plus 1 year"
-
# </LocationMatch>
-
#
-
# # We use cached-busting location names with the far-future expires
-
# # headers to ensure that if a file does change it can force a new
-
# # request. The actual asset filenames are still the same though so we
-
# # need to rewrite the location from the cache-busting location to the
-
# # real asset location so that we can serve it.
-
# RewriteEngine On
-
# RewriteRule ^/release-\d+/(images|javascripts|stylesheets)/(.*)$ /$1/$2 [L]
-
2
module AssetTagHelper
-
2
include TagHelper
-
2
include JavascriptTagHelpers
-
2
include StylesheetTagHelpers
-
# Returns a link tag that browsers and news readers can use to auto-detect
-
# an RSS or ATOM feed. The +type+ can either be <tt>:rss</tt> (default) or
-
# <tt>:atom</tt>. Control the link options in url_for format using the
-
# +url_options+. You can modify the LINK tag itself in +tag_options+.
-
#
-
# ==== Options
-
# * <tt>:rel</tt> - Specify the relation of this link, defaults to "alternate"
-
# * <tt>:type</tt> - Override the auto-generated mime type
-
# * <tt>:title</tt> - Specify the title of the link, defaults to the +type+
-
#
-
# ==== Examples
-
# auto_discovery_link_tag # =>
-
# <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" />
-
# auto_discovery_link_tag(:atom) # =>
-
# <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" />
-
# auto_discovery_link_tag(:rss, {:action => "feed"}) # =>
-
# <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" />
-
# auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"}) # =>
-
# <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" />
-
# auto_discovery_link_tag(:rss, {:controller => "news", :action => "feed"}) # =>
-
# <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
-
# auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "Example RSS"}) # =>
-
# <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" />
-
2
def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
-
tag(
-
"link",
-
"rel" => tag_options[:rel] || "alternate",
-
"type" => tag_options[:type] || Mime::Type.lookup_by_extension(type.to_s).to_s,
-
"title" => tag_options[:title] || type.to_s.upcase,
-
"href" => url_options.is_a?(Hash) ? url_for(url_options.merge(:only_path => false)) : url_options
-
)
-
end
-
-
# <%= favicon_link_tag %>
-
#
-
# generates
-
#
-
# <link href="/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
-
#
-
# You may specify a different file in the first argument:
-
#
-
# <%= favicon_link_tag '/myicon.ico' %>
-
#
-
# That's passed to +path_to_image+ as is, so it gives
-
#
-
# <link href="/myicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
-
#
-
# The helper accepts an additional options hash where you can override "rel" and "type".
-
#
-
# For example, Mobile Safari looks for a different LINK tag, pointing to an image that
-
# will be used if you add the page to the home screen of an iPod Touch, iPhone, or iPad.
-
# The following call would generate such a tag:
-
#
-
# <%= favicon_link_tag 'mb-icon.png', :rel => 'apple-touch-icon', :type => 'image/png' %>
-
#
-
2
def favicon_link_tag(source='/favicon.ico', options={})
-
tag('link', {
-
:rel => 'shortcut icon',
-
:type => 'image/vnd.microsoft.icon',
-
:href => path_to_image(source)
-
}.merge(options.symbolize_keys))
-
end
-
-
# Computes the path to an image asset in the public images directory.
-
# Full paths from the document root will be passed through.
-
# Used internally by +image_tag+ to build the image path:
-
#
-
# image_path("edit") # => "/images/edit"
-
# image_path("edit.png") # => "/images/edit.png"
-
# image_path("icons/edit.png") # => "/images/icons/edit.png"
-
# image_path("/icons/edit.png") # => "/icons/edit.png"
-
# image_path("http://www.example.com/img/edit.png") # => "http://www.example.com/img/edit.png"
-
#
-
# If you have images as application resources this method may conflict with their named routes.
-
# The alias +path_to_image+ is provided to avoid that. Rails uses the alias internally, and
-
# plugin authors are encouraged to do so.
-
2
def image_path(source)
-
source.present? ? asset_paths.compute_public_path(source, 'images') : ""
-
end
-
2
alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
-
-
# Computes the path to a video asset in the public videos directory.
-
# Full paths from the document root will be passed through.
-
# Used internally by +video_tag+ to build the video path.
-
#
-
# ==== Examples
-
# video_path("hd") # => /videos/hd
-
# video_path("hd.avi") # => /videos/hd.avi
-
# video_path("trailers/hd.avi") # => /videos/trailers/hd.avi
-
# video_path("/trailers/hd.avi") # => /trailers/hd.avi
-
# video_path("http://www.example.com/vid/hd.avi") # => http://www.example.com/vid/hd.avi
-
2
def video_path(source)
-
asset_paths.compute_public_path(source, 'videos')
-
end
-
2
alias_method :path_to_video, :video_path # aliased to avoid conflicts with a video_path named route
-
-
# Computes the path to an audio asset in the public audios directory.
-
# Full paths from the document root will be passed through.
-
# Used internally by +audio_tag+ to build the audio path.
-
#
-
# ==== Examples
-
# audio_path("horse") # => /audios/horse
-
# audio_path("horse.wav") # => /audios/horse.wav
-
# audio_path("sounds/horse.wav") # => /audios/sounds/horse.wav
-
# audio_path("/sounds/horse.wav") # => /sounds/horse.wav
-
# audio_path("http://www.example.com/sounds/horse.wav") # => http://www.example.com/sounds/horse.wav
-
2
def audio_path(source)
-
asset_paths.compute_public_path(source, 'audios')
-
end
-
2
alias_method :path_to_audio, :audio_path # aliased to avoid conflicts with an audio_path named route
-
-
# Computes the path to a font asset in the public fonts directory.
-
# Full paths from the document root will be passed through.
-
#
-
# ==== Examples
-
# font_path("font") # => /fonts/font
-
# font_path("font.ttf") # => /fonts/font.ttf
-
# font_path("dir/font.ttf") # => /fonts/dir/font.ttf
-
# font_path("/dir/font.ttf") # => /dir/font.ttf
-
# font_path("http://www.example.com/dir/font.ttf") # => http://www.example.com/dir/font.ttf
-
2
def font_path(source)
-
asset_paths.compute_public_path(source, 'fonts')
-
end
-
2
alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route
-
-
# Returns an html image tag for the +source+. The +source+ can be a full
-
# path or a file that exists in your public images directory.
-
#
-
# ==== Options
-
# You can add HTML attributes using the +options+. The +options+ supports
-
# three additional keys for convenience and conformance:
-
#
-
# * <tt>:alt</tt> - If no alt text is given, the file name part of the
-
# +source+ is used (capitalized and without the extension)
-
# * <tt>:size</tt> - Supplied as "{Width}x{Height}", so "30x45" becomes
-
# width="30" and height="45". <tt>:size</tt> will be ignored if the
-
# value is not in the correct format.
-
# * <tt>:mouseover</tt> - Set an alternate image to be used when the onmouseover
-
# event is fired, and sets the original image to be replaced onmouseout.
-
# This can be used to implement an easy image toggle that fires on onmouseover.
-
#
-
# ==== Examples
-
# image_tag("icon") # =>
-
# <img src="/images/icon" alt="Icon" />
-
# image_tag("icon.png") # =>
-
# <img src="/images/icon.png" alt="Icon" />
-
# image_tag("icon.png", :size => "16x10", :alt => "Edit Entry") # =>
-
# <img src="/images/icon.png" width="16" height="10" alt="Edit Entry" />
-
# image_tag("/icons/icon.gif", :size => "16x16") # =>
-
# <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
-
# image_tag("/icons/icon.gif", :height => '32', :width => '32') # =>
-
# <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
-
# image_tag("/icons/icon.gif", :class => "menu_icon") # =>
-
# <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
-
# image_tag("mouse.png", :mouseover => "/images/mouse_over.png") # =>
-
# <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" />
-
# image_tag("mouse.png", :mouseover => image_path("mouse_over.png")) # =>
-
# <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" />
-
2
def image_tag(source, options = {})
-
options.symbolize_keys!
-
-
src = options[:src] = path_to_image(source)
-
-
unless src =~ /^(?:cid|data):/ || src.blank?
-
options[:alt] = options.fetch(:alt){ image_alt(src) }
-
end
-
-
if size = options.delete(:size)
-
options[:width], options[:height] = size.split("x") if size =~ %r{^\d+x\d+$}
-
end
-
-
if mouseover = options.delete(:mouseover)
-
options[:onmouseover] = "this.src='#{path_to_image(mouseover)}'"
-
options[:onmouseout] = "this.src='#{src}'"
-
end
-
-
tag("img", options)
-
end
-
-
2
def image_alt(src)
-
File.basename(src, '.*').sub(/-[[:xdigit:]]{32}\z/, '').capitalize
-
end
-
-
# Returns an html video tag for the +sources+. If +sources+ is a string,
-
# a single video tag will be returned. If +sources+ is an array, a video
-
# tag with nested source tags for each source will be returned. The
-
# +sources+ can be full paths or files that exists in your public videos
-
# directory.
-
#
-
# ==== Options
-
# You can add HTML attributes using the +options+. The +options+ supports
-
# two additional keys for convenience and conformance:
-
#
-
# * <tt>:poster</tt> - Set an image (like a screenshot) to be shown
-
# before the video loads. The path is calculated like the +src+ of +image_tag+.
-
# * <tt>:size</tt> - Supplied as "{Width}x{Height}", so "30x45" becomes
-
# width="30" and height="45". <tt>:size</tt> will be ignored if the
-
# value is not in the correct format.
-
#
-
# ==== Examples
-
# video_tag("trailer") # =>
-
# <video src="/videos/trailer" />
-
# video_tag("trailer.ogg") # =>
-
# <video src="/videos/trailer.ogg" />
-
# video_tag("trailer.ogg", :controls => true, :autobuffer => true) # =>
-
# <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" />
-
# video_tag("trailer.m4v", :size => "16x10", :poster => "screenshot.png") # =>
-
# <video src="/videos/trailer.m4v" width="16" height="10" poster="/images/screenshot.png" />
-
# video_tag("/trailers/hd.avi", :size => "16x16") # =>
-
# <video src="/trailers/hd.avi" width="16" height="16" />
-
# video_tag("/trailers/hd.avi", :height => '32', :width => '32') # =>
-
# <video height="32" src="/trailers/hd.avi" width="32" />
-
# video_tag(["trailer.ogg", "trailer.flv"]) # =>
-
# <video><source src="trailer.ogg" /><source src="trailer.ogg" /><source src="trailer.flv" /></video>
-
# video_tag(["trailer.ogg", "trailer.flv"] :size => "160x120") # =>
-
# <video height="120" width="160"><source src="trailer.ogg" /><source src="trailer.flv" /></video>
-
2
def video_tag(sources, options = {})
-
options.symbolize_keys!
-
-
options[:poster] = path_to_image(options[:poster]) if options[:poster]
-
-
if size = options.delete(:size)
-
options[:width], options[:height] = size.split("x") if size =~ %r{^\d+x\d+$}
-
end
-
-
if sources.is_a?(Array)
-
content_tag("video", options) do
-
sources.map { |source| tag("source", :src => source) }.join.html_safe
-
end
-
else
-
options[:src] = path_to_video(sources)
-
tag("video", options)
-
end
-
end
-
-
# Returns an html audio tag for the +source+.
-
# The +source+ can be full path or file that exists in
-
# your public audios directory.
-
#
-
# ==== Examples
-
# audio_tag("sound") # =>
-
# <audio src="/audios/sound" />
-
# audio_tag("sound.wav") # =>
-
# <audio src="/audios/sound.wav" />
-
# audio_tag("sound.wav", :autoplay => true, :controls => true) # =>
-
# <audio autoplay="autoplay" controls="controls" src="/audios/sound.wav" />
-
2
def audio_tag(source, options = {})
-
options.symbolize_keys!
-
options[:src] = path_to_audio(source)
-
tag("audio", options)
-
end
-
-
2
private
-
-
2
def asset_paths
-
@asset_paths ||= AssetTagHelper::AssetPaths.new(config, controller)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/core_ext/file'
-
2
require 'action_view/helpers/tag_helper'
-
-
2
module ActionView
-
2
module Helpers
-
2
module AssetTagHelper
-
-
2
class AssetIncludeTag
-
2
include TagHelper
-
-
2
attr_reader :config, :asset_paths
-
2
class_attribute :expansions
-
-
2
def self.inherited(base)
-
4
base.expansions = { }
-
end
-
-
2
def initialize(config, asset_paths)
-
@config = config
-
@asset_paths = asset_paths
-
end
-
-
2
def asset_name
-
raise NotImplementedError
-
end
-
-
2
def extension
-
raise NotImplementedError
-
end
-
-
2
def custom_dir
-
raise NotImplementedError
-
end
-
-
2
def asset_tag(source, options)
-
raise NotImplementedError
-
end
-
-
2
def include_tag(*sources)
-
options = sources.extract_options!.stringify_keys
-
concat = options.delete("concat")
-
cache = concat || options.delete("cache")
-
recursive = options.delete("recursive")
-
-
if concat || (config.perform_caching && cache)
-
joined_name = (cache == true ? "all" : cache) + ".#{extension}"
-
joined_path = File.join((joined_name[/^#{File::SEPARATOR}/] ? config.assets_dir : custom_dir), joined_name)
-
unless config.perform_caching && File.exists?(joined_path)
-
write_asset_file_contents(joined_path, compute_paths(sources, recursive))
-
end
-
asset_tag(joined_name, options)
-
else
-
sources = expand_sources(sources, recursive)
-
ensure_sources!(sources) if cache
-
sources.collect { |source| asset_tag(source, options) }.join("\n").html_safe
-
end
-
end
-
-
2
private
-
-
2
def path_to_asset(source, options = {})
-
asset_paths.compute_public_path(source, asset_name.to_s.pluralize, options.merge(:ext => extension))
-
end
-
-
2
def path_to_asset_source(source)
-
asset_paths.compute_source_path(source, asset_name.to_s.pluralize, extension)
-
end
-
-
2
def compute_paths(*args)
-
expand_sources(*args).collect { |source| path_to_asset_source(source) }
-
end
-
-
2
def expand_sources(sources, recursive)
-
if sources.first == :all
-
collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}")
-
else
-
sources.inject([]) do |list, source|
-
determined_source = determine_source(source, expansions)
-
update_source_list(list, determined_source)
-
end
-
end
-
end
-
-
2
def update_source_list(list, source)
-
case source
-
when String
-
list.delete(source)
-
list << source
-
when Array
-
updated_sources = source - list
-
list.concat(updated_sources)
-
end
-
end
-
-
2
def ensure_sources!(sources)
-
sources.each do |source|
-
asset_file_path!(path_to_asset_source(source))
-
end
-
end
-
-
2
def collect_asset_files(*path)
-
dir = path.first
-
-
Dir[File.join(*path.compact)].collect do |file|
-
file[-(file.size - dir.size - 1)..-1].sub(/\.\w+$/, '')
-
end.sort
-
end
-
-
2
def determine_source(source, collection)
-
case source
-
when Symbol
-
collection[source] || raise(ArgumentError, "No expansion found for #{source.inspect}")
-
else
-
source
-
end
-
end
-
-
2
def join_asset_file_contents(paths)
-
paths.collect { |path| File.read(asset_file_path!(path, true)) }.join("\n\n")
-
end
-
-
2
def write_asset_file_contents(joined_asset_path, asset_paths)
-
FileUtils.mkdir_p(File.dirname(joined_asset_path))
-
File.atomic_write(joined_asset_path) { |cache| cache.write(join_asset_file_contents(asset_paths)) }
-
-
# Set mtime to the latest of the combined files to allow for
-
# consistent ETag without a shared filesystem.
-
mt = asset_paths.map { |p| File.mtime(asset_file_path!(p)) }.max
-
File.utime(mt, mt, joined_asset_path)
-
end
-
-
2
def asset_file_path!(absolute_path, error_if_file_is_uri = false)
-
if asset_paths.is_uri?(absolute_path)
-
raise(Errno::ENOENT, "Asset file #{path} is uri and cannot be merged into single file") if error_if_file_is_uri
-
else
-
raise(Errno::ENOENT, "Asset file not found at '#{absolute_path}'" ) unless File.exist?(absolute_path)
-
return absolute_path
-
end
-
end
-
end
-
-
end
-
end
-
end
-
2
require 'thread'
-
2
require 'active_support/core_ext/file'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
-
2
module ActionView
-
2
module Helpers
-
2
module AssetTagHelper
-
-
2
class AssetPaths < ::ActionView::AssetPaths #:nodoc:
-
# You can enable or disable the asset tag ids cache.
-
# With the cache enabled, the asset tag helper methods will make fewer
-
# expensive file system calls (the default implementation checks the file
-
# system timestamp). However this prevents you from modifying any asset
-
# files while the server is running.
-
#
-
# ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids = false
-
2
mattr_accessor :cache_asset_ids
-
-
# Add or change an asset id in the asset id cache. This can be used
-
# for SASS on Heroku.
-
# :api: public
-
2
def add_to_asset_ids_cache(source, asset_id)
-
self.asset_ids_cache_guard.synchronize do
-
self.asset_ids_cache[source] = asset_id
-
end
-
end
-
-
2
private
-
-
2
def rewrite_extension(source, dir, ext)
-
source_ext = File.extname(source)
-
-
source_with_ext = if source_ext.empty?
-
"#{source}.#{ext}"
-
elsif ext != source_ext[1..-1]
-
with_ext = "#{source}.#{ext}"
-
with_ext if File.exist?(File.join(config.assets_dir, dir, with_ext))
-
end
-
-
source_with_ext || source
-
end
-
-
# Break out the asset path rewrite in case plugins wish to put the asset id
-
# someplace other than the query string.
-
2
def rewrite_asset_path(source, dir, options = nil)
-
source = "/#{dir}/#{source}" unless source[0] == ?/
-
path = config.asset_path
-
-
if path && path.respond_to?(:call)
-
return path.call(source)
-
elsif path && path.is_a?(String)
-
return path % [source]
-
end
-
-
asset_id = rails_asset_id(source)
-
if asset_id.empty?
-
source
-
else
-
"#{source}?#{asset_id}"
-
end
-
end
-
-
2
mattr_accessor :asset_ids_cache
-
2
self.asset_ids_cache = {}
-
-
2
mattr_accessor :asset_ids_cache_guard
-
2
self.asset_ids_cache_guard = Mutex.new
-
-
# Use the RAILS_ASSET_ID environment variable or the source's
-
# modification time as its cache-busting asset id.
-
2
def rails_asset_id(source)
-
if asset_id = ENV["RAILS_ASSET_ID"]
-
asset_id
-
else
-
if self.cache_asset_ids && (asset_id = self.asset_ids_cache[source])
-
asset_id
-
else
-
path = File.join(config.assets_dir, source)
-
asset_id = File.exist?(path) ? File.mtime(path).to_i.to_s : ''
-
-
if self.cache_asset_ids
-
add_to_asset_ids_cache(source, asset_id)
-
end
-
-
asset_id
-
end
-
end
-
end
-
end
-
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/core_ext/file'
-
2
require 'action_view/helpers/asset_tag_helpers/asset_include_tag'
-
-
2
module ActionView
-
2
module Helpers
-
2
module AssetTagHelper
-
-
2
class JavascriptIncludeTag < AssetIncludeTag
-
2
def asset_name
-
'javascript'
-
end
-
-
2
def extension
-
'js'
-
end
-
-
2
def asset_tag(source, options)
-
content_tag("script", "", { "type" => Mime::JS, "src" => path_to_asset(source) }.merge(options))
-
end
-
-
2
def custom_dir
-
config.javascripts_dir
-
end
-
-
2
private
-
-
2
def expand_sources(sources, recursive = false)
-
if sources.include?(:all)
-
all_asset_files = (collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}") - ['application'])
-
add_application_js(all_asset_files, sources)
-
((determine_source(:defaults, expansions).dup & all_asset_files) + all_asset_files).uniq
-
else
-
expanded_sources = sources.inject([]) do |list, source|
-
determined_source = determine_source(source, expansions)
-
update_source_list(list, determined_source)
-
end
-
add_application_js(expanded_sources, sources)
-
expanded_sources
-
end
-
end
-
-
2
def add_application_js(expanded_sources, sources)
-
if (sources.include?(:defaults) || sources.include?(:all)) && File.exist?(File.join(custom_dir, "application.#{extension}"))
-
expanded_sources.delete('application')
-
expanded_sources << "application"
-
end
-
end
-
end
-
-
-
2
module JavascriptTagHelpers
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
# Register one or more javascript files to be included when <tt>symbol</tt>
-
# is passed to <tt>javascript_include_tag</tt>. This method is typically intended
-
# to be called from plugin initialization to register javascript files
-
# that the plugin installed in <tt>public/javascripts</tt>.
-
#
-
# ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
-
#
-
# javascript_include_tag :monkey # =>
-
# <script type="text/javascript" src="/javascripts/head.js"></script>
-
# <script type="text/javascript" src="/javascripts/body.js"></script>
-
# <script type="text/javascript" src="/javascripts/tail.js"></script>
-
2
def register_javascript_expansion(expansions)
-
2
js_expansions = JavascriptIncludeTag.expansions
-
2
expansions.each do |key, values|
-
2
js_expansions[key] = (js_expansions[key] || []) | Array(values)
-
end
-
end
-
end
-
-
# Computes the path to a javascript asset in the public javascripts directory.
-
# If the +source+ filename has no extension, .js will be appended (except for explicit URIs)
-
# Full paths from the document root will be passed through.
-
# Used internally by javascript_include_tag to build the script path.
-
#
-
# ==== Examples
-
# javascript_path "xmlhr" # => /javascripts/xmlhr.js
-
# javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js
-
# javascript_path "/dir/xmlhr" # => /dir/xmlhr.js
-
# javascript_path "http://www.example.com/js/xmlhr" # => http://www.example.com/js/xmlhr
-
# javascript_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js
-
2
def javascript_path(source)
-
asset_paths.compute_public_path(source, 'javascripts', :ext => 'js')
-
end
-
2
alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
-
-
# Returns an HTML script tag for each of the +sources+ provided.
-
#
-
# Sources may be paths to JavaScript files. Relative paths are assumed to be relative
-
# to <tt>public/javascripts</tt>, full paths are assumed to be relative to the document
-
# root. Relative paths are idiomatic, use absolute paths only when needed.
-
#
-
# When passing paths, the ".js" extension is optional.
-
#
-
# If the application is not using the asset pipeline, to include the default JavaScript
-
# expansion pass <tt>:defaults</tt> as source. By default, <tt>:defaults</tt> loads jQuery,
-
# and that can be overridden in <tt>config/application.rb</tt>:
-
#
-
# config.action_view.javascript_expansions[:defaults] = %w(foo.js bar.js)
-
#
-
# When using <tt>:defaults</tt> or <tt>:all</tt>, if an <tt>application.js</tt> file exists
-
# in <tt>public/javascripts</tt> it will be included as well at the end.
-
#
-
# You can modify the HTML attributes of the script tag by passing a hash as the
-
# last argument.
-
#
-
# ==== Examples
-
# javascript_include_tag "xmlhr"
-
# # => <script type="text/javascript" src="/javascripts/xmlhr.js?1284139606"></script>
-
#
-
# javascript_include_tag "xmlhr.js"
-
# # => <script type="text/javascript" src="/javascripts/xmlhr.js?1284139606"></script>
-
#
-
# javascript_include_tag "common.javascript", "/elsewhere/cools"
-
# # => <script type="text/javascript" src="/javascripts/common.javascript?1284139606"></script>
-
# # <script type="text/javascript" src="/elsewhere/cools.js?1423139606"></script>
-
#
-
# javascript_include_tag "http://www.example.com/xmlhr"
-
# # => <script type="text/javascript" src="http://www.example.com/xmlhr"></script>
-
#
-
# javascript_include_tag "http://www.example.com/xmlhr.js"
-
# # => <script type="text/javascript" src="http://www.example.com/xmlhr.js"></script>
-
#
-
# javascript_include_tag :defaults
-
# # => <script type="text/javascript" src="/javascripts/jquery.js?1284139606"></script>
-
# # <script type="text/javascript" src="/javascripts/rails.js?1284139606"></script>
-
# # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script>
-
#
-
# Note: The application.js file is only referenced if it exists
-
#
-
# You can also include all JavaScripts in the +javascripts+ directory using <tt>:all</tt> as the source:
-
#
-
# javascript_include_tag :all
-
# # => <script type="text/javascript" src="/javascripts/jquery.js?1284139606"></script>
-
# # <script type="text/javascript" src="/javascripts/rails.js?1284139606"></script>
-
# # <script type="text/javascript" src="/javascripts/shop.js?1284139606"></script>
-
# # <script type="text/javascript" src="/javascripts/checkout.js?1284139606"></script>
-
# # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script>
-
#
-
# Note that your defaults of choice will be included first, so they will be available to all subsequently
-
# included files.
-
#
-
# If you want Rails to search in all the subdirectories under <tt>public/javascripts</tt>, you should
-
# explicitly set <tt>:recursive</tt>:
-
#
-
# javascript_include_tag :all, :recursive => true
-
#
-
# == Caching multiple JavaScripts into one
-
#
-
# You can also cache multiple JavaScripts into one file, which requires less HTTP connections to download
-
# and can better be compressed by gzip (leading to faster transfers). Caching will only happen if
-
# <tt>config.perform_caching</tt> is set to true (which is the case by default for the Rails
-
# production environment, but not for the development environment).
-
#
-
# ==== Examples
-
#
-
# # assuming config.perform_caching is false
-
# javascript_include_tag :all, :cache => true
-
# # => <script type="text/javascript" src="/javascripts/jquery.js?1284139606"></script>
-
# # <script type="text/javascript" src="/javascripts/rails.js?1284139606"></script>
-
# # <script type="text/javascript" src="/javascripts/shop.js?1284139606"></script>
-
# # <script type="text/javascript" src="/javascripts/checkout.js?1284139606"></script>
-
# # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script>
-
#
-
# # assuming config.perform_caching is true
-
# javascript_include_tag :all, :cache => true
-
# # => <script type="text/javascript" src="/javascripts/all.js?1344139789"></script>
-
#
-
# # assuming config.perform_caching is false
-
# javascript_include_tag "jquery", "cart", "checkout", :cache => "shop"
-
# # => <script type="text/javascript" src="/javascripts/jquery.js?1284139606"></script>
-
# # <script type="text/javascript" src="/javascripts/cart.js?1289139157"></script>
-
# # <script type="text/javascript" src="/javascripts/checkout.js?1299139816"></script>
-
#
-
# # assuming config.perform_caching is true
-
# javascript_include_tag "jquery", "cart", "checkout", :cache => "shop"
-
# # => <script type="text/javascript" src="/javascripts/shop.js?1299139816"></script>
-
#
-
# The <tt>:recursive</tt> option is also available for caching:
-
#
-
# javascript_include_tag :all, :cache => true, :recursive => true
-
2
def javascript_include_tag(*sources)
-
@javascript_include ||= JavascriptIncludeTag.new(config, asset_paths)
-
@javascript_include.include_tag(*sources)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/core_ext/file'
-
2
require 'action_view/helpers/asset_tag_helpers/asset_include_tag'
-
-
2
module ActionView
-
2
module Helpers
-
2
module AssetTagHelper
-
-
2
class StylesheetIncludeTag < AssetIncludeTag
-
2
def asset_name
-
'stylesheet'
-
end
-
-
2
def extension
-
'css'
-
end
-
-
2
def asset_tag(source, options)
-
# We force the :request protocol here to avoid a double-download bug in IE7 and IE8
-
tag("link", { "rel" => "stylesheet", "type" => Mime::CSS, "media" => "screen", "href" => path_to_asset(source, :protocol => :request) }.merge(options))
-
end
-
-
2
def custom_dir
-
config.stylesheets_dir
-
end
-
end
-
-
-
2
module StylesheetTagHelpers
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
# Register one or more stylesheet files to be included when <tt>symbol</tt>
-
# is passed to <tt>stylesheet_link_tag</tt>. This method is typically intended
-
# to be called from plugin initialization to register stylesheet files
-
# that the plugin installed in <tt>public/stylesheets</tt>.
-
#
-
# ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
-
#
-
# stylesheet_link_tag :monkey # =>
-
# <link href="/stylesheets/head.css" media="screen" rel="stylesheet" type="text/css" />
-
# <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" />
-
# <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" />
-
2
def register_stylesheet_expansion(expansions)
-
2
style_expansions = StylesheetIncludeTag.expansions
-
2
expansions.each do |key, values|
-
style_expansions[key] = (style_expansions[key] || []) | Array(values)
-
end
-
end
-
end
-
-
# Computes the path to a stylesheet asset in the public stylesheets directory.
-
# If the +source+ filename has no extension, <tt>.css</tt> will be appended (except for explicit URIs).
-
# Full paths from the document root will be passed through.
-
# Used internally by +stylesheet_link_tag+ to build the stylesheet path.
-
#
-
# ==== Examples
-
# stylesheet_path "style" # => /stylesheets/style.css
-
# stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css
-
# stylesheet_path "/dir/style.css" # => /dir/style.css
-
# stylesheet_path "http://www.example.com/css/style" # => http://www.example.com/css/style
-
# stylesheet_path "http://www.example.com/css/style.css" # => http://www.example.com/css/style.css
-
2
def stylesheet_path(source)
-
asset_paths.compute_public_path(source, 'stylesheets', :ext => 'css', :protocol => :request)
-
end
-
2
alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
-
-
# Returns a stylesheet link tag for the sources specified as arguments. If
-
# you don't specify an extension, <tt>.css</tt> will be appended automatically.
-
# You can modify the link attributes by passing a hash as the last argument.
-
# For historical reasons, the 'media' attribute will always be present and defaults
-
# to "screen", so you must explicitely set it to "all" for the stylesheet(s) to
-
# apply to all media types.
-
#
-
# ==== Examples
-
# stylesheet_link_tag "style" # =>
-
# <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# stylesheet_link_tag "style.css" # =>
-
# <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# stylesheet_link_tag "http://www.example.com/style.css" # =>
-
# <link href="http://www.example.com/style.css" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# stylesheet_link_tag "style", :media => "all" # =>
-
# <link href="/stylesheets/style.css" media="all" rel="stylesheet" type="text/css" />
-
#
-
# stylesheet_link_tag "style", :media => "print" # =>
-
# <link href="/stylesheets/style.css" media="print" rel="stylesheet" type="text/css" />
-
#
-
# stylesheet_link_tag "random.styles", "/css/stylish" # =>
-
# <link href="/stylesheets/random.styles" media="screen" rel="stylesheet" type="text/css" />
-
# <link href="/css/stylish.css" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# You can also include all styles in the stylesheets directory using <tt>:all</tt> as the source:
-
#
-
# stylesheet_link_tag :all # =>
-
# <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
-
# <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" />
-
# <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# If you want Rails to search in all the subdirectories under stylesheets, you should explicitly set <tt>:recursive</tt>:
-
#
-
# stylesheet_link_tag :all, :recursive => true
-
#
-
# == Caching multiple stylesheets into one
-
#
-
# You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be
-
# compressed by gzip (leading to faster transfers). Caching will only happen if config.perform_caching
-
# is set to true (which is the case by default for the Rails production environment, but not for the development
-
# environment). Examples:
-
#
-
# ==== Examples
-
# stylesheet_link_tag :all, :cache => true # when config.perform_caching is false =>
-
# <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />
-
# <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" />
-
# <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# stylesheet_link_tag :all, :cache => true # when config.perform_caching is true =>
-
# <link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when config.perform_caching is false =>
-
# <link href="/stylesheets/shop.css" media="screen" rel="stylesheet" type="text/css" />
-
# <link href="/stylesheets/cart.css" media="screen" rel="stylesheet" type="text/css" />
-
# <link href="/stylesheets/checkout.css" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when config.perform_caching is true =>
-
# <link href="/stylesheets/payment.css" media="screen" rel="stylesheet" type="text/css" />
-
#
-
# The <tt>:recursive</tt> option is also available for caching:
-
#
-
# stylesheet_link_tag :all, :cache => true, :recursive => true
-
#
-
# To force concatenation (even in development mode) set <tt>:concat</tt> to true. This is useful if
-
# you have too many stylesheets for IE to load.
-
#
-
# stylesheet_link_tag :all, :concat => true
-
#
-
2
def stylesheet_link_tag(*sources)
-
@stylesheet_include ||= StylesheetIncludeTag.new(config, asset_paths)
-
@stylesheet_include.include_tag(*sources)
-
end
-
-
end
-
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module ActionView
-
# = Action View Atom Feed Helpers
-
2
module Helpers #:nodoc:
-
2
module AtomFeedHelper
-
# Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERB or any other
-
# template languages).
-
#
-
# Full usage example:
-
#
-
# config/routes.rb:
-
# Basecamp::Application.routes.draw do
-
# resources :posts
-
# root :to => "posts#index"
-
# end
-
#
-
# app/controllers/posts_controller.rb:
-
# class PostsController < ApplicationController::Base
-
# # GET /posts.html
-
# # GET /posts.atom
-
# def index
-
# @posts = Post.all
-
#
-
# respond_to do |format|
-
# format.html
-
# format.atom
-
# end
-
# end
-
# end
-
#
-
# app/views/posts/index.atom.builder:
-
# atom_feed do |feed|
-
# feed.title("My great blog!")
-
# feed.updated(@posts[0].created_at) if @posts.length > 0
-
#
-
# @posts.each do |post|
-
# feed.entry(post) do |entry|
-
# entry.title(post.title)
-
# entry.content(post.body, :type => 'html')
-
#
-
# entry.author do |author|
-
# author.name("DHH")
-
# end
-
# end
-
# end
-
# end
-
#
-
# The options for atom_feed are:
-
#
-
# * <tt>:language</tt>: Defaults to "en-US".
-
# * <tt>:root_url</tt>: The HTML alternative that this feed is doubling for. Defaults to / on the current host.
-
# * <tt>:url</tt>: The URL for this feed. Defaults to the current URL.
-
# * <tt>:id</tt>: The id for this feed. Defaults to "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}"
-
# * <tt>:schema_date</tt>: The date at which the tag scheme for the feed was first used. A good default is the year you
-
# created the feed. See http://feedvalidator.org/docs/error/InvalidTAG.html for more information. If not specified,
-
# 2005 is used (as an "I don't care" value).
-
# * <tt>:instruct</tt>: Hash of XML processing instructions in the form {target => {attribute => value, }} or {target => [{attribute => value, }, ]}
-
#
-
# Other namespaces can be added to the root element:
-
#
-
# app/views/posts/index.atom.builder:
-
# atom_feed({'xmlns:app' => 'http://www.w3.org/2007/app',
-
# 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearch/1.1/'}) do |feed|
-
# feed.title("My great blog!")
-
# feed.updated((@posts.first.created_at))
-
# feed.tag!(openSearch:totalResults, 10)
-
#
-
# @posts.each do |post|
-
# feed.entry(post) do |entry|
-
# entry.title(post.title)
-
# entry.content(post.body, :type => 'html')
-
# entry.tag!('app:edited', Time.now)
-
#
-
# entry.author do |author|
-
# author.name("DHH")
-
# end
-
# end
-
# end
-
# end
-
#
-
# The Atom spec defines five elements (content rights title subtitle
-
# summary) which may directly contain xhtml content if :type => 'xhtml'
-
# is specified as an attribute. If so, this helper will take care of
-
# the enclosing div and xhtml namespace declaration. Example usage:
-
#
-
# entry.summary :type => 'xhtml' do |xhtml|
-
# xhtml.p pluralize(order.line_items.count, "line item")
-
# xhtml.p "Shipped to #{order.address}"
-
# xhtml.p "Paid by #{order.pay_type}"
-
# end
-
#
-
#
-
# <tt>atom_feed</tt> yields an +AtomFeedBuilder+ instance. Nested elements yield
-
# an +AtomBuilder+ instance.
-
2
def atom_feed(options = {}, &block)
-
if options[:schema_date]
-
options[:schema_date] = options[:schema_date].strftime("%Y-%m-%d") if options[:schema_date].respond_to?(:strftime)
-
else
-
options[:schema_date] = "2005" # The Atom spec copyright date
-
end
-
-
xml = options.delete(:xml) || eval("xml", block.binding)
-
xml.instruct!
-
if options[:instruct]
-
options[:instruct].each do |target,attrs|
-
if attrs.respond_to?(:keys)
-
xml.instruct!(target, attrs)
-
elsif attrs.respond_to?(:each)
-
attrs.each { |attr_group| xml.instruct!(target, attr_group) }
-
end
-
end
-
end
-
-
feed_opts = {"xml:lang" => options[:language] || "en-US", "xmlns" => 'http://www.w3.org/2005/Atom'}
-
feed_opts.merge!(options).reject!{|k,v| !k.to_s.match(/^xml/)}
-
-
xml.feed(feed_opts) do
-
xml.id(options[:id] || "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}")
-
xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:root_url] || (request.protocol + request.host_with_port))
-
xml.link(:rel => 'self', :type => 'application/atom+xml', :href => options[:url] || request.url)
-
-
yield AtomFeedBuilder.new(xml, self, options)
-
end
-
end
-
-
2
class AtomBuilder
-
2
XHTML_TAG_NAMES = %w(content rights title subtitle summary).to_set
-
-
2
def initialize(xml)
-
@xml = xml
-
end
-
-
2
private
-
# Delegate to xml builder, first wrapping the element in a xhtml
-
# namespaced div element if the method and arguments indicate
-
# that an xhtml_block? is desired.
-
2
def method_missing(method, *arguments, &block)
-
if xhtml_block?(method, arguments)
-
@xml.__send__(method, *arguments) do
-
@xml.div(:xmlns => 'http://www.w3.org/1999/xhtml') do |xhtml|
-
block.call(xhtml)
-
end
-
end
-
else
-
@xml.__send__(method, *arguments, &block)
-
end
-
end
-
-
# True if the method name matches one of the five elements defined
-
# in the Atom spec as potentially containing XHTML content and
-
# if :type => 'xhtml' is, in fact, specified.
-
2
def xhtml_block?(method, arguments)
-
if XHTML_TAG_NAMES.include?(method.to_s)
-
last = arguments.last
-
last.is_a?(Hash) && last[:type].to_s == 'xhtml'
-
end
-
end
-
end
-
-
2
class AtomFeedBuilder < AtomBuilder
-
2
def initialize(xml, view, feed_options = {})
-
@xml, @view, @feed_options = xml, view, feed_options
-
end
-
-
# Accepts a Date or Time object and inserts it in the proper format. If nil is passed, current time in UTC is used.
-
2
def updated(date_or_time = nil)
-
@xml.updated((date_or_time || Time.now.utc).xmlschema)
-
end
-
-
# Creates an entry tag for a specific record and prefills the id using class and id.
-
#
-
# Options:
-
#
-
# * <tt>:published</tt>: Time first published. Defaults to the created_at attribute on the record if one such exists.
-
# * <tt>:updated</tt>: Time of update. Defaults to the updated_at attribute on the record if one such exists.
-
# * <tt>:url</tt>: The URL for this entry. Defaults to the polymorphic_url for the record.
-
# * <tt>:id</tt>: The ID for this entry. Defaults to "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}"
-
2
def entry(record, options = {})
-
@xml.entry do
-
@xml.id(options[:id] || "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}")
-
-
if options[:published] || (record.respond_to?(:created_at) && record.created_at)
-
@xml.published((options[:published] || record.created_at).xmlschema)
-
end
-
-
if options[:updated] || (record.respond_to?(:updated_at) && record.updated_at)
-
@xml.updated((options[:updated] || record.updated_at).xmlschema)
-
end
-
-
@xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:url] || @view.polymorphic_url(record))
-
-
yield AtomBuilder.new(@xml)
-
end
-
end
-
end
-
-
end
-
end
-
end
-
2
module ActionView
-
# = Action View Cache Helper
-
2
module Helpers
-
2
module CacheHelper
-
# This helper exposes a method for caching fragments of a view
-
# rather than an entire action or page. This technique is useful
-
# caching pieces like menus, lists of newstopics, static HTML
-
# fragments, and so on. This method takes a block that contains
-
# the content you wish to cache.
-
#
-
# See ActionController::Caching::Fragments for usage instructions.
-
#
-
# ==== Examples
-
# If you want to cache a navigation menu, you can do following:
-
#
-
# <% cache do %>
-
# <%= render :partial => "menu" %>
-
# <% end %>
-
#
-
# You can also cache static content:
-
#
-
# <% cache do %>
-
# <p>Hello users! Welcome to our website!</p>
-
# <% end %>
-
#
-
# Static content with embedded ruby content can be cached as
-
# well:
-
#
-
# <% cache do %>
-
# Topics:
-
# <%= render :partial => "topics", :collection => @topic_list %>
-
# <i>Topics listed alphabetically</i>
-
# <% end %>
-
2
def cache(name = {}, options = nil, &block)
-
if controller.perform_caching
-
safe_concat(fragment_for(name, options, &block))
-
else
-
yield
-
end
-
-
nil
-
end
-
-
2
private
-
# TODO: Create an object that has caching read/write on it
-
2
def fragment_for(name = {}, options = nil, &block) #:nodoc:
-
if fragment = controller.read_fragment(name, options)
-
fragment
-
else
-
# VIEW TODO: Make #capture usable outside of ERB
-
# This dance is needed because Builder can't use capture
-
pos = output_buffer.length
-
yield
-
output_safe = output_buffer.html_safe?
-
fragment = output_buffer.slice!(pos..-1)
-
if output_safe
-
self.output_buffer = output_buffer.class.new(output_buffer)
-
end
-
controller.write_fragment(name, fragment, options)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/string/output_safety'
-
-
2
module ActionView
-
# = Action View Capture Helper
-
2
module Helpers
-
# CaptureHelper exposes methods to let you extract generated markup which
-
# can be used in other parts of a template or layout file.
-
#
-
# It provides a method to capture blocks into variables through capture and
-
# a way to capture a block of markup for use in a layout through content_for.
-
2
module CaptureHelper
-
# The capture method allows you to extract part of a template into a
-
# variable. You can then use this variable anywhere in your templates or layout.
-
#
-
# ==== Examples
-
# The capture method can be used in ERB templates...
-
#
-
# <% @greeting = capture do %>
-
# Welcome to my shiny new web page! The date and time is
-
# <%= Time.now %>
-
# <% end %>
-
#
-
# ...and Builder (RXML) templates.
-
#
-
# @timestamp = capture do
-
# "The current timestamp is #{Time.now}."
-
# end
-
#
-
# You can then use that variable anywhere else. For example:
-
#
-
# <html>
-
# <head><title><%= @greeting %></title></head>
-
# <body>
-
# <b><%= @greeting %></b>
-
# </body></html>
-
#
-
2
def capture(*args)
-
value = nil
-
buffer = with_output_buffer { value = yield(*args) }
-
if string = buffer.presence || value and string.is_a?(String)
-
ERB::Util.html_escape string
-
end
-
end
-
-
# Calling content_for stores a block of markup in an identifier for later use.
-
# You can make subsequent calls to the stored content in other templates, helper modules
-
# or the layout by passing the identifier as an argument to <tt>content_for</tt>.
-
#
-
# Note: <tt>yield</tt> can still be used to retrieve the stored content, but calling
-
# <tt>yield</tt> doesn't work in helper modules, while <tt>content_for</tt> does.
-
#
-
# ==== Examples
-
#
-
# <% content_for :not_authorized do %>
-
# alert('You are not authorized to do that!')
-
# <% end %>
-
#
-
# You can then use <tt>content_for :not_authorized</tt> anywhere in your templates.
-
#
-
# <%= content_for :not_authorized if current_user.nil? %>
-
#
-
# This is equivalent to:
-
#
-
# <%= yield :not_authorized if current_user.nil? %>
-
#
-
# <tt>content_for</tt>, however, can also be used in helper modules.
-
#
-
# module StorageHelper
-
# def stored_content
-
# content_for(:storage) || "Your storage is empty"
-
# end
-
# end
-
#
-
# This helper works just like normal helpers.
-
#
-
# <%= stored_content %>
-
#
-
# You can use the <tt>yield</tt> syntax alongside an existing call to <tt>yield</tt> in a layout. For example:
-
#
-
# <%# This is the layout %>
-
# <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-
# <head>
-
# <title>My Website</title>
-
# <%= yield :script %>
-
# </head>
-
# <body>
-
# <%= yield %>
-
# </body>
-
# </html>
-
#
-
# And now, we'll create a view that has a <tt>content_for</tt> call that
-
# creates the <tt>script</tt> identifier.
-
#
-
# <%# This is our view %>
-
# Please login!
-
#
-
# <% content_for :script do %>
-
# <script type="text/javascript">alert('You are not authorized to view this page!')</script>
-
# <% end %>
-
#
-
# Then, in another view, you could to do something like this:
-
#
-
# <%= link_to 'Logout', :action => 'logout', :remote => true %>
-
#
-
# <% content_for :script do %>
-
# <%= javascript_include_tag :defaults %>
-
# <% end %>
-
#
-
# That will place +script+ tags for your default set of JavaScript files on the page;
-
# this technique is useful if you'll only be using these scripts in a few views.
-
#
-
# Note that content_for concatenates the blocks it is given for a particular
-
# identifier in order. For example:
-
#
-
# <% content_for :navigation do %>
-
# <li><%= link_to 'Home', :action => 'index' %></li>
-
# <% end %>
-
#
-
# <%# Add some other content, or use a different template: %>
-
#
-
# <% content_for :navigation do %>
-
# <li><%= link_to 'Login', :action => 'login' %></li>
-
# <% end %>
-
#
-
# Then, in another template or layout, this code would render both links in order:
-
#
-
# <ul><%= content_for :navigation %></ul>
-
#
-
# Lastly, simple content can be passed as a parameter:
-
#
-
# <% content_for :script, javascript_include_tag(:defaults) %>
-
#
-
# WARNING: content_for is ignored in caches. So you shouldn't use it
-
# for elements that will be fragment cached.
-
2
def content_for(name, content = nil, &block)
-
if content || block_given?
-
content = capture(&block) if block_given?
-
@view_flow.append(name, content) if content
-
nil
-
else
-
@view_flow.get(name)
-
end
-
end
-
-
# The same as +content_for+ but when used with streaming flushes
-
# straight back to the layout. In other words, if you want to
-
# concatenate several times to the same buffer when rendering a given
-
# template, you should use +content_for+, if not, use +provide+ to tell
-
# the layout to stop looking for more contents.
-
2
def provide(name, content = nil, &block)
-
content = capture(&block) if block_given?
-
result = @view_flow.append!(name, content) if content
-
result unless content
-
end
-
-
# content_for? simply checks whether any content has been captured yet using content_for
-
# Useful to render parts of your layout differently based on what is in your views.
-
#
-
# ==== Examples
-
#
-
# Perhaps you will use different css in you layout if no content_for :right_column
-
#
-
# <%# This is the layout %>
-
# <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-
# <head>
-
# <title>My Website</title>
-
# <%= yield :script %>
-
# </head>
-
# <body class="<%= content_for?(:right_col) ? 'one-column' : 'two-column' %>">
-
# <%= yield %>
-
# <%= yield :right_col %>
-
# </body>
-
# </html>
-
2
def content_for?(name)
-
@view_flow.get(name).present?
-
end
-
-
# Use an alternate output buffer for the duration of the block.
-
# Defaults to a new empty string.
-
2
def with_output_buffer(buf = nil) #:nodoc:
-
unless buf
-
buf = ActionView::OutputBuffer.new
-
buf.force_encoding(output_buffer.encoding) if output_buffer.respond_to?(:encoding) && buf.respond_to?(:force_encoding)
-
end
-
self.output_buffer, old_buffer = buf, output_buffer
-
yield
-
output_buffer
-
ensure
-
self.output_buffer = old_buffer
-
end
-
-
# Add the output buffer to the response body and start a new one.
-
2
def flush_output_buffer #:nodoc:
-
if output_buffer && !output_buffer.empty?
-
response.body_parts << output_buffer
-
self.output_buffer = output_buffer.respond_to?(:clone_empty) ? output_buffer.clone_empty : output_buffer[0, 0]
-
nil
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attr_internal'
-
-
2
module ActionView
-
2
module Helpers
-
# This module keeps all methods and behavior in ActionView
-
# that simply delegates to the controller.
-
2
module ControllerHelper #:nodoc:
-
2
attr_internal :controller, :request
-
-
2
delegate :request_forgery_protection_token, :params, :session, :cookies, :response, :headers,
-
:flash, :action_name, :controller_name, :controller_path, :to => :controller
-
-
2
def assign_controller(controller)
-
4
if @_controller = controller
-
4
@_request = controller.request if controller.respond_to?(:request)
-
4
@_config = controller.config.inheritable_copy if controller.respond_to?(:config)
-
end
-
end
-
-
2
def logger
-
controller.logger if controller.respond_to?(:logger)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/string/strip'
-
-
2
module ActionView
-
# = Action View CSRF Helper
-
2
module Helpers
-
2
module CsrfHelper
-
# Returns meta tags "csrf-param" and "csrf-token" with the name of the cross-site
-
# request forgery protection parameter and token, respectively.
-
#
-
# <head>
-
# <%= csrf_meta_tags %>
-
# </head>
-
#
-
# These are used to generate the dynamic forms that implement non-remote links with
-
# <tt>:method</tt>.
-
#
-
# Note that regular forms generate hidden fields, and that Ajax calls are whitelisted,
-
# so they do not use these tags.
-
2
def csrf_meta_tags
-
if protect_against_forgery?
-
[
-
tag('meta', :name => 'csrf-param', :content => request_forgery_protection_token),
-
tag('meta', :name => 'csrf-token', :content => form_authenticity_token)
-
].join("\n").html_safe
-
end
-
end
-
-
# For backwards compatibility.
-
2
alias csrf_meta_tag csrf_meta_tags
-
end
-
end
-
end
-
2
require 'date'
-
2
require 'action_view/helpers/tag_helper'
-
2
require 'active_support/core_ext/date/conversions'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/object/with_options'
-
-
2
module ActionView
-
2
module Helpers
-
# = Action View Date Helpers
-
#
-
# The Date Helper primarily creates select/option tags for different kinds of dates and times or date and time
-
# elements. All of the select-type methods share a number of common options that are as follows:
-
#
-
# * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday"
-
# would give birthday[month] instead of date[month] if passed to the <tt>select_month</tt> method.
-
# * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date.
-
# * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true,
-
# the <tt>select_month</tt> method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead
-
# of "date[month]".
-
2
module DateHelper
-
# Reports the approximate distance in time between two Time, Date or DateTime objects or integers as seconds.
-
# Set <tt>include_seconds</tt> to true if you want more detailed approximations when distance < 1 min, 29 secs.
-
# Distances are reported based on the following table:
-
#
-
# 0 <-> 29 secs # => less than a minute
-
# 30 secs <-> 1 min, 29 secs # => 1 minute
-
# 1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes
-
# 44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour
-
# 89 mins, 30 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours
-
# 23 hrs, 59 mins, 30 secs <-> 41 hrs, 59 mins, 29 secs # => 1 day
-
# 41 hrs, 59 mins, 30 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
-
# 29 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 1 month
-
# 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months
-
# 1 yr <-> 1 yr, 3 months # => about 1 year
-
# 1 yr, 3 months <-> 1 yr, 9 months # => over 1 year
-
# 1 yr, 9 months <-> 2 yr minus 1 sec # => almost 2 years
-
# 2 yrs <-> max time or date # => (same rules as 1 yr)
-
#
-
# With <tt>include_seconds</tt> = true and the difference < 1 minute 29 seconds:
-
# 0-4 secs # => less than 5 seconds
-
# 5-9 secs # => less than 10 seconds
-
# 10-19 secs # => less than 20 seconds
-
# 20-39 secs # => half a minute
-
# 40-59 secs # => less than a minute
-
# 60-89 secs # => 1 minute
-
#
-
# ==== Examples
-
# from_time = Time.now
-
# distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour
-
# distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour
-
# distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute
-
# distance_of_time_in_words(from_time, from_time + 15.seconds, true) # => less than 20 seconds
-
# distance_of_time_in_words(from_time, 3.years.from_now) # => about 3 years
-
# distance_of_time_in_words(from_time, from_time + 60.hours) # => 3 days
-
# distance_of_time_in_words(from_time, from_time + 45.seconds, true) # => less than a minute
-
# distance_of_time_in_words(from_time, from_time - 45.seconds, true) # => less than a minute
-
# distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute
-
# distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year
-
# distance_of_time_in_words(from_time, from_time + 3.years + 6.months) # => over 3 years
-
# distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => about 4 years
-
#
-
# to_time = Time.now + 6.years + 19.days
-
# distance_of_time_in_words(from_time, to_time, true) # => about 6 years
-
# distance_of_time_in_words(to_time, from_time, true) # => about 6 years
-
# distance_of_time_in_words(Time.now, Time.now) # => less than a minute
-
#
-
2
def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {})
-
options = {
-
:scope => :'datetime.distance_in_words',
-
}.merge!(options)
-
-
from_time = from_time.to_time if from_time.respond_to?(:to_time)
-
to_time = to_time.to_time if to_time.respond_to?(:to_time)
-
distance = (to_time.to_f - from_time.to_f).abs
-
distance_in_minutes = (distance / 60.0).round
-
distance_in_seconds = distance.round
-
-
I18n.with_options :locale => options[:locale], :scope => options[:scope] do |locale|
-
case distance_in_minutes
-
when 0..1
-
return distance_in_minutes == 0 ?
-
locale.t(:less_than_x_minutes, :count => 1) :
-
locale.t(:x_minutes, :count => distance_in_minutes) unless include_seconds
-
-
case distance_in_seconds
-
when 0..4 then locale.t :less_than_x_seconds, :count => 5
-
when 5..9 then locale.t :less_than_x_seconds, :count => 10
-
when 10..19 then locale.t :less_than_x_seconds, :count => 20
-
when 20..39 then locale.t :half_a_minute
-
when 40..59 then locale.t :less_than_x_minutes, :count => 1
-
else locale.t :x_minutes, :count => 1
-
end
-
-
when 2..44 then locale.t :x_minutes, :count => distance_in_minutes
-
when 45..89 then locale.t :about_x_hours, :count => 1
-
when 90..1439 then locale.t :about_x_hours, :count => (distance_in_minutes.to_f / 60.0).round
-
when 1440..2519 then locale.t :x_days, :count => 1
-
when 2520..43199 then locale.t :x_days, :count => (distance_in_minutes.to_f / 1440.0).round
-
when 43200..86399 then locale.t :about_x_months, :count => 1
-
when 86400..525599 then locale.t :x_months, :count => (distance_in_minutes.to_f / 43200.0).round
-
else
-
fyear = from_time.year
-
fyear += 1 if from_time.month >= 3
-
tyear = to_time.year
-
tyear -= 1 if to_time.month < 3
-
leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count{|x| Date.leap?(x)}
-
minute_offset_for_leap_year = leap_years * 1440
-
# Discount the leap year days when calculating year distance.
-
# e.g. if there are 20 leap year days between 2 dates having the same day
-
# and month then the based on 365 days calculation
-
# the distance in years will come out to over 80 years when in written
-
# english it would read better as about 80 years.
-
minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year
-
remainder = (minutes_with_offset % 525600)
-
distance_in_years = (minutes_with_offset.div 525600)
-
if remainder < 131400
-
locale.t(:about_x_years, :count => distance_in_years)
-
elsif remainder < 394200
-
locale.t(:over_x_years, :count => distance_in_years)
-
else
-
locale.t(:almost_x_years, :count => distance_in_years + 1)
-
end
-
end
-
end
-
end
-
-
# Like <tt>distance_of_time_in_words</tt>, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
-
#
-
# ==== Examples
-
# time_ago_in_words(3.minutes.from_now) # => 3 minutes
-
# time_ago_in_words(Time.now - 15.hours) # => about 15 hours
-
# time_ago_in_words(Time.now) # => less than a minute
-
#
-
# from_time = Time.now - 3.days - 14.minutes - 25.seconds
-
# time_ago_in_words(from_time) # => 3 days
-
#
-
2
def time_ago_in_words(from_time, include_seconds = false, options = {})
-
distance_of_time_in_words(from_time, Time.now, include_seconds, options)
-
end
-
-
2
alias_method :distance_of_time_in_words_to_now, :time_ago_in_words
-
-
# Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based
-
# attribute (identified by +method+) on an object assigned to the template (identified by +object+).
-
#
-
#
-
# ==== Options
-
# * <tt>:use_month_numbers</tt> - Set to true if you want to use month numbers rather than month names (e.g.
-
# "2" instead of "February").
-
# * <tt>:use_short_month</tt> - Set to true if you want to use abbreviated month names instead of full
-
# month names (e.g. "Feb" instead of "February").
-
# * <tt>:add_month_numbers</tt> - Set to true if you want to use both month numbers and month names (e.g.
-
# "2 - February" instead of "February").
-
# * <tt>:use_month_names</tt> - Set to an array with 12 month names if you want to customize month names.
-
# Note: You can also use Rails' i18n functionality for this.
-
# * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing).
-
# * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Time.now.year - 5</tt>.
-
# * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Time.now.year + 5</tt>.
-
# * <tt>:discard_day</tt> - Set to true if you don't want to show a day select. This includes the day
-
# as a hidden field instead of showing a select field. Also note that this implicitly sets the day to be the
-
# first of the given month in order to not create invalid dates like 31 February.
-
# * <tt>:discard_month</tt> - Set to true if you don't want to show a month select. This includes the month
-
# as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true.
-
# * <tt>:discard_year</tt> - Set to true if you don't want to show a year select. This includes the year
-
# as a hidden field instead of showing a select field.
-
# * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> to
-
# customize the order in which the select fields are shown. If you leave out any of the symbols, the respective
-
# select will not be shown (like when you set <tt>:discard_xxx => true</tt>. Defaults to the order defined in
-
# the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails).
-
# * <tt>:include_blank</tt> - Include a blank option in every select field so it's possible to set empty
-
# dates.
-
# * <tt>:default</tt> - Set a default date if the affected date isn't set or is nil.
-
# * <tt>:disabled</tt> - Set to true if you want show the select fields as disabled.
-
# * <tt>:prompt</tt> - Set to true (for a generic prompt), a prompt string or a hash of prompt strings
-
# for <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt> and <tt>:second</tt>.
-
# Setting this option prepends a select option with a generic prompt (Day, Month, Year, Hour, Minute, Seconds)
-
# or the given prompt string.
-
#
-
# If anything is passed in the +html_options+ hash it will be applied to every select tag in the set.
-
#
-
# NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed.
-
#
-
# ==== Examples
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute.
-
# date_select("article", "written_on")
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
-
# # with the year in the year drop down box starting at 1995.
-
# date_select("article", "written_on", :start_year => 1995)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
-
# # with the year in the year drop down box starting at 1995, numbers used for months instead of words,
-
# # and without a day select box.
-
# date_select("article", "written_on", :start_year => 1995, :use_month_numbers => true,
-
# :discard_day => true, :include_blank => true)
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
-
# # with the fields ordered as day, month, year rather than month, day, year.
-
# date_select("article", "written_on", :order => [:day, :month, :year])
-
#
-
# # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute
-
# # lacking a year field.
-
# date_select("user", "birthday", :order => [:month, :day])
-
#
-
# # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
-
# # which is initially set to the date 3 days from the current date
-
# date_select("article", "written_on", :default => 3.days.from_now)
-
#
-
# # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute
-
# # that will have a default day of 20.
-
# date_select("credit_card", "bill_due", :default => { :day => 20 })
-
#
-
# # Generates a date select with custom prompts.
-
# date_select("article", "written_on", :prompt => { :day => 'Select day', :month => 'Select month', :year => 'Select year' })
-
#
-
# The selects are prepared for multi-parameter assignment to an Active Record object.
-
#
-
# Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
-
# all month choices are valid.
-
2
def date_select(object_name, method, options = {}, html_options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_date_select_tag(options, html_options)
-
end
-
-
# Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a
-
# specified time-based attribute (identified by +method+) on an object assigned to the template (identified by
-
# +object+). You can include the seconds with <tt>:include_seconds</tt>. You can get hours in the AM/PM format
-
# with <tt>:ampm</tt> option.
-
#
-
# This method will also generate 3 input hidden tags, for the actual year, month and day unless the option
-
# <tt>:ignore_date</tt> is set to +true+. If you set the <tt>:ignore_date</tt> to +true+, you must have a
-
# +date_select+ on the same method within the form otherwise an exception will be raised.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# ==== Examples
-
# # Creates a time select tag that, when POSTed, will be stored in the article variable in the sunrise attribute.
-
# time_select("article", "sunrise")
-
#
-
# # Creates a time select tag with a seconds field that, when POSTed, will be stored in the article variables in
-
# # the sunrise attribute.
-
# time_select("article", "start_time", :include_seconds => true)
-
#
-
# # You can set the <tt>:minute_step</tt> to 15 which will give you: 00, 15, 30 and 45.
-
# time_select 'game', 'game_time', {:minute_step => 15}
-
#
-
# # Creates a time select tag with a custom prompt. Use <tt>:prompt => true</tt> for generic prompts.
-
# time_select("article", "written_on", :prompt => {:hour => 'Choose hour', :minute => 'Choose minute', :second => 'Choose seconds'})
-
# time_select("article", "written_on", :prompt => {:hour => true}) # generic prompt for hours
-
# time_select("article", "written_on", :prompt => true) # generic prompts for all
-
#
-
# # You can set :ampm option to true which will show the hours as: 12 PM, 01 AM .. 11 PM.
-
# time_select 'game', 'game_time', {:ampm => true}
-
#
-
# The selects are prepared for multi-parameter assignment to an Active Record object.
-
#
-
# Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
-
# all month choices are valid.
-
2
def time_select(object_name, method, options = {}, html_options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_time_select_tag(options, html_options)
-
end
-
-
# Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a
-
# specified datetime-based attribute (identified by +method+) on an object assigned to the template (identified
-
# by +object+).
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# ==== Examples
-
# # Generates a datetime select that, when POSTed, will be stored in the article variable in the written_on
-
# # attribute.
-
# datetime_select("article", "written_on")
-
#
-
# # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the
-
# # article variable in the written_on attribute.
-
# datetime_select("article", "written_on", :start_year => 1995)
-
#
-
# # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will
-
# # be stored in the trip variable in the departing attribute.
-
# datetime_select("trip", "departing", :default => 3.days.from_now)
-
#
-
# # Generate a datetime select with hours in the AM/PM format
-
# datetime_select("article", "written_on", :ampm => true)
-
#
-
# # Generates a datetime select that discards the type that, when POSTed, will be stored in the article variable
-
# # as the written_on attribute.
-
# datetime_select("article", "written_on", :discard_type => true)
-
#
-
# # Generates a datetime select with a custom prompt. Use <tt>:prompt => true</tt> for generic prompts.
-
# datetime_select("article", "written_on", :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
-
# datetime_select("article", "written_on", :prompt => {:hour => true}) # generic prompt for hours
-
# datetime_select("article", "written_on", :prompt => true) # generic prompts for all
-
#
-
# The selects are prepared for multi-parameter assignment to an Active Record object.
-
2
def datetime_select(object_name, method, options = {}, html_options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_datetime_select_tag(options, html_options)
-
end
-
-
# Returns a set of html select-tags (one for year, month, day, hour, minute, and second) pre-selected with the
-
# +datetime+. It's also possible to explicitly set the order of the tags using the <tt>:order</tt> option with
-
# an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not
-
# supply a Symbol, it will be appended onto the <tt>:order</tt> passed in. You can also add
-
# <tt>:date_separator</tt>, <tt>:datetime_separator</tt> and <tt>:time_separator</tt> keys to the +options+ to
-
# control visual display of the elements.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# ==== Examples
-
# my_date_time = Time.now + 4.days
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today).
-
# select_datetime(my_date_time)
-
#
-
# # Generates a datetime select that defaults to today (no specified datetime)
-
# select_datetime()
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # with the fields ordered year, month, day rather than month, day, year.
-
# select_datetime(my_date_time, :order => [:year, :month, :day])
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # with a '/' between each date field.
-
# select_datetime(my_date_time, :date_separator => '/')
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # with a date fields separated by '/', time fields separated by '' and the date and time fields
-
# # separated by a comma (',').
-
# select_datetime(my_date_time, :date_separator => '/', :time_separator => '', :datetime_separator => ',')
-
#
-
# # Generates a datetime select that discards the type of the field and defaults to the datetime in
-
# # my_date_time (four days after today)
-
# select_datetime(my_date_time, :discard_type => true)
-
#
-
# # Generate a datetime field with hours in the AM/PM format
-
# select_datetime(my_date_time, :ampm => true)
-
#
-
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
-
# # prefixed with 'payday' rather than 'date'
-
# select_datetime(my_date_time, :prefix => 'payday')
-
#
-
# # Generates a datetime select with a custom prompt. Use <tt>:prompt => true</tt> for generic prompts.
-
# select_datetime(my_date_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
-
# select_datetime(my_date_time, :prompt => {:hour => true}) # generic prompt for hours
-
# select_datetime(my_date_time, :prompt => true) # generic prompts for all
-
#
-
2
def select_datetime(datetime = Time.current, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_datetime
-
end
-
-
# Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+.
-
# It's possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of
-
# symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order.
-
# If the array passed to the <tt>:order</tt> option does not contain all the three symbols, all tags will be hidden.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# ==== Examples
-
# my_date = Time.now + 6.days
-
#
-
# # Generates a date select that defaults to the date in my_date (six days after today).
-
# select_date(my_date)
-
#
-
# # Generates a date select that defaults to today (no specified date).
-
# select_date()
-
#
-
# # Generates a date select that defaults to the date in my_date (six days after today)
-
# # with the fields ordered year, month, day rather than month, day, year.
-
# select_date(my_date, :order => [:year, :month, :day])
-
#
-
# # Generates a date select that discards the type of the field and defaults to the date in
-
# # my_date (six days after today).
-
# select_date(my_date, :discard_type => true)
-
#
-
# # Generates a date select that defaults to the date in my_date,
-
# # which has fields separated by '/'.
-
# select_date(my_date, :date_separator => '/')
-
#
-
# # Generates a date select that defaults to the datetime in my_date (six days after today)
-
# # prefixed with 'payday' rather than 'date'.
-
# select_date(my_date, :prefix => 'payday')
-
#
-
# # Generates a date select with a custom prompt. Use <tt>:prompt => true</tt> for generic prompts.
-
# select_date(my_date, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
-
# select_date(my_date, :prompt => {:hour => true}) # generic prompt for hours
-
# select_date(my_date, :prompt => true) # generic prompts for all
-
#
-
2
def select_date(date = Date.current, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_date
-
end
-
-
# Returns a set of html select-tags (one for hour and minute).
-
# You can set <tt>:time_separator</tt> key to format the output, and
-
# the <tt>:include_seconds</tt> option to include an input for seconds.
-
#
-
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
-
#
-
# ==== Examples
-
# my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds
-
#
-
# # Generates a time select that defaults to the time in my_time.
-
# select_time(my_time)
-
#
-
# # Generates a time select that defaults to the current time (no specified time).
-
# select_time()
-
#
-
# # Generates a time select that defaults to the time in my_time,
-
# # which has fields separated by ':'.
-
# select_time(my_time, :time_separator => ':')
-
#
-
# # Generates a time select that defaults to the time in my_time,
-
# # that also includes an input for seconds.
-
# select_time(my_time, :include_seconds => true)
-
#
-
# # Generates a time select that defaults to the time in my_time, that has fields
-
# # separated by ':' and includes an input for seconds.
-
# select_time(my_time, :time_separator => ':', :include_seconds => true)
-
#
-
# # Generate a time select field with hours in the AM/PM format
-
# select_time(my_time, :ampm => true)
-
#
-
# # Generates a time select with a custom prompt. Use <tt>:prompt</tt> to true for generic prompts.
-
# select_time(my_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
-
# select_time(my_time, :prompt => {:hour => true}) # generic prompt for hours
-
# select_time(my_time, :prompt => true) # generic prompts for all
-
#
-
2
def select_time(datetime = Time.current, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_time
-
end
-
-
# Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
-
# The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
-
# Override the field name using the <tt>:field_name</tt> option, 'second' by default.
-
#
-
# ==== Examples
-
# my_time = Time.now + 16.minutes
-
#
-
# # Generates a select field for seconds that defaults to the seconds for the time in my_time.
-
# select_second(my_time)
-
#
-
# # Generates a select field for seconds that defaults to the number given.
-
# select_second(33)
-
#
-
# # Generates a select field for seconds that defaults to the seconds for the time in my_time
-
# # that is named 'interval' rather than 'second'.
-
# select_second(my_time, :field_name => 'interval')
-
#
-
# # Generates a select field for seconds with a custom prompt. Use <tt>:prompt => true</tt> for a
-
# # generic prompt.
-
# select_second(14, :prompt => 'Choose seconds')
-
#
-
2
def select_second(datetime, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_second
-
end
-
-
# Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
-
# Also can return a select tag with options by <tt>minute_step</tt> from 0 through 59 with the 00 minute
-
# selected. The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
-
# Override the field name using the <tt>:field_name</tt> option, 'minute' by default.
-
#
-
# ==== Examples
-
# my_time = Time.now + 6.hours
-
#
-
# # Generates a select field for minutes that defaults to the minutes for the time in my_time.
-
# select_minute(my_time)
-
#
-
# # Generates a select field for minutes that defaults to the number given.
-
# select_minute(14)
-
#
-
# # Generates a select field for minutes that defaults to the minutes for the time in my_time
-
# # that is named 'moment' rather than 'minute'.
-
# select_minute(my_time, :field_name => 'moment')
-
#
-
# # Generates a select field for minutes with a custom prompt. Use <tt>:prompt => true</tt> for a
-
# # generic prompt.
-
# select_minute(14, :prompt => 'Choose minutes')
-
#
-
2
def select_minute(datetime, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_minute
-
end
-
-
# Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
-
# The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
-
# Override the field name using the <tt>:field_name</tt> option, 'hour' by default.
-
#
-
# ==== Examples
-
# my_time = Time.now + 6.hours
-
#
-
# # Generates a select field for hours that defaults to the hour for the time in my_time.
-
# select_hour(my_time)
-
#
-
# # Generates a select field for hours that defaults to the number given.
-
# select_hour(13)
-
#
-
# # Generates a select field for hours that defaults to the hour for the time in my_time
-
# # that is named 'stride' rather than 'hour'.
-
# select_hour(my_time, :field_name => 'stride')
-
#
-
# # Generates a select field for hours with a custom prompt. Use <tt>:prompt => true</tt> for a
-
# # generic prompt.
-
# select_hour(13, :prompt => 'Choose hour')
-
#
-
# # Generate a select field for hours in the AM/PM format
-
# select_hour(my_time, :ampm => true)
-
#
-
2
def select_hour(datetime, options = {}, html_options = {})
-
DateTimeSelector.new(datetime, options, html_options).select_hour
-
end
-
-
# Returns a select tag with options for each of the days 1 through 31 with the current day selected.
-
# The <tt>date</tt> can also be substituted for a day number.
-
# Override the field name using the <tt>:field_name</tt> option, 'day' by default.
-
#
-
# ==== Examples
-
# my_date = Time.now + 2.days
-
#
-
# # Generates a select field for days that defaults to the day for the date in my_date.
-
# select_day(my_time)
-
#
-
# # Generates a select field for days that defaults to the number given.
-
# select_day(5)
-
#
-
# # Generates a select field for days that defaults to the day for the date in my_date
-
# # that is named 'due' rather than 'day'.
-
# select_day(my_time, :field_name => 'due')
-
#
-
# # Generates a select field for days with a custom prompt. Use <tt>:prompt => true</tt> for a
-
# # generic prompt.
-
# select_day(5, :prompt => 'Choose day')
-
#
-
2
def select_day(date, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_day
-
end
-
-
# Returns a select tag with options for each of the months January through December with the current month
-
# selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are
-
# used as values (what's submitted to the server). It's also possible to use month numbers for the presentation
-
# instead of names -- set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you
-
# want both numbers and names, set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer
-
# to show month names as abbreviations, set the <tt>:use_short_month</tt> key in +options+ to true. If you want
-
# to use your own month names, set the <tt>:use_month_names</tt> key in +options+ to an array of 12 month names.
-
# Override the field name using the <tt>:field_name</tt> option, 'month' by default.
-
#
-
# ==== Examples
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "January", "March".
-
# select_month(Date.today)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # is named "start" rather than "month".
-
# select_month(Date.today, :field_name => 'start')
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "1", "3".
-
# select_month(Date.today, :use_month_numbers => true)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "1 - January", "3 - March".
-
# select_month(Date.today, :add_month_numbers => true)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "Jan", "Mar".
-
# select_month(Date.today, :use_short_month => true)
-
#
-
# # Generates a select field for months that defaults to the current month that
-
# # will use keys like "Januar", "Marts."
-
# select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...))
-
#
-
# # Generates a select field for months with a custom prompt. Use <tt>:prompt => true</tt> for a
-
# # generic prompt.
-
# select_month(14, :prompt => 'Choose month')
-
#
-
2
def select_month(date, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_month
-
end
-
-
# Returns a select tag with options for each of the five years on each side of the current, which is selected.
-
# The five year radius can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the
-
# +options+. Both ascending and descending year lists are supported by making <tt>:start_year</tt> less than or
-
# greater than <tt>:end_year</tt>. The <tt>date</tt> can also be substituted for a year given as a number.
-
# Override the field name using the <tt>:field_name</tt> option, 'year' by default.
-
#
-
# ==== Examples
-
# # Generates a select field for years that defaults to the current year that
-
# # has ascending year values.
-
# select_year(Date.today, :start_year => 1992, :end_year => 2007)
-
#
-
# # Generates a select field for years that defaults to the current year that
-
# # is named 'birth' rather than 'year'.
-
# select_year(Date.today, :field_name => 'birth')
-
#
-
# # Generates a select field for years that defaults to the current year that
-
# # has descending year values.
-
# select_year(Date.today, :start_year => 2005, :end_year => 1900)
-
#
-
# # Generates a select field for years that defaults to the year 2006 that
-
# # has ascending year values.
-
# select_year(2006, :start_year => 2000, :end_year => 2010)
-
#
-
# # Generates a select field for years with a custom prompt. Use <tt>:prompt => true</tt> for a
-
# # generic prompt.
-
# select_year(14, :prompt => 'Choose year')
-
#
-
2
def select_year(date, options = {}, html_options = {})
-
DateTimeSelector.new(date, options, html_options).select_year
-
end
-
-
# Returns an html time tag for the given date or time.
-
#
-
# ==== Examples
-
# time_tag Date.today # =>
-
# <time datetime="2010-11-04">November 04, 2010</time>
-
# time_tag Time.now # =>
-
# <time datetime="2010-11-04T17:55:45+01:00">November 04, 2010 17:55</time>
-
# time_tag Date.yesterday, 'Yesterday' # =>
-
# <time datetime="2010-11-03">Yesterday</time>
-
# time_tag Date.today, :pubdate => true # =>
-
# <time datetime="2010-11-04" pubdate="pubdate">November 04, 2010</time>
-
#
-
2
def time_tag(date_or_time, *args)
-
options = args.extract_options!
-
format = options.delete(:format) || :long
-
content = args.first || I18n.l(date_or_time, :format => format)
-
datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.rfc3339
-
-
content_tag(:time, content, options.reverse_merge(:datetime => datetime))
-
end
-
end
-
-
2
class DateTimeSelector #:nodoc:
-
2
include ActionView::Helpers::TagHelper
-
-
2
DEFAULT_PREFIX = 'date'.freeze
-
2
POSITION = {
-
:year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6
-
}.freeze
-
-
2
AMPM_TRANSLATION = Hash[
-
[[0, "12 AM"], [1, "01 AM"], [2, "02 AM"], [3, "03 AM"],
-
[4, "04 AM"], [5, "05 AM"], [6, "06 AM"], [7, "07 AM"],
-
[8, "08 AM"], [9, "09 AM"], [10, "10 AM"], [11, "11 AM"],
-
[12, "12 PM"], [13, "01 PM"], [14, "02 PM"], [15, "03 PM"],
-
[16, "04 PM"], [17, "05 PM"], [18, "06 PM"], [19, "07 PM"],
-
[20, "08 PM"], [21, "09 PM"], [22, "10 PM"], [23, "11 PM"]]
-
].freeze
-
-
2
def initialize(datetime, options = {}, html_options = {})
-
@options = options.dup
-
@html_options = html_options.dup
-
@datetime = datetime
-
@options[:datetime_separator] ||= ' — '
-
@options[:time_separator] ||= ' : '
-
end
-
-
2
def select_datetime
-
order = date_order.dup
-
order -= [:hour, :minute, :second]
-
@options[:discard_year] ||= true unless order.include?(:year)
-
@options[:discard_month] ||= true unless order.include?(:month)
-
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
-
@options[:discard_minute] ||= true if @options[:discard_hour]
-
@options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute]
-
-
# If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are
-
# valid (otherwise it could be 31 and February wouldn't be a valid date)
-
if @datetime && @options[:discard_day] && !@options[:discard_month]
-
@datetime = @datetime.change(:day => 1)
-
end
-
-
if @options[:tag] && @options[:ignore_date]
-
select_time
-
else
-
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
-
order += [:hour, :minute, :second] unless @options[:discard_hour]
-
-
build_selects_from_types(order)
-
end
-
end
-
-
2
def select_date
-
order = date_order.dup
-
-
@options[:discard_hour] = true
-
@options[:discard_minute] = true
-
@options[:discard_second] = true
-
-
@options[:discard_year] ||= true unless order.include?(:year)
-
@options[:discard_month] ||= true unless order.include?(:month)
-
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
-
-
# If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are
-
# valid (otherwise it could be 31 and February wouldn't be a valid date)
-
if @datetime && @options[:discard_day] && !@options[:discard_month]
-
@datetime = @datetime.change(:day => 1)
-
end
-
-
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
-
-
build_selects_from_types(order)
-
end
-
-
2
def select_time
-
order = []
-
-
@options[:discard_month] = true
-
@options[:discard_year] = true
-
@options[:discard_day] = true
-
@options[:discard_second] ||= true unless @options[:include_seconds]
-
-
order += [:year, :month, :day] unless @options[:ignore_date]
-
-
order += [:hour, :minute]
-
order << :second if @options[:include_seconds]
-
-
build_selects_from_types(order)
-
end
-
-
2
def select_second
-
if @options[:use_hidden] || @options[:discard_second]
-
build_hidden(:second, sec) if @options[:include_seconds]
-
else
-
build_options_and_select(:second, sec)
-
end
-
end
-
-
2
def select_minute
-
if @options[:use_hidden] || @options[:discard_minute]
-
build_hidden(:minute, min)
-
else
-
build_options_and_select(:minute, min, :step => @options[:minute_step])
-
end
-
end
-
-
2
def select_hour
-
if @options[:use_hidden] || @options[:discard_hour]
-
build_hidden(:hour, hour)
-
else
-
build_options_and_select(:hour, hour, :end => 23, :ampm => @options[:ampm])
-
end
-
end
-
-
2
def select_day
-
if @options[:use_hidden] || @options[:discard_day]
-
build_hidden(:day, day || 1)
-
else
-
build_options_and_select(:day, day, :start => 1, :end => 31, :leading_zeros => false, :use_two_digit_numbers => @options[:use_two_digit_numbers])
-
end
-
end
-
-
2
def select_month
-
if @options[:use_hidden] || @options[:discard_month]
-
build_hidden(:month, month || 1)
-
else
-
month_options = []
-
1.upto(12) do |month_number|
-
options = { :value => month_number }
-
options[:selected] = "selected" if month == month_number
-
month_options << content_tag(:option, month_name(month_number), options) + "\n"
-
end
-
build_select(:month, month_options.join)
-
end
-
end
-
-
2
def select_year
-
if !@datetime || @datetime == 0
-
val = '1'
-
middle_year = Date.today.year
-
else
-
val = middle_year = year
-
end
-
-
if @options[:use_hidden] || @options[:discard_year]
-
build_hidden(:year, val)
-
else
-
options = {}
-
options[:start] = @options[:start_year] || middle_year - 5
-
options[:end] = @options[:end_year] || middle_year + 5
-
options[:step] = options[:start] < options[:end] ? 1 : -1
-
options[:leading_zeros] = false
-
options[:max_years_allowed] = @options[:max_years_allowed] || 1000
-
-
if (options[:end] - options[:start]).abs > options[:max_years_allowed]
-
raise ArgumentError, "There're too many years options to be built. Are you sure you haven't mistyped something? You can provide the :max_years_allowed parameter"
-
end
-
-
build_options_and_select(:year, val, options)
-
end
-
end
-
-
2
private
-
2
%w( sec min hour day month year ).each do |method|
-
12
define_method(method) do
-
@datetime.kind_of?(Numeric) ? @datetime : @datetime.send(method) if @datetime
-
end
-
end
-
-
# Returns translated month names, but also ensures that a custom month
-
# name array has a leading nil element.
-
2
def month_names
-
@month_names ||= begin
-
month_names = @options[:use_month_names] || translated_month_names
-
month_names.unshift(nil) if month_names.size < 13
-
month_names
-
end
-
end
-
-
# Returns translated month names.
-
# => [nil, "January", "February", "March",
-
# "April", "May", "June", "July",
-
# "August", "September", "October",
-
# "November", "December"]
-
#
-
# If <tt>:use_short_month</tt> option is set
-
# => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
-
# "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
-
2
def translated_month_names
-
key = @options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names'
-
I18n.translate(key, :locale => @options[:locale])
-
end
-
-
# Lookup month name for number.
-
# month_name(1) => "January"
-
#
-
# If <tt>:use_month_numbers</tt> option is passed
-
# month_name(1) => 1
-
#
-
# If <tt>:add_month_numbers</tt> option is passed
-
# month_name(1) => "1 - January"
-
2
def month_name(number)
-
if @options[:use_month_numbers]
-
number
-
elsif @options[:use_two_digit_numbers]
-
sprintf "%02d", number
-
elsif @options[:add_month_numbers]
-
"#{number} - #{month_names[number]}"
-
else
-
month_names[number]
-
end
-
end
-
-
2
def date_order
-
@date_order ||= @options[:order] || translated_date_order
-
end
-
-
2
def translated_date_order
-
I18n.translate(:'date.order', :locale => @options[:locale]) || []
-
end
-
-
# Build full select tag from date type and options.
-
2
def build_options_and_select(type, selected, options = {})
-
build_select(type, build_options(selected, options))
-
end
-
-
# Build select option html from date value and options.
-
# build_options(15, :start => 1, :end => 31)
-
# => "<option value="1">1</option>
-
# <option value="2">2</option>
-
# <option value="3">3</option>..."
-
#
-
# If <tt>:step</tt> options is passed
-
# build_options(15, :start => 1, :end => 31, :step => 2)
-
# => "<option value="1">1</option>
-
# <option value="3">3</option>
-
# <option value="5">5</option>..."
-
2
def build_options(selected, options = {})
-
start = options.delete(:start) || 0
-
stop = options.delete(:end) || 59
-
step = options.delete(:step) || 1
-
options.reverse_merge!({:leading_zeros => true, :ampm => false, :use_two_digit_numbers => false})
-
leading_zeros = options.delete(:leading_zeros)
-
-
select_options = []
-
start.step(stop, step) do |i|
-
value = leading_zeros ? sprintf("%02d", i) : i
-
tag_options = { :value => value }
-
tag_options[:selected] = "selected" if selected == i
-
text = options[:use_two_digit_numbers] ? sprintf("%02d", i) : value
-
text = options[:ampm] ? AMPM_TRANSLATION[i] : text
-
select_options << content_tag(:option, text, tag_options)
-
end
-
(select_options.join("\n") + "\n").html_safe
-
end
-
-
# Builds select tag from date type and html select options.
-
# build_select(:month, "<option value="1">January</option>...")
-
# => "<select id="post_written_on_2i" name="post[written_on(2i)]">
-
# <option value="1">January</option>...
-
# </select>"
-
2
def build_select(type, select_options_as_html)
-
select_options = {
-
:id => input_id_from_type(type),
-
:name => input_name_from_type(type)
-
}.merge(@html_options)
-
select_options.merge!(:disabled => 'disabled') if @options[:disabled]
-
-
select_html = "\n"
-
select_html << content_tag(:option, '', :value => '') + "\n" if @options[:include_blank]
-
select_html << prompt_option_tag(type, @options[:prompt]) + "\n" if @options[:prompt]
-
select_html << select_options_as_html
-
-
(content_tag(:select, select_html.html_safe, select_options) + "\n").html_safe
-
end
-
-
# Builds a prompt option tag with supplied options or from default options.
-
# prompt_option_tag(:month, :prompt => 'Select month')
-
# => "<option value="">Select month</option>"
-
2
def prompt_option_tag(type, options)
-
prompt = case options
-
when Hash
-
default_options = {:year => false, :month => false, :day => false, :hour => false, :minute => false, :second => false}
-
default_options.merge!(options)[type.to_sym]
-
when String
-
options
-
else
-
I18n.translate(:"datetime.prompts.#{type}", :locale => @options[:locale])
-
end
-
-
prompt ? content_tag(:option, prompt, :value => '') : ''
-
end
-
-
# Builds hidden input tag for date part and value.
-
# build_hidden(:year, 2008)
-
# => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />"
-
2
def build_hidden(type, value)
-
select_options = {
-
:type => "hidden",
-
:id => input_id_from_type(type),
-
:name => input_name_from_type(type),
-
:value => value
-
}.merge(@html_options.slice(:disabled))
-
select_options.merge!(:disabled => 'disabled') if @options[:disabled]
-
-
tag(:input, select_options) + "\n".html_safe
-
end
-
-
# Returns the name attribute for the input tag.
-
# => post[written_on(1i)]
-
2
def input_name_from_type(type)
-
prefix = @options[:prefix] || ActionView::Helpers::DateTimeSelector::DEFAULT_PREFIX
-
prefix += "[#{@options[:index]}]" if @options.has_key?(:index)
-
-
field_name = @options[:field_name] || type
-
if @options[:include_position]
-
field_name += "(#{ActionView::Helpers::DateTimeSelector::POSITION[type]}i)"
-
end
-
-
@options[:discard_type] ? prefix : "#{prefix}[#{field_name}]"
-
end
-
-
# Returns the id attribute for the input tag.
-
# => "post_written_on_1i"
-
2
def input_id_from_type(type)
-
id = input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '')
-
id = @options[:namespace] + '_' + id if @options[:namespace]
-
-
id
-
end
-
-
# Given an ordering of datetime components, create the selection HTML
-
# and join them with their appropriate separators.
-
2
def build_selects_from_types(order)
-
select = ''
-
first_visible = order.find { |type| !@options[:"discard_#{type}"] }
-
order.reverse.each do |type|
-
separator = separator(type) unless type == first_visible # don't add before first visible field
-
select.insert(0, separator.to_s + send("select_#{type}").to_s)
-
end
-
select.html_safe
-
end
-
-
# Returns the separator for a given datetime component.
-
2
def separator(type)
-
case type
-
when :year
-
@options[:discard_year] ? "" : @options[:date_separator]
-
when :month
-
@options[:discard_month] ? "" : @options[:date_separator]
-
when :day
-
@options[:discard_day] ? "" : @options[:date_separator]
-
when :hour
-
(@options[:discard_year] && @options[:discard_day]) ? "" : @options[:datetime_separator]
-
when :minute
-
@options[:discard_minute] ? "" : @options[:time_separator]
-
when :second
-
@options[:include_seconds] ? @options[:time_separator] : ""
-
end
-
end
-
end
-
-
2
module DateHelperInstanceTag
-
2
def to_date_select_tag(options = {}, html_options = {})
-
datetime_selector(options, html_options).select_date.html_safe
-
end
-
-
2
def to_time_select_tag(options = {}, html_options = {})
-
datetime_selector(options, html_options).select_time.html_safe
-
end
-
-
2
def to_datetime_select_tag(options = {}, html_options = {})
-
datetime_selector(options, html_options).select_datetime.html_safe
-
end
-
-
2
private
-
2
def datetime_selector(options, html_options)
-
datetime = value(object) || default_datetime(options)
-
@auto_index ||= nil
-
-
options = options.dup
-
options[:field_name] = @method_name
-
options[:include_position] = true
-
options[:prefix] ||= @object_name
-
options[:index] = @auto_index if @auto_index && !options.has_key?(:index)
-
-
DateTimeSelector.new(datetime, options, html_options)
-
end
-
-
2
def default_datetime(options)
-
return if options[:include_blank] || options[:prompt]
-
-
case options[:default]
-
when nil
-
Time.current
-
when Date, Time
-
options[:default]
-
else
-
default = options[:default].dup
-
-
# Rename :minute and :second to :min and :sec
-
default[:min] ||= default[:minute]
-
default[:sec] ||= default[:second]
-
-
time = Time.current
-
-
[:year, :month, :day, :hour, :min, :sec].each do |key|
-
default[key] ||= time.send(key)
-
end
-
-
Time.utc_time(
-
default[:year], default[:month], default[:day],
-
default[:hour], default[:min], default[:sec]
-
)
-
end
-
end
-
end
-
-
2
class InstanceTag #:nodoc:
-
2
include DateHelperInstanceTag
-
end
-
-
2
class FormBuilder
-
2
def date_select(method, options = {}, html_options = {})
-
@template.date_select(@object_name, method, objectify_options(options), html_options)
-
end
-
-
2
def time_select(method, options = {}, html_options = {})
-
@template.time_select(@object_name, method, objectify_options(options), html_options)
-
end
-
-
2
def datetime_select(method, options = {}, html_options = {})
-
@template.datetime_select(@object_name, method, objectify_options(options), html_options)
-
end
-
end
-
end
-
end
-
2
module ActionView
-
# = Action View Debug Helper
-
#
-
# Provides a set of methods for making it easier to debug Rails objects.
-
2
module Helpers
-
2
module DebugHelper
-
# Returns a YAML representation of +object+ wrapped with <pre> and </pre>.
-
# If the object cannot be converted to YAML using +to_yaml+, +inspect+ will be called instead.
-
# Useful for inspecting an object at the time of rendering.
-
#
-
# ==== Example
-
#
-
# @user = User.new({ :username => 'testing', :password => 'xyz', :age => 42}) %>
-
# debug(@user)
-
# # =>
-
# <pre class='debug_dump'>--- !ruby/object:User
-
# attributes:
-
# updated_at:
-
# username: testing
-
#
-
# age: 42
-
# password: xyz
-
# created_at:
-
# attributes_cache: {}
-
#
-
# new_record: true
-
# </pre>
-
-
2
def debug(object)
-
begin
-
Marshal::dump(object)
-
"<pre class='debug_dump'>#{h(object.to_yaml).gsub(" ", " ")}</pre>".html_safe
-
rescue Exception # errors from Marshal or YAML
-
# Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback
-
"<code class='debug_dump'>#{h(object.inspect)}</code>".html_safe
-
end
-
end
-
end
-
end
-
end
-
2
require 'cgi'
-
2
require 'action_view/helpers/date_helper'
-
2
require 'action_view/helpers/tag_helper'
-
2
require 'action_view/helpers/form_tag_helper'
-
2
require 'action_view/helpers/active_model_helper'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/module/method_names'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/string/output_safety'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/string/inflections'
-
-
2
module ActionView
-
# = Action View Form Helpers
-
2
module Helpers
-
# Form helpers are designed to make working with resources much easier
-
# compared to using vanilla HTML.
-
#
-
# Forms for models are created with +form_for+. That method yields a form
-
# builder that knows the model the form is about. The form builder is thus
-
# able to generate default values for input fields that correspond to model
-
# attributes, and also convenient names, IDs, endpoints, etc.
-
#
-
# Conventions in the generated field names allow controllers to receive form
-
# data nicely structured in +params+ with no effort on your side.
-
#
-
# For example, to create a new person you typically set up a new instance of
-
# +Person+ in the <tt>PeopleController#new</tt> action, <tt>@person</tt>, and
-
# pass it to +form_for+:
-
#
-
# <%= form_for @person do |f| %>
-
# <%= f.label :first_name %>:
-
# <%= f.text_field :first_name %><br />
-
#
-
# <%= f.label :last_name %>:
-
# <%= f.text_field :last_name %><br />
-
#
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# The HTML generated for this would be (modulus formatting):
-
#
-
# <form action="/people" class="new_person" id="new_person" method="post">
-
# <div style="margin:0;padding:0;display:inline">
-
# <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
-
# </div>
-
# <label for="person_first_name">First name</label>:
-
# <input id="person_first_name" name="person[first_name]" size="30" type="text" /><br />
-
#
-
# <label for="person_last_name">Last name</label>:
-
# <input id="person_last_name" name="person[last_name]" size="30" type="text" /><br />
-
#
-
# <input name="commit" type="submit" value="Create Person" />
-
# </form>
-
#
-
# As you see, the HTML reflects knowledge about the resource in several spots,
-
# like the path the form should be submitted to, or the names of the input fields.
-
#
-
# In particular, thanks to the conventions followed in the generated field names, the
-
# controller gets a nested hash <tt>params[:person]</tt> with the person attributes
-
# set in the form. That hash is ready to be passed to <tt>Person.create</tt>:
-
#
-
# if @person = Person.create(params[:person])
-
# # success
-
# else
-
# # error handling
-
# end
-
#
-
# Interestingly, the exact same view code in the previous example can be used to edit
-
# a person. If <tt>@person</tt> is an existing record with name "John Smith" and ID 256,
-
# the code above as is would yield instead:
-
#
-
# <form action="/people/256" class="edit_person" id="edit_person_256" method="post">
-
# <div style="margin:0;padding:0;display:inline">
-
# <input name="_method" type="hidden" value="put" />
-
# <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
-
# </div>
-
# <label for="person_first_name">First name</label>:
-
# <input id="person_first_name" name="person[first_name]" size="30" type="text" value="John" /><br />
-
#
-
# <label for="person_last_name">Last name</label>:
-
# <input id="person_last_name" name="person[last_name]" size="30" type="text" value="Smith" /><br />
-
#
-
# <input name="commit" type="submit" value="Update Person" />
-
# </form>
-
#
-
# Note that the endpoint, default values, and submit button label are tailored for <tt>@person</tt>.
-
# That works that way because the involved helpers know whether the resource is a new record or not,
-
# and generate HTML accordingly.
-
#
-
# The controller would receive the form data again in <tt>params[:person]</tt>, ready to be
-
# passed to <tt>Person#update_attributes</tt>:
-
#
-
# if @person.update_attributes(params[:person])
-
# # success
-
# else
-
# # error handling
-
# end
-
#
-
# That's how you typically work with resources.
-
2
module FormHelper
-
2
extend ActiveSupport::Concern
-
-
2
include FormTagHelper
-
2
include UrlHelper
-
-
# Converts the given object to an ActiveModel compliant one.
-
2
def convert_to_model(object)
-
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
-
# Creates a form and a scope around a specific model object that is used
-
# as a base for questioning about values for the fields.
-
#
-
# Rails provides succinct resource-oriented form generation with +form_for+
-
# like this:
-
#
-
# <%= form_for @offer do |f| %>
-
# <%= f.label :version, 'Version' %>:
-
# <%= f.text_field :version %><br />
-
# <%= f.label :author, 'Author' %>:
-
# <%= f.text_field :author %><br />
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# There, +form_for+ is able to generate the rest of RESTful form
-
# parameters based on introspection on the record, but to understand what
-
# it does we need to dig first into the alternative generic usage it is
-
# based upon.
-
#
-
# === Generic form_for
-
#
-
# The generic way to call +form_for+ yields a form builder around a
-
# model:
-
#
-
# <%= form_for :person do |f| %>
-
# First name: <%= f.text_field :first_name %><br />
-
# Last name : <%= f.text_field :last_name %><br />
-
# Biography : <%= f.text_area :biography %><br />
-
# Admin? : <%= f.check_box :admin %><br />
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# There, the argument is a symbol or string with the name of the
-
# object the form is about.
-
#
-
# The form builder acts as a regular form helper that somehow carries the
-
# model. Thus, the idea is that
-
#
-
# <%= f.text_field :first_name %>
-
#
-
# gets expanded to
-
#
-
# <%= text_field :person, :first_name %>
-
#
-
# The rightmost argument to +form_for+ is an
-
# optional hash of options:
-
#
-
# * <tt>:url</tt> - The URL the form is submitted to. It takes the same
-
# fields you pass to +url_for+ or +link_to+. In particular you may pass
-
# here a named route directly as well. Defaults to the current action.
-
# * <tt>:namespace</tt> - A namespace for your form to ensure uniqueness of
-
# id attributes on form elements. The namespace attribute will be prefixed
-
# with underscore on the generated HTML id.
-
# * <tt>:html</tt> - Optional HTML attributes for the form tag.
-
#
-
# Also note that +form_for+ doesn't create an exclusive scope. It's still
-
# possible to use both the stand-alone FormHelper methods and methods
-
# from FormTagHelper. For example:
-
#
-
# <%= form_for @person do |f| %>
-
# First name: <%= f.text_field :first_name %>
-
# Last name : <%= f.text_field :last_name %>
-
# Biography : <%= text_area :person, :biography %>
-
# Admin? : <%= check_box_tag "person[admin]", @person.company.admin? %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# This also works for the methods in FormOptionHelper and DateHelper that
-
# are designed to work with an object as base, like
-
# FormOptionHelper#collection_select and DateHelper#datetime_select.
-
#
-
# === Resource-oriented style
-
#
-
# As we said above, in addition to manually configuring the +form_for+
-
# call, you can rely on automated resource identification, which will use
-
# the conventions and named routes of that approach. This is the
-
# preferred way to use +form_for+ nowadays.
-
#
-
# For example, if <tt>@post</tt> is an existing record you want to edit
-
#
-
# <%= form_for @post do |f| %>
-
# ...
-
# <% end %>
-
#
-
# is equivalent to something like:
-
#
-
# <%= form_for @post, :as => :post, :url => post_path(@post), :method => :put, :html => { :class => "edit_post", :id => "edit_post_45" } do |f| %>
-
# ...
-
# <% end %>
-
#
-
# And for new records
-
#
-
# <%= form_for(Post.new) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# is equivalent to something like:
-
#
-
# <%= form_for @post, :as => :post, :url => posts_path, :html => { :class => "new_post", :id => "new_post" } do |f| %>
-
# ...
-
# <% end %>
-
#
-
# You can also overwrite the individual conventions, like this:
-
#
-
# <%= form_for(@post, :url => super_posts_path) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# You can also set the answer format, like this:
-
#
-
# <%= form_for(@post, :format => :json) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# If you have an object that needs to be represented as a different
-
# parameter, like a Person that acts as a Client:
-
#
-
# <%= form_for(@person, :as => :client) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# For namespaced routes, like +admin_post_url+:
-
#
-
# <%= form_for([:admin, @post]) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# If your resource has associations defined, for example, you want to add comments
-
# to the document given that the routes are set correctly:
-
#
-
# <%= form_for([@document, @comment]) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# Where <tt>@document = Document.find(params[:id])</tt> and
-
# <tt>@comment = Comment.new</tt>.
-
#
-
# === Setting the method
-
#
-
# You can force the form to use the full array of HTTP verbs by setting
-
#
-
# :method => (:get|:post|:put|:delete)
-
#
-
# in the options hash. If the verb is not GET or POST, which are natively supported by HTML forms, the
-
# form will be set to POST and a hidden input called _method will carry the intended verb for the server
-
# to interpret.
-
#
-
# === Unobtrusive JavaScript
-
#
-
# Specifying:
-
#
-
# :remote => true
-
#
-
# in the options hash creates a form that will allow the unobtrusive JavaScript drivers to modify its
-
# behavior. The expected default behavior is an XMLHttpRequest in the background instead of the regular
-
# POST arrangement, but ultimately the behavior is the choice of the JavaScript driver implementor.
-
# Even though it's using JavaScript to serialize the form elements, the form submission will work just like
-
# a regular submission as viewed by the receiving side (all elements available in <tt>params</tt>).
-
#
-
# Example:
-
#
-
# <%= form_for(@post, :remote => true) do |f| %>
-
# ...
-
# <% end %>
-
#
-
# The HTML generated for this would be:
-
#
-
# <form action='http://www.example.com' method='post' data-remote='true'>
-
# <div style='margin:0;padding:0;display:inline'>
-
# <input name='_method' type='hidden' value='put' />
-
# </div>
-
# ...
-
# </form>
-
#
-
# === Removing hidden model id's
-
#
-
# The form_for method automatically includes the model id as a hidden field in the form.
-
# This is used to maintain the correlation between the form data and its associated model.
-
# Some ORM systems do not use IDs on nested models so in this case you want to be able
-
# to disable the hidden id.
-
#
-
# In the following example the Post model has many Comments stored within it in a NoSQL database,
-
# thus there is no primary key for comments.
-
#
-
# Example:
-
#
-
# <%= form_for(@post) do |f| %>
-
# <% f.fields_for(:comments, :include_id => false) do |cf| %>
-
# ...
-
# <% end %>
-
# <% end %>
-
#
-
# === Customized form builders
-
#
-
# You can also build forms using a customized FormBuilder class. Subclass
-
# FormBuilder and override or define some more helpers, then use your
-
# custom builder. For example, let's say you made a helper to
-
# automatically add labels to form inputs.
-
#
-
# <%= form_for @person, :url => { :action => "create" }, :builder => LabellingFormBuilder do |f| %>
-
# <%= f.text_field :first_name %>
-
# <%= f.text_field :last_name %>
-
# <%= f.text_area :biography %>
-
# <%= f.check_box :admin %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# In this case, if you use this:
-
#
-
# <%= render f %>
-
#
-
# The rendered template is <tt>people/_labelling_form</tt> and the local
-
# variable referencing the form builder is called
-
# <tt>labelling_form</tt>.
-
#
-
# The custom FormBuilder class is automatically merged with the options
-
# of a nested fields_for call, unless it's explicitly set.
-
#
-
# In many cases you will want to wrap the above in another helper, so you
-
# could do something like the following:
-
#
-
# def labelled_form_for(record_or_name_or_array, *args, &block)
-
# options = args.extract_options!
-
# form_for(record_or_name_or_array, *(args << options.merge(:builder => LabellingFormBuilder)), &block)
-
# end
-
#
-
# If you don't need to attach a form to a model instance, then check out
-
# FormTagHelper#form_tag.
-
#
-
# === Form to external resources
-
#
-
# When you build forms to external resources sometimes you need to set an authenticity token or just render a form
-
# without it, for example when you submit data to a payment gateway number and types of fields could be limited.
-
#
-
# To set an authenticity token you need to pass an <tt>:authenticity_token</tt> parameter
-
#
-
# <%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f|
-
# ...
-
# <% end %>
-
#
-
# If you don't want to an authenticity token field be rendered at all just pass <tt>false</tt>:
-
#
-
# <%= form_for @invoice, :url => external_url, :authenticity_token => false do |f|
-
# ...
-
# <% end %>
-
2
def form_for(record, options = {}, &block)
-
raise ArgumentError, "Missing block" unless block_given?
-
-
options[:html] ||= {}
-
-
case record
-
when String, Symbol
-
object_name = record
-
object = nil
-
else
-
object = record.is_a?(Array) ? record.last : record
-
object_name = options[:as] || ActiveModel::Naming.param_key(object)
-
apply_form_for_options!(record, options)
-
end
-
-
options[:html][:remote] = options.delete(:remote) if options.has_key?(:remote)
-
options[:html][:method] = options.delete(:method) if options.has_key?(:method)
-
options[:html][:authenticity_token] = options.delete(:authenticity_token)
-
-
builder = options[:parent_builder] = instantiate_builder(object_name, object, options, &block)
-
output = capture(builder, &block)
-
default_options = builder.multipart? ? { :multipart => true } : {}
-
form_tag(options.delete(:url) || {}, default_options.merge!(options.delete(:html))) { output }
-
end
-
-
2
def apply_form_for_options!(object_or_array, options) #:nodoc:
-
object = object_or_array.is_a?(Array) ? object_or_array.last : object_or_array
-
object = convert_to_model(object)
-
-
as = options[:as]
-
action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :put] : [:new, :post]
-
options[:html].reverse_merge!(
-
:class => as ? "#{action}_#{as}" : dom_class(object, action),
-
:id => as ? "#{action}_#{as}" : [options[:namespace], dom_id(object, action)].compact.join("_").presence,
-
:method => method
-
)
-
-
options[:url] ||= polymorphic_path(object_or_array, :format => options.delete(:format))
-
end
-
2
private :apply_form_for_options!
-
-
# Creates a scope around a specific model object like form_for, but
-
# doesn't create the form tags themselves. This makes fields_for suitable
-
# for specifying additional model objects in the same form.
-
#
-
# === Generic Examples
-
#
-
# <%= form_for @person do |person_form| %>
-
# First name: <%= person_form.text_field :first_name %>
-
# Last name : <%= person_form.text_field :last_name %>
-
#
-
# <%= fields_for @person.permission do |permission_fields| %>
-
# Admin? : <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# ...or if you have an object that needs to be represented as a different
-
# parameter, like a Client that acts as a Person:
-
#
-
# <%= fields_for :person, @client do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# ...or if you don't have an object, just a name of the parameter:
-
#
-
# <%= fields_for :person do |permission_fields| %>
-
# Admin?: <%= permission_fields.check_box :admin %>
-
# <% end %>
-
#
-
# Note: This also works for the methods in FormOptionHelper and
-
# DateHelper that are designed to work with an object as base, like
-
# FormOptionHelper#collection_select and DateHelper#datetime_select.
-
#
-
# === Nested Attributes Examples
-
#
-
# When the object belonging to the current scope has a nested attribute
-
# writer for a certain attribute, fields_for will yield a new scope
-
# for that attribute. This allows you to create forms that set or change
-
# the attributes of a parent object and its associations in one go.
-
#
-
# Nested attribute writers are normal setter methods named after an
-
# association. The most common way of defining these writers is either
-
# with +accepts_nested_attributes_for+ in a model definition or by
-
# defining a method with the proper name. For example: the attribute
-
# writer for the association <tt>:address</tt> is called
-
# <tt>address_attributes=</tt>.
-
#
-
# Whether a one-to-one or one-to-many style form builder will be yielded
-
# depends on whether the normal reader method returns a _single_ object
-
# or an _array_ of objects.
-
#
-
# ==== One-to-one
-
#
-
# Consider a Person class which returns a _single_ Address from the
-
# <tt>address</tt> reader method and responds to the
-
# <tt>address_attributes=</tt> writer method:
-
#
-
# class Person
-
# def address
-
# @address
-
# end
-
#
-
# def address_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# This model can now be used with a nested fields_for, like so:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# Street : <%= address_fields.text_field :street %>
-
# Zip code: <%= address_fields.text_field :zip_code %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When address is already an association on a Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address
-
# end
-
#
-
# If you want to destroy the associated model through the form, you have
-
# to enable it first using the <tt>:allow_destroy</tt> option for
-
# +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :address
-
# accepts_nested_attributes_for :address, :allow_destroy => true
-
# end
-
#
-
# Now, when you use a form element with the <tt>_destroy</tt> parameter,
-
# with a value that evaluates to +true+, you will destroy the associated
-
# model (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :address do |address_fields| %>
-
# ...
-
# Delete: <%= address_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# ==== One-to-many
-
#
-
# Consider a Person class which returns an _array_ of Project instances
-
# from the <tt>projects</tt> reader method and responds to the
-
# <tt>projects_attributes=</tt> writer method:
-
#
-
# class Person
-
# def projects
-
# [@project1, @project2]
-
# end
-
#
-
# def projects_attributes=(attributes)
-
# # Process the attributes hash
-
# end
-
# end
-
#
-
# Note that the <tt>projects_attributes=</tt> writer method is in fact
-
# required for fields_for to correctly identify <tt>:projects</tt> as a
-
# collection, and the correct indices to be set in the form markup.
-
#
-
# When projects is already an association on Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects
-
# end
-
#
-
# This model can now be used with a nested fields_for. The block given to
-
# the nested fields_for call will be repeated for each instance in the
-
# collection:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# <% if project_fields.object.active? %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# It's also possible to specify the instance to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <% @person.projects.each do |project| %>
-
# <% if project.active? %>
-
# <%= person_form.fields_for :projects, project do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# <% end %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# Or a collection to be used:
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects, @active_projects do |project_fields| %>
-
# Name: <%= project_fields.text_field :name %>
-
# <% end %>
-
# ...
-
# <% end %>
-
#
-
# When projects is already an association on Person you can use
-
# +accepts_nested_attributes_for+ to define the writer method for you:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects
-
# end
-
#
-
# If you want to destroy any of the associated models through the
-
# form, you have to enable it first using the <tt>:allow_destroy</tt>
-
# option for +accepts_nested_attributes_for+:
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :projects
-
# accepts_nested_attributes_for :projects, :allow_destroy => true
-
# end
-
#
-
# This will allow you to specify which models to destroy in the
-
# attributes hash by adding a form element for the <tt>_destroy</tt>
-
# parameter with a value that evaluates to +true+
-
# (eg. 1, '1', true, or 'true'):
-
#
-
# <%= form_for @person do |person_form| %>
-
# ...
-
# <%= person_form.fields_for :projects do |project_fields| %>
-
# Delete: <%= project_fields.check_box :_destroy %>
-
# <% end %>
-
# ...
-
# <% end %>
-
2
def fields_for(record_name, record_object = nil, options = {}, &block)
-
builder = instantiate_builder(record_name, record_object, options, &block)
-
output = capture(builder, &block)
-
output.concat builder.hidden_field(:id) if output && options[:hidden_field_id] && !builder.emitted_hidden_id?
-
output
-
end
-
-
# Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation
-
# is found in the current I18n locale (through helpers.label.<modelname>.<attribute>) or you specify it explicitly.
-
# Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
-
# onto the HTML as an HTML element attribute as in the example shown, except for the <tt>:value</tt> option, which is designed to
-
# target labels for radio_button tags (where the value is used in the ID of the input tag).
-
#
-
# ==== Examples
-
# label(:post, :title)
-
# # => <label for="post_title">Title</label>
-
#
-
# You can localize your labels based on model and attribute names.
-
# For example you can define the following in your locale (e.g. en.yml)
-
#
-
# helpers:
-
# label:
-
# post:
-
# body: "Write your entire text here"
-
#
-
# Which then will result in
-
#
-
# label(:post, :body)
-
# # => <label for="post_body">Write your entire text here</label>
-
#
-
# Localization can also be based purely on the translation of the attribute-name
-
# (if you are using ActiveRecord):
-
#
-
# activerecord:
-
# attributes:
-
# post:
-
# cost: "Total cost"
-
#
-
# label(:post, :cost)
-
# # => <label for="post_cost">Total cost</label>
-
#
-
# label(:post, :title, "A short title")
-
# # => <label for="post_title">A short title</label>
-
#
-
# label(:post, :title, "A short title", :class => "title_label")
-
# # => <label for="post_title" class="title_label">A short title</label>
-
#
-
# label(:post, :privacy, "Public Post", :value => "public")
-
# # => <label for="post_privacy_public">Public Post</label>
-
#
-
# label(:post, :terms) do
-
# 'Accept <a href="/terms">Terms</a>.'.html_safe
-
# end
-
2
def label(object_name, method, content_or_options = nil, options = nil, &block)
-
options ||= {}
-
-
content_is_options = content_or_options.is_a?(Hash)
-
if content_is_options || block_given?
-
options.merge!(content_or_options) if content_is_options
-
text = nil
-
else
-
text = content_or_options
-
end
-
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_label_tag(text, options, &block)
-
end
-
-
# Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# ==== Examples
-
# text_field(:post, :title, :size => 20)
-
# # => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />
-
#
-
# text_field(:post, :title, :class => "create_input")
-
# # => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" class="create_input" />
-
#
-
# text_field(:session, :user, :onchange => "if $('session[user]').value == 'admin' { alert('Your login can not be admin!'); }")
-
# # => <input type="text" id="session_user" name="session[user]" value="#{@session.user}" onchange = "if $('session[user]').value == 'admin' { alert('Your login can not be admin!'); }"/>
-
#
-
# text_field(:snippet, :code, :size => 20, :class => 'code_input')
-
# # => <input type="text" id="snippet_code" name="snippet[code]" size="20" value="#{@snippet.code}" class="code_input" />
-
#
-
2
def text_field(object_name, method, options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("text", options)
-
end
-
-
# Returns an input tag of the "password" type tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# ==== Examples
-
# password_field(:login, :pass, :size => 20)
-
# # => <input type="password" id="login_pass" name="login[pass]" size="20" />
-
#
-
# password_field(:account, :secret, :class => "form_input", :value => @account.secret)
-
# # => <input type="password" id="account_secret" name="account[secret]" value="#{@account.secret}" class="form_input" />
-
#
-
# password_field(:user, :password, :onchange => "if $('user[password]').length > 30 { alert('Your password needs to be shorter!'); }")
-
# # => <input type="password" id="user_password" name="user[password]" onchange = "if $('user[password]').length > 30 { alert('Your password needs to be shorter!'); }"/>
-
#
-
# password_field(:account, :pin, :size => 20, :class => 'form_input')
-
# # => <input type="password" id="account_pin" name="account[pin]" size="20" class="form_input" />
-
#
-
2
def password_field(object_name, method, options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("password", { :value => nil }.merge!(options))
-
end
-
-
# Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# ==== Examples
-
# hidden_field(:signup, :pass_confirm)
-
# # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />
-
#
-
# hidden_field(:post, :tag_list)
-
# # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" />
-
#
-
# hidden_field(:user, :token)
-
# # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
-
2
def hidden_field(object_name, method, options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("hidden", options)
-
end
-
-
# Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
-
# shown.
-
#
-
# Using this method inside a +form_for+ block will set the enclosing form's encoding to <tt>multipart/form-data</tt>.
-
#
-
# ==== Examples
-
# file_field(:user, :avatar)
-
# # => <input type="file" id="user_avatar" name="user[avatar]" />
-
#
-
# file_field(:post, :attached, :accept => 'text/html')
-
# # => <input accept="text/html" type="file" id="post_attached" name="post[attached]" />
-
#
-
# file_field(:attachment, :file, :class => 'file_input')
-
# # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
-
#
-
2
def file_field(object_name, method, options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("file", options.update({:size => nil}))
-
end
-
-
# Returns a textarea opening and closing tag set tailored for accessing a specified attribute (identified by +method+)
-
# on an object assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
-
# hash with +options+.
-
#
-
# ==== Examples
-
# text_area(:post, :body, :cols => 20, :rows => 40)
-
# # => <textarea cols="20" rows="40" id="post_body" name="post[body]">
-
# # #{@post.body}
-
# # </textarea>
-
#
-
# text_area(:comment, :text, :size => "20x30")
-
# # => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
-
# # #{@comment.text}
-
# # </textarea>
-
#
-
# text_area(:application, :notes, :cols => 40, :rows => 15, :class => 'app_input')
-
# # => <textarea cols="40" rows="15" id="application_notes" name="application[notes]" class="app_input">
-
# # #{@application.notes}
-
# # </textarea>
-
#
-
# text_area(:entry, :body, :size => "20x20", :disabled => 'disabled')
-
# # => <textarea cols="20" rows="20" id="entry_body" name="entry[body]" disabled="disabled">
-
# # #{@entry.body}
-
# # </textarea>
-
2
def text_area(object_name, method, options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_text_area_tag(options)
-
end
-
-
# Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
-
# It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
-
# Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
-
# while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
-
#
-
# ==== Gotcha
-
#
-
# The HTML specification says unchecked check boxes are not successful, and
-
# thus web browsers do not send them. Unfortunately this introduces a gotcha:
-
# if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid
-
# invoice the user unchecks its check box, no +paid+ parameter is sent. So,
-
# any mass-assignment idiom like
-
#
-
# @invoice.update_attributes(params[:invoice])
-
#
-
# wouldn't update the flag.
-
#
-
# To prevent this the helper generates an auxiliary hidden field before
-
# the very check box. The hidden field has the same name and its
-
# attributes mimic an unchecked check box.
-
#
-
# This way, the client either sends only the hidden field (representing
-
# the check box is unchecked), or both fields. Since the HTML specification
-
# says key/value pairs have to be sent in the same order they appear in the
-
# form, and parameters extraction gets the last occurrence of any repeated
-
# key in the query string, that works for ordinary forms.
-
#
-
# Unfortunately that workaround does not work when the check box goes
-
# within an array-like parameter, as in
-
#
-
# <%= fields_for "project[invoice_attributes][]", invoice, :index => nil do |form| %>
-
# <%= form.check_box :paid %>
-
# ...
-
# <% end %>
-
#
-
# because parameter name repetition is precisely what Rails seeks to distinguish
-
# the elements of the array. For each item with a checked check box you
-
# get an extra ghost item with only that attribute, assigned to "0".
-
#
-
# In that case it is preferable to either use +check_box_tag+ or to use
-
# hashes instead of arrays.
-
#
-
# ==== Examples
-
# # Let's say that @post.validated? is 1:
-
# check_box("post", "validated")
-
# # => <input name="post[validated]" type="hidden" value="0" />
-
# # <input type="checkbox" id="post_validated" name="post[validated]" value="1" />
-
#
-
# # Let's say that @puppy.gooddog is "no":
-
# check_box("puppy", "gooddog", {}, "yes", "no")
-
# # => <input name="puppy[gooddog]" type="hidden" value="no" />
-
# # <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
-
#
-
# check_box("eula", "accepted", { :class => 'eula_check' }, "yes", "no")
-
# # => <input name="eula[accepted]" type="hidden" value="no" />
-
# # <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
-
#
-
2
def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_check_box_tag(options, checked_value, unchecked_value)
-
end
-
-
# Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the
-
# radio button will be checked.
-
#
-
# To force the radio button to be checked pass <tt>:checked => true</tt> in the
-
# +options+ hash. You may pass HTML options there as well.
-
#
-
# ==== Examples
-
# # Let's say that @post.category returns "rails":
-
# radio_button("post", "category", "rails")
-
# radio_button("post", "category", "java")
-
# # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
-
# # <input type="radio" id="post_category_java" name="post[category]" value="java" />
-
#
-
# radio_button("user", "receive_newsletter", "yes")
-
# radio_button("user", "receive_newsletter", "no")
-
# # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
-
# # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
-
2
def radio_button(object_name, method, tag_value, options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_radio_button_tag(tag_value, options)
-
end
-
-
# Returns an input of type "search" for accessing a specified attribute (identified by +method+) on an object
-
# assigned to the template (identified by +object_name+). Inputs of type "search" may be styled differently by
-
# some browsers.
-
#
-
# ==== Examples
-
#
-
# search_field(:user, :name)
-
# # => <input id="user_name" name="user[name]" size="30" type="search" />
-
# search_field(:user, :name, :autosave => false)
-
# # => <input autosave="false" id="user_name" name="user[name]" size="30" type="search" />
-
# search_field(:user, :name, :results => 3)
-
# # => <input id="user_name" name="user[name]" results="3" size="30" type="search" />
-
# # Assume request.host returns "www.example.com"
-
# search_field(:user, :name, :autosave => true)
-
# # => <input autosave="com.example.www" id="user_name" name="user[name]" results="10" size="30" type="search" />
-
# search_field(:user, :name, :onsearch => true)
-
# # => <input id="user_name" incremental="true" name="user[name]" onsearch="true" size="30" type="search" />
-
# search_field(:user, :name, :autosave => false, :onsearch => true)
-
# # => <input autosave="false" id="user_name" incremental="true" name="user[name]" onsearch="true" size="30" type="search" />
-
# search_field(:user, :name, :autosave => true, :onsearch => true)
-
# # => <input autosave="com.example.www" id="user_name" incremental="true" name="user[name]" onsearch="true" results="10" size="30" type="search" />
-
#
-
2
def search_field(object_name, method, options = {})
-
options = options.stringify_keys
-
-
if options["autosave"]
-
if options["autosave"] == true
-
options["autosave"] = request.host.split(".").reverse.join(".")
-
end
-
options["results"] ||= 10
-
end
-
-
if options["onsearch"]
-
options["incremental"] = true unless options.has_key?("incremental")
-
end
-
-
InstanceTag.new(object_name, method, self, options.delete("object")).to_input_field_tag("search", options)
-
end
-
-
# Returns a text_field of type "tel".
-
#
-
# telephone_field("user", "phone")
-
# # => <input id="user_phone" name="user[phone]" size="30" type="tel" />
-
#
-
2
def telephone_field(object_name, method, options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("tel", options)
-
end
-
2
alias phone_field telephone_field
-
-
# Returns a text_field of type "url".
-
#
-
# url_field("user", "homepage")
-
# # => <input id="user_homepage" size="30" name="user[homepage]" type="url" />
-
#
-
2
def url_field(object_name, method, options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("url", options)
-
end
-
-
# Returns a text_field of type "email".
-
#
-
# email_field("user", "address")
-
# # => <input id="user_address" size="30" name="user[address]" type="email" />
-
#
-
2
def email_field(object_name, method, options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("email", options)
-
end
-
-
# Returns an input tag of type "number".
-
#
-
# ==== Options
-
# * Accepts same options as number_field_tag
-
2
def number_field(object_name, method, options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_number_field_tag("number", options)
-
end
-
-
# Returns an input tag of type "range".
-
#
-
# ==== Options
-
# * Accepts same options as range_field_tag
-
2
def range_field(object_name, method, options = {})
-
InstanceTag.new(object_name, method, self, options.delete(:object)).to_number_field_tag("range", options)
-
end
-
-
2
private
-
-
2
def instantiate_builder(record_name, record_object, options, &block)
-
case record_name
-
when String, Symbol
-
object = record_object
-
object_name = record_name
-
else
-
object = record_name
-
object_name = ActiveModel::Naming.param_key(object)
-
end
-
-
builder = options[:builder] || default_form_builder
-
builder.new(object_name, object, self, options, block)
-
end
-
-
2
def default_form_builder
-
builder = ActionView::Base.default_form_builder
-
builder.respond_to?(:constantize) ? builder.constantize : builder
-
end
-
end
-
-
2
class InstanceTag
-
2
include Helpers::ActiveModelInstanceTag, Helpers::TagHelper, Helpers::FormTagHelper
-
-
2
attr_reader :object, :method_name, :object_name
-
-
2
DEFAULT_FIELD_OPTIONS = { "size" => 30 }
-
2
DEFAULT_RADIO_OPTIONS = { }
-
2
DEFAULT_TEXT_AREA_OPTIONS = { "cols" => 40, "rows" => 20 }
-
-
2
def initialize(object_name, method_name, template_object, object = nil)
-
@object_name, @method_name = object_name.to_s.dup, method_name.to_s.dup
-
@template_object = template_object
-
-
@object_name.sub!(/\[\]$/,"") || @object_name.sub!(/\[\]\]$/,"]")
-
@object = retrieve_object(object)
-
@auto_index = retrieve_autoindex(Regexp.last_match.pre_match) if Regexp.last_match
-
end
-
-
2
def to_label_tag(text = nil, options = {}, &block)
-
options = options.stringify_keys
-
tag_value = options.delete("value")
-
name_and_id = options.dup
-
-
if name_and_id["for"]
-
name_and_id["id"] = name_and_id["for"]
-
else
-
name_and_id.delete("id")
-
end
-
-
add_default_name_and_id_for_value(tag_value, name_and_id)
-
options.delete("index")
-
options.delete("namespace")
-
options["for"] ||= name_and_id["id"]
-
-
if block_given?
-
@template_object.label_tag(name_and_id["id"], options, &block)
-
else
-
content = if text.blank?
-
object_name.gsub!(/\[(.*)_attributes\]\[\d\]/, '.\1')
-
method_and_value = tag_value.present? ? "#{method_name}.#{tag_value}" : method_name
-
-
if object.respond_to?(:to_model)
-
key = object.class.model_name.i18n_key
-
i18n_default = ["#{key}.#{method_and_value}".to_sym, ""]
-
end
-
-
i18n_default ||= ""
-
I18n.t("#{object_name}.#{method_and_value}", :default => i18n_default, :scope => "helpers.label").presence
-
else
-
text.to_s
-
end
-
-
content ||= if object && object.class.respond_to?(:human_attribute_name)
-
object.class.human_attribute_name(method_name)
-
end
-
-
content ||= method_name.humanize
-
-
label_tag(name_and_id["id"], content, options)
-
end
-
end
-
-
2
def to_input_field_tag(field_type, options = {})
-
options = options.stringify_keys
-
options["size"] = options["maxlength"] || DEFAULT_FIELD_OPTIONS["size"] unless options.key?("size")
-
options = DEFAULT_FIELD_OPTIONS.merge(options)
-
if field_type == "hidden"
-
options.delete("size")
-
end
-
options["type"] ||= field_type
-
options["value"] = options.fetch("value"){ value_before_type_cast(object) } unless field_type == "file"
-
options["value"] &&= ERB::Util.html_escape(options["value"])
-
add_default_name_and_id(options)
-
tag("input", options)
-
end
-
-
2
def to_number_field_tag(field_type, options = {})
-
options = options.stringify_keys
-
options['size'] ||= nil
-
-
if range = options.delete("in") || options.delete("within")
-
options.update("min" => range.min, "max" => range.max)
-
end
-
to_input_field_tag(field_type, options)
-
end
-
-
2
def to_radio_button_tag(tag_value, options = {})
-
options = DEFAULT_RADIO_OPTIONS.merge(options.stringify_keys)
-
options["type"] = "radio"
-
options["value"] = tag_value
-
if options.has_key?("checked")
-
cv = options.delete "checked"
-
checked = cv == true || cv == "checked"
-
else
-
checked = self.class.radio_button_checked?(value(object), tag_value)
-
end
-
options["checked"] = "checked" if checked
-
add_default_name_and_id_for_value(tag_value, options)
-
tag("input", options)
-
end
-
-
2
def to_text_area_tag(options = {})
-
options = DEFAULT_TEXT_AREA_OPTIONS.merge(options.stringify_keys)
-
add_default_name_and_id(options)
-
-
if size = options.delete("size")
-
options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
-
end
-
-
content_tag("textarea", options.delete('value') || value_before_type_cast(object), options)
-
end
-
-
2
def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
-
options = options.stringify_keys
-
options["type"] = "checkbox"
-
options["value"] = checked_value
-
if options.has_key?("checked")
-
cv = options.delete "checked"
-
checked = cv == true || cv == "checked"
-
else
-
checked = self.class.check_box_checked?(value(object), checked_value)
-
end
-
options["checked"] = "checked" if checked
-
if options["multiple"]
-
add_default_name_and_id_for_value(checked_value, options)
-
options.delete("multiple")
-
else
-
add_default_name_and_id(options)
-
end
-
hidden = unchecked_value ? tag("input", "name" => options["name"], "type" => "hidden", "value" => unchecked_value, "disabled" => options["disabled"]) : ""
-
checkbox = tag("input", options)
-
(hidden + checkbox).html_safe
-
end
-
-
2
def to_boolean_select_tag(options = {})
-
options = options.stringify_keys
-
add_default_name_and_id(options)
-
value = value(object)
-
tag_text = "<select"
-
tag_text << tag_options(options)
-
tag_text << "><option value=\"false\""
-
tag_text << " selected" if value == false
-
tag_text << ">False</option><option value=\"true\""
-
tag_text << " selected" if value
-
tag_text << ">True</option></select>"
-
end
-
-
2
def to_content_tag(tag_name, options = {})
-
content_tag(tag_name, value(object), options)
-
end
-
-
2
def retrieve_object(object)
-
if object
-
object
-
elsif @template_object.instance_variable_defined?("@#{@object_name}")
-
@template_object.instance_variable_get("@#{@object_name}")
-
end
-
rescue NameError
-
# As @object_name may contain the nested syntax (item[subobject]) we need to fallback to nil.
-
nil
-
end
-
-
2
def retrieve_autoindex(pre_match)
-
object = self.object || @template_object.instance_variable_get("@#{pre_match}")
-
if object && object.respond_to?(:to_param)
-
object.to_param
-
else
-
raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
-
end
-
end
-
-
2
def value(object)
-
self.class.value(object, @method_name)
-
end
-
-
2
def value_before_type_cast(object)
-
self.class.value_before_type_cast(object, @method_name)
-
end
-
-
2
class << self
-
2
def value(object, method_name)
-
object.send method_name if object
-
end
-
-
2
def value_before_type_cast(object, method_name)
-
unless object.nil?
-
object.respond_to?(method_name + "_before_type_cast") ?
-
object.send(method_name + "_before_type_cast") :
-
object.send(method_name)
-
end
-
end
-
-
2
def check_box_checked?(value, checked_value)
-
case value
-
when TrueClass, FalseClass
-
value
-
when NilClass
-
false
-
when Integer
-
value != 0
-
when String
-
value == checked_value
-
when Array
-
value.include?(checked_value)
-
else
-
value.to_i != 0
-
end
-
end
-
-
2
def radio_button_checked?(value, checked_value)
-
value.to_s == checked_value.to_s
-
end
-
end
-
-
2
private
-
2
def add_default_name_and_id_for_value(tag_value, options)
-
unless tag_value.nil?
-
pretty_tag_value = tag_value.to_s.gsub(/\s/, "_").gsub(/[^-\w]/, "").downcase
-
specified_id = options["id"]
-
add_default_name_and_id(options)
-
options["id"] += "_#{pretty_tag_value}" if specified_id.blank? && options["id"].present?
-
else
-
add_default_name_and_id(options)
-
end
-
end
-
-
2
def add_default_name_and_id(options)
-
if options.has_key?("index")
-
options["name"] ||= tag_name_with_index(options["index"], options["multiple"])
-
options["id"] = options.fetch("id"){ tag_id_with_index(options["index"]) }
-
options.delete("index")
-
elsif defined?(@auto_index)
-
options["name"] ||= tag_name_with_index(@auto_index, options["multiple"])
-
options["id"] = options.fetch("id"){ tag_id_with_index(@auto_index) }
-
else
-
options["name"] ||= tag_name(options["multiple"])
-
options["id"] = options.fetch("id"){ tag_id }
-
end
-
-
options["id"] = [options.delete('namespace'), options["id"]].compact.join("_").presence
-
end
-
-
2
def tag_name(multiple = false)
-
"#{@object_name}[#{sanitized_method_name}]#{"[]" if multiple}"
-
end
-
-
2
def tag_name_with_index(index, multiple = false)
-
"#{@object_name}[#{index}][#{sanitized_method_name}]#{"[]" if multiple}"
-
end
-
-
2
def tag_id
-
"#{sanitized_object_name}_#{sanitized_method_name}"
-
end
-
-
2
def tag_id_with_index(index)
-
"#{sanitized_object_name}_#{index}_#{sanitized_method_name}"
-
end
-
-
2
def sanitized_object_name
-
@sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
-
end
-
-
2
def sanitized_method_name
-
@sanitized_method_name ||= @method_name.sub(/\?$/,"")
-
end
-
end
-
-
2
class FormBuilder
-
# The methods which wrap a form helper call.
-
2
class_attribute :field_helpers
-
2
self.field_helpers = FormHelper.instance_method_names - %w(form_for convert_to_model)
-
-
2
attr_accessor :object_name, :object, :options
-
-
2
attr_reader :multipart, :parent_builder
-
2
alias :multipart? :multipart
-
-
2
def multipart=(multipart)
-
@multipart = multipart
-
parent_builder.multipart = multipart if parent_builder
-
end
-
-
2
def self._to_partial_path
-
@_to_partial_path ||= name.demodulize.underscore.sub!(/_builder$/, '')
-
end
-
-
2
def to_partial_path
-
self.class._to_partial_path
-
end
-
-
2
def to_model
-
self
-
end
-
-
2
def initialize(object_name, object, template, options, proc)
-
@nested_child_index = {}
-
@object_name, @object, @template, @options, @proc = object_name, object, template, options, proc
-
@parent_builder = options[:parent_builder]
-
@default_options = @options ? @options.slice(:index, :namespace) : {}
-
if @object_name.to_s.match(/\[\]$/)
-
if object ||= @template.instance_variable_get("@#{Regexp.last_match.pre_match}") and object.respond_to?(:to_param)
-
@auto_index = object.to_param
-
else
-
raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
-
end
-
end
-
@multipart = nil
-
end
-
-
2
(field_helpers - %w(label check_box radio_button fields_for hidden_field file_field)).each do |selector|
-
20
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{selector}(method, options = {}) # def text_field(method, options = {})
-
@template.send( # @template.send(
-
#{selector.inspect}, # "text_field",
-
@object_name, # @object_name,
-
method, # method,
-
objectify_options(options)) # objectify_options(options))
-
end # end
-
RUBY_EVAL
-
end
-
-
2
def fields_for(record_name, record_object = nil, fields_options = {}, &block)
-
fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
-
fields_options[:builder] ||= options[:builder]
-
fields_options[:parent_builder] = self
-
fields_options[:namespace] = fields_options[:parent_builder].options[:namespace]
-
-
case record_name
-
when String, Symbol
-
if nested_attributes_association?(record_name)
-
return fields_for_with_nested_attributes(record_name, record_object, fields_options, block)
-
end
-
else
-
record_object = record_name.is_a?(Array) ? record_name.last : record_name
-
record_name = ActiveModel::Naming.param_key(record_object)
-
end
-
-
index = if options.has_key?(:index)
-
"[#{options[:index]}]"
-
elsif defined?(@auto_index)
-
self.object_name = @object_name.to_s.sub(/\[\]$/,"")
-
"[#{@auto_index}]"
-
end
-
record_name = "#{object_name}#{index}[#{record_name}]"
-
-
@template.fields_for(record_name, record_object, fields_options, &block)
-
end
-
-
2
def label(method, text = nil, options = {}, &block)
-
@template.label(@object_name, method, text, objectify_options(options), &block)
-
end
-
-
2
def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
-
@template.check_box(@object_name, method, objectify_options(options), checked_value, unchecked_value)
-
end
-
-
2
def radio_button(method, tag_value, options = {})
-
@template.radio_button(@object_name, method, tag_value, objectify_options(options))
-
end
-
-
2
def hidden_field(method, options = {})
-
@emitted_hidden_id = true if method == :id
-
@template.hidden_field(@object_name, method, objectify_options(options))
-
end
-
-
2
def file_field(method, options = {})
-
self.multipart = true
-
@template.file_field(@object_name, method, objectify_options(options))
-
end
-
-
# Add the submit button for the given form. When no value is given, it checks
-
# if the object is a new resource or not to create the proper label:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.submit %>
-
# <% end %>
-
#
-
# In the example above, if @post is a new record, it will use "Create Post" as
-
# submit button label, otherwise, it uses "Update Post".
-
#
-
# Those labels can be customized using I18n, under the helpers.submit key and accept
-
# the %{model} as translation interpolation:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# create: "Create a %{model}"
-
# update: "Confirm changes to %{model}"
-
#
-
# It also searches for a key specific for the given object:
-
#
-
# en:
-
# helpers:
-
# submit:
-
# post:
-
# create: "Add %{model}"
-
#
-
2
def submit(value=nil, options={})
-
value, options = nil, value if value.is_a?(Hash)
-
value ||= submit_default_value
-
@template.submit_tag(value, options)
-
end
-
-
# Add the submit button for the given form. When no value is given, it checks
-
# if the object is a new resource or not to create the proper label:
-
#
-
# <%= form_for @post do |f| %>
-
# <%= f.button %>
-
# <% end %>
-
#
-
# In the example above, if @post is a new record, it will use "Create Post" as
-
# submit button label, otherwise, it uses "Update Post".
-
#
-
# Those labels can be customized using I18n, under the helpers.submit key and accept
-
# the %{model} as translation interpolation:
-
#
-
# en:
-
# helpers:
-
# button:
-
# create: "Create a %{model}"
-
# update: "Confirm changes to %{model}"
-
#
-
# It also searches for a key specific for the given object:
-
#
-
# en:
-
# helpers:
-
# button:
-
# post:
-
# create: "Add %{model}"
-
#
-
2
def button(value=nil, options={})
-
value, options = nil, value if value.is_a?(Hash)
-
value ||= submit_default_value
-
@template.button_tag(value, options)
-
end
-
-
2
def emitted_hidden_id?
-
@emitted_hidden_id ||= nil
-
end
-
-
2
private
-
2
def objectify_options(options)
-
@default_options.merge(options.merge(:object => @object))
-
end
-
-
2
def submit_default_value
-
object = convert_to_model(@object)
-
key = object ? (object.persisted? ? :update : :create) : :submit
-
-
model = if object.class.respond_to?(:model_name)
-
object.class.model_name.human
-
else
-
@object_name.to_s.humanize
-
end
-
-
defaults = []
-
defaults << :"helpers.submit.#{object_name}.#{key}"
-
defaults << :"helpers.submit.#{key}"
-
defaults << "#{key.to_s.humanize} #{model}"
-
-
I18n.t(defaults.shift, :model => model, :default => defaults)
-
end
-
-
2
def nested_attributes_association?(association_name)
-
@object.respond_to?("#{association_name}_attributes=")
-
end
-
-
2
def fields_for_with_nested_attributes(association_name, association, options, block)
-
name = "#{object_name}[#{association_name}_attributes]"
-
association = convert_to_model(association)
-
-
if association.respond_to?(:persisted?)
-
association = [association] if @object.send(association_name).is_a?(Array)
-
elsif !association.respond_to?(:to_ary)
-
association = @object.send(association_name)
-
end
-
-
if association.respond_to?(:to_ary)
-
explicit_child_index = options[:child_index]
-
output = ActiveSupport::SafeBuffer.new
-
association.each do |child|
-
output << fields_for_nested_model("#{name}[#{explicit_child_index || nested_child_index(name)}]", child, options, block)
-
end
-
output
-
elsif association
-
fields_for_nested_model(name, association, options, block)
-
end
-
end
-
-
2
def fields_for_nested_model(name, object, options, block)
-
object = convert_to_model(object)
-
-
parent_include_id = self.options.fetch(:include_id, true)
-
include_id = options.fetch(:include_id, parent_include_id)
-
options[:hidden_field_id] = object.persisted? && include_id
-
@template.fields_for(name, object, options, &block)
-
end
-
-
2
def nested_child_index(name)
-
@nested_child_index[name] ||= -1
-
@nested_child_index[name] += 1
-
end
-
-
2
def convert_to_model(object)
-
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
end
-
end
-
-
2
ActiveSupport.on_load(:action_view) do
-
2
class ActionView::Base
-
2
cattr_accessor :default_form_builder
-
2
@@default_form_builder = ::ActionView::Helpers::FormBuilder
-
end
-
end
-
end
-
2
require 'cgi'
-
2
require 'erb'
-
2
require 'action_view/helpers/form_helper'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/string/output_safety'
-
-
2
module ActionView
-
# = Action View Form Option Helpers
-
2
module Helpers
-
# Provides a number of methods for turning different kinds of containers into a set of option tags.
-
# == Options
-
# The <tt>collection_select</tt>, <tt>select</tt> and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter, a hash:
-
#
-
# * <tt>:include_blank</tt> - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element.
-
#
-
# For example,
-
#
-
# select("post", "category", Post::CATEGORIES, {:include_blank => true})
-
#
-
# could become:
-
#
-
# <select name="post[category]">
-
# <option></option>
-
# <option>joke</option>
-
# <option>poem</option>
-
# </select>
-
#
-
# Another common case is a select tag for an <tt>belongs_to</tt>-associated object.
-
#
-
# Example with @post.person_id => 2:
-
#
-
# select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:include_blank => 'None'})
-
#
-
# could become:
-
#
-
# <select name="post[person_id]">
-
# <option value="">None</option>
-
# <option value="1">David</option>
-
# <option value="2" selected="selected">Sam</option>
-
# <option value="3">Tobias</option>
-
# </select>
-
#
-
# * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this prepends an option with a generic prompt -- "Please select" -- or the given prompt string.
-
#
-
# Example:
-
#
-
# select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:prompt => 'Select Person'})
-
#
-
# could become:
-
#
-
# <select name="post[person_id]">
-
# <option value="">Select Person</option>
-
# <option value="1">David</option>
-
# <option value="2">Sam</option>
-
# <option value="3">Tobias</option>
-
# </select>
-
#
-
# Like the other form helpers, +select+ can accept an <tt>:index</tt> option to manually set the ID used in the resulting output. Unlike other helpers, +select+ expects this
-
# option to be in the +html_options+ parameter.
-
#
-
# Example:
-
#
-
# select("album[]", "genre", %w[rap rock country], {}, { :index => nil })
-
#
-
# becomes:
-
#
-
# <select name="album[][genre]" id="album__genre">
-
# <option value="rap">rap</option>
-
# <option value="rock">rock</option>
-
# <option value="country">country</option>
-
# </select>
-
#
-
# * <tt>:disabled</tt> - can be a single value or an array of values that will be disabled options in the final output.
-
#
-
# Example:
-
#
-
# select("post", "category", Post::CATEGORIES, {:disabled => 'restricted'})
-
#
-
# could become:
-
#
-
# <select name="post[category]">
-
# <option></option>
-
# <option>joke</option>
-
# <option>poem</option>
-
# <option disabled="disabled">restricted</option>
-
# </select>
-
#
-
# When used with the <tt>collection_select</tt> helper, <tt>:disabled</tt> can also be a Proc that identifies those options that should be disabled.
-
#
-
# Example:
-
#
-
# collection_select(:post, :category_id, Category.all, :id, :name, {:disabled => lambda{|category| category.archived? }})
-
#
-
# If the categories "2008 stuff" and "Christmas" return true when the method <tt>archived?</tt> is called, this would return:
-
# <select name="post[category_id]">
-
# <option value="1" disabled="disabled">2008 stuff</option>
-
# <option value="2" disabled="disabled">Christmas</option>
-
# <option value="3">Jokes</option>
-
# <option value="4">Poems</option>
-
# </select>
-
#
-
2
module FormOptionsHelper
-
# ERB::Util can mask some helpers like textilize. Make sure to include them.
-
2
include TextHelper
-
-
# Create a select tag and a series of contained option tags for the provided object and method.
-
# The option currently held by the object will be selected, provided that the object is available.
-
#
-
# There are two possible formats for the choices parameter, corresponding to other helpers' output:
-
# * A flat collection: see options_for_select
-
# * A nested collection: see grouped_options_for_select
-
#
-
# Example with @post.person_id => 1:
-
# select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })
-
#
-
# could become:
-
#
-
# <select name="post[person_id]">
-
# <option value=""></option>
-
# <option value="1" selected="selected">David</option>
-
# <option value="2">Sam</option>
-
# <option value="3">Tobias</option>
-
# </select>
-
#
-
# This can be used to provide a default set of options in the standard way: before rendering the create form, a
-
# new model instance is assigned the default options and bound to @model_name. Usually this model is not saved
-
# to the database. Instead, a second model object is created when the create request is received.
-
# This allows the user to submit a form page more than once with the expected results of creating multiple records.
-
# In addition, this allows a single partial to be used to generate form inputs for both edit and create forms.
-
#
-
# By default, <tt>post.person_id</tt> is the selected option. Specify <tt>:selected => value</tt> to use a different selection
-
# or <tt>:selected => nil</tt> to leave all options unselected. Similarly, you can specify values to be disabled in the option
-
# tags by specifying the <tt>:disabled</tt> option. This can either be a single value or an array of values to be disabled.
-
#
-
# ==== Gotcha
-
#
-
# The HTML specification says when +multiple+ parameter passed to select and all options got deselected
-
# web browsers do not send any value to server. Unfortunately this introduces a gotcha:
-
# if an +User+ model has many +roles+ and have +role_ids+ accessor, and in the form that edits roles of the user
-
# the user deselects all roles from +role_ids+ multiple select box, no +role_ids+ parameter is sent. So,
-
# any mass-assignment idiom like
-
#
-
# @user.update_attributes(params[:user])
-
#
-
# wouldn't update roles.
-
#
-
# To prevent this the helper generates an auxiliary hidden field before
-
# every multiple select. The hidden field has the same name as multiple select and blank value.
-
#
-
# This way, the client either sends only the hidden field (representing
-
# the deselected multiple select box), or both fields. Since the HTML specification
-
# says key/value pairs have to be sent in the same order they appear in the
-
# form, and parameters extraction gets the last occurrence of any repeated
-
# key in the query string, that works for ordinary forms.
-
#
-
2
def select(object, method, choices, options = {}, html_options = {})
-
InstanceTag.new(object, method, self, options.delete(:object)).to_select_tag(choices, options, html_options)
-
end
-
-
# Returns <tt><select></tt> and <tt><option></tt> tags for the collection of existing return values of
-
# +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
-
# be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
-
# or <tt>:include_blank</tt> in the +options+ hash.
-
#
-
# The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are methods to be called on each member
-
# of +collection+. The return values are used as the +value+ attribute and contents of each
-
# <tt><option></tt> tag, respectively.
-
#
-
# Example object structure for use with this method:
-
# class Post < ActiveRecord::Base
-
# belongs_to :author
-
# end
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# def name_with_initial
-
# "#{first_name.first}. #{last_name}"
-
# end
-
# end
-
#
-
# Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
-
# collection_select(:post, :author_id, Author.all, :id, :name_with_initial, :prompt => true)
-
#
-
# If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
-
# <select name="post[author_id]">
-
# <option value="">Please select</option>
-
# <option value="1" selected="selected">D. Heinemeier Hansson</option>
-
# <option value="2">D. Thomas</option>
-
# <option value="3">M. Clark</option>
-
# </select>
-
2
def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
-
InstanceTag.new(object, method, self, options.delete(:object)).to_collection_select_tag(collection, value_method, text_method, options, html_options)
-
end
-
-
-
# Returns <tt><select></tt>, <tt><optgroup></tt> and <tt><option></tt> tags for the collection of existing return values of
-
# +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
-
# be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
-
# or <tt>:include_blank</tt> in the +options+ hash.
-
#
-
# Parameters:
-
# * +object+ - The instance of the class to be used for the select tag
-
# * +method+ - The attribute of +object+ corresponding to the select tag
-
# * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
-
# * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
-
# array of child objects representing the <tt><option></tt> tags.
-
# * +group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
-
# string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
-
# * +option_key_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
-
# * +option_value_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
-
#
-
# Example object structure for use with this method:
-
# class Continent < ActiveRecord::Base
-
# has_many :countries
-
# # attribs: id, name
-
# end
-
# class Country < ActiveRecord::Base
-
# belongs_to :continent
-
# # attribs: id, name, continent_id
-
# end
-
# class City < ActiveRecord::Base
-
# belongs_to :country
-
# # attribs: id, name, country_id
-
# end
-
#
-
# Sample usage:
-
# grouped_collection_select(:city, :country_id, @continents, :countries, :name, :id, :name)
-
#
-
# Possible output:
-
# <select name="city[country_id]">
-
# <optgroup label="Africa">
-
# <option value="1">South Africa</option>
-
# <option value="3">Somalia</option>
-
# </optgroup>
-
# <optgroup label="Europe">
-
# <option value="7" selected="selected">Denmark</option>
-
# <option value="2">Ireland</option>
-
# </optgroup>
-
# </select>
-
#
-
2
def grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
-
InstanceTag.new(object, method, self, options.delete(:object)).to_grouped_collection_select_tag(collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options)
-
end
-
-
# Return select and option tags for the given object and method, using
-
# #time_zone_options_for_select to generate the list of option tags.
-
#
-
# In addition to the <tt>:include_blank</tt> option documented above,
-
# this method also supports a <tt>:model</tt> option, which defaults
-
# to ActiveSupport::TimeZone. This may be used by users to specify a
-
# different time zone model object. (See +time_zone_options_for_select+
-
# for more information.)
-
#
-
# You can also supply an array of ActiveSupport::TimeZone objects
-
# as +priority_zones+, so that they will be listed above the rest of the
-
# (long) list. (You can use ActiveSupport::TimeZone.us_zones as a convenience
-
# for obtaining a list of the US time zones, or a Regexp to select the zones
-
# of your choice)
-
#
-
# Finally, this method supports a <tt>:default</tt> option, which selects
-
# a default ActiveSupport::TimeZone if the object's time zone is +nil+.
-
#
-
# Examples:
-
# time_zone_select( "user", "time_zone", nil, :include_blank => true)
-
#
-
# time_zone_select( "user", "time_zone", nil, :default => "Pacific Time (US & Canada)" )
-
#
-
# time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.us_zones, :default => "Pacific Time (US & Canada)")
-
#
-
# time_zone_select( "user", 'time_zone', [ ActiveSupport::TimeZone['Alaska'], ActiveSupport::TimeZone['Hawaii'] ])
-
#
-
# time_zone_select( "user", 'time_zone', /Australia/)
-
#
-
# time_zone_select( "user", "time_zone", ActiveSupport::TimeZone.all.sort, :model => ActiveSupport::TimeZone)
-
2
def time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {})
-
InstanceTag.new(object, method, self, options.delete(:object)).to_time_zone_select_tag(priority_zones, options, html_options)
-
end
-
-
# Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container
-
# where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and
-
# the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values
-
# become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +selected+
-
# may also be an array of values to be selected when using a multiple select.
-
#
-
# Examples (call, result):
-
# options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
-
# <option value="$">Dollar</option>\n<option value="DKK">Kroner</option>
-
#
-
# options_for_select([ "VISA", "MasterCard" ], "MasterCard")
-
# <option>VISA</option>\n<option selected="selected">MasterCard</option>
-
#
-
# options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
-
# <option value="$20">Basic</option>\n<option value="$40" selected="selected">Plus</option>
-
#
-
# options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
-
# <option selected="selected">VISA</option>\n<option>MasterCard</option>\n<option selected="selected">Discover</option>
-
#
-
# You can optionally provide html attributes as the last element of the array.
-
#
-
# Examples:
-
# options_for_select([ "Denmark", ["USA", {:class => 'bold'}], "Sweden" ], ["USA", "Sweden"])
-
# <option value="Denmark">Denmark</option>\n<option value="USA" class="bold" selected="selected">USA</option>\n<option value="Sweden" selected="selected">Sweden</option>
-
#
-
# options_for_select([["Dollar", "$", {:class => "bold"}], ["Kroner", "DKK", {:onclick => "alert('HI');"}]])
-
# <option value="$" class="bold">Dollar</option>\n<option value="DKK" onclick="alert('HI');">Kroner</option>
-
#
-
# If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value
-
# or array of values to be disabled. In this case, you can use <tt>:selected</tt> to specify selected option tags.
-
#
-
# Examples:
-
# options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => "Super Platinum")
-
# <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>
-
#
-
# options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => ["Advanced", "Super Platinum"])
-
# <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced" disabled="disabled">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>
-
#
-
# options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :selected => "Free", :disabled => "Super Platinum")
-
# <option value="Free" selected="selected">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>
-
#
-
# NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.
-
2
def options_for_select(container, selected = nil)
-
return container if String === container
-
-
selected, disabled = extract_selected_and_disabled(selected).map do | r |
-
Array.wrap(r).map { |item| item.to_s }
-
end
-
-
container.map do |element|
-
html_attributes = option_html_attributes(element)
-
text, value = option_text_and_value(element).map { |item| item.to_s }
-
selected_attribute = ' selected="selected"' if option_value_selected?(value, selected)
-
disabled_attribute = ' disabled="disabled"' if disabled && option_value_selected?(value, disabled)
-
%(<option value="#{ERB::Util.html_escape(value)}"#{selected_attribute}#{disabled_attribute}#{html_attributes}>#{ERB::Util.html_escape(text)}</option>)
-
end.join("\n").html_safe
-
-
end
-
-
# Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning
-
# the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
-
# Example:
-
# options_from_collection_for_select(@people, 'id', 'name')
-
# This will output the same HTML as if you did this:
-
# <option value="#{person.id}">#{person.name}</option>
-
#
-
# This is more often than not used inside a #select_tag like this example:
-
# select_tag 'person', options_from_collection_for_select(@people, 'id', 'name')
-
#
-
# If +selected+ is specified as a value or array of values, the element(s) returning a match on +value_method+
-
# will be selected option tag(s).
-
#
-
# If +selected+ is specified as a Proc, those members of the collection that return true for the anonymous
-
# function are the selected values.
-
#
-
# +selected+ can also be a hash, specifying both <tt>:selected</tt> and/or <tt>:disabled</tt> values as required.
-
#
-
# Be sure to specify the same class as the +value_method+ when specifying selected or disabled options.
-
# Failure to do this will produce undesired results. Example:
-
# options_from_collection_for_select(@people, 'id', 'name', '1')
-
# Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string)
-
# options_from_collection_for_select(@people, 'id', 'name', 1)
-
# should produce the desired results.
-
2
def options_from_collection_for_select(collection, value_method, text_method, selected = nil)
-
options = collection.map do |element|
-
[element.send(text_method), element.send(value_method)]
-
end
-
selected, disabled = extract_selected_and_disabled(selected)
-
select_deselect = {}
-
select_deselect[:selected] = extract_values_from_collection(collection, value_method, selected)
-
select_deselect[:disabled] = extract_values_from_collection(collection, value_method, disabled)
-
-
options_for_select(options, select_deselect)
-
end
-
-
# Returns a string of <tt><option></tt> tags, like <tt>options_from_collection_for_select</tt>, but
-
# groups them by <tt><optgroup></tt> tags based on the object relationships of the arguments.
-
#
-
# Parameters:
-
# * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
-
# * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
-
# array of child objects representing the <tt><option></tt> tags.
-
# * group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
-
# string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
-
# * +option_key_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
-
# * +option_value_method+ - The name of a method which, when called on a child object of a member of
-
# +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
-
# * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
-
# which will have the +selected+ attribute set. Corresponds to the return value of one of the calls
-
# to +option_key_method+. If +nil+, no selection is made. Can also be a hash if disabled values are
-
# to be specified.
-
#
-
# Example object structure for use with this method:
-
# class Continent < ActiveRecord::Base
-
# has_many :countries
-
# # attribs: id, name
-
# end
-
# class Country < ActiveRecord::Base
-
# belongs_to :continent
-
# # attribs: id, name, continent_id
-
# end
-
#
-
# Sample usage:
-
# option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
-
#
-
# Possible output:
-
# <optgroup label="Africa">
-
# <option value="1">Egypt</option>
-
# <option value="4">Rwanda</option>
-
# ...
-
# </optgroup>
-
# <optgroup label="Asia">
-
# <option value="3" selected="selected">China</option>
-
# <option value="12">India</option>
-
# <option value="5">Japan</option>
-
# ...
-
# </optgroup>
-
#
-
# <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
-
# wrap the output in an appropriate <tt><select></tt> tag.
-
2
def option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil)
-
collection.map do |group|
-
group_label_string = eval("group.#{group_label_method}")
-
"<optgroup label=\"#{ERB::Util.html_escape(group_label_string)}\">" +
-
options_from_collection_for_select(eval("group.#{group_method}"), option_key_method, option_value_method, selected_key) +
-
'</optgroup>'
-
end.join.html_safe
-
end
-
-
# Returns a string of <tt><option></tt> tags, like <tt>options_for_select</tt>, but
-
# wraps them with <tt><optgroup></tt> tags.
-
#
-
# Parameters:
-
# * +grouped_options+ - Accepts a nested array or hash of strings. The first value serves as the
-
# <tt><optgroup></tt> label while the second value must be an array of options. The second value can be a
-
# nested array of text-value pairs. See <tt>options_for_select</tt> for more info.
-
# Ex. ["North America",[["United States","US"],["Canada","CA"]]]
-
# * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
-
# which will have the +selected+ attribute set. Note: It is possible for this value to match multiple options
-
# as you might have the same option in multiple groups. Each will then get <tt>selected="selected"</tt>.
-
# * +prompt+ - set to true or a prompt string. When the select element doesn't have a value yet, this
-
# prepends an option with a generic prompt - "Please select" - or the given prompt string.
-
#
-
# Sample usage (Array):
-
# grouped_options = [
-
# ['North America',
-
# [['United States','US'],'Canada']],
-
# ['Europe',
-
# ['Denmark','Germany','France']]
-
# ]
-
# grouped_options_for_select(grouped_options)
-
#
-
# Sample usage (Hash):
-
# grouped_options = {
-
# 'North America' => [['United States','US'], 'Canada'],
-
# 'Europe' => ['Denmark','Germany','France']
-
# }
-
# grouped_options_for_select(grouped_options)
-
#
-
# Possible output:
-
# <optgroup label="Europe">
-
# <option value="Denmark">Denmark</option>
-
# <option value="Germany">Germany</option>
-
# <option value="France">France</option>
-
# </optgroup>
-
# <optgroup label="North America">
-
# <option value="US">United States</option>
-
# <option value="Canada">Canada</option>
-
# </optgroup>
-
#
-
# <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
-
# wrap the output in an appropriate <tt><select></tt> tag.
-
2
def grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil)
-
body = ''
-
body << content_tag(:option, prompt, { :value => "" }, true) if prompt
-
-
grouped_options = grouped_options.sort if grouped_options.is_a?(Hash)
-
-
grouped_options.each do |group|
-
body << content_tag(:optgroup, options_for_select(group[1], selected_key), :label => group[0])
-
end
-
-
body.html_safe
-
end
-
-
# Returns a string of option tags for pretty much any time zone in the
-
# world. Supply a ActiveSupport::TimeZone name as +selected+ to have it
-
# marked as the selected option tag. You can also supply an array of
-
# ActiveSupport::TimeZone objects as +priority_zones+, so that they will
-
# be listed above the rest of the (long) list. (You can use
-
# ActiveSupport::TimeZone.us_zones as a convenience for obtaining a list
-
# of the US time zones, or a Regexp to select the zones of your choice)
-
#
-
# The +selected+ parameter must be either +nil+, or a string that names
-
# a ActiveSupport::TimeZone.
-
#
-
# By default, +model+ is the ActiveSupport::TimeZone constant (which can
-
# be obtained in Active Record as a value object). The only requirement
-
# is that the +model+ parameter be an object that responds to +all+, and
-
# returns an array of objects that represent time zones.
-
#
-
# NOTE: Only the option tags are returned, you have to wrap this call in
-
# a regular HTML select tag.
-
2
def time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone)
-
zone_options = ""
-
-
zones = model.all
-
convert_zones = lambda { |list| list.map { |z| [ z.to_s, z.name ] } }
-
-
if priority_zones
-
if priority_zones.is_a?(Regexp)
-
priority_zones = model.all.find_all {|z| z =~ priority_zones}
-
end
-
zone_options += options_for_select(convert_zones[priority_zones], selected)
-
zone_options += "<option value=\"\" disabled=\"disabled\">-------------</option>\n"
-
-
zones = zones.reject { |z| priority_zones.include?( z ) }
-
end
-
-
zone_options += options_for_select(convert_zones[zones], selected)
-
zone_options.html_safe
-
end
-
-
2
private
-
2
def option_html_attributes(element)
-
return "" unless Array === element
-
html_attributes = []
-
element.select { |e| Hash === e }.reduce({}, :merge).each do |k, v|
-
html_attributes << " #{k}=\"#{ERB::Util.html_escape(v.to_s)}\""
-
end
-
html_attributes.join
-
end
-
-
2
def option_text_and_value(option)
-
# Options are [text, value] pairs or strings used for both.
-
case
-
when Array === option
-
option = option.reject { |e| Hash === e }
-
[option.first, option.last]
-
when !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last)
-
[option.first, option.last]
-
else
-
[option, option]
-
end
-
end
-
-
2
def option_value_selected?(value, selected)
-
if selected.respond_to?(:include?) && !selected.is_a?(String)
-
selected.include? value
-
else
-
value == selected
-
end
-
end
-
-
2
def extract_selected_and_disabled(selected)
-
if selected.is_a?(Proc)
-
[ selected, nil ]
-
else
-
selected = Array.wrap(selected)
-
options = selected.extract_options!.symbolize_keys
-
[ options.include?(:selected) ? options[:selected] : selected, options[:disabled] ]
-
end
-
end
-
-
2
def extract_values_from_collection(collection, value_method, selected)
-
if selected.is_a?(Proc)
-
collection.map do |element|
-
element.send(value_method) if selected.call(element)
-
end.compact
-
else
-
selected
-
end
-
end
-
end
-
-
2
class InstanceTag #:nodoc:
-
2
include FormOptionsHelper
-
-
2
def to_select_tag(choices, options, html_options)
-
selected_value = options.has_key?(:selected) ? options[:selected] : value(object)
-
choices = choices.to_a if choices.is_a?(Range)
-
-
# Grouped choices look like this:
-
#
-
# [nil, []]
-
# { nil => [] }
-
#
-
if !choices.empty? && choices.first.respond_to?(:last) && Array === choices.first.last
-
option_tags = grouped_options_for_select(choices, :selected => selected_value, :disabled => options[:disabled])
-
else
-
option_tags = options_for_select(choices, :selected => selected_value, :disabled => options[:disabled])
-
end
-
-
select_content_tag(option_tags, options, html_options)
-
end
-
-
2
def to_collection_select_tag(collection, value_method, text_method, options, html_options)
-
selected_value = options.has_key?(:selected) ? options[:selected] : value(object)
-
select_content_tag(
-
options_from_collection_for_select(collection, value_method, text_method, :selected => selected_value, :disabled => options[:disabled]), options, html_options
-
)
-
end
-
-
2
def to_grouped_collection_select_tag(collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options)
-
select_content_tag(
-
option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, value(object)), options, html_options
-
)
-
end
-
-
2
def to_time_zone_select_tag(priority_zones, options, html_options)
-
select_content_tag(
-
time_zone_options_for_select(value(object) || options[:default], priority_zones, options[:model] || ActiveSupport::TimeZone), options, html_options
-
)
-
end
-
-
2
private
-
2
def add_options(option_tags, options, value = nil)
-
if options[:include_blank]
-
option_tags = content_tag_string('option', options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, :value => '') + "\n" + option_tags
-
end
-
if value.blank? && options[:prompt]
-
prompt = options[:prompt].kind_of?(String) ? options[:prompt] : I18n.translate('helpers.select.prompt', :default => 'Please select')
-
option_tags = content_tag_string('option', prompt, :value => '') + "\n" + option_tags
-
end
-
option_tags
-
end
-
-
2
def select_content_tag(option_tags, options, html_options)
-
html_options = html_options.stringify_keys
-
add_default_name_and_id(html_options)
-
select = content_tag("select", add_options(option_tags, options, value(object)), html_options)
-
if html_options["multiple"]
-
tag("input", :disabled => html_options["disabled"], :name => html_options["name"], :type => "hidden", :value => "") + select
-
else
-
select
-
end
-
end
-
end
-
-
2
class FormBuilder
-
2
def select(method, choices, options = {}, html_options = {})
-
@template.select(@object_name, method, choices, objectify_options(options), @default_options.merge(html_options))
-
end
-
-
2
def collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
-
@template.collection_select(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options))
-
end
-
-
2
def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
-
@template.grouped_collection_select(@object_name, method, collection, group_method, group_label_method, option_key_method, option_value_method, objectify_options(options), @default_options.merge(html_options))
-
end
-
-
2
def time_zone_select(method, priority_zones = nil, options = {}, html_options = {})
-
@template.time_zone_select(@object_name, method, priority_zones, objectify_options(options), @default_options.merge(html_options))
-
end
-
end
-
end
-
end
-
2
require 'cgi'
-
2
require 'action_view/helpers/tag_helper'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/string/output_safety'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
-
2
module ActionView
-
# = Action View Form Tag Helpers
-
2
module Helpers
-
# Provides a number of methods for creating form tags that doesn't rely on an Active Record object assigned to the template like
-
# FormHelper does. Instead, you provide the names and values manually.
-
#
-
# NOTE: The HTML options <tt>disabled</tt>, <tt>readonly</tt>, and <tt>multiple</tt> can all be treated as booleans. So specifying
-
# <tt>:disabled => true</tt> will give <tt>disabled="disabled"</tt>.
-
2
module FormTagHelper
-
2
extend ActiveSupport::Concern
-
-
2
include UrlHelper
-
2
include TextHelper
-
-
2
mattr_accessor :embed_authenticity_token_in_remote_forms
-
2
self.embed_authenticity_token_in_remote_forms = true
-
-
# Starts a form tag that points the action to an url configured with <tt>url_for_options</tt> just like
-
# ActionController::Base#url_for. The method for the form defaults to POST.
-
#
-
# ==== Options
-
# * <tt>:multipart</tt> - If set to true, the enctype is set to "multipart/form-data".
-
# * <tt>:method</tt> - The method to use when submitting the form, usually either "get" or "post".
-
# If "put", "delete", or another verb is used, a hidden input with name <tt>_method</tt>
-
# is added to simulate the verb over post.
-
# * <tt>:authenticity_token</tt> - Authenticity token to use in the form. Use only if you need to
-
# pass custom authenticity token string, or to not add authenticity_token field at all
-
# (by passing <tt>false</tt>). Remote forms may omit the embedded authenticity token
-
# by setting <tt>config.action_view.embed_authenticity_token_in_remote_forms = false</tt>.
-
# This is helpful when you're fragment-caching the form. Remote forms get the
-
# authenticity from the <tt>meta</tt> tag, so embedding is unnecessary unless you
-
# support browsers without JavaScript.
-
# * A list of parameters to feed to the URL the form will be posted to.
-
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
-
# submit behavior. By default this behavior is an ajax submit.
-
#
-
# ==== Examples
-
# form_tag('/posts')
-
# # => <form action="/posts" method="post">
-
#
-
# form_tag('/posts/1', :method => :put)
-
# # => <form action="/posts/1" method="post"> ... <input name="_method" type="hidden" value="put" /> ...
-
#
-
# form_tag('/upload', :multipart => true)
-
# # => <form action="/upload" method="post" enctype="multipart/form-data">
-
#
-
# <%= form_tag('/posts') do -%>
-
# <div><%= submit_tag 'Save' %></div>
-
# <% end -%>
-
# # => <form action="/posts" method="post"><div><input type="submit" name="commit" value="Save" /></div></form>
-
#
-
# <%= form_tag('/posts', :remote => true) %>
-
# # => <form action="/posts" method="post" data-remote="true">
-
#
-
# form_tag('http://far.away.com/form', :authenticity_token => false)
-
# # form without authenticity token
-
#
-
# form_tag('http://far.away.com/form', :authenticity_token => "cf50faa3fe97702ca1ae")
-
# # form with custom authenticity token
-
#
-
2
def form_tag(url_for_options = {}, options = {}, &block)
-
html_options = html_options_for_form(url_for_options, options)
-
if block_given?
-
form_tag_in_block(html_options, &block)
-
else
-
form_tag_html(html_options)
-
end
-
end
-
-
# Creates a dropdown selection box, or if the <tt>:multiple</tt> option is set to true, a multiple
-
# choice selection box.
-
#
-
# Helpers::FormOptions can be used to create common select boxes such as countries, time zones, or
-
# associated records. <tt>option_tags</tt> is a string containing the option tags for the select box.
-
#
-
# ==== Options
-
# * <tt>:multiple</tt> - If set to true the selection will allow multiple choices.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:include_blank</tt> - If set to true, an empty option will be create
-
# * <tt>:prompt</tt> - Create a prompt option with blank value and the text asking user to select something
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name")
-
# # <select id="people" name="people"><option value="1">David</option></select>
-
#
-
# select_tag "people", "<option>David</option>".html_safe
-
# # => <select id="people" name="people"><option>David</option></select>
-
#
-
# select_tag "count", "<option>1</option><option>2</option><option>3</option><option>4</option>".html_safe
-
# # => <select id="count" name="count"><option>1</option><option>2</option>
-
# # <option>3</option><option>4</option></select>
-
#
-
# select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>".html_safe, :multiple => true
-
# # => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option>
-
# # <option>Green</option><option>Blue</option></select>
-
#
-
# select_tag "locations", "<option>Home</option><option selected="selected">Work</option><option>Out</option>".html_safe
-
# # => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option>
-
# # <option>Out</option></select>
-
#
-
# select_tag "access", "<option>Read</option><option>Write</option>".html_safe, :multiple => true, :class => 'form_input'
-
# # => <select class="form_input" id="access" multiple="multiple" name="access[]"><option>Read</option>
-
# # <option>Write</option></select>
-
#
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name"), :include_blank => true
-
# # => <select id="people" name="people"><option value=""></option><option value="1">David</option></select>
-
#
-
# select_tag "people", options_from_collection_for_select(@people, "id", "name"), :prompt => "Select something"
-
# # => <select id="people" name="people"><option value="">Select something</option><option value="1">David</option></select>
-
#
-
# select_tag "destination", "<option>NYC</option><option>Paris</option><option>Rome</option>".html_safe, :disabled => true
-
# # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option>
-
# # <option>Paris</option><option>Rome</option></select>
-
2
def select_tag(name, option_tags = nil, options = {})
-
option_tags ||= ""
-
html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name
-
-
if options.delete(:include_blank)
-
option_tags = content_tag(:option, '', :value => '').safe_concat(option_tags)
-
end
-
-
if prompt = options.delete(:prompt)
-
option_tags = content_tag(:option, prompt, :value => '').safe_concat(option_tags)
-
end
-
-
content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys)
-
end
-
-
# Creates a standard text field; use these text fields to input smaller chunks of text like a username
-
# or a search query.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:size</tt> - The number of visible characters that will fit in the input.
-
# * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter.
-
# * <tt>:placeholder</tt> - The text contained in the field by default which is removed when the field receives focus.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# text_field_tag 'name'
-
# # => <input id="name" name="name" type="text" />
-
#
-
# text_field_tag 'query', 'Enter your search query here'
-
# # => <input id="query" name="query" type="text" value="Enter your search query here" />
-
#
-
# text_field_tag 'search', nil, :placeholder => 'Enter search term...'
-
# # => <input id="search" name="search" placeholder="Enter search term..." type="text" />
-
#
-
# text_field_tag 'request', nil, :class => 'special_input'
-
# # => <input class="special_input" id="request" name="request" type="text" />
-
#
-
# text_field_tag 'address', '', :size => 75
-
# # => <input id="address" name="address" size="75" type="text" value="" />
-
#
-
# text_field_tag 'zip', nil, :maxlength => 5
-
# # => <input id="zip" maxlength="5" name="zip" type="text" />
-
#
-
# text_field_tag 'payment_amount', '$0.00', :disabled => true
-
# # => <input disabled="disabled" id="payment_amount" name="payment_amount" type="text" value="$0.00" />
-
#
-
# text_field_tag 'ip', '0.0.0.0', :maxlength => 15, :size => 20, :class => "ip-input"
-
# # => <input class="ip-input" id="ip" maxlength="15" name="ip" size="20" type="text" value="0.0.0.0" />
-
2
def text_field_tag(name, value = nil, options = {})
-
tag :input, { "type" => "text", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
-
end
-
-
# Creates a label element. Accepts a block.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# label_tag 'name'
-
# # => <label for="name">Name</label>
-
#
-
# label_tag 'name', 'Your name'
-
# # => <label for="name">Your name</label>
-
#
-
# label_tag 'name', nil, :class => 'small_label'
-
# # => <label for="name" class="small_label">Name</label>
-
2
def label_tag(name = nil, content_or_options = nil, options = nil, &block)
-
if block_given? && content_or_options.is_a?(Hash)
-
options = content_or_options = content_or_options.stringify_keys
-
else
-
options ||= {}
-
options = options.stringify_keys
-
end
-
options["for"] = sanitize_to_id(name) unless name.blank? || options.has_key?("for")
-
content_tag :label, content_or_options || name.to_s.humanize, options, &block
-
end
-
-
# Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or
-
# data that should be hidden from the user.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# hidden_field_tag 'tags_list'
-
# # => <input id="tags_list" name="tags_list" type="hidden" />
-
#
-
# hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@'
-
# # => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" />
-
#
-
# hidden_field_tag 'collected_input', '', :onchange => "alert('Input collected!')"
-
# # => <input id="collected_input" name="collected_input" onchange="alert('Input collected!')"
-
# # type="hidden" value="" />
-
2
def hidden_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "hidden"))
-
end
-
-
# Creates a file upload field. If you are using file uploads then you will also need
-
# to set the multipart option for the form tag:
-
#
-
# <%= form_tag '/upload', :multipart => true do %>
-
# <label for="file">File to Upload</label> <%= file_field_tag "file" %>
-
# <%= submit_tag %>
-
# <% end %>
-
#
-
# The specified URL will then be passed a File object containing the selected file, or if the field
-
# was left blank, a StringIO object.
-
#
-
# ==== Options
-
# * Creates standard HTML attributes for the tag.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
#
-
# ==== Examples
-
# file_field_tag 'attachment'
-
# # => <input id="attachment" name="attachment" type="file" />
-
#
-
# file_field_tag 'avatar', :class => 'profile_input'
-
# # => <input class="profile_input" id="avatar" name="avatar" type="file" />
-
#
-
# file_field_tag 'picture', :disabled => true
-
# # => <input disabled="disabled" id="picture" name="picture" type="file" />
-
#
-
# file_field_tag 'resume', :value => '~/resume.doc'
-
# # => <input id="resume" name="resume" type="file" value="~/resume.doc" />
-
#
-
# file_field_tag 'user_pic', :accept => 'image/png,image/gif,image/jpeg'
-
# # => <input accept="image/png,image/gif,image/jpeg" id="user_pic" name="user_pic" type="file" />
-
#
-
# file_field_tag 'file', :accept => 'text/html', :class => 'upload', :value => 'index.html'
-
# # => <input accept="text/html" class="upload" id="file" name="file" type="file" value="index.html" />
-
2
def file_field_tag(name, options = {})
-
text_field_tag(name, nil, options.update("type" => "file"))
-
end
-
-
# Creates a password field, a masked text field that will hide the users input behind a mask character.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:size</tt> - The number of visible characters that will fit in the input.
-
# * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# password_field_tag 'pass'
-
# # => <input id="pass" name="pass" type="password" />
-
#
-
# password_field_tag 'secret', 'Your secret here'
-
# # => <input id="secret" name="secret" type="password" value="Your secret here" />
-
#
-
# password_field_tag 'masked', nil, :class => 'masked_input_field'
-
# # => <input class="masked_input_field" id="masked" name="masked" type="password" />
-
#
-
# password_field_tag 'token', '', :size => 15
-
# # => <input id="token" name="token" size="15" type="password" value="" />
-
#
-
# password_field_tag 'key', nil, :maxlength => 16
-
# # => <input id="key" maxlength="16" name="key" type="password" />
-
#
-
# password_field_tag 'confirm_pass', nil, :disabled => true
-
# # => <input disabled="disabled" id="confirm_pass" name="confirm_pass" type="password" />
-
#
-
# password_field_tag 'pin', '1234', :maxlength => 4, :size => 6, :class => "pin_input"
-
# # => <input class="pin_input" id="pin" maxlength="4" name="pin" size="6" type="password" value="1234" />
-
2
def password_field_tag(name = "password", value = nil, options = {})
-
text_field_tag(name, value, options.update("type" => "password"))
-
end
-
-
# Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions.
-
#
-
# ==== Options
-
# * <tt>:size</tt> - A string specifying the dimensions (columns by rows) of the textarea (e.g., "25x10").
-
# * <tt>:rows</tt> - Specify the number of rows in the textarea
-
# * <tt>:cols</tt> - Specify the number of columns in the textarea
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * <tt>:escape</tt> - By default, the contents of the text input are HTML escaped.
-
# If you need unescaped contents, set this to false.
-
# * Any other key creates standard HTML attributes for the tag.
-
#
-
# ==== Examples
-
# text_area_tag 'post'
-
# # => <textarea id="post" name="post"></textarea>
-
#
-
# text_area_tag 'bio', @user.bio
-
# # => <textarea id="bio" name="bio">This is my biography.</textarea>
-
#
-
# text_area_tag 'body', nil, :rows => 10, :cols => 25
-
# # => <textarea cols="25" id="body" name="body" rows="10"></textarea>
-
#
-
# text_area_tag 'body', nil, :size => "25x10"
-
# # => <textarea name="body" id="body" cols="25" rows="10"></textarea>
-
#
-
# text_area_tag 'description', "Description goes here.", :disabled => true
-
# # => <textarea disabled="disabled" id="description" name="description">Description goes here.</textarea>
-
#
-
# text_area_tag 'comment', nil, :class => 'comment_input'
-
# # => <textarea class="comment_input" id="comment" name="comment"></textarea>
-
2
def text_area_tag(name, content = nil, options = {})
-
options = options.stringify_keys
-
-
if size = options.delete("size")
-
options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
-
end
-
-
escape = options.key?("escape") ? options.delete("escape") : true
-
content = ERB::Util.html_escape(content) if escape
-
-
content_tag :textarea, content.to_s.html_safe, { "name" => name, "id" => sanitize_to_id(name) }.update(options)
-
end
-
-
# Creates a check box form input tag.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Examples
-
# check_box_tag 'accept'
-
# # => <input id="accept" name="accept" type="checkbox" value="1" />
-
#
-
# check_box_tag 'rock', 'rock music'
-
# # => <input id="rock" name="rock" type="checkbox" value="rock music" />
-
#
-
# check_box_tag 'receive_email', 'yes', true
-
# # => <input checked="checked" id="receive_email" name="receive_email" type="checkbox" value="yes" />
-
#
-
# check_box_tag 'tos', 'yes', false, :class => 'accept_tos'
-
# # => <input class="accept_tos" id="tos" name="tos" type="checkbox" value="yes" />
-
#
-
# check_box_tag 'eula', 'accepted', false, :disabled => true
-
# # => <input disabled="disabled" id="eula" name="eula" type="checkbox" value="accepted" />
-
2
def check_box_tag(name, value = "1", checked = false, options = {})
-
html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
-
html_options["checked"] = "checked" if checked
-
tag :input, html_options
-
end
-
-
# Creates a radio button; use groups of radio buttons named the same to allow users to
-
# select from a group of options.
-
#
-
# ==== Options
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Examples
-
# radio_button_tag 'gender', 'male'
-
# # => <input id="gender_male" name="gender" type="radio" value="male" />
-
#
-
# radio_button_tag 'receive_updates', 'no', true
-
# # => <input checked="checked" id="receive_updates_no" name="receive_updates" type="radio" value="no" />
-
#
-
# radio_button_tag 'time_slot', "3:00 p.m.", false, :disabled => true
-
# # => <input disabled="disabled" id="time_slot_300_pm" name="time_slot" type="radio" value="3:00 p.m." />
-
#
-
# radio_button_tag 'color', "green", true, :class => "color_input"
-
# # => <input checked="checked" class="color_input" id="color_green" name="color" type="radio" value="green" />
-
2
def radio_button_tag(name, value, checked = false, options = {})
-
html_options = { "type" => "radio", "name" => name, "id" => "#{sanitize_to_id(name)}_#{sanitize_to_id(value)}", "value" => value }.update(options.stringify_keys)
-
html_options["checked"] = "checked" if checked
-
tag :input, html_options
-
end
-
-
# Creates a submit button with the text <tt>value</tt> as the caption.
-
#
-
# ==== Options
-
# * <tt>:confirm => 'question?'</tt> - If present the unobtrusive JavaScript
-
# drivers will provide a prompt with the question specified. If the user accepts,
-
# the form is processed normally, otherwise no action is taken.
-
# * <tt>:disabled</tt> - If true, the user will not be able to use this input.
-
# * <tt>:disable_with</tt> - Value of this parameter will be used as the value for a
-
# disabled version of the submit button when the form is submitted. This feature is
-
# provided by the unobtrusive JavaScript driver.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Examples
-
# submit_tag
-
# # => <input name="commit" type="submit" value="Save changes" />
-
#
-
# submit_tag "Edit this article"
-
# # => <input name="commit" type="submit" value="Edit this article" />
-
#
-
# submit_tag "Save edits", :disabled => true
-
# # => <input disabled="disabled" name="commit" type="submit" value="Save edits" />
-
#
-
# submit_tag "Complete sale", :disable_with => "Please wait..."
-
# # => <input name="commit" data-disable-with="Please wait..." type="submit" value="Complete sale" />
-
#
-
# submit_tag nil, :class => "form_submit"
-
# # => <input class="form_submit" name="commit" type="submit" />
-
#
-
# submit_tag "Edit", :disable_with => "Editing...", :class => "edit_button"
-
# # => <input class="edit_button" data-disable_with="Editing..." name="commit" type="submit" value="Edit" />
-
#
-
# submit_tag "Save", :confirm => "Are you sure?"
-
# # => <input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />
-
#
-
2
def submit_tag(value = "Save changes", options = {})
-
options = options.stringify_keys
-
-
if disable_with = options.delete("disable_with")
-
options["data-disable-with"] = disable_with
-
end
-
-
if confirm = options.delete("confirm")
-
options["data-confirm"] = confirm
-
end
-
-
tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options)
-
end
-
-
# Creates a button element that defines a <tt>submit</tt> button,
-
# <tt>reset</tt>button or a generic button which can be used in
-
# JavaScript, for example. You can use the button tag as a regular
-
# submit tag but it isn't supported in legacy browsers. However,
-
# the button tag allows richer labels such as images and emphasis,
-
# so this helper will also accept a block.
-
#
-
# ==== Options
-
# * <tt>:confirm => 'question?'</tt> - If present, the
-
# unobtrusive JavaScript drivers will provide a prompt with
-
# the question specified. If the user accepts, the form is
-
# processed normally, otherwise no action is taken.
-
# * <tt>:disabled</tt> - If true, the user will not be able to
-
# use this input.
-
# * <tt>:disable_with</tt> - Value of this parameter will be
-
# used as the value for a disabled version of the submit
-
# button when the form is submitted. This feature is provided
-
# by the unobtrusive JavaScript driver.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Examples
-
# button_tag
-
# # => <button name="button" type="submit">Button</button>
-
#
-
# button_tag(:type => 'button') do
-
# content_tag(:strong, 'Ask me!')
-
# end
-
# # => <button name="button" type="button">
-
# # <strong>Ask me!</strong>
-
# # </button>
-
#
-
# button_tag "Checkout", :disable_with => "Please wait..."
-
# # => <button data-disable-with="Please wait..." name="button" type="submit">Checkout</button>
-
#
-
2
def button_tag(content_or_options = nil, options = nil, &block)
-
options = content_or_options if block_given? && content_or_options.is_a?(Hash)
-
options ||= {}
-
options = options.stringify_keys
-
-
if disable_with = options.delete("disable_with")
-
options["data-disable-with"] = disable_with
-
end
-
-
if confirm = options.delete("confirm")
-
options["data-confirm"] = confirm
-
end
-
-
options.reverse_merge! 'name' => 'button', 'type' => 'submit'
-
-
content_tag :button, content_or_options || 'Button', options, &block
-
end
-
-
# Displays an image which when clicked will submit the form.
-
#
-
# <tt>source</tt> is passed to AssetTagHelper#path_to_image
-
#
-
# ==== Options
-
# * <tt>:confirm => 'question?'</tt> - This will add a JavaScript confirm
-
# prompt with the question specified. If the user accepts, the form is
-
# processed normally, otherwise no action is taken.
-
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
-
# * Any other key creates standard HTML options for the tag.
-
#
-
# ==== Examples
-
# image_submit_tag("login.png")
-
# # => <input src="/images/login.png" type="image" />
-
#
-
# image_submit_tag("purchase.png", :disabled => true)
-
# # => <input disabled="disabled" src="/images/purchase.png" type="image" />
-
#
-
# image_submit_tag("search.png", :class => 'search_button')
-
# # => <input class="search_button" src="/images/search.png" type="image" />
-
#
-
# image_submit_tag("agree.png", :disabled => true, :class => "agree_disagree_button")
-
# # => <input class="agree_disagree_button" disabled="disabled" src="/images/agree.png" type="image" />
-
2
def image_submit_tag(source, options = {})
-
options = options.stringify_keys
-
-
if confirm = options.delete("confirm")
-
options["data-confirm"] = confirm
-
end
-
-
tag :input, { "type" => "image", "src" => path_to_image(source) }.update(options)
-
end
-
-
# Creates a field set for grouping HTML form elements.
-
#
-
# <tt>legend</tt> will become the fieldset's title (optional as per W3C).
-
# <tt>options</tt> accept the same values as tag.
-
#
-
# ==== Examples
-
# <%= field_set_tag do %>
-
# <p><%= text_field_tag 'name' %></p>
-
# <% end %>
-
# # => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset>
-
#
-
# <%= field_set_tag 'Your details' do %>
-
# <p><%= text_field_tag 'name' %></p>
-
# <% end %>
-
# # => <fieldset><legend>Your details</legend><p><input id="name" name="name" type="text" /></p></fieldset>
-
#
-
# <%= field_set_tag nil, :class => 'format' do %>
-
# <p><%= text_field_tag 'name' %></p>
-
# <% end %>
-
# # => <fieldset class="format"><p><input id="name" name="name" type="text" /></p></fieldset>
-
2
def field_set_tag(legend = nil, options = nil, &block)
-
content = capture(&block)
-
output = tag(:fieldset, options, true)
-
output.safe_concat(content_tag(:legend, legend)) unless legend.blank?
-
output.concat(content)
-
output.safe_concat("</fieldset>")
-
end
-
-
# Creates a text field of type "search".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
2
def search_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "search"))
-
end
-
-
# Creates a text field of type "tel".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
2
def telephone_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "tel"))
-
end
-
2
alias phone_field_tag telephone_field_tag
-
-
# Creates a text field of type "url".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
2
def url_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "url"))
-
end
-
-
# Creates a text field of type "email".
-
#
-
# ==== Options
-
# * Accepts the same options as text_field_tag.
-
2
def email_field_tag(name, value = nil, options = {})
-
text_field_tag(name, value, options.stringify_keys.update("type" => "email"))
-
end
-
-
# Creates a number field.
-
#
-
# ==== Options
-
# * <tt>:min</tt> - The minimum acceptable value.
-
# * <tt>:max</tt> - The maximum acceptable value.
-
# * <tt>:in</tt> - A range specifying the <tt>:min</tt> and
-
# <tt>:max</tt> values.
-
# * <tt>:step</tt> - The acceptable value granularity.
-
# * Otherwise accepts the same options as text_field_tag.
-
#
-
# ==== Examples
-
# number_field_tag 'quantity', nil, :in => 1...10
-
# # => <input id="quantity" name="quantity" min="1" max="9" type="number" />
-
2
def number_field_tag(name, value = nil, options = {})
-
options = options.stringify_keys
-
options["type"] ||= "number"
-
if range = options.delete("in") || options.delete("within")
-
options.update("min" => range.min, "max" => range.max)
-
end
-
text_field_tag(name, value, options)
-
end
-
-
# Creates a range form element.
-
#
-
# ==== Options
-
# * Accepts the same options as number_field_tag.
-
2
def range_field_tag(name, value = nil, options = {})
-
number_field_tag(name, value, options.stringify_keys.update("type" => "range"))
-
end
-
-
# Creates the hidden UTF8 enforcer tag. Override this method in a helper
-
# to customize the tag.
-
2
def utf8_enforcer_tag
-
tag(:input, :type => "hidden", :name => "utf8", :value => "✓".html_safe)
-
end
-
-
2
private
-
2
def html_options_for_form(url_for_options, options)
-
options.stringify_keys.tap do |html_options|
-
html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart")
-
# The following URL is unescaped, this is just a hash of options, and it is the
-
# responsibility of the caller to escape all the values.
-
html_options["action"] = url_for(url_for_options)
-
html_options["accept-charset"] = "UTF-8"
-
-
html_options["data-remote"] = true if html_options.delete("remote")
-
-
if html_options["data-remote"] &&
-
!embed_authenticity_token_in_remote_forms &&
-
html_options["authenticity_token"].blank?
-
# The authenticity token is taken from the meta tag in this case
-
html_options["authenticity_token"] = false
-
elsif html_options["authenticity_token"] == true
-
# Include the default authenticity_token, which is only generated when its set to nil,
-
# but we needed the true value to override the default of no authenticity_token on data-remote.
-
html_options["authenticity_token"] = nil
-
end
-
end
-
end
-
-
2
def extra_tags_for_form(html_options)
-
authenticity_token = html_options.delete("authenticity_token")
-
method = html_options.delete("method").to_s
-
-
method_tag = case method
-
when /^get$/i # must be case-insensitive, but can't use downcase as might be nil
-
html_options["method"] = "get"
-
''
-
when /^post$/i, "", nil
-
html_options["method"] = "post"
-
token_tag(authenticity_token)
-
else
-
html_options["method"] = "post"
-
tag(:input, :type => "hidden", :name => "_method", :value => method) + token_tag(authenticity_token)
-
end
-
-
tags = utf8_enforcer_tag << method_tag
-
content_tag(:div, tags, :style => 'margin:0;padding:0;display:inline')
-
end
-
-
2
def form_tag_html(html_options)
-
extra_tags = extra_tags_for_form(html_options)
-
(tag(:form, html_options, true) + extra_tags).html_safe
-
end
-
-
2
def form_tag_in_block(html_options, &block)
-
content = capture(&block)
-
output = ActiveSupport::SafeBuffer.new
-
output.safe_concat(form_tag_html(html_options))
-
output << content
-
output.safe_concat("</form>")
-
end
-
-
2
def token_tag(token)
-
if token == false || !protect_against_forgery?
-
''
-
else
-
token ||= form_authenticity_token
-
tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => token)
-
end
-
end
-
-
# see http://www.w3.org/TR/html4/types.html#type-name
-
2
def sanitize_to_id(name)
-
name.to_s.gsub(']','').gsub(/[^-a-zA-Z0-9:.]/, "_")
-
end
-
end
-
end
-
end
-
2
require 'action_view/helpers/tag_helper'
-
2
require 'active_support/core_ext/string/encoding'
-
-
2
module ActionView
-
2
module Helpers
-
2
module JavaScriptHelper
-
2
JS_ESCAPE_MAP = {
-
'\\' => '\\\\',
-
'</' => '<\/',
-
"\r\n" => '\n',
-
"\n" => '\n',
-
"\r" => '\n',
-
'"' => '\\"',
-
"'" => "\\'"
-
}
-
-
2
if "ruby".encoding_aware?
-
2
JS_ESCAPE_MAP["\342\200\250".force_encoding('UTF-8').encode!] = '
'
-
else
-
JS_ESCAPE_MAP["\342\200\250"] = '
'
-
end
-
-
# Escapes carriage returns and single and double quotes for JavaScript segments.
-
#
-
# Also available through the alias j(). This is particularly helpful in JavaScript responses, like:
-
#
-
# $('some_element').replaceWith('<%=j render 'some/element_template' %>');
-
2
def escape_javascript(javascript)
-
if javascript
-
result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] }
-
javascript.html_safe? ? result.html_safe : result
-
else
-
''
-
end
-
end
-
-
2
alias_method :j, :escape_javascript
-
-
# Returns a JavaScript tag with the +content+ inside. Example:
-
# javascript_tag "alert('All is good')"
-
#
-
# Returns:
-
# <script type="text/javascript">
-
# //<![CDATA[
-
# alert('All is good')
-
# //]]>
-
# </script>
-
#
-
# +html_options+ may be a hash of attributes for the <tt>\<script></tt>
-
# tag. Example:
-
# javascript_tag "alert('All is good')", :defer => 'defer'
-
# # => <script defer="defer" type="text/javascript">alert('All is good')</script>
-
#
-
# Instead of passing the content as an argument, you can also use a block
-
# in which case, you pass your +html_options+ as the first parameter.
-
# <%= javascript_tag :defer => 'defer' do -%>
-
# alert('All is good')
-
# <% end -%>
-
2
def javascript_tag(content_or_options_with_block = nil, html_options = {}, &block)
-
content =
-
if block_given?
-
html_options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
-
capture(&block)
-
else
-
content_or_options_with_block
-
end
-
-
content_tag(:script, javascript_cdata_section(content), html_options.merge(:type => Mime::JS))
-
end
-
-
2
def javascript_cdata_section(content) #:nodoc:
-
"\n//#{cdata_section("\n#{content}\n//")}\n".html_safe
-
end
-
-
# Returns a button whose +onclick+ handler triggers the passed JavaScript.
-
#
-
# The helper receives a name, JavaScript code, and an optional hash of HTML options. The
-
# name is used as button label and the JavaScript code goes into its +onclick+ attribute.
-
# If +html_options+ has an <tt>:onclick</tt>, that one is put before +function+.
-
#
-
# button_to_function "Greeting", "alert('Hello world!')", :class => "ok"
-
# # => <input class="ok" onclick="alert('Hello world!');" type="button" value="Greeting" />
-
#
-
2
def button_to_function(name, function=nil, html_options={})
-
onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function};"
-
-
tag(:input, html_options.merge(:type => 'button', :value => name, :onclick => onclick))
-
end
-
-
# Returns a link whose +onclick+ handler triggers the passed JavaScript.
-
#
-
# The helper receives a name, JavaScript code, and an optional hash of HTML options. The
-
# name is used as the link text and the JavaScript code goes into the +onclick+ attribute.
-
# If +html_options+ has an <tt>:onclick</tt>, that one is put before +function+. Once all
-
# the JavaScript is set, the helper appends "; return false;".
-
#
-
# The +href+ attribute of the tag is set to "#" unless +html_options+ has one.
-
#
-
# link_to_function "Greeting", "alert('Hello world!')", :class => "nav_link"
-
# # => <a class="nav_link" href="#" onclick="alert('Hello world!'); return false;">Greeting</a>
-
#
-
2
def link_to_function(name, function, html_options={})
-
onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function}; return false;"
-
href = html_options[:href] || '#'
-
-
content_tag(:a, name, html_options.merge(:href => href, :onclick => onclick))
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
2
require 'active_support/core_ext/big_decimal/conversions'
-
2
require 'active_support/core_ext/float/rounding'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/string/output_safety'
-
-
2
module ActionView
-
# = Action View Number Helpers
-
2
module Helpers #:nodoc:
-
-
# Provides methods for converting numbers into formatted strings.
-
# Methods are provided for phone numbers, currency, percentage,
-
# precision, positional notation, file size and pretty printing.
-
#
-
# Most methods expect a +number+ argument, and will return it
-
# unchanged if can't be converted into a valid number.
-
2
module NumberHelper
-
-
2
DEFAULT_CURRENCY_VALUES = { :format => "%u%n", :negative_format => "-%u%n", :unit => "$", :separator => ".", :delimiter => ",",
-
:precision => 2, :significant => false, :strip_insignificant_zeros => false }
-
-
# Raised when argument +number+ param given to the helpers is invalid and
-
# the option :raise is set to +true+.
-
2
class InvalidNumberError < StandardError
-
2
attr_accessor :number
-
2
def initialize(number)
-
@number = number
-
end
-
end
-
-
# Formats a +number+ into a US phone number (e.g., (555)
-
# 123-9876). You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:area_code</tt> - Adds parentheses around the area code.
-
# * <tt>:delimiter</tt> - Specifies the delimiter to use
-
# (defaults to "-").
-
# * <tt>:extension</tt> - Specifies an extension to add to the
-
# end of the generated number.
-
# * <tt>:country_code</tt> - Sets the country code for the phone
-
# number.
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_phone(5551234) # => 555-1234
-
# number_to_phone("5551234") # => 555-1234
-
# number_to_phone(1235551234) # => 123-555-1234
-
# number_to_phone(1235551234, :area_code => true) # => (123) 555-1234
-
# number_to_phone(1235551234, :delimiter => " ") # => 123 555 1234
-
# number_to_phone(1235551234, :area_code => true, :extension => 555) # => (123) 555-1234 x 555
-
# number_to_phone(1235551234, :country_code => 1) # => +1-123-555-1234
-
# number_to_phone("123a456") # => 123a456
-
#
-
# number_to_phone("1234a567", :raise => true) # => InvalidNumberError
-
#
-
# number_to_phone(1235551234, :country_code => 1, :extension => 1343, :delimiter => ".")
-
# # => +1.123.555.1234 x 1343
-
2
def number_to_phone(number, options = {})
-
return unless number
-
-
begin
-
Float(number)
-
rescue ArgumentError, TypeError
-
raise InvalidNumberError, number
-
end if options[:raise]
-
-
number = number.to_s.strip
-
options = options.symbolize_keys
-
area_code = options[:area_code]
-
delimiter = options[:delimiter] || "-"
-
extension = options[:extension]
-
country_code = options[:country_code]
-
-
if area_code
-
number.gsub!(/(\d{1,3})(\d{3})(\d{4}$)/,"(\\1) \\2#{delimiter}\\3")
-
else
-
number.gsub!(/(\d{0,3})(\d{3})(\d{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
-
number.slice!(0, 1) if number.starts_with?(delimiter) && !delimiter.blank?
-
end
-
-
str = []
-
str << "+#{country_code}#{delimiter}" unless country_code.blank?
-
str << number
-
str << " x #{extension}" unless extension.blank?
-
ERB::Util.html_escape(str.join)
-
end
-
-
# Formats a +number+ into a currency string (e.g., $13.65). You
-
# can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the level of precision (defaults
-
# to 2).
-
# * <tt>:unit</tt> - Sets the denomination of the currency
-
# (defaults to "$").
-
# * <tt>:separator</tt> - Sets the separator between the units
-
# (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:format</tt> - Sets the format for non-negative numbers
-
# (defaults to "%u%n"). Fields are <tt>%u</tt> for the
-
# currency, and <tt>%n</tt> for the number.
-
# * <tt>:negative_format</tt> - Sets the format for negative
-
# numbers (defaults to prepending an hyphen to the formatted
-
# number given by <tt>:format</tt>). Accepts the same fields
-
# than <tt>:format</tt>, except <tt>%n</tt> is here the
-
# absolute value of the number.
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_currency(1234567890.50) # => $1,234,567,890.50
-
# number_to_currency(1234567890.506) # => $1,234,567,890.51
-
# number_to_currency(1234567890.506, :precision => 3) # => $1,234,567,890.506
-
# number_to_currency(1234567890.506, :locale => :fr) # => 1 234 567 890,51 €
-
# number_to_currency("123a456") # => $123a456
-
#
-
# number_to_currency("123a456", :raise => true) # => InvalidNumberError
-
#
-
# number_to_currency(-1234567890.50, :negative_format => "(%u%n)")
-
# # => ($1,234,567,890.50)
-
# number_to_currency(1234567890.50, :unit => "£", :separator => ",", :delimiter => "")
-
# # => £1234567890,50
-
# number_to_currency(1234567890.50, :unit => "£", :separator => ",", :delimiter => "", :format => "%n %u")
-
# # => 1234567890,50 £
-
2
def number_to_currency(number, options = {})
-
return unless number
-
-
options.symbolize_keys!
-
-
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
-
currency = I18n.translate(:'number.currency.format', :locale => options[:locale], :default => {})
-
currency[:negative_format] ||= "-" + currency[:format] if currency[:format]
-
-
defaults = DEFAULT_CURRENCY_VALUES.merge(defaults).merge!(currency)
-
defaults[:negative_format] = "-" + options[:format] if options[:format]
-
options = defaults.merge!(options)
-
-
unit = options.delete(:unit)
-
format = options.delete(:format)
-
-
if number.to_f < 0
-
format = options.delete(:negative_format)
-
number = number.respond_to?("abs") ? number.abs : number.sub(/^-/, '')
-
end
-
-
begin
-
value = number_with_precision(number, options.merge(:raise => true))
-
format.gsub(/%n/, ERB::Util.html_escape(value)).gsub(/%u/, ERB::Util.html_escape(unit)).html_safe
-
rescue InvalidNumberError => e
-
if options[:raise]
-
raise
-
else
-
formatted_number = format.gsub(/%n/, e.number).gsub(/%u/, unit)
-
e.number.to_s.html_safe? ? formatted_number.html_safe : formatted_number
-
end
-
end
-
-
end
-
-
# Formats a +number+ as a percentage string (e.g., 65%). You can
-
# customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_percentage(100) # => 100.000%
-
# number_to_percentage("98") # => 98.000%
-
# number_to_percentage(100, :precision => 0) # => 100%
-
# number_to_percentage(1000, :delimiter => '.', :separator => ',') # => 1.000,000%
-
# number_to_percentage(302.24398923423, :precision => 5) # => 302.24399%
-
# number_to_percentage(1000, :locale => :fr) # => 1 000,000%
-
# number_to_percentage("98a") # => 98a%
-
#
-
# number_to_percentage("98a", :raise => true) # => InvalidNumberError
-
2
def number_to_percentage(number, options = {})
-
return unless number
-
-
options.symbolize_keys!
-
-
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
-
percentage = I18n.translate(:'number.percentage.format', :locale => options[:locale], :default => {})
-
defaults = defaults.merge(percentage)
-
-
options = options.reverse_merge(defaults)
-
-
begin
-
"#{number_with_precision(number, options.merge(:raise => true))}%".html_safe
-
rescue InvalidNumberError => e
-
if options[:raise]
-
raise
-
else
-
e.number.to_s.html_safe? ? "#{e.number}%".html_safe : "#{e.number}%"
-
end
-
end
-
end
-
-
# Formats a +number+ with grouped thousands using +delimiter+
-
# (e.g., 12,324). You can customize the format in the +options+
-
# hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_with_delimiter(12345678) # => 12,345,678
-
# number_with_delimiter("123456") # => 123,456
-
# number_with_delimiter(12345678.05) # => 12,345,678.05
-
# number_with_delimiter(12345678, :delimiter => ".") # => 12.345.678
-
# number_with_delimiter(12345678, :delimiter => ",") # => 12,345,678
-
# number_with_delimiter(12345678.05, :separator => " ") # => 12,345,678 05
-
# number_with_delimiter(12345678.05, :locale => :fr) # => 12 345 678,05
-
# number_with_delimiter("112a") # => 112a
-
# number_with_delimiter(98765432.98, :delimiter => " ", :separator => ",")
-
# # => 98 765 432,98
-
#
-
# number_with_delimiter("112a", :raise => true) # => raise InvalidNumberError
-
2
def number_with_delimiter(number, options = {})
-
options.symbolize_keys!
-
-
begin
-
Float(number)
-
rescue ArgumentError, TypeError
-
if options[:raise]
-
raise InvalidNumberError, number
-
else
-
return number
-
end
-
end
-
-
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
-
options = options.reverse_merge(defaults)
-
-
parts = number.to_s.to_str.split('.')
-
parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
-
parts.join(options[:separator]).html_safe
-
-
end
-
-
# Formats a +number+ with the specified level of
-
# <tt>:precision</tt> (e.g., 112.32 has a precision of 2 if
-
# +:significant+ is +false+, and 5 if +:significant+ is +true+).
-
# You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_with_precision(111.2345) # => 111.235
-
# number_with_precision(111.2345, :precision => 2) # => 111.23
-
# number_with_precision(13, :precision => 5) # => 13.00000
-
# number_with_precision(389.32314, :precision => 0) # => 389
-
# number_with_precision(111.2345, :significant => true) # => 111
-
# number_with_precision(111.2345, :precision => 1, :significant => true) # => 100
-
# number_with_precision(13, :precision => 5, :significant => true) # => 13.000
-
# number_with_precision(111.234, :locale => :fr) # => 111,234
-
#
-
# number_with_precision(13, :precision => 5, :significant => true, :strip_insignificant_zeros => true)
-
# # => 13
-
#
-
# number_with_precision(389.32314, :precision => 4, :significant => true) # => 389.3
-
# number_with_precision(1111.2345, :precision => 2, :separator => ',', :delimiter => '.')
-
# # => 1.111,23
-
2
def number_with_precision(number, options = {})
-
options.symbolize_keys!
-
-
number = begin
-
Float(number)
-
rescue ArgumentError, TypeError
-
if options[:raise]
-
raise InvalidNumberError, number
-
else
-
return number
-
end
-
end
-
-
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
-
precision_defaults = I18n.translate(:'number.precision.format', :locale => options[:locale], :default => {})
-
defaults = defaults.merge(precision_defaults)
-
-
options = options.reverse_merge(defaults) # Allow the user to unset default values: Eg.: :significant => false
-
precision = options.delete :precision
-
significant = options.delete :significant
-
strip_insignificant_zeros = options.delete :strip_insignificant_zeros
-
-
if significant and precision > 0
-
if number == 0
-
digits, rounded_number = 1, 0
-
else
-
digits = (Math.log10(number.abs) + 1).floor
-
rounded_number = (BigDecimal.new(number.to_s) / BigDecimal.new((10 ** (digits - precision)).to_f.to_s)).round.to_f * 10 ** (digits - precision)
-
digits = (Math.log10(rounded_number.abs) + 1).floor # After rounding, the number of digits may have changed
-
end
-
precision -= digits
-
precision = precision > 0 ? precision : 0 #don't let it be negative
-
else
-
rounded_number = BigDecimal.new(number.to_s).round(precision).to_f
-
end
-
formatted_number = number_with_delimiter("%01.#{precision}f" % rounded_number, options)
-
if strip_insignificant_zeros
-
escaped_separator = Regexp.escape(options[:separator])
-
formatted_number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '').html_safe
-
else
-
formatted_number
-
end
-
-
end
-
-
2
STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb]
-
-
# Formats the bytes in +number+ into a more understandable
-
# representation (e.g., giving it 1500 yields 1.5 KB). This
-
# method is useful for reporting file sizes to users. You can
-
# customize the format in the +options+ hash.
-
#
-
# See <tt>number_to_human</tt> if you want to pretty-print a
-
# generic number.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:prefix</tt> - If +:si+ formats the number using the SI
-
# prefix (defaults to :binary)
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_human_size(123) # => 123 Bytes
-
# number_to_human_size(1234) # => 1.21 KB
-
# number_to_human_size(12345) # => 12.1 KB
-
# number_to_human_size(1234567) # => 1.18 MB
-
# number_to_human_size(1234567890) # => 1.15 GB
-
# number_to_human_size(1234567890123) # => 1.12 TB
-
# number_to_human_size(1234567, :precision => 2) # => 1.2 MB
-
# number_to_human_size(483989, :precision => 2) # => 470 KB
-
# number_to_human_size(1234567, :precision => 2, :separator => ',') # => 1,2 MB
-
#
-
# Non-significant zeros after the fractional separator are
-
# stripped out by default (set
-
# <tt>:strip_insignificant_zeros</tt> to +false+ to change
-
# that):
-
# number_to_human_size(1234567890123, :precision => 5) # => "1.1229 TB"
-
# number_to_human_size(524288000, :precision => 5) # => "500 MB"
-
2
def number_to_human_size(number, options = {})
-
options.symbolize_keys!
-
-
number = begin
-
Float(number)
-
rescue ArgumentError, TypeError
-
if options[:raise]
-
raise InvalidNumberError, number
-
else
-
return number
-
end
-
end
-
-
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
-
human = I18n.translate(:'number.human.format', :locale => options[:locale], :default => {})
-
defaults = defaults.merge(human)
-
-
options = options.reverse_merge(defaults)
-
#for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
-
options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
-
-
storage_units_format = I18n.translate(:'number.human.storage_units.format', :locale => options[:locale], :raise => true)
-
-
base = options[:prefix] == :si ? 1000 : 1024
-
-
if number.to_i < base
-
unit = I18n.translate(:'number.human.storage_units.units.byte', :locale => options[:locale], :count => number.to_i, :raise => true)
-
storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit).html_safe
-
else
-
max_exp = STORAGE_UNITS.size - 1
-
exponent = (Math.log(number) / Math.log(base)).to_i # Convert to base
-
exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit
-
number /= base ** exponent
-
-
unit_key = STORAGE_UNITS[exponent]
-
unit = I18n.translate(:"number.human.storage_units.units.#{unit_key}", :locale => options[:locale], :count => number, :raise => true)
-
-
formatted_number = number_with_precision(number, options)
-
storage_units_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).html_safe
-
end
-
end
-
-
2
DECIMAL_UNITS = {0 => :unit, 1 => :ten, 2 => :hundred, 3 => :thousand, 6 => :million, 9 => :billion, 12 => :trillion, 15 => :quadrillion,
-
-1 => :deci, -2 => :centi, -3 => :mili, -6 => :micro, -9 => :nano, -12 => :pico, -15 => :femto}
-
-
# Pretty prints (formats and approximates) a number in a way it
-
# is more readable by humans (eg.: 1200000000 becomes "1.2
-
# Billion"). This is useful for numbers that can get very large
-
# (and too hard to read).
-
#
-
# See <tt>number_to_human_size</tt> if you want to print a file
-
# size.
-
#
-
# You can also define you own unit-quantifier names if you want
-
# to use other decimal units (eg.: 1500 becomes "1.5
-
# kilometers", 0.150 becomes "150 milliliters", etc). You may
-
# define a wide range of unit quantifiers, even fractional ones
-
# (centi, deci, mili, etc).
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:units</tt> - A Hash of unit quantifier names. Or a
-
# string containing an i18n scope where to find this hash. It
-
# might have the following keys:
-
# * *integers*: <tt>:unit</tt>, <tt>:ten</tt>,
-
# *<tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>,
-
# *<tt>:billion</tt>, <tt>:trillion</tt>,
-
# *<tt>:quadrillion</tt>
-
# * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>,
-
# *<tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>,
-
# *<tt>:pico</tt>, <tt>:femto</tt>
-
# * <tt>:format</tt> - Sets the format of the output string
-
# (defaults to "%n %u"). The field types are:
-
# * %u - The quantifier (ex.: 'thousand')
-
# * %n - The number
-
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when
-
# the argument is invalid.
-
#
-
# ==== Examples
-
#
-
# number_to_human(123) # => "123"
-
# number_to_human(1234) # => "1.23 Thousand"
-
# number_to_human(12345) # => "12.3 Thousand"
-
# number_to_human(1234567) # => "1.23 Million"
-
# number_to_human(1234567890) # => "1.23 Billion"
-
# number_to_human(1234567890123) # => "1.23 Trillion"
-
# number_to_human(1234567890123456) # => "1.23 Quadrillion"
-
# number_to_human(1234567890123456789) # => "1230 Quadrillion"
-
# number_to_human(489939, :precision => 2) # => "490 Thousand"
-
# number_to_human(489939, :precision => 4) # => "489.9 Thousand"
-
# number_to_human(1234567, :precision => 4,
-
# :significant => false) # => "1.2346 Million"
-
# number_to_human(1234567, :precision => 1,
-
# :separator => ',',
-
# :significant => false) # => "1,2 Million"
-
#
-
# Non-significant zeros after the decimal separator are stripped
-
# out by default (set <tt>:strip_insignificant_zeros</tt> to
-
# +false+ to change that):
-
# number_to_human(12345012345, :significant_digits => 6) # => "12.345 Billion"
-
# number_to_human(500000000, :precision => 5) # => "500 Million"
-
#
-
# ==== Custom Unit Quantifiers
-
#
-
# You can also use your own custom unit quantifiers:
-
# number_to_human(500000, :units => {:unit => "ml", :thousand => "lt"}) # => "500 lt"
-
#
-
# If in your I18n locale you have:
-
# distance:
-
# centi:
-
# one: "centimeter"
-
# other: "centimeters"
-
# unit:
-
# one: "meter"
-
# other: "meters"
-
# thousand:
-
# one: "kilometer"
-
# other: "kilometers"
-
# billion: "gazillion-distance"
-
#
-
# Then you could do:
-
#
-
# number_to_human(543934, :units => :distance) # => "544 kilometers"
-
# number_to_human(54393498, :units => :distance) # => "54400 kilometers"
-
# number_to_human(54393498000, :units => :distance) # => "54.4 gazillion-distance"
-
# number_to_human(343, :units => :distance, :precision => 1) # => "300 meters"
-
# number_to_human(1, :units => :distance) # => "1 meter"
-
# number_to_human(0.34, :units => :distance) # => "34 centimeters"
-
#
-
2
def number_to_human(number, options = {})
-
options.symbolize_keys!
-
-
number = begin
-
Float(number)
-
rescue ArgumentError, TypeError
-
if options[:raise]
-
raise InvalidNumberError, number
-
else
-
return number
-
end
-
end
-
-
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
-
human = I18n.translate(:'number.human.format', :locale => options[:locale], :default => {})
-
defaults = defaults.merge(human)
-
-
options = options.reverse_merge(defaults)
-
#for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
-
options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
-
-
inverted_du = DECIMAL_UNITS.invert
-
-
units = options.delete :units
-
unit_exponents = case units
-
when Hash
-
units
-
when String, Symbol
-
I18n.translate(:"#{units}", :locale => options[:locale], :raise => true)
-
when nil
-
I18n.translate(:"number.human.decimal_units.units", :locale => options[:locale], :raise => true)
-
else
-
raise ArgumentError, ":units must be a Hash or String translation scope."
-
end.keys.map{|e_name| inverted_du[e_name] }.sort_by{|e| -e}
-
-
number_exponent = number != 0 ? Math.log10(number.abs).floor : 0
-
display_exponent = unit_exponents.find{ |e| number_exponent >= e } || 0
-
number /= 10 ** display_exponent
-
-
unit = case units
-
when Hash
-
units[DECIMAL_UNITS[display_exponent]] || ''
-
when String, Symbol
-
I18n.translate(:"#{units}.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
-
else
-
I18n.translate(:"number.human.decimal_units.units.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
-
end
-
-
decimal_format = options[:format] || I18n.translate(:'number.human.decimal_units.format', :locale => options[:locale], :default => "%n %u")
-
formatted_number = number_with_precision(number, options)
-
decimal_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).strip.html_safe
-
end
-
-
end
-
end
-
end
-
2
require 'active_support/core_ext/string/output_safety'
-
-
2
module ActionView #:nodoc:
-
# = Action View Raw Output Helper
-
2
module Helpers #:nodoc:
-
2
module OutputSafetyHelper
-
# This method outputs without escaping a string. Since escaping tags is
-
# now default, this can be used when you don't want Rails to automatically
-
# escape tags. This is not recommended if the data is coming from the user's
-
# input.
-
#
-
# For example:
-
#
-
# <%=raw @user.name %>
-
2
def raw(stringish)
-
stringish.to_s.html_safe
-
end
-
-
# This method returns a html safe string similar to what <tt>Array#join</tt>
-
# would return. All items in the array, including the supplied separator, are
-
# html escaped unless they are html safe, and the returned string is marked
-
# as html safe.
-
#
-
# safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />")
-
# # => "<p>foo</p><br /><p>bar</p>"
-
#
-
# safe_join(["<p>foo</p>".html_safe, "<p>bar</p>".html_safe], "<br />".html_safe)
-
# # => "<p>foo</p><br /><p>bar</p>"
-
#
-
2
def safe_join(array, sep=$,)
-
sep ||= "".html_safe
-
sep = ERB::Util.html_escape(sep)
-
-
array.map { |i| ERB::Util.html_escape(i) }.join(sep).html_safe
-
end
-
end
-
end
-
end
-
2
require 'action_controller/record_identifier'
-
-
2
module ActionView
-
# = Action View Record Tag Helpers
-
2
module Helpers
-
2
module RecordTagHelper
-
2
include ActionController::RecordIdentifier
-
-
# Produces a wrapper DIV element with id and class parameters that
-
# relate to the specified Active Record object. Usage example:
-
#
-
# <%= div_for(@person, :class => "foo") do %>
-
# <%= @person.name %>
-
# <% end %>
-
#
-
# produces:
-
#
-
# <div id="person_123" class="person foo"> Joe Bloggs </div>
-
#
-
# You can also pass an array of Active Record objects, which will then
-
# get iterated over and yield each record as an argument for the block.
-
# For example:
-
#
-
# <%= div_for(@people, :class => "foo") do |person| %>
-
# <%= person.name %>
-
# <% end %>
-
#
-
# produces:
-
#
-
# <div id="person_123" class="person foo"> Joe Bloggs </div>
-
# <div id="person_124" class="person foo"> Jane Bloggs </div>
-
#
-
2
def div_for(record, *args, &block)
-
content_tag_for(:div, record, *args, &block)
-
end
-
-
# content_tag_for creates an HTML element with id and class parameters
-
# that relate to the specified Active Record object. For example:
-
#
-
# <%= content_tag_for(:tr, @person) do %>
-
# <td><%= @person.first_name %></td>
-
# <td><%= @person.last_name %></td>
-
# <% end %>
-
#
-
# would produce the following HTML (assuming @person is an instance of
-
# a Person object, with an id value of 123):
-
#
-
# <tr id="person_123" class="person">....</tr>
-
#
-
# If you require the HTML id attribute to have a prefix, you can specify it:
-
#
-
# <%= content_tag_for(:tr, @person, :foo) do %> ...
-
#
-
# produces:
-
#
-
# <tr id="foo_person_123" class="person">...
-
#
-
# You can also pass an array of objects which this method will loop through
-
# and yield the current object to the supplied block, reducing the need for
-
# having to iterate through the object (using <tt>each</tt>) beforehand.
-
# For example (assuming @people is an array of Person objects):
-
#
-
# <%= content_tag_for(:tr, @people) do |person| %>
-
# <td><%= person.first_name %></td>
-
# <td><%= person.last_name %></td>
-
# <% end %>
-
#
-
# produces:
-
#
-
# <tr id="person_123" class="person">...</tr>
-
# <tr id="person_124" class="person">...</tr>
-
#
-
# content_tag_for also accepts a hash of options, which will be converted to
-
# additional HTML attributes. If you specify a <tt>:class</tt> value, it will be combined
-
# with the default class name for your object. For example:
-
#
-
# <%= content_tag_for(:li, @person, :class => "bar") %>...
-
#
-
# produces:
-
#
-
# <li id="person_123" class="person bar">...
-
#
-
2
def content_tag_for(tag_name, single_or_multiple_records, prefix = nil, options = nil, &block)
-
if single_or_multiple_records.respond_to?(:to_ary)
-
single_or_multiple_records.to_ary.map do |single_record|
-
capture { content_tag_for_single_record(tag_name, single_record, prefix, options, &block) }
-
end.join("\n").html_safe
-
else
-
content_tag_for_single_record(tag_name, single_or_multiple_records, prefix, options, &block)
-
end
-
end
-
-
2
private
-
-
# Called by <tt>content_tag_for</tt> internally to render a content tag
-
# for each record.
-
2
def content_tag_for_single_record(tag_name, record, prefix, options, &block)
-
options, prefix = prefix, nil if prefix.is_a?(Hash)
-
options = options ? options.dup : {}
-
options.merge!(:class => "#{dom_class(record, prefix)} #{options[:class]}".strip, :id => dom_id(record, prefix))
-
if !block_given?
-
content_tag(tag_name, "", options)
-
elsif block.arity == 0
-
content_tag(tag_name, capture(&block), options)
-
else
-
content_tag(tag_name, capture(record, &block), options)
-
end
-
end
-
end
-
end
-
end
-
2
module ActionView
-
2
module Helpers
-
# = Action View Rendering
-
#
-
# Implements methods that allow rendering from a view context.
-
# In order to use this module, all you need is to implement
-
# view_renderer that returns an ActionView::Renderer object.
-
2
module RenderingHelper
-
# Returns the result of a render that's dictated by the options hash. The primary options are:
-
#
-
# * <tt>:partial</tt> - See <tt>ActionView::PartialRenderer</tt>.
-
# * <tt>:file</tt> - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
-
# * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller.
-
# * <tt>:text</tt> - Renders the text passed in out.
-
#
-
# If no options hash is passed or :update specified, the default is to render a partial and use the second parameter
-
# as the locals hash.
-
2
def render(options = {}, locals = {}, &block)
-
case options
-
when Hash
-
if block_given?
-
view_renderer.render_partial(self, options.merge(:partial => options[:layout]), &block)
-
else
-
view_renderer.render(self, options)
-
end
-
else
-
view_renderer.render_partial(self, :partial => options, :locals => locals)
-
end
-
end
-
-
# Overwrites _layout_for in the context object so it supports the case a block is
-
# passed to a partial. Returns the contents that are yielded to a layout, given a
-
# name or a block.
-
#
-
# You can think of a layout as a method that is called with a block. If the user calls
-
# <tt>yield :some_name</tt>, the block, by default, returns <tt>content_for(:some_name)</tt>.
-
# If the user calls simply +yield+, the default block returns <tt>content_for(:layout)</tt>.
-
#
-
# The user can override this default by passing a block to the layout:
-
#
-
# # The template
-
# <%= render :layout => "my_layout" do %>
-
# Content
-
# <% end %>
-
#
-
# # The layout
-
# <html>
-
# <%= yield %>
-
# </html>
-
#
-
# In this case, instead of the default block, which would return <tt>content_for(:layout)</tt>,
-
# this method returns the block that was passed in to <tt>render :layout</tt>, and the response
-
# would be
-
#
-
# <html>
-
# Content
-
# </html>
-
#
-
# Finally, the block can take block arguments, which can be passed in by +yield+:
-
#
-
# # The template
-
# <%= render :layout => "my_layout" do |customer| %>
-
# Hello <%= customer.name %>
-
# <% end %>
-
#
-
# # The layout
-
# <html>
-
# <%= yield Struct.new(:name).new("David") %>
-
# </html>
-
#
-
# In this case, the layout would receive the block passed into <tt>render :layout</tt>,
-
# and the struct specified would be passed into the block as an argument. The result
-
# would be
-
#
-
# <html>
-
# Hello David
-
# </html>
-
#
-
2
def _layout_for(*args, &block)
-
name = args.first
-
-
if block && !name.is_a?(Symbol)
-
capture(*args, &block)
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/try'
-
2
require 'action_controller/vendor/html-scanner'
-
-
2
module ActionView
-
# = Action View Sanitize Helpers
-
2
module Helpers #:nodoc:
-
# The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements.
-
# These helper methods extend Action View making them callable within your template files.
-
2
module SanitizeHelper
-
2
extend ActiveSupport::Concern
-
# This +sanitize+ helper will html encode all tags and strip all attributes that
-
# aren't specifically allowed.
-
#
-
# It also strips href/src tags with invalid protocols, like javascript: especially.
-
# It does its best to counter any tricks that hackers may use, like throwing in
-
# unicode/ascii/hex values to get past the javascript: filters. Check out
-
# the extensive test suite.
-
#
-
# <%= sanitize @article.body %>
-
#
-
# You can add or remove tags/attributes if you want to customize it a bit.
-
# See ActionView::Base for full docs on the available options. You can add
-
# tags/attributes for single uses of +sanitize+ by passing either the
-
# <tt>:attributes</tt> or <tt>:tags</tt> options:
-
#
-
# Normal Use
-
#
-
# <%= sanitize @article.body %>
-
#
-
# Custom Use (only the mentioned tags and attributes are allowed, nothing else)
-
#
-
# <%= sanitize @article.body, :tags => %w(table tr td), :attributes => %w(id class style) %>
-
#
-
# Add table tags to the default allowed tags
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td'
-
# end
-
#
-
# Remove tags to the default allowed tags
-
#
-
# class Application < Rails::Application
-
# config.after_initialize do
-
# ActionView::Base.sanitized_allowed_tags.delete 'div'
-
# end
-
# end
-
#
-
# Change allowed default attributes
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_attributes = 'id', 'class', 'style'
-
# end
-
#
-
# Please note that sanitizing user-provided text does not guarantee that the
-
# resulting markup is valid (conforming to a document type) or even well-formed.
-
# The output may still contain e.g. unescaped '<', '>', '&' characters and
-
# confuse browsers.
-
#
-
2
def sanitize(html, options = {})
-
self.class.white_list_sanitizer.sanitize(html, options).try(:html_safe)
-
end
-
-
# Sanitizes a block of CSS code. Used by +sanitize+ when it comes across a style attribute.
-
2
def sanitize_css(style)
-
self.class.white_list_sanitizer.sanitize_css(style)
-
end
-
-
# Strips all HTML tags from the +html+, including comments. This uses the
-
# html-scanner tokenizer and so its HTML parsing ability is limited by
-
# that of html-scanner.
-
#
-
# ==== Examples
-
#
-
# strip_tags("Strip <i>these</i> tags!")
-
# # => Strip these tags!
-
#
-
# strip_tags("<b>Bold</b> no more! <a href='more.html'>See more here</a>...")
-
# # => Bold no more! See more here...
-
#
-
# strip_tags("<div id='top-bar'>Welcome to my website!</div>")
-
# # => Welcome to my website!
-
2
def strip_tags(html)
-
self.class.full_sanitizer.sanitize(html)
-
end
-
-
# Strips all link tags from +text+ leaving just the link text.
-
#
-
# ==== Examples
-
# strip_links('<a href="http://www.rubyonrails.org">Ruby on Rails</a>')
-
# # => Ruby on Rails
-
#
-
# strip_links('Please e-mail me at <a href="mailto:me@email.com">me@email.com</a>.')
-
# # => Please e-mail me at me@email.com.
-
#
-
# strip_links('Blog: <a href="http://www.myblog.com/" class="nav" target=\"_blank\">Visit</a>.')
-
# # => Blog: Visit.
-
2
def strip_links(html)
-
self.class.link_sanitizer.sanitize(html)
-
end
-
-
2
module ClassMethods #:nodoc:
-
2
attr_writer :full_sanitizer, :link_sanitizer, :white_list_sanitizer
-
-
2
def sanitized_protocol_separator
-
white_list_sanitizer.protocol_separator
-
end
-
-
2
def sanitized_uri_attributes
-
white_list_sanitizer.uri_attributes
-
end
-
-
2
def sanitized_bad_tags
-
white_list_sanitizer.bad_tags
-
end
-
-
2
def sanitized_allowed_tags
-
white_list_sanitizer.allowed_tags
-
end
-
-
2
def sanitized_allowed_attributes
-
white_list_sanitizer.allowed_attributes
-
end
-
-
2
def sanitized_allowed_css_properties
-
white_list_sanitizer.allowed_css_properties
-
end
-
-
2
def sanitized_allowed_css_keywords
-
white_list_sanitizer.allowed_css_keywords
-
end
-
-
2
def sanitized_shorthand_css_properties
-
white_list_sanitizer.shorthand_css_properties
-
end
-
-
2
def sanitized_allowed_protocols
-
white_list_sanitizer.allowed_protocols
-
end
-
-
2
def sanitized_protocol_separator=(value)
-
white_list_sanitizer.protocol_separator = value
-
end
-
-
# Gets the HTML::FullSanitizer instance used by +strip_tags+. Replace with
-
# any object that responds to +sanitize+.
-
#
-
# class Application < Rails::Application
-
# config.action_view.full_sanitizer = MySpecialSanitizer.new
-
# end
-
#
-
2
def full_sanitizer
-
@full_sanitizer ||= HTML::FullSanitizer.new
-
end
-
-
# Gets the HTML::LinkSanitizer instance used by +strip_links+. Replace with
-
# any object that responds to +sanitize+.
-
#
-
# class Application < Rails::Application
-
# config.action_view.link_sanitizer = MySpecialSanitizer.new
-
# end
-
#
-
2
def link_sanitizer
-
@link_sanitizer ||= HTML::LinkSanitizer.new
-
end
-
-
# Gets the HTML::WhiteListSanitizer instance used by sanitize and +sanitize_css+.
-
# Replace with any object that responds to +sanitize+.
-
#
-
# class Application < Rails::Application
-
# config.action_view.white_list_sanitizer = MySpecialSanitizer.new
-
# end
-
#
-
2
def white_list_sanitizer
-
@white_list_sanitizer ||= HTML::WhiteListSanitizer.new
-
end
-
-
# Adds valid HTML attributes that the +sanitize+ helper checks for URIs.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_uri_attributes = 'lowsrc', 'target'
-
# end
-
#
-
2
def sanitized_uri_attributes=(attributes)
-
HTML::WhiteListSanitizer.uri_attributes.merge(attributes)
-
end
-
-
# Adds to the Set of 'bad' tags for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_bad_tags = 'embed', 'object'
-
# end
-
#
-
2
def sanitized_bad_tags=(attributes)
-
HTML::WhiteListSanitizer.bad_tags.merge(attributes)
-
end
-
-
# Adds to the Set of allowed tags for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td'
-
# end
-
#
-
2
def sanitized_allowed_tags=(attributes)
-
HTML::WhiteListSanitizer.allowed_tags.merge(attributes)
-
end
-
-
# Adds to the Set of allowed HTML attributes for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_attributes = 'onclick', 'longdesc'
-
# end
-
#
-
2
def sanitized_allowed_attributes=(attributes)
-
HTML::WhiteListSanitizer.allowed_attributes.merge(attributes)
-
end
-
-
# Adds to the Set of allowed CSS properties for the #sanitize and +sanitize_css+ helpers.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_css_properties = 'expression'
-
# end
-
#
-
2
def sanitized_allowed_css_properties=(attributes)
-
HTML::WhiteListSanitizer.allowed_css_properties.merge(attributes)
-
end
-
-
# Adds to the Set of allowed CSS keywords for the +sanitize+ and +sanitize_css+ helpers.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_css_keywords = 'expression'
-
# end
-
#
-
2
def sanitized_allowed_css_keywords=(attributes)
-
HTML::WhiteListSanitizer.allowed_css_keywords.merge(attributes)
-
end
-
-
# Adds to the Set of allowed shorthand CSS properties for the +sanitize+ and +sanitize_css+ helpers.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_shorthand_css_properties = 'expression'
-
# end
-
#
-
2
def sanitized_shorthand_css_properties=(attributes)
-
HTML::WhiteListSanitizer.shorthand_css_properties.merge(attributes)
-
end
-
-
# Adds to the Set of allowed protocols for the +sanitize+ helper.
-
#
-
# class Application < Rails::Application
-
# config.action_view.sanitized_allowed_protocols = 'ssh', 'feed'
-
# end
-
#
-
2
def sanitized_allowed_protocols=(attributes)
-
HTML::WhiteListSanitizer.allowed_protocols.merge(attributes)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/string/output_safety'
-
2
require 'set'
-
-
2
module ActionView
-
# = Action View Tag Helpers
-
2
module Helpers #:nodoc:
-
# Provides methods to generate HTML tags programmatically when you can't use
-
# a Builder. By default, they output XHTML compliant tags.
-
2
module TagHelper
-
2
extend ActiveSupport::Concern
-
2
include CaptureHelper
-
-
2
BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked autobuffer
-
autoplay controls loop selected hidden scoped async
-
defer reversed ismap seemless muted required
-
autofocus novalidate formnovalidate open pubdate).to_set
-
48
BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym })
-
-
2
PRE_CONTENT_STRINGS = {
-
:textarea => "\n"
-
}
-
-
# Returns an empty HTML tag of type +name+ which by default is XHTML
-
# compliant. Set +open+ to true to create an open tag compatible
-
# with HTML 4.0 and below. Add HTML attributes by passing an attributes
-
# hash to +options+. Set +escape+ to false to disable attribute value
-
# escaping.
-
#
-
# ==== Options
-
# You can use symbols or strings for the attribute names.
-
#
-
# Use +true+ with boolean attributes that can render with no value, like
-
# +disabled+ and +readonly+.
-
#
-
# HTML5 <tt>data-*</tt> attributes can be set with a single +data+ key
-
# pointing to a hash of sub-attributes.
-
#
-
# To play nicely with JavaScript conventions sub-attributes are dasherized.
-
# For example, a key +user_id+ would render as <tt>data-user-id</tt> and
-
# thus accessed as <tt>dataset.userId</tt>.
-
#
-
# Values are encoded to JSON, with the exception of strings and symbols.
-
# This may come in handy when using jQuery's HTML5-aware <tt>.data()<tt>
-
# from 1.4.3.
-
#
-
# ==== Examples
-
# tag("br")
-
# # => <br />
-
#
-
# tag("br", nil, true)
-
# # => <br>
-
#
-
# tag("input", :type => 'text', :disabled => true)
-
# # => <input type="text" disabled="disabled" />
-
#
-
# tag("img", :src => "open & shut.png")
-
# # => <img src="open & shut.png" />
-
#
-
# tag("img", {:src => "open & shut.png"}, false, false)
-
# # => <img src="open & shut.png" />
-
#
-
# tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
-
# # => <div data-name="Stephen" data-city-state="["Chicago","IL"]" />
-
2
def tag(name, options = nil, open = false, escape = true)
-
"<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
-
end
-
-
# Returns an HTML block tag of type +name+ surrounding the +content+. Add
-
# HTML attributes by passing an attributes hash to +options+.
-
# Instead of passing the content as an argument, you can also use a block
-
# in which case, you pass your +options+ as the second parameter.
-
# Set escape to false to disable attribute value escaping.
-
#
-
# ==== Options
-
# The +options+ hash is used with attributes with no value like (<tt>disabled</tt> and
-
# <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use
-
# symbols or strings for the attribute names.
-
#
-
# ==== Examples
-
# content_tag(:p, "Hello world!")
-
# # => <p>Hello world!</p>
-
# content_tag(:div, content_tag(:p, "Hello world!"), :class => "strong")
-
# # => <div class="strong"><p>Hello world!</p></div>
-
# content_tag("select", options, :multiple => true)
-
# # => <select multiple="multiple">...options...</select>
-
#
-
# <%= content_tag :div, :class => "strong" do -%>
-
# Hello world!
-
# <% end -%>
-
# # => <div class="strong">Hello world!</div>
-
2
def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
-
if block_given?
-
options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
-
content_tag_string(name, capture(&block), options, escape)
-
else
-
content_tag_string(name, content_or_options_with_block, options, escape)
-
end
-
end
-
-
# Returns a CDATA section with the given +content+. CDATA sections
-
# are used to escape blocks of text containing characters which would
-
# otherwise be recognized as markup. CDATA sections begin with the string
-
# <tt><![CDATA[</tt> and end with (and may not contain) the string <tt>]]></tt>.
-
#
-
# ==== Examples
-
# cdata_section("<hello world>")
-
# # => <![CDATA[<hello world>]]>
-
#
-
# cdata_section(File.read("hello_world.txt"))
-
# # => <![CDATA[<hello from a text file]]>
-
2
def cdata_section(content)
-
"<![CDATA[#{content}]]>".html_safe
-
end
-
-
# Returns an escaped version of +html+ without affecting existing escaped entities.
-
#
-
# ==== Examples
-
# escape_once("1 < 2 & 3")
-
# # => "1 < 2 & 3"
-
#
-
# escape_once("<< Accept & Checkout")
-
# # => "<< Accept & Checkout"
-
2
def escape_once(html)
-
ActiveSupport::Multibyte.clean(html.to_s).gsub(/[\"><]|&(?!([a-zA-Z]+|(#\d+));)/) { |special| ERB::Util::HTML_ESCAPE[special] }
-
end
-
-
2
private
-
-
2
def content_tag_string(name, content, options, escape = true)
-
tag_options = tag_options(options, escape) if options
-
"<#{name}#{tag_options}>#{PRE_CONTENT_STRINGS[name.to_sym]}#{escape ? ERB::Util.h(content) : content}</#{name}>".html_safe
-
end
-
-
2
def tag_options(options, escape = true)
-
unless options.blank?
-
attrs = []
-
options.each_pair do |key, value|
-
if key.to_s == 'data' && value.is_a?(Hash)
-
value.each do |k, v|
-
unless v.is_a?(String) || v.is_a?(Symbol) || v.is_a?(BigDecimal)
-
v = v.to_json
-
end
-
v = ERB::Util.html_escape(v) if escape
-
attrs << %(data-#{k.to_s.dasherize}="#{v}")
-
end
-
elsif BOOLEAN_ATTRIBUTES.include?(key)
-
attrs << %(#{key}="#{key}") if value
-
elsif !value.nil?
-
final_value = value.is_a?(Array) ? value.join(" ") : value
-
final_value = ERB::Util.html_escape(final_value) if escape
-
attrs << %(#{key}="#{final_value}")
-
end
-
end
-
" #{attrs.sort * ' '}".html_safe unless attrs.empty?
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/string/filters'
-
-
2
module ActionView
-
# = Action View Text Helpers
-
2
module Helpers #:nodoc:
-
# The TextHelper module provides a set of methods for filtering, formatting
-
# and transforming strings, which can reduce the amount of inline Ruby code in
-
# your views. These helper methods extend Action View making them callable
-
# within your template files.
-
#
-
# ==== Sanitization
-
#
-
# Most text helpers by default sanitize the given content, but do not escape it.
-
# This means HTML tags will appear in the page but all malicious code will be removed.
-
# Let's look at some examples using the +simple_format+ method:
-
#
-
# simple_format('<a href="http://example.com/">Example</a>')
-
# # => "<p><a href=\"http://example.com/\">Example</a></p>"
-
#
-
# simple_format('<a href="javascript:alert(\'no!\')">Example</a>')
-
# # => "<p><a>Example</a></p>"
-
#
-
# If you want to escape all content, you should invoke the +h+ method before
-
# calling the text helper.
-
#
-
# simple_format h('<a href="http://example.com/">Example</a>')
-
# # => "<p><a href=\"http://example.com/\">Example</a></p>"
-
2
module TextHelper
-
2
extend ActiveSupport::Concern
-
-
2
include SanitizeHelper
-
2
include TagHelper
-
# The preferred method of outputting text in your views is to use the
-
# <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods
-
# do not operate as expected in an eRuby code block. If you absolutely must
-
# output text within a non-output code block (i.e., <% %>), you can use the concat method.
-
#
-
# ==== Examples
-
# <%
-
# concat "hello"
-
# # is the equivalent of <%= "hello" %>
-
#
-
# if logged_in
-
# concat "Logged in!"
-
# else
-
# concat link_to('login', :action => login)
-
# end
-
# # will either display "Logged in!" or a login link
-
# %>
-
2
def concat(string)
-
output_buffer << string
-
end
-
-
2
def safe_concat(string)
-
output_buffer.respond_to?(:safe_concat) ? output_buffer.safe_concat(string) : concat(string)
-
end
-
-
# Truncates a given +text+ after a given <tt>:length</tt> if +text+ is longer than <tt>:length</tt>
-
# (defaults to 30). The last characters will be replaced with the <tt>:omission</tt> (defaults to "...")
-
# for a total length not exceeding <tt>:length</tt>.
-
#
-
# Pass a <tt>:separator</tt> to truncate +text+ at a natural break.
-
#
-
# The result is not marked as HTML-safe, so will be subject to the default escaping when
-
# used in views, unless wrapped by <tt>raw()</tt>. Care should be taken if +text+ contains HTML tags
-
# or entities, because truncation may produce invalid HTML (such as unbalanced or incomplete tags).
-
#
-
# ==== Examples
-
#
-
# truncate("Once upon a time in a world far far away")
-
# # => "Once upon a time in a world..."
-
#
-
# truncate("Once upon a time in a world far far away", :length => 17)
-
# # => "Once upon a ti..."
-
#
-
# truncate("Once upon a time in a world far far away", :length => 17, :separator => ' ')
-
# # => "Once upon a..."
-
#
-
# truncate("And they found that many people were sleeping better.", :length => 25, :omission => '... (continued)')
-
# # => "And they f... (continued)"
-
#
-
# truncate("<p>Once upon a time in a world far far away</p>")
-
# # => "<p>Once upon a time in a wo..."
-
2
def truncate(text, options = {})
-
options.reverse_merge!(:length => 30)
-
text.truncate(options.delete(:length), options) if text
-
end
-
-
# Highlights one or more +phrases+ everywhere in +text+ by inserting it into
-
# a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt>
-
# as a single-quoted string with \1 where the phrase is to be inserted (defaults to
-
# '<strong class="highlight">\1</strong>')
-
#
-
# ==== Examples
-
# highlight('You searched for: rails', 'rails')
-
# # => You searched for: <strong class="highlight">rails</strong>
-
#
-
# highlight('You searched for: ruby, rails, dhh', 'actionpack')
-
# # => You searched for: ruby, rails, dhh
-
#
-
# highlight('You searched for: rails', ['for', 'rails'], :highlighter => '<em>\1</em>')
-
# # => You searched <em>for</em>: <em>rails</em>
-
#
-
# highlight('You searched for: rails', 'rails', :highlighter => '<a href="search?q=\1">\1</a>')
-
# # => You searched for: <a href="search?q=rails">rails</a>
-
#
-
# You can still use <tt>highlight</tt> with the old API that accepts the
-
# +highlighter+ as its optional third parameter:
-
# highlight('You searched for: rails', 'rails', '<a href="search?q=\1">\1</a>') # => You searched for: <a href="search?q=rails">rails</a>
-
2
def highlight(text, phrases, *args)
-
options = args.extract_options!
-
unless args.empty?
-
ActiveSupport::Deprecation.warn "Calling highlight with a highlighter as an argument is deprecated. " \
-
"Please call with :highlighter => '#{args[0]}' instead.", caller
-
-
options[:highlighter] = args[0] || '<strong class="highlight">\1</strong>'
-
end
-
options.reverse_merge!(:highlighter => '<strong class="highlight">\1</strong>')
-
-
text = sanitize(text) unless options[:sanitize] == false
-
if text.blank? || phrases.blank?
-
text
-
else
-
match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
-
text.gsub(/(#{match})(?![^<]*?>)/i, options[:highlighter])
-
end.html_safe
-
end
-
-
# Extracts an excerpt from +text+ that matches the first instance of +phrase+.
-
# The <tt>:radius</tt> option expands the excerpt on each side of the first occurrence of +phrase+ by the number of characters
-
# defined in <tt>:radius</tt> (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+,
-
# then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. The resulting string
-
# will be stripped in any case. If the +phrase+ isn't found, nil is returned.
-
#
-
# ==== Examples
-
# excerpt('This is an example', 'an', :radius => 5)
-
# # => ...s is an exam...
-
#
-
# excerpt('This is an example', 'is', :radius => 5)
-
# # => This is a...
-
#
-
# excerpt('This is an example', 'is')
-
# # => This is an example
-
#
-
# excerpt('This next thing is an example', 'ex', :radius => 2)
-
# # => ...next...
-
#
-
# excerpt('This is also an example', 'an', :radius => 8, :omission => '<chop> ')
-
# # => <chop> is also an example
-
#
-
# You can still use <tt>excerpt</tt> with the old API that accepts the
-
# +radius+ as its optional third and the +ellipsis+ as its
-
# optional forth parameter:
-
# excerpt('This is an example', 'an', 5) # => ...s is an exam...
-
# excerpt('This is also an example', 'an', 8, '<chop> ') # => <chop> is also an example
-
2
def excerpt(text, phrase, *args)
-
return unless text && phrase
-
-
options = args.extract_options!
-
unless args.empty?
-
ActiveSupport::Deprecation.warn "Calling excerpt with radius and omission as arguments is deprecated. " \
-
"Please call with :radius => #{args[0]}#{", :omission => '#{args[1]}'" if args[1]} instead.", caller
-
-
options[:radius] = args[0] || 100
-
options[:omission] = args[1] || "..."
-
end
-
options.reverse_merge!(:radius => 100, :omission => "...")
-
-
phrase = Regexp.escape(phrase)
-
return unless found_pos = text.mb_chars =~ /(#{phrase})/i
-
-
start_pos = [ found_pos - options[:radius], 0 ].max
-
end_pos = [ [ found_pos + phrase.mb_chars.length + options[:radius] - 1, 0].max, text.mb_chars.length ].min
-
-
prefix = start_pos > 0 ? options[:omission] : ""
-
postfix = end_pos < text.mb_chars.length - 1 ? options[:omission] : ""
-
-
prefix + text.mb_chars[start_pos..end_pos].strip + postfix
-
end
-
-
# Attempts to pluralize the +singular+ word unless +count+ is 1. If
-
# +plural+ is supplied, it will use that when count is > 1, otherwise
-
# it will use the Inflector to determine the plural form
-
#
-
# ==== Examples
-
# pluralize(1, 'person')
-
# # => 1 person
-
#
-
# pluralize(2, 'person')
-
# # => 2 people
-
#
-
# pluralize(3, 'person', 'users')
-
# # => 3 users
-
#
-
# pluralize(0, 'person')
-
# # => 0 people
-
2
def pluralize(count, singular, plural = nil)
-
"#{count || 0} " + ((count == 1 || count =~ /^1(\.0+)?$/) ? singular : (plural || singular.pluralize))
-
end
-
-
# Wraps the +text+ into lines no longer than +line_width+ width. This method
-
# breaks on the first whitespace character that does not exceed +line_width+
-
# (which is 80 by default).
-
#
-
# ==== Examples
-
#
-
# word_wrap('Once upon a time')
-
# # => Once upon a time
-
#
-
# word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...')
-
# # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\n a successor to the throne turned out to be more trouble than anyone could have\n imagined...
-
#
-
# word_wrap('Once upon a time', :line_width => 8)
-
# # => Once upon\na time
-
#
-
# word_wrap('Once upon a time', :line_width => 1)
-
# # => Once\nupon\na\ntime
-
#
-
# You can still use <tt>word_wrap</tt> with the old API that accepts the
-
# +line_width+ as its optional second parameter:
-
# word_wrap('Once upon a time', 8) # => Once upon\na time
-
2
def word_wrap(text, *args)
-
options = args.extract_options!
-
unless args.blank?
-
ActiveSupport::Deprecation.warn "Calling word_wrap with line_width as an argument is deprecated. " \
-
"Please call with :line_width => #{args[0]} instead.", caller
-
-
options[:line_width] = args[0] || 80
-
end
-
options.reverse_merge!(:line_width => 80)
-
-
text.split("\n").collect do |line|
-
line.length > options[:line_width] ? line.gsub(/(.{1,#{options[:line_width]}})(\s+|$)/, "\\1\n").strip : line
-
end * "\n"
-
end
-
-
# Returns +text+ transformed into HTML using simple formatting rules.
-
# Two or more consecutive newlines(<tt>\n\n</tt>) are considered as a
-
# paragraph and wrapped in <tt><p></tt> tags. One newline (<tt>\n</tt>) is
-
# considered as a linebreak and a <tt><br /></tt> tag is appended. This
-
# method does not remove the newlines from the +text+.
-
#
-
# You can pass any HTML attributes into <tt>html_options</tt>. These
-
# will be added to all created paragraphs.
-
#
-
# ==== Options
-
# * <tt>:sanitize</tt> - If +false+, does not sanitize +text+.
-
#
-
# ==== Examples
-
# my_text = "Here is some basic text...\n...with a line break."
-
#
-
# simple_format(my_text)
-
# # => "<p>Here is some basic text...\n<br />...with a line break.</p>"
-
#
-
# more_text = "We want to put a paragraph...\n\n...right there."
-
#
-
# simple_format(more_text)
-
# # => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>"
-
#
-
# simple_format("Look ma! A class!", :class => 'description')
-
# # => "<p class='description'>Look ma! A class!</p>"
-
#
-
# simple_format("<span>I'm allowed!</span> It's true.", {}, :sanitize => false)
-
# # => "<p><span>I'm allowed!</span> It's true.</p>"
-
2
def simple_format(text, html_options={}, options={})
-
text = '' if text.nil?
-
text = text.dup
-
start_tag = tag('p', html_options, true)
-
text = sanitize(text) unless options[:sanitize] == false
-
text = text.to_str
-
text.gsub!(/\r\n?/, "\n") # \r\n and \r -> \n
-
text.gsub!(/\n\n+/, "</p>\n\n#{start_tag}") # 2+ newline -> paragraph
-
text.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br
-
text.insert 0, start_tag
-
text.html_safe.safe_concat("</p>")
-
end
-
-
# Creates a Cycle object whose _to_s_ method cycles through elements of an
-
# array every time it is called. This can be used for example, to alternate
-
# classes for table rows. You can use named cycles to allow nesting in loops.
-
# Passing a Hash as the last parameter with a <tt>:name</tt> key will create a
-
# named cycle. The default name for a cycle without a +:name+ key is
-
# <tt>"default"</tt>. You can manually reset a cycle by calling reset_cycle
-
# and passing the name of the cycle. The current cycle string can be obtained
-
# anytime using the current_cycle method.
-
#
-
# ==== Examples
-
# # Alternate CSS classes for even and odd numbers...
-
# @items = [1,2,3,4]
-
# <table>
-
# <% @items.each do |item| %>
-
# <tr class="<%= cycle("odd", "even") -%>">
-
# <td>item</td>
-
# </tr>
-
# <% end %>
-
# </table>
-
#
-
#
-
# # Cycle CSS classes for rows, and text colors for values within each row
-
# @items = x = [{:first => 'Robert', :middle => 'Daniel', :last => 'James'},
-
# {:first => 'Emily', :middle => 'Shannon', :maiden => 'Pike', :last => 'Hicks'},
-
# {:first => 'June', :middle => 'Dae', :last => 'Jones'}]
-
# <% @items.each do |item| %>
-
# <tr class="<%= cycle("odd", "even", :name => "row_class") -%>">
-
# <td>
-
# <% item.values.each do |value| %>
-
# <%# Create a named cycle "colors" %>
-
# <span style="color:<%= cycle("red", "green", "blue", :name => "colors") -%>">
-
# <%= value %>
-
# </span>
-
# <% end %>
-
# <% reset_cycle("colors") %>
-
# </td>
-
# </tr>
-
# <% end %>
-
2
def cycle(first_value, *values)
-
if (values.last.instance_of? Hash)
-
params = values.pop
-
name = params[:name]
-
else
-
name = "default"
-
end
-
values.unshift(first_value)
-
-
cycle = get_cycle(name)
-
unless cycle && cycle.values == values
-
cycle = set_cycle(name, Cycle.new(*values))
-
end
-
cycle.to_s
-
end
-
-
# Returns the current cycle string after a cycle has been started. Useful
-
# for complex table highlighting or any other design need which requires
-
# the current cycle string in more than one place.
-
#
-
# ==== Example
-
# # Alternate background colors
-
# @items = [1,2,3,4]
-
# <% @items.each do |item| %>
-
# <div style="background-color:<%= cycle("red","white","blue") %>">
-
# <span style="background-color:<%= current_cycle %>"><%= item %></span>
-
# </div>
-
# <% end %>
-
2
def current_cycle(name = "default")
-
cycle = get_cycle(name)
-
cycle.current_value if cycle
-
end
-
-
# Resets a cycle so that it starts from the first element the next time
-
# it is called. Pass in +name+ to reset a named cycle.
-
#
-
# ==== Example
-
# # Alternate CSS classes for even and odd numbers...
-
# @items = [[1,2,3,4], [5,6,3], [3,4,5,6,7,4]]
-
# <table>
-
# <% @items.each do |item| %>
-
# <tr class="<%= cycle("even", "odd") -%>">
-
# <% item.each do |value| %>
-
# <span style="color:<%= cycle("#333", "#666", "#999", :name => "colors") -%>">
-
# <%= value %>
-
# </span>
-
# <% end %>
-
#
-
# <% reset_cycle("colors") %>
-
# </tr>
-
# <% end %>
-
# </table>
-
2
def reset_cycle(name = "default")
-
cycle = get_cycle(name)
-
cycle.reset if cycle
-
end
-
-
2
class Cycle #:nodoc:
-
2
attr_reader :values
-
-
2
def initialize(first_value, *values)
-
@values = values.unshift(first_value)
-
reset
-
end
-
-
2
def reset
-
@index = 0
-
end
-
-
2
def current_value
-
@values[previous_index].to_s
-
end
-
-
2
def to_s
-
value = @values[@index].to_s
-
@index = next_index
-
return value
-
end
-
-
2
private
-
-
2
def next_index
-
step_index(1)
-
end
-
-
2
def previous_index
-
step_index(-1)
-
end
-
-
2
def step_index(n)
-
(@index + n) % @values.size
-
end
-
end
-
-
2
private
-
# The cycle helpers need to store the cycles in a place that is
-
# guaranteed to be reset every time a page is rendered, so it
-
# uses an instance variable of ActionView::Base.
-
2
def get_cycle(name)
-
@_cycles = Hash.new unless defined?(@_cycles)
-
return @_cycles[name]
-
end
-
-
2
def set_cycle(name, cycle_object)
-
@_cycles = Hash.new unless defined?(@_cycles)
-
@_cycles[name] = cycle_object
-
end
-
end
-
end
-
end
-
2
require 'action_view/helpers/tag_helper'
-
2
require 'i18n/exceptions'
-
-
2
module ActionView
-
# = Action View Translation Helpers
-
2
module Helpers
-
2
module TranslationHelper
-
# Delegates to <tt>I18n#translate</tt> but also performs three additional functions.
-
#
-
# First, it will ensure that any thrown +MissingTranslation+ messages will be turned
-
# into inline spans that:
-
#
-
# * have a "translation-missing" class set,
-
# * contain the missing key as a title attribute and
-
# * a titleized version of the last key segment as a text.
-
#
-
# E.g. the value returned for a missing translation key :"blog.post.title" will be
-
# <span class="translation_missing" title="translation missing: en.blog.post.title">Title</span>.
-
# This way your views will display rather reasonable strings but it will still
-
# be easy to spot missing translations.
-
#
-
# Second, it'll scope the key by the current partial if the key starts
-
# with a period. So if you call <tt>translate(".foo")</tt> from the
-
# <tt>people/index.html.erb</tt> template, you'll actually be calling
-
# <tt>I18n.translate("people.index.foo")</tt>. This makes it less repetitive
-
# to translate many keys within the same partials and gives you a simple framework
-
# for scoping them consistently. If you don't prepend the key with a period,
-
# nothing is converted.
-
#
-
# Third, it'll mark the translation as safe HTML if the key has the suffix
-
# "_html" or the last element of the key is the word "html". For example,
-
# calling translate("footer_html") or translate("footer.html") will return
-
# a safe HTML string that won't be escaped by other HTML helper methods. This
-
# naming convention helps to identify translations that include HTML tags so that
-
# you know what kind of output to expect when you call translate in a template.
-
2
def translate(key, options = {})
-
# If the user has specified rescue_format then pass it all through, otherwise use
-
# raise and do the work ourselves
-
options[:raise] = true unless options.key?(:raise) || options.key?(:rescue_format)
-
if html_safe_translation_key?(key)
-
html_safe_options = options.dup
-
options.except(*I18n::RESERVED_KEYS).each do |name, value|
-
unless name == :count && value.is_a?(Numeric)
-
html_safe_options[name] = ERB::Util.html_escape(value.to_s)
-
end
-
end
-
translation = I18n.translate(scope_key_by_partial(key), html_safe_options)
-
-
translation.respond_to?(:html_safe) ? translation.html_safe : translation
-
else
-
I18n.translate(scope_key_by_partial(key), options)
-
end
-
rescue I18n::MissingTranslationData => e
-
keys = I18n.normalize_keys(e.locale, e.key, e.options[:scope])
-
content_tag('span', keys.last.to_s.titleize, :class => 'translation_missing', :title => "translation missing: #{keys.join('.')}")
-
end
-
2
alias :t :translate
-
-
# Delegates to <tt>I18n.localize</tt> with no additional functionality.
-
2
def localize(*args)
-
I18n.localize(*args)
-
end
-
2
alias :l :localize
-
-
2
private
-
2
def scope_key_by_partial(key)
-
if key.to_s.first == "."
-
if @virtual_path
-
@virtual_path.gsub(%r{/_?}, ".") + key.to_s
-
else
-
raise "Cannot use t(#{key.inspect}) shortcut because path is not available"
-
end
-
else
-
key
-
end
-
end
-
-
2
def html_safe_translation_key?(key)
-
key.to_s =~ /(\b|_|\.)html$/
-
end
-
end
-
end
-
end
-
2
require 'action_view/helpers/javascript_helper'
-
2
require 'active_support/core_ext/array/access'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/string/output_safety'
-
2
require 'action_dispatch'
-
-
2
module ActionView
-
# = Action View URL Helpers
-
2
module Helpers #:nodoc:
-
# Provides a set of methods for making links and getting URLs that
-
# depend on the routing subsystem (see ActionDispatch::Routing).
-
# This allows you to use the same format for links in views
-
# and controllers.
-
2
module UrlHelper
-
# This helper may be included in any class that includes the
-
# URL helpers of a routes (routes.url_helpers). Some methods
-
# provided here will only work in the context of a request
-
# (link_to_unless_current, for instance), which must be provided
-
# as a method called #request on the context.
-
-
2
extend ActiveSupport::Concern
-
-
2
include ActionDispatch::Routing::UrlFor
-
2
include TagHelper
-
-
2
def _routes_context
-
controller
-
end
-
-
# Need to map default url options to controller one.
-
# def default_url_options(*args) #:nodoc:
-
# controller.send(:default_url_options, *args)
-
# end
-
#
-
2
def url_options
-
return super unless controller.respond_to?(:url_options)
-
controller.url_options
-
end
-
-
# Returns the URL for the set of +options+ provided. This takes the
-
# same options as +url_for+ in Action Controller (see the
-
# documentation for <tt>ActionController::Base#url_for</tt>). Note that by default
-
# <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action"
-
# instead of the fully qualified URL like "http://example.com/controller/action".
-
#
-
# ==== Options
-
# * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path.
-
# * <tt>:only_path</tt> - If true, returns the relative URL (omitting the protocol, host name, and port) (<tt>true</tt> by default unless <tt>:host</tt> is specified).
-
# * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this
-
# is currently not recommended since it breaks caching.
-
# * <tt>:host</tt> - Overrides the default (current) host if provided.
-
# * <tt>:protocol</tt> - Overrides the default (current) protocol if provided.
-
# * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present).
-
# * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present).
-
#
-
# ==== Relying on named routes
-
#
-
# Passing a record (like an Active Record or Active Resource) instead of a Hash as the options parameter will
-
# trigger the named route for that record. The lookup will happen on the name of the class. So passing a
-
# Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as
-
# +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route).
-
#
-
# ==== Examples
-
# <%= url_for(:action => 'index') %>
-
# # => /blog/
-
#
-
# <%= url_for(:action => 'find', :controller => 'books') %>
-
# # => /books/find
-
#
-
# <%= url_for(:action => 'login', :controller => 'members', :only_path => false, :protocol => 'https') %>
-
# # => https://www.example.com/members/login/
-
#
-
# <%= url_for(:action => 'play', :anchor => 'player') %>
-
# # => /messages/play/#player
-
#
-
# <%= url_for(:action => 'jump', :anchor => 'tax&ship') %>
-
# # => /testing/jump/#tax&ship
-
#
-
# <%= url_for(Workshop.new) %>
-
# # relies on Workshop answering a persisted? call (and in this case returning false)
-
# # => /workshops
-
#
-
# <%= url_for(@workshop) %>
-
# # calls @workshop.to_param which by default returns the id
-
# # => /workshops/5
-
#
-
# # to_param can be re-defined in a model to provide different URL names:
-
# # => /workshops/1-workshop-name
-
#
-
# <%= url_for("http://www.example.com") %>
-
# # => http://www.example.com
-
#
-
# <%= url_for(:back) %>
-
# # if request.env["HTTP_REFERER"] is set to "http://www.example.com"
-
# # => http://www.example.com
-
#
-
# <%= url_for(:back) %>
-
# # if request.env["HTTP_REFERER"] is not set or is blank
-
# # => javascript:history.back()
-
2
def url_for(options = {})
-
options ||= {}
-
case options
-
when String
-
options
-
when Hash
-
options = options.symbolize_keys.reverse_merge!(:only_path => options[:host].nil?)
-
super
-
when :back
-
controller.request.env["HTTP_REFERER"] || 'javascript:history.back()'
-
else
-
polymorphic_path(options)
-
end
-
end
-
-
# Creates a link tag of the given +name+ using a URL created by the set of +options+.
-
# See the valid options in the documentation for +url_for+. It's also possible to
-
# pass a String instead of an options hash, which generates a link tag that uses the
-
# value of the String as the href for the link. Using a <tt>:back</tt> Symbol instead
-
# of an options hash will generate a link to the referrer (a JavaScript back link
-
# will be used in place of a referrer if none exists). If +nil+ is passed as the name
-
# the value of the link itself will become the name.
-
#
-
# ==== Signatures
-
#
-
# link_to(body, url, html_options = {})
-
# # url is a String; you can use URL helpers like
-
# # posts_path
-
#
-
# link_to(body, url_options = {}, html_options = {})
-
# # url_options, except :confirm or :method,
-
# # is passed to url_for
-
#
-
# link_to(options = {}, html_options = {}) do
-
# # name
-
# end
-
#
-
# link_to(url, html_options = {}) do
-
# # name
-
# end
-
#
-
# ==== Options
-
# * <tt>:confirm => 'question?'</tt> - This will allow the unobtrusive JavaScript
-
# driver to prompt with the question specified. If the user accepts, the link is
-
# processed normally, otherwise no action is taken.
-
# * <tt>:method => symbol of HTTP verb</tt> - This modifier will dynamically
-
# create an HTML form and immediately submit the form for processing using
-
# the HTTP verb specified. Useful for having links perform a POST operation
-
# in dangerous actions like deleting a record (which search bots can follow
-
# while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt> and <tt>:put</tt>.
-
# Note that if the user has JavaScript disabled, the request will fall back
-
# to using GET. If <tt>:href => '#'</tt> is used and the user has JavaScript
-
# disabled clicking the link will have no effect. If you are relying on the
-
# POST behavior, you should check for it in your controller's action by using
-
# the request object's methods for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>.
-
# * <tt>:remote => true</tt> - This will allow the unobtrusive JavaScript
-
# driver to make an Ajax request to the URL in question instead of following
-
# the link. The drivers each provide mechanisms for listening for the
-
# completion of the Ajax request and performing JavaScript operations once
-
# they're complete
-
#
-
# ==== Examples
-
# Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments
-
# and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base
-
# your application on resources and use
-
#
-
# link_to "Profile", profile_path(@profile)
-
# # => <a href="/profiles/1">Profile</a>
-
#
-
# or the even pithier
-
#
-
# link_to "Profile", @profile
-
# # => <a href="/profiles/1">Profile</a>
-
#
-
# in place of the older more verbose, non-resource-oriented
-
#
-
# link_to "Profile", :controller => "profiles", :action => "show", :id => @profile
-
# # => <a href="/profiles/show/1">Profile</a>
-
#
-
# Similarly,
-
#
-
# link_to "Profiles", profiles_path
-
# # => <a href="/profiles">Profiles</a>
-
#
-
# is better than
-
#
-
# link_to "Profiles", :controller => "profiles"
-
# # => <a href="/profiles">Profiles</a>
-
#
-
# You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
-
#
-
# <%= link_to(@profile) do %>
-
# <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
-
# <% end %>
-
# # => <a href="/profiles/1">
-
# <strong>David</strong> -- <span>Check it out!</span>
-
# </a>
-
#
-
# Classes and ids for CSS are easy to produce:
-
#
-
# link_to "Articles", articles_path, :id => "news", :class => "article"
-
# # => <a href="/articles" class="article" id="news">Articles</a>
-
#
-
# Be careful when using the older argument style, as an extra literal hash is needed:
-
#
-
# link_to "Articles", { :controller => "articles" }, :id => "news", :class => "article"
-
# # => <a href="/articles" class="article" id="news">Articles</a>
-
#
-
# Leaving the hash off gives the wrong link:
-
#
-
# link_to "WRONG!", :controller => "articles", :id => "news", :class => "article"
-
# # => <a href="/articles/index/news?class=article">WRONG!</a>
-
#
-
# +link_to+ can also produce links with anchors or query strings:
-
#
-
# link_to "Comment wall", profile_path(@profile, :anchor => "wall")
-
# # => <a href="/profiles/1#wall">Comment wall</a>
-
#
-
# link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
-
# # => <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
-
#
-
# link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
-
# # => <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
-
#
-
# The two options specific to +link_to+ (<tt>:confirm</tt> and <tt>:method</tt>) are used as follows:
-
#
-
# link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?"
-
# # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?"">Visit Other Site</a>
-
#
-
# link_to("Destroy", "http://www.example.com", :method => :delete, :confirm => "Are you sure?")
-
# # => <a href='http://www.example.com' rel="nofollow" data-method="delete" data-confirm="Are you sure?">Destroy</a>
-
2
def link_to(*args, &block)
-
if block_given?
-
options = args.first || {}
-
html_options = args.second
-
link_to(capture(&block), options, html_options)
-
else
-
name = args[0]
-
options = args[1] || {}
-
html_options = args[2]
-
-
html_options = convert_options_to_data_attributes(options, html_options)
-
url = url_for(options)
-
-
href = html_options['href']
-
tag_options = tag_options(html_options)
-
-
href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href
-
"<a #{href_attr}#{tag_options}>#{ERB::Util.html_escape(name || url)}</a>".html_safe
-
end
-
end
-
-
# Generates a form containing a single button that submits to the URL created
-
# by the set of +options+. This is the safest method to ensure links that
-
# cause changes to your data are not triggered by search bots or accelerators.
-
# If the HTML button does not work with your layout, you can also consider
-
# using the +link_to+ method with the <tt>:method</tt> modifier as described in
-
# the +link_to+ documentation.
-
#
-
# By default, the generated form element has a class name of <tt>button_to</tt>
-
# to allow styling of the form itself and its children. This can be changed
-
# using the <tt>:form_class</tt> modifier within +html_options+. You can control
-
# the form submission and input element behavior using +html_options+.
-
# This method accepts the <tt>:method</tt> and <tt>:confirm</tt> modifiers
-
# described in the +link_to+ documentation. If no <tt>:method</tt> modifier
-
# is given, it will default to performing a POST operation. You can also
-
# disable the button by passing <tt>:disabled => true</tt> in +html_options+.
-
# If you are using RESTful routes, you can pass the <tt>:method</tt>
-
# to change the HTTP verb used to submit the form.
-
#
-
# ==== Options
-
# The +options+ hash accepts the same options as +url_for+.
-
#
-
# There are a few special +html_options+:
-
# * <tt>:method</tt> - Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>,
-
# <tt>:delete</tt> and <tt>:put</tt>. By default it will be <tt>:post</tt>.
-
# * <tt>:disabled</tt> - If set to true, it will generate a disabled button.
-
# * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
-
# prompt with the question specified. If the user accepts, the link is
-
# processed normally, otherwise no action is taken.
-
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
-
# submit behavior. By default this behavior is an ajax submit.
-
# * <tt>:form</tt> - This hash will be form attributes
-
# * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
-
# be placed
-
#
-
# ==== Examples
-
# <%= button_to "New", :action => "new" %>
-
# # => "<form method="post" action="/controller/new" class="button_to">
-
# # <div><input value="New" type="submit" /></div>
-
# # </form>"
-
#
-
#
-
# <%= button_to "New", :action => "new", :form_class => "new-thing" %>
-
# # => "<form method="post" action="/controller/new" class="new-thing">
-
# # <div><input value="New" type="submit" /></div>
-
# # </form>"
-
#
-
#
-
# <%= button_to "Create", :action => "create", :remote => true, :form => { "data-type" => "json" } %>
-
# # => "<form method="post" action="/images/create" class="button_to" data-remote="true" data-type="json">
-
# # <div><input value="Create" type="submit" /></div>
-
# # </form>"
-
#
-
#
-
# <%= button_to "Delete Image", { :action => "delete", :id => @image.id },
-
# :confirm => "Are you sure?", :method => :delete %>
-
# # => "<form method="post" action="/images/delete/1" class="button_to">
-
# # <div>
-
# # <input type="hidden" name="_method" value="delete" />
-
# # <input data-confirm='Are you sure?' value="Delete" type="submit" />
-
# # </div>
-
# # </form>"
-
#
-
#
-
# <%= button_to('Destroy', 'http://www.example.com', :confirm => 'Are you sure?',
-
# :method => "delete", :remote => true, :disable_with => 'loading...') %>
-
# # => "<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
-
# # <div>
-
# # <input name='_method' value='delete' type='hidden' />
-
# # <input value='Destroy' type='submit' disable_with='loading...' data-confirm='Are you sure?' />
-
# # </div>
-
# # </form>"
-
# #
-
2
def button_to(name, options = {}, html_options = {})
-
html_options = html_options.stringify_keys
-
convert_boolean_attributes!(html_options, %w( disabled ))
-
-
method_tag = ''
-
if (method = html_options.delete('method')) && %w{put delete}.include?(method.to_s)
-
method_tag = tag('input', :type => 'hidden', :name => '_method', :value => method.to_s)
-
end
-
-
form_method = method.to_s == 'get' ? 'get' : 'post'
-
form_options = html_options.delete('form') || {}
-
form_options[:class] ||= html_options.delete('form_class') || 'button_to'
-
-
remote = html_options.delete('remote')
-
-
request_token_tag = ''
-
if form_method == 'post' && protect_against_forgery?
-
request_token_tag = tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)
-
end
-
-
url = options.is_a?(String) ? options : self.url_for(options)
-
name ||= url
-
-
html_options = convert_options_to_data_attributes(options, html_options)
-
-
html_options.merge!("type" => "submit", "value" => name)
-
-
form_options.merge!(:method => form_method, :action => url)
-
form_options.merge!("data-remote" => "true") if remote
-
-
"#{tag(:form, form_options, true)}<div>#{method_tag}#{tag("input", html_options)}#{request_token_tag}</div></form>".html_safe
-
end
-
-
-
# Creates a link tag of the given +name+ using a URL created by the set of
-
# +options+ unless the current request URI is the same as the links, in
-
# which case only the name is returned (or the given block is yielded, if
-
# one exists). You can give +link_to_unless_current+ a block which will
-
# specialize the default behavior (e.g., show a "Start Here" link rather
-
# than the link's text).
-
#
-
# ==== Examples
-
# Let's say you have a navigation menu...
-
#
-
# <ul id="navbar">
-
# <li><%= link_to_unless_current("Home", { :action => "index" }) %></li>
-
# <li><%= link_to_unless_current("About Us", { :action => "about" }) %></li>
-
# </ul>
-
#
-
# If in the "about" action, it will render...
-
#
-
# <ul id="navbar">
-
# <li><a href="/controller/index">Home</a></li>
-
# <li>About Us</li>
-
# </ul>
-
#
-
# ...but if in the "index" action, it will render:
-
#
-
# <ul id="navbar">
-
# <li>Home</li>
-
# <li><a href="/controller/about">About Us</a></li>
-
# </ul>
-
#
-
# The implicit block given to +link_to_unless_current+ is evaluated if the current
-
# action is the action given. So, if we had a comments page and wanted to render a
-
# "Go Back" link instead of a link to the comments page, we could do something like this...
-
#
-
# <%=
-
# link_to_unless_current("Comment", { :controller => "comments", :action => "new" }) do
-
# link_to("Go back", { :controller => "posts", :action => "index" })
-
# end
-
# %>
-
2
def link_to_unless_current(name, options = {}, html_options = {}, &block)
-
link_to_unless current_page?(options), name, options, html_options, &block
-
end
-
-
# Creates a link tag of the given +name+ using a URL created by the set of
-
# +options+ unless +condition+ is true, in which case only the name is
-
# returned. To specialize the default behavior (i.e., show a login link rather
-
# than just the plaintext link text), you can pass a block that
-
# accepts the name or the full argument list for +link_to_unless+.
-
#
-
# ==== Examples
-
# <%= link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) %>
-
# # If the user is logged in...
-
# # => <a href="/controller/reply/">Reply</a>
-
#
-
# <%=
-
# link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) do |name|
-
# link_to(name, { :controller => "accounts", :action => "signup" })
-
# end
-
# %>
-
# # If the user is logged in...
-
# # => <a href="/controller/reply/">Reply</a>
-
# # If not...
-
# # => <a href="/accounts/signup">Reply</a>
-
2
def link_to_unless(condition, name, options = {}, html_options = {}, &block)
-
if condition
-
if block_given?
-
block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
-
else
-
ERB::Util.html_escape(name)
-
end
-
else
-
link_to(name, options, html_options)
-
end
-
end
-
-
# Creates a link tag of the given +name+ using a URL created by the set of
-
# +options+ if +condition+ is true, otherwise only the name is
-
# returned. To specialize the default behavior, you can pass a block that
-
# accepts the name or the full argument list for +link_to_unless+ (see the examples
-
# in +link_to_unless+).
-
#
-
# ==== Examples
-
# <%= link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) %>
-
# # If the user isn't logged in...
-
# # => <a href="/sessions/new/">Login</a>
-
#
-
# <%=
-
# link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) do
-
# link_to(@current_user.login, { :controller => "accounts", :action => "show", :id => @current_user })
-
# end
-
# %>
-
# # If the user isn't logged in...
-
# # => <a href="/sessions/new/">Login</a>
-
# # If they are logged in...
-
# # => <a href="/accounts/show/3">my_username</a>
-
2
def link_to_if(condition, name, options = {}, html_options = {}, &block)
-
link_to_unless !condition, name, options, html_options, &block
-
end
-
-
# Creates a mailto link tag to the specified +email_address+, which is
-
# also used as the name of the link unless +name+ is specified. Additional
-
# HTML attributes for the link can be passed in +html_options+.
-
#
-
# +mail_to+ has several methods for hindering email harvesters and customizing
-
# the email itself by passing special keys to +html_options+.
-
#
-
# ==== Options
-
# * <tt>:encode</tt> - This key will accept the strings "javascript" or "hex".
-
# Passing "javascript" will dynamically create and encode the mailto link then
-
# eval it into the DOM of the page. This method will not show the link on
-
# the page if the user has JavaScript disabled. Passing "hex" will hex
-
# encode the +email_address+ before outputting the mailto link.
-
# * <tt>:replace_at</tt> - When the link +name+ isn't provided, the
-
# +email_address+ is used for the link label. You can use this option to
-
# obfuscate the +email_address+ by substituting the @ sign with the string
-
# given as the value.
-
# * <tt>:replace_dot</tt> - When the link +name+ isn't provided, the
-
# +email_address+ is used for the link label. You can use this option to
-
# obfuscate the +email_address+ by substituting the . in the email with the
-
# string given as the value.
-
# * <tt>:subject</tt> - Preset the subject line of the email.
-
# * <tt>:body</tt> - Preset the body of the email.
-
# * <tt>:cc</tt> - Carbon Copy additional recipients on the email.
-
# * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
-
#
-
# ==== Examples
-
# mail_to "me@domain.com"
-
# # => <a href="mailto:me@domain.com">me@domain.com</a>
-
#
-
# mail_to "me@domain.com", "My email", :encode => "javascript"
-
# # => <script type="text/javascript">eval(decodeURIComponent('%64%6f%63...%27%29%3b'))</script>
-
#
-
# mail_to "me@domain.com", "My email", :encode => "hex"
-
# # => <a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>
-
#
-
# mail_to "me@domain.com", nil, :replace_at => "_at_", :replace_dot => "_dot_", :class => "email"
-
# # => <a href="mailto:me@domain.com" class="email">me_at_domain_dot_com</a>
-
#
-
# mail_to "me@domain.com", "My email", :cc => "ccaddress@domain.com",
-
# :subject => "This is an example email"
-
# # => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">My email</a>
-
2
def mail_to(email_address, name = nil, html_options = {})
-
email_address = ERB::Util.html_escape(email_address)
-
-
html_options = html_options.stringify_keys
-
encode = html_options.delete("encode").to_s
-
-
extras = %w{ cc bcc body subject }.map { |item|
-
option = html_options.delete(item) || next
-
"#{item}=#{Rack::Utils.escape(option).gsub("+", "%20")}"
-
}.compact
-
extras = extras.empty? ? '' : '?' + ERB::Util.html_escape(extras.join('&'))
-
-
email_address_obfuscated = email_address.to_str
-
email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.key?("replace_at")
-
email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.key?("replace_dot")
-
case encode
-
when "javascript"
-
string = ''
-
html = content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe))
-
html = escape_javascript(html.to_str)
-
"document.write('#{html}');".each_byte do |c|
-
string << sprintf("%%%x", c)
-
end
-
"<script type=\"#{Mime::JS}\">eval(decodeURIComponent('#{string}'))</script>".html_safe
-
when "hex"
-
email_address_encoded = email_address_obfuscated.unpack('C*').map {|c|
-
sprintf("&#%d;", c)
-
}.join
-
-
string = 'mailto:'.unpack('C*').map { |c|
-
sprintf("&#%d;", c)
-
}.join + email_address.unpack('C*').map { |c|
-
char = c.chr
-
char =~ /\w/ ? sprintf("%%%x", c) : char
-
}.join
-
-
content_tag "a", name || email_address_encoded.html_safe, html_options.merge("href" => "#{string}#{extras}".html_safe)
-
else
-
content_tag "a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe)
-
end
-
end
-
-
# True if the current request URI was generated by the given +options+.
-
#
-
# ==== Examples
-
# Let's say we're in the <tt>/shop/checkout?order=desc</tt> action.
-
#
-
# current_page?(:action => 'process')
-
# # => false
-
#
-
# current_page?(:controller => 'shop', :action => 'checkout')
-
# # => true
-
#
-
# current_page?(:controller => 'shop', :action => 'checkout', :order => 'asc')
-
# # => false
-
#
-
# current_page?(:action => 'checkout')
-
# # => true
-
#
-
# current_page?(:controller => 'library', :action => 'checkout')
-
# # => false
-
#
-
# Let's say we're in the <tt>/shop/checkout?order=desc&page=1</tt> action.
-
#
-
# current_page?(:action => 'process')
-
# # => false
-
#
-
# current_page?(:controller => 'shop', :action => 'checkout')
-
# # => true
-
#
-
# current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page => '1')
-
# # => true
-
#
-
# current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc', :page => '2')
-
# # => false
-
#
-
# current_page?(:controller => 'shop', :action => 'checkout', :order => 'desc')
-
# # => false
-
#
-
# current_page?(:action => 'checkout')
-
# # => true
-
#
-
# current_page?(:controller => 'library', :action => 'checkout')
-
# # => false
-
#
-
# Let's say we're in the <tt>/products</tt> action with method POST in case of invalid product.
-
#
-
# current_page?(:controller => 'product', :action => 'index')
-
# # => false
-
#
-
2
def current_page?(options)
-
unless request
-
raise "You cannot use helpers that need to determine the current " \
-
"page unless your view context provides a Request object " \
-
"in a #request method"
-
end
-
-
return false unless request.get?
-
-
url_string = url_for(options)
-
-
# We ignore any extra parameters in the request_uri if the
-
# submitted url doesn't have any either. This lets the function
-
# work with things like ?order=asc
-
if url_string.index("?")
-
request_uri = request.fullpath
-
else
-
request_uri = request.path
-
end
-
-
if url_string =~ /^\w+:\/\//
-
url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
-
else
-
url_string == request_uri
-
end
-
end
-
-
2
private
-
2
def convert_options_to_data_attributes(options, html_options)
-
if html_options
-
html_options = html_options.stringify_keys
-
html_options['data-remote'] = 'true' if link_to_remote_options?(options) || link_to_remote_options?(html_options)
-
-
disable_with = html_options.delete("disable_with")
-
confirm = html_options.delete('confirm')
-
method = html_options.delete('method')
-
-
html_options["data-disable-with"] = disable_with if disable_with
-
html_options["data-confirm"] = confirm if confirm
-
add_method_to_attributes!(html_options, method) if method
-
-
html_options
-
else
-
link_to_remote_options?(options) ? {'data-remote' => 'true'} : {}
-
end
-
end
-
-
2
def link_to_remote_options?(options)
-
if options.is_a?(Hash)
-
options.delete('remote') || options.delete(:remote)
-
end
-
end
-
-
2
def add_method_to_attributes!(html_options, method)
-
if method && method.to_s.downcase != "get" && html_options["rel"] !~ /nofollow/
-
html_options["rel"] = "#{html_options["rel"]} nofollow".strip
-
end
-
html_options["data-method"] = method
-
end
-
-
2
def options_for_javascript(options)
-
if options.empty?
-
'{}'
-
else
-
"{#{options.keys.map { |k| "#{k}:#{options[k]}" }.sort.join(', ')}}"
-
end
-
end
-
-
2
def array_or_string_for_javascript(option)
-
if option.kind_of?(Array)
-
"['#{option.join('\',\'')}']"
-
elsif !option.nil?
-
"'#{option}'"
-
end
-
end
-
-
# Processes the +html_options+ hash, converting the boolean
-
# attributes from true/false form into the form required by
-
# HTML/XHTML. (An attribute is considered to be boolean if
-
# its name is listed in the given +bool_attrs+ array.)
-
#
-
# More specifically, for each boolean attribute in +html_options+
-
# given as:
-
#
-
# "attr" => bool_value
-
#
-
# if the associated +bool_value+ evaluates to true, it is
-
# replaced with the attribute's name; otherwise the attribute is
-
# removed from the +html_options+ hash. (See the XHTML 1.0 spec,
-
# section 4.5 "Attribute Minimization" for more:
-
# http://www.w3.org/TR/xhtml1/#h-4.5)
-
#
-
# Returns the updated +html_options+ hash, which is also modified
-
# in place.
-
#
-
# Example:
-
#
-
# convert_boolean_attributes!( html_options,
-
# %w( checked disabled readonly ) )
-
2
def convert_boolean_attributes!(html_options, bool_attrs)
-
bool_attrs.each { |x| html_options[x] = x if html_options.delete(x) }
-
html_options
-
end
-
end
-
end
-
end
-
2
module ActionView
-
# = Action View Log Subscriber
-
#
-
# Provides functionality so that Rails can output logs from Action View.
-
2
class LogSubscriber < ActiveSupport::LogSubscriber
-
2
def render_template(event)
-
4
message = " Rendered #{from_rails_root(event.payload[:identifier])}"
-
4
message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout]
-
4
message << (" (%.1fms)" % event.duration)
-
4
info(message)
-
end
-
2
alias :render_partial :render_template
-
2
alias :render_collection :render_template
-
-
# TODO: Ideally, ActionView should have its own logger so it does not depend on AC.logger
-
2
def logger
-
12
ActionController::Base.logger if defined?(ActionController::Base)
-
end
-
-
2
protected
-
-
2
def from_rails_root(string)
-
4
string.sub("#{Rails.root}/", "").sub(/^app\/views\//, "")
-
end
-
end
-
end
-
-
2
ActionView::LogSubscriber.attach_to :action_view
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/module/remove_method'
-
-
2
module ActionView
-
# = Action View Lookup Context
-
#
-
# LookupContext is the object responsible to hold all information required to lookup
-
# templates, i.e. view paths and details. The LookupContext is also responsible to
-
# generate a key, given to view paths, used in the resolver cache lookup. Since
-
# this key is generated just once during the request, it speeds up all cache accesses.
-
2
class LookupContext #:nodoc:
-
2
attr_accessor :prefixes, :rendered_format
-
-
2
mattr_accessor :fallbacks
-
2
@@fallbacks = FallbackFileSystemResolver.instances
-
-
2
mattr_accessor :registered_details
-
2
self.registered_details = []
-
-
2
def self.register_detail(name, options = {}, &block)
-
6
self.registered_details << name
-
18
initialize = registered_details.map { |n| "@details[:#{n}] = details[:#{n}] || default_#{n}" }
-
-
6
Accessors.send :define_method, :"default_#{name}", &block
-
6
Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{name}
-
@details[:#{name}]
-
end
-
-
def #{name}=(value)
-
value = value.present? ? Array.wrap(value) : default_#{name}
-
_set_detail(:#{name}, value) if value != @details[:#{name}]
-
end
-
-
remove_possible_method :initialize_details
-
def initialize_details(details)
-
#{initialize.join("\n")}
-
end
-
METHOD
-
end
-
-
# Holds accessors for the registered details.
-
2
module Accessors #:nodoc:
-
end
-
-
2
register_detail(:locale) do
-
14
locales = [I18n.locale]
-
14
locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks
-
14
locales << I18n.default_locale
-
14
locales.uniq!
-
14
locales
-
end
-
26
register_detail(:formats) { Mime::SET.symbols }
-
17
register_detail(:handlers){ Template::Handlers.extensions }
-
-
2
class DetailsKey #:nodoc:
-
2
alias :eql? :equal?
-
2
alias :object_hash :hash
-
-
2
attr_reader :hash
-
2
@details_keys = Hash.new
-
-
2
def self.get(details)
-
8
if details[:formats]
-
8
details = details.dup
-
8
syms = Set.new Mime::SET.symbols
-
8
details[:formats] = details[:formats].select { |v|
-
88
syms.include? v
-
}
-
end
-
8
@details_keys[details] ||= new
-
end
-
-
2
def self.clear
-
@details_keys.clear
-
end
-
-
2
def initialize
-
2
@hash = object_hash
-
end
-
end
-
-
# Add caching behavior on top of Details.
-
2
module DetailsCache
-
2
attr_accessor :cache
-
-
# Calculate the details key. Remove the handlers from calculation to improve performance
-
# since the user cannot modify it explicitly.
-
2
def details_key #:nodoc:
-
12
@details_key ||= DetailsKey.get(@details) if @cache
-
end
-
-
# Temporary skip passing the details_key forward.
-
2
def disable_cache
-
old_value, @cache = @cache, false
-
yield
-
ensure
-
@cache = old_value
-
end
-
-
2
protected
-
-
2
def _set_detail(key, value)
-
4
@details = @details.dup if @details_key
-
4
@details_key = nil
-
4
@details[key] = value
-
end
-
end
-
-
# Helpers related to template lookup using the lookup context information.
-
2
module ViewPaths
-
2
attr_reader :view_paths
-
-
# Whenever setting view paths, makes a copy so we can manipulate then in
-
# instance objects as we wish.
-
2
def view_paths=(paths)
-
14
@view_paths = ActionView::PathSet.new(Array.wrap(paths))
-
end
-
-
2
def find(name, prefixes = [], partial = false, keys = [], options = {})
-
@view_paths.find(*args_for_lookup(name, prefixes, partial, keys, options))
-
end
-
2
alias :find_template :find
-
-
2
def find_all(name, prefixes = [], partial = false, keys = [], options = {})
-
12
@view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys, options))
-
end
-
-
2
def exists?(name, prefixes = [], partial = false, keys = [], options = {})
-
@view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys, options))
-
end
-
2
alias :template_exists? :exists?
-
-
# Add fallbacks to the view paths. Useful in cases you are rendering a :file.
-
2
def with_fallbacks
-
added_resolvers = 0
-
self.class.fallbacks.each do |resolver|
-
next if view_paths.include?(resolver)
-
view_paths.push(resolver)
-
added_resolvers += 1
-
end
-
yield
-
ensure
-
added_resolvers.times { view_paths.pop }
-
end
-
-
2
protected
-
-
2
def args_for_lookup(name, prefixes, partial, keys, details_options) #:nodoc:
-
12
name, prefixes = normalize_name(name, prefixes)
-
12
details, details_key = detail_args_for(details_options)
-
12
[name, prefixes, partial || false, details, details_key, keys]
-
end
-
-
# Compute details hash and key according to user options (e.g. passed from #render).
-
2
def detail_args_for(options)
-
12
return @details, details_key if options.empty? # most common path.
-
user_details = @details.merge(options)
-
[user_details, DetailsKey.get(user_details)]
-
end
-
-
# Support legacy foo.erb names even though we now ignore .erb
-
# as well as incorrectly putting part of the path in the template
-
# name instead of the prefix.
-
2
def normalize_name(name, prefixes) #:nodoc:
-
12
name = name.to_s.sub(handlers_regexp) do |match|
-
ActiveSupport::Deprecation.warn "Passing a template handler in the template name is deprecated. " \
-
"You can simply remove the handler name or pass render :handlers => [:#{match[1..-1]}] instead.", caller
-
""
-
end
-
-
12
prefixes = nil if prefixes.blank?
-
12
parts = name.split('/')
-
12
name = parts.pop
-
-
12
return name, prefixes || [""] if parts.empty?
-
-
4
parts = parts.join('/')
-
8
prefixes = prefixes ? prefixes.map { |p| "#{p}/#{parts}" } : [parts]
-
-
4
return name, prefixes
-
end
-
-
2
def handlers_regexp #:nodoc:
-
12
@@handlers_regexp ||= /\.(?:#{default_handlers.join('|')})$/
-
end
-
end
-
-
2
include Accessors
-
2
include DetailsCache
-
2
include ViewPaths
-
-
2
def initialize(view_paths, details = {}, prefixes = [])
-
14
@details, @details_key = {}, nil
-
14
@skip_default_locale = false
-
14
@cache = true
-
14
@prefixes = prefixes
-
14
@rendered_format = nil
-
-
14
self.view_paths = view_paths
-
14
initialize_details(details)
-
end
-
-
# Override formats= to expand ["*/*"] values and automatically
-
# add :html as fallback to :js.
-
2
def formats=(values)
-
18
if values
-
8
values.concat(default_formats) if values.delete "*/*"
-
8
values << :html if values == [:js]
-
end
-
18
super(values)
-
end
-
-
# Do not use the default locale on template lookup.
-
2
def skip_default_locale!
-
4
@skip_default_locale = true
-
4
self.locale = nil
-
end
-
-
# Override locale to return a symbol instead of array.
-
2
def locale
-
@details[:locale].first
-
end
-
-
# Overload locale= to also set the I18n.locale. If the current I18n.config object responds
-
# to original_config, it means that it's has a copy of the original I18n configuration and it's
-
# acting as proxy, which we need to skip.
-
2
def locale=(value)
-
4
if value
-
config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config
-
config.locale = value
-
end
-
-
4
super(@skip_default_locale ? I18n.locale : default_locale)
-
end
-
-
# A method which only uses the first format in the formats array for layout lookup.
-
2
def with_layout_format
-
4
if formats.size == 1
-
4
yield
-
else
-
old_formats = formats
-
_set_detail(:formats, formats[0,1])
-
-
begin
-
yield
-
ensure
-
_set_detail(:formats, old_formats)
-
end
-
end
-
end
-
end
-
end
-
2
module ActionView #:nodoc:
-
# = Action View PathSet
-
2
class PathSet #:nodoc:
-
2
include Enumerable
-
-
2
attr_reader :paths
-
-
2
def initialize(paths = [])
-
26
@paths = typecast paths
-
end
-
-
2
def initialize_copy(other)
-
@paths = other.paths.dup
-
self
-
end
-
-
2
def [](i)
-
paths[i]
-
end
-
-
2
def to_ary
-
22
paths.dup
-
end
-
-
2
def include?(item)
-
paths.include? item
-
end
-
-
2
def pop
-
paths.pop
-
end
-
-
2
def size
-
paths.size
-
end
-
-
2
def each(&block)
-
paths.each(&block)
-
end
-
-
2
def compact
-
PathSet.new paths.compact
-
end
-
-
2
def +(array)
-
PathSet.new(paths + array)
-
end
-
-
2
%w(<< concat push insert unshift).each do |method|
-
10
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{method}(*args)
-
paths.#{method}(*typecast(args))
-
end
-
METHOD
-
end
-
-
2
def find(*args)
-
find_all(*args).first || raise(MissingTemplate.new(self, *args))
-
end
-
-
2
def find_all(path, prefixes = [], *args)
-
12
prefixes = [prefixes] if String === prefixes
-
12
prefixes.each do |prefix|
-
12
paths.each do |resolver|
-
20
templates = resolver.find_all(path, prefix, *args)
-
20
return templates unless templates.empty?
-
end
-
end
-
8
[]
-
end
-
-
2
def exists?(path, prefixes, *args)
-
find_all(path, prefixes, *args).any?
-
end
-
-
2
private
-
-
2
def typecast(paths)
-
26
paths.map do |path|
-
40
case path
-
when Pathname, String
-
8
OptimizedFileSystemResolver.new path.to_s
-
else
-
32
path
-
end
-
end
-
end
-
end
-
end
-
2
require "action_view"
-
2
require "rails"
-
-
2
module ActionView
-
# = Action View Railtie
-
2
class Railtie < Rails::Railtie
-
2
config.action_view = ActiveSupport::OrderedOptions.new
-
2
config.action_view.stylesheet_expansions = {}
-
2
config.action_view.javascript_expansions = { :defaults => %w(jquery jquery_ujs) }
-
2
config.action_view.embed_authenticity_token_in_remote_forms = true
-
-
2
initializer "action_view.embed_authenticity_token_in_remote_forms" do |app|
-
2
ActiveSupport.on_load(:action_view) do
-
2
ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms =
-
app.config.action_view.delete(:embed_authenticity_token_in_remote_forms)
-
end
-
end
-
-
2
initializer "action_view.cache_asset_ids" do |app|
-
2
unless app.config.cache_classes
-
ActiveSupport.on_load(:action_view) do
-
ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids = false
-
end
-
end
-
end
-
-
2
initializer "action_view.javascript_expansions" do |app|
-
2
ActiveSupport.on_load(:action_view) do
-
2
ActionView::Helpers::AssetTagHelper.register_javascript_expansion(
-
app.config.action_view.delete(:javascript_expansions)
-
)
-
-
2
ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion(
-
app.config.action_view.delete(:stylesheet_expansions)
-
)
-
end
-
end
-
-
2
initializer "action_view.set_configs" do |app|
-
2
ActiveSupport.on_load(:action_view) do
-
2
app.config.action_view.each do |k,v|
-
send "#{k}=", v
-
end
-
end
-
end
-
-
2
initializer "action_view.caching" do |app|
-
2
ActiveSupport.on_load(:action_view) do
-
2
if app.config.action_view.cache_template_loading.nil?
-
2
ActionView::Resolver.caching = app.config.cache_classes
-
end
-
end
-
end
-
end
-
end
-
1
module ActionView
-
1
class AbstractRenderer #:nodoc:
-
1
delegate :find_template, :template_exists?, :with_fallbacks, :update_details,
-
:with_layout_format, :formats, :to => :@lookup_context
-
-
1
def initialize(lookup_context)
-
4
@lookup_context = lookup_context
-
end
-
-
1
def render
-
raise NotImplementedError
-
end
-
-
1
protected
-
-
1
def extract_details(options)
-
4
details = {}
-
4
@lookup_context.registered_details.each do |key|
-
12
next unless value = options[key]
-
details[key] = Array.wrap(value)
-
end
-
4
details
-
end
-
-
1
def extract_format(value, details)
-
4
if value.is_a?(String) && value.sub!(formats_regexp, "")
-
ActiveSupport::Deprecation.warn "Passing the format in the template name is deprecated. " \
-
"Please pass render with :formats => [:#{$1}] instead.", caller
-
details[:formats] ||= [$1.to_sym]
-
end
-
end
-
-
1
def formats_regexp
-
@@formats_regexp ||= /\.(#{Mime::SET.symbols.join('|')})$/
-
end
-
-
1
def instrument(name, options={})
-
8
ActiveSupport::Notifications.instrument("render_#{name}.action_view", options){ yield }
-
end
-
end
-
end
-
1
module ActionView
-
# This is the main entry point for rendering. It basically delegates
-
# to other objects like TemplateRenderer and PartialRenderer which
-
# actually renders the template.
-
1
class Renderer
-
1
attr_accessor :lookup_context
-
-
1
def initialize(lookup_context)
-
4
@lookup_context = lookup_context
-
end
-
-
# Main render entry point shared by AV and AC.
-
1
def render(context, options)
-
4
if options.key?(:partial)
-
render_partial(context, options)
-
else
-
4
render_template(context, options)
-
end
-
end
-
-
# Render but returns a valid Rack body. If fibers are defined, we return
-
# a streaming body that renders the template piece by piece.
-
#
-
# Note that partials are not supported to be rendered with streaming,
-
# so in such cases, we just wrap them in an array.
-
1
def render_body(context, options)
-
if options.key?(:partial)
-
[render_partial(context, options)]
-
else
-
StreamingTemplateRenderer.new(@lookup_context).render(context, options)
-
end
-
end
-
-
# Direct accessor to template rendering.
-
1
def render_template(context, options) #:nodoc:
-
4
_template_renderer.render(context, options)
-
end
-
-
# Direct access to partial rendering.
-
1
def render_partial(context, options, &block) #:nodoc:
-
_partial_renderer.render(context, options, block)
-
end
-
-
1
private
-
-
1
def _template_renderer #:nodoc:
-
4
@_template_renderer ||= TemplateRenderer.new(@lookup_context)
-
end
-
-
1
def _partial_renderer #:nodoc:
-
@_partial_renderer ||= PartialRenderer.new(@lookup_context)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/try'
-
1
require 'active_support/core_ext/array/wrap'
-
-
1
module ActionView
-
1
class TemplateRenderer < AbstractRenderer #:nodoc:
-
1
def render(context, options)
-
4
@view = context
-
4
@details = extract_details(options)
-
4
extract_format(options[:file] || options[:template], @details)
-
4
template = determine_template(options)
-
4
context = @lookup_context
-
-
4
unless context.rendered_format
-
4
context.formats = template.formats unless template.formats.empty?
-
4
context.rendered_format = context.formats.first
-
end
-
-
4
render_template(template, options[:layout], options[:locals])
-
end
-
-
# Determine the template to be rendered using the given options.
-
1
def determine_template(options) #:nodoc:
-
4
keys = options[:locals].try(:keys) || []
-
-
4
if options.key?(:text)
-
Template::Text.new(options[:text], formats.try(:first))
-
4
elsif options.key?(:file)
-
with_fallbacks { find_template(options[:file], nil, false, keys, @details) }
-
4
elsif options.key?(:inline)
-
handler = Template.handler_for_extension(options[:type] || "erb")
-
Template.new(options[:inline], "inline template", handler, :locals => keys)
-
4
elsif options.key?(:template)
-
4
options[:template].respond_to?(:render) ?
-
options[:template] : find_template(options[:template], options[:prefixes], false, keys, @details)
-
else
-
raise ArgumentError, "You invoked render but did not give any of :partial, :template, :inline, :file or :text option."
-
end
-
end
-
-
# Renders the given template. An string representing the layout can be
-
# supplied as well.
-
1
def render_template(template, layout_name = nil, locals = {}) #:nodoc:
-
4
view, locals = @view, locals || {}
-
-
4
render_with_layout(layout_name, locals) do |layout|
-
4
instrument(:template, :identifier => template.identifier, :layout => layout.try(:virtual_path)) do
-
4
template.render(view, locals) { |*name| view._layout_for(*name) }
-
end
-
end
-
end
-
-
1
def render_with_layout(path, locals) #:nodoc:
-
4
layout = path && find_layout(path, locals.keys)
-
4
content = yield(layout)
-
-
4
if layout
-
view = @view
-
view.view_flow.set(:layout, content)
-
layout.render(view, locals){ |*name| view._layout_for(*name) }
-
else
-
4
content
-
end
-
end
-
-
# This is the method which actually finds the layout using details in the lookup
-
# context object. If no layout is found, it checks if at least a layout with
-
# the given name exists across all details before raising the error.
-
1
def find_layout(layout, keys)
-
8
with_layout_format { resolve_layout(layout, keys) }
-
end
-
-
1
def resolve_layout(layout, keys)
-
8
case layout
-
when String
-
begin
-
if layout =~ /^\//
-
with_fallbacks { find_template(layout, nil, false, keys, @details) }
-
else
-
find_template(layout, nil, false, keys, @details)
-
end
-
rescue ActionView::MissingTemplate
-
all_details = @details.merge(:formats => @lookup_context.default_formats)
-
raise unless template_exists?(layout, nil, false, keys, all_details)
-
end
-
when Proc
-
4
resolve_layout(layout.call, keys)
-
when FalseClass
-
nil
-
else
-
4
layout
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/object/try'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'thread'
-
-
2
module ActionView
-
# = Action View Template
-
2
class Template
-
2
extend ActiveSupport::Autoload
-
-
# === Encodings in ActionView::Template
-
#
-
# ActionView::Template is one of a few sources of potential
-
# encoding issues in Rails. This is because the source for
-
# templates are usually read from disk, and Ruby (like most
-
# encoding-aware programming languages) assumes that the
-
# String retrieved through File IO is encoded in the
-
# <tt>default_external</tt> encoding. In Rails, the default
-
# <tt>default_external</tt> encoding is UTF-8.
-
#
-
# As a result, if a user saves their template as ISO-8859-1
-
# (for instance, using a non-Unicode-aware text editor),
-
# and uses characters outside of the ASCII range, their
-
# users will see diamonds with question marks in them in
-
# the browser.
-
#
-
# For the rest of this documentation, when we say "UTF-8",
-
# we mean "UTF-8 or whatever the default_internal encoding
-
# is set to". By default, it will be UTF-8.
-
#
-
# To mitigate this problem, we use a few strategies:
-
# 1. If the source is not valid UTF-8, we raise an exception
-
# when the template is compiled to alert the user
-
# to the problem.
-
# 2. The user can specify the encoding using Ruby-style
-
# encoding comments in any template engine. If such
-
# a comment is supplied, Rails will apply that encoding
-
# to the resulting compiled source returned by the
-
# template handler.
-
# 3. In all cases, we transcode the resulting String to
-
# the UTF-8.
-
#
-
# This means that other parts of Rails can always assume
-
# that templates are encoded in UTF-8, even if the original
-
# source of the template was not UTF-8.
-
#
-
# From a user's perspective, the easiest thing to do is
-
# to save your templates as UTF-8. If you do this, you
-
# do not need to do anything else for things to "just work".
-
#
-
# === Instructions for template handlers
-
#
-
# The easiest thing for you to do is to simply ignore
-
# encodings. Rails will hand you the template source
-
# as the default_internal (generally UTF-8), raising
-
# an exception for the user before sending the template
-
# to you if it could not determine the original encoding.
-
#
-
# For the greatest simplicity, you can support only
-
# UTF-8 as the <tt>default_internal</tt>. This means
-
# that from the perspective of your handler, the
-
# entire pipeline is just UTF-8.
-
#
-
# === Advanced: Handlers with alternate metadata sources
-
#
-
# If you want to provide an alternate mechanism for
-
# specifying encodings (like ERB does via <%# encoding: ... %>),
-
# you may indicate that you will handle encodings yourself
-
# by implementing <tt>self.handles_encoding?</tt>
-
# on your handler.
-
#
-
# If you do, Rails will not try to encode the String
-
# into the default_internal, passing you the unaltered
-
# bytes tagged with the assumed encoding (from
-
# default_external).
-
#
-
# In this case, make sure you return a String from
-
# your handler encoded in the default_internal. Since
-
# you are handling out-of-band metadata, you are
-
# also responsible for alerting the user to any
-
# problems with converting the user's data to
-
# the <tt>default_internal</tt>.
-
#
-
# To do so, simply raise the raise +WrongEncodingError+
-
# as follows:
-
#
-
# raise WrongEncodingError.new(
-
# problematic_string,
-
# expected_encoding
-
# )
-
-
2
eager_autoload do
-
2
autoload :Error
-
2
autoload :Handlers
-
2
autoload :Text
-
end
-
-
2
extend Template::Handlers
-
-
2
attr_accessor :locals, :formats, :virtual_path
-
-
2
attr_reader :source, :identifier, :handler, :original_encoding, :updated_at
-
-
# This finalizer is needed (and exactly with a proc inside another proc)
-
# otherwise templates leak in development.
-
2
Finalizer = proc do |method_name, mod|
-
1
proc do
-
mod.module_eval do
-
remove_possible_method method_name
-
end
-
end
-
end
-
-
2
def initialize(source, identifier, handler, details)
-
1
format = details[:format] || (handler.default_format if handler.respond_to?(:default_format))
-
-
1
@source = source
-
1
@identifier = identifier
-
1
@handler = handler
-
1
@compiled = false
-
1
@original_encoding = nil
-
1
@locals = details[:locals] || []
-
1
@virtual_path = details[:virtual_path]
-
1
@updated_at = details[:updated_at] || Time.now
-
2
@formats = Array.wrap(format).map { |f| f.is_a?(Mime::Type) ? f.ref : f }
-
1
@compile_mutex = Mutex.new
-
end
-
-
# Returns if the underlying handler supports streaming. If so,
-
# a streaming buffer *may* be passed when it start rendering.
-
2
def supports_streaming?
-
handler.respond_to?(:supports_streaming?) && handler.supports_streaming?
-
end
-
-
# Render a template. If the template was not compiled yet, it is done
-
# exactly before rendering.
-
#
-
# This method is instrumented as "!render_template.action_view". Notice that
-
# we use a bang in this instrumentation because you don't want to
-
# consume this in production. This is only slow if it's being listened to.
-
2
def render(view, locals, buffer=nil, &block)
-
4
ActiveSupport::Notifications.instrument("!render_template.action_view", :virtual_path => @virtual_path) do
-
4
compile!(view)
-
4
view.send(method_name, locals, buffer, &block)
-
end
-
rescue Exception => e
-
handle_render_error(view, e)
-
end
-
-
2
def mime_type
-
5
@mime_type ||= Mime::Type.lookup_by_extension(@formats.first.to_s) if @formats.first
-
end
-
-
# Receives a view object and return a template similar to self by using @virtual_path.
-
#
-
# This method is useful if you have a template object but it does not contain its source
-
# anymore since it was already compiled. In such cases, all you need to do is to call
-
# refresh passing in the view object.
-
#
-
# Notice this method raises an error if the template to be refreshed does not have a
-
# virtual path set (true just for inline templates).
-
2
def refresh(view)
-
raise "A template needs to have a virtual path in order to be refreshed" unless @virtual_path
-
lookup = view.lookup_context
-
pieces = @virtual_path.split("/")
-
name = pieces.pop
-
partial = !!name.sub!(/^_/, "")
-
lookup.disable_cache do
-
lookup.find_template(name, [ pieces.join('/') ], partial, @locals)
-
end
-
end
-
-
2
def inspect
-
1
@inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", '') : identifier
-
end
-
-
# This method is responsible for properly setting the encoding of the
-
# source. Until this point, we assume that the source is BINARY data.
-
# If no additional information is supplied, we assume the encoding is
-
# the same as <tt>Encoding.default_external</tt>.
-
#
-
# The user can also specify the encoding via a comment on the first
-
# line of the template (# encoding: NAME-OF-ENCODING). This will work
-
# with any template engine, as we process out the encoding comment
-
# before passing the source on to the template engine, leaving a
-
# blank line in its stead.
-
2
def encode!
-
1
return unless source.encoding_aware? && source.encoding == Encoding::BINARY
-
-
# Look for # encoding: *. If we find one, we'll encode the
-
# String in that encoding, otherwise, we'll use the
-
# default external encoding.
-
1
if source.sub!(/\A#{ENCODING_FLAG}/, '')
-
encoding = magic_encoding = $1
-
else
-
1
encoding = Encoding.default_external
-
end
-
-
# Tag the source with the default external encoding
-
# or the encoding specified in the file
-
1
source.force_encoding(encoding)
-
-
# If the user didn't specify an encoding, and the handler
-
# handles encodings, we simply pass the String as is to
-
# the handler (with the default_external tag)
-
1
if !magic_encoding && @handler.respond_to?(:handles_encoding?) && @handler.handles_encoding?
-
1
source
-
# Otherwise, if the String is valid in the encoding,
-
# encode immediately to default_internal. This means
-
# that if a handler doesn't handle encodings, it will
-
# always get Strings in the default_internal
-
elsif source.valid_encoding?
-
source.encode!
-
# Otherwise, since the String is invalid in the encoding
-
# specified, raise an exception
-
else
-
raise WrongEncodingError.new(source, encoding)
-
end
-
end
-
-
2
protected
-
-
# Compile a template. This method ensures a template is compiled
-
# just once and removes the source after it is compiled.
-
2
def compile!(view) #:nodoc:
-
4
return if @compiled
-
-
# Templates can be used concurrently in threaded environments
-
# so compilation and any instance variable modification must
-
# be synchronized
-
1
@compile_mutex.synchronize do
-
# Any thread holding this lock will be compiling the template needed
-
# by the threads waiting. So re-check the @compiled flag to avoid
-
# re-compilation
-
1
return if @compiled
-
-
1
if view.is_a?(ActionView::CompiledTemplates)
-
1
mod = ActionView::CompiledTemplates
-
else
-
mod = view.singleton_class
-
end
-
-
1
compile(view, mod)
-
-
# Just discard the source if we have a virtual path. This
-
# means we can get the template back.
-
1
@source = nil if @virtual_path
-
1
@compiled = true
-
end
-
end
-
-
# Among other things, this method is responsible for properly setting
-
# the encoding of the compiled template.
-
#
-
# If the template engine handles encodings, we send the encoded
-
# String to the engine without further processing. This allows
-
# the template engine to support additional mechanisms for
-
# specifying the encoding. For instance, ERB supports <%# encoding: %>
-
#
-
# Otherwise, after we figure out the correct encoding, we then
-
# encode the source into <tt>Encoding.default_internal</tt>.
-
# In general, this means that templates will be UTF-8 inside of Rails,
-
# regardless of the original source encoding.
-
2
def compile(view, mod) #:nodoc:
-
1
encode!
-
1
method_name = self.method_name
-
1
code = @handler.call(self)
-
-
# Make sure that the resulting String to be evalled is in the
-
# encoding of the code
-
1
source = <<-end_src
-
def #{method_name}(local_assigns, output_buffer)
-
_old_virtual_path, @virtual_path = @virtual_path, #{@virtual_path.inspect};_old_output_buffer = @output_buffer;#{locals_code};#{code}
-
ensure
-
@virtual_path, @output_buffer = _old_virtual_path, _old_output_buffer
-
end
-
end_src
-
-
1
if source.encoding_aware?
-
# Make sure the source is in the encoding of the returned code
-
1
source.force_encoding(code.encoding)
-
-
# In case we get back a String from a handler that is not in
-
# BINARY or the default_internal, encode it to the default_internal
-
1
source.encode!
-
-
# Now, validate that the source we got back from the template
-
# handler is valid in the default_internal. This is for handlers
-
# that handle encoding but screw up
-
1
unless source.valid_encoding?
-
raise WrongEncodingError.new(@source, Encoding.default_internal)
-
end
-
end
-
-
1
begin
-
1
mod.module_eval(source, identifier, 0)
-
1
ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
-
rescue Exception => e # errors from template code
-
if logger = (view && view.logger)
-
logger.debug "ERROR: compiling #{method_name} RAISED #{e}"
-
logger.debug "Function body: #{source}"
-
logger.debug "Backtrace: #{e.backtrace.join("\n")}"
-
end
-
-
raise ActionView::Template::Error.new(self, {}, e)
-
end
-
end
-
-
2
def handle_render_error(view, e) #:nodoc:
-
if e.is_a?(Template::Error)
-
e.sub_template_of(self)
-
raise e
-
else
-
assigns = view.respond_to?(:assigns) ? view.assigns : {}
-
template = self
-
unless template.source
-
template = refresh(view)
-
template.encode!
-
end
-
raise Template::Error.new(template, assigns, e)
-
end
-
end
-
-
2
def locals_code #:nodoc:
-
1
@locals.map { |key| "#{key} = local_assigns[:#{key}];" }.join
-
end
-
-
2
def method_name #:nodoc:
-
5
@method_name ||= "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}".gsub('-', "_")
-
end
-
-
2
def identifier_method_name #:nodoc:
-
1
inspect.gsub(/[^a-z_]/, '_')
-
end
-
end
-
end
-
2
module ActionView #:nodoc:
-
# = Action View Template Handlers
-
2
class Template
-
2
module Handlers #:nodoc:
-
2
autoload :ERB, 'action_view/template/handlers/erb'
-
2
autoload :Builder, 'action_view/template/handlers/builder'
-
-
2
def self.extended(base)
-
2
base.register_default_template_handler :erb, ERB.new
-
2
base.register_template_handler :builder, Builder.new
-
end
-
-
2
@@template_handlers = {}
-
2
@@default_template_handlers = nil
-
-
2
def self.extensions
-
15
@@template_extensions ||= @@template_handlers.keys
-
end
-
-
# Register a class that knows how to handle template files with the given
-
# extension. This can be used to implement new template types.
-
# The constructor for the class must take the ActiveView::Base instance
-
# as a parameter, and the class must implement a +render+ method that
-
# takes the contents of the template to render as well as the Hash of
-
# local assigns available to the template. The +render+ method ought to
-
# return the rendered template as a string.
-
2
def register_template_handler(extension, klass)
-
6
@@template_handlers[extension.to_sym] = klass
-
6
@@template_extensions = nil
-
end
-
-
2
def template_handler_extensions
-
@@template_handlers.keys.map {|key| key.to_s }.sort
-
end
-
-
2
def registered_template_handler(extension)
-
1
extension && @@template_handlers[extension.to_sym]
-
end
-
-
2
def register_default_template_handler(extension, klass)
-
2
register_template_handler(extension, klass)
-
2
@@default_template_handlers = klass
-
end
-
-
2
def handler_for_extension(extension)
-
1
registered_template_handler(extension) || @@default_template_handlers
-
end
-
end
-
end
-
end
-
2
module ActionView
-
2
module Template::Handlers
-
2
class Builder
-
# Default format used by Builder.
-
2
class_attribute :default_format
-
2
self.default_format = Mime::XML
-
-
2
def call(template)
-
require_engine
-
"xml = ::Builder::XmlMarkup.new(:indent => 2);" +
-
"self.output_buffer = xml.target!;" +
-
template.source +
-
";xml.target!;"
-
end
-
-
2
protected
-
-
2
def require_engine
-
@required ||= begin
-
require "builder"
-
true
-
end
-
end
-
end
-
end
-
end
-
2
require 'action_dispatch/http/mime_type'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'erubis'
-
-
2
module ActionView
-
2
class Template
-
2
module Handlers
-
2
class Erubis < ::Erubis::Eruby
-
2
def add_preamble(src)
-
1
src << "@output_buffer = output_buffer || ActionView::OutputBuffer.new;"
-
end
-
-
2
def add_text(src, text)
-
9
return if text.empty?
-
7
src << "@output_buffer.safe_concat('" << escape_text(text) << "');"
-
end
-
-
# Erubis toggles <%= and <%== behavior when escaping is enabled.
-
# We override to always treat <%== as escaped.
-
2
def add_expr(src, code, indicator)
-
3
case indicator
-
when '=='
-
add_expr_escaped(src, code)
-
else
-
3
super
-
end
-
end
-
-
2
BLOCK_EXPR = /\s+(do|\{)(\s*\|[^|]*\|)?\s*\Z/
-
-
2
def add_expr_literal(src, code)
-
3
if code =~ BLOCK_EXPR
-
src << '@output_buffer.append= ' << code
-
else
-
3
src << '@output_buffer.append= (' << code << ');'
-
end
-
end
-
-
2
def add_expr_escaped(src, code)
-
if code =~ BLOCK_EXPR
-
src << "@output_buffer.safe_append= " << code
-
else
-
src << "@output_buffer.safe_concat((" << code << ").to_s);"
-
end
-
end
-
-
2
def add_postamble(src)
-
1
src << '@output_buffer.to_s'
-
end
-
end
-
-
2
class ERB
-
# Specify trim mode for the ERB compiler. Defaults to '-'.
-
# See ERB documentation for suitable values.
-
2
class_attribute :erb_trim_mode
-
2
self.erb_trim_mode = '-'
-
-
# Default implementation used.
-
2
class_attribute :erb_implementation
-
2
self.erb_implementation = Erubis
-
-
# Do not escape templates of these mime types.
-
2
class_attribute :escape_whitelist
-
2
self.escape_whitelist = ["text/plain"]
-
-
2
ENCODING_TAG = Regexp.new("\\A(<%#{ENCODING_FLAG}-?%>)[ \\t]*")
-
-
2
def self.call(template)
-
new.call(template)
-
end
-
-
2
def supports_streaming?
-
true
-
end
-
-
2
def handles_encoding?
-
1
true
-
end
-
-
2
def call(template)
-
1
if template.source.encoding_aware?
-
# First, convert to BINARY, so in case the encoding is
-
# wrong, we can still find an encoding tag
-
# (<%# encoding %>) inside the String using a regular
-
# expression
-
1
template_source = template.source.dup.force_encoding("BINARY")
-
-
1
erb = template_source.gsub(ENCODING_TAG, '')
-
1
encoding = $2
-
-
1
erb.force_encoding valid_encoding(template.source.dup, encoding)
-
-
# Always make sure we return a String in the default_internal
-
1
erb.encode!
-
else
-
erb = template.source.dup
-
end
-
-
1
self.class.erb_implementation.new(
-
erb,
-
1
:escape => (self.class.escape_whitelist.include? template.mime_type),
-
1
:trim => (self.class.erb_trim_mode == "-")
-
).src
-
end
-
-
2
private
-
-
2
def valid_encoding(string, encoding)
-
# If a magic encoding comment was found, tag the
-
# String with this encoding. This is for a case
-
# where the original String was assumed to be,
-
# for instance, UTF-8, but a magic comment
-
# proved otherwise
-
1
string.force_encoding(encoding) if encoding
-
-
# If the String is valid, return the encoding we found
-
1
return string.encoding if string.valid_encoding?
-
-
# Otherwise, raise an exception
-
raise WrongEncodingError.new(string, string.encoding)
-
end
-
end
-
end
-
end
-
end
-
2
require "pathname"
-
2
require "active_support/core_ext/class"
-
2
require "active_support/core_ext/io"
-
2
require "action_view/template"
-
-
2
module ActionView
-
# = Action View Resolver
-
2
class Resolver
-
# Keeps all information about view path and builds virtual path.
-
2
class Path < String
-
2
attr_reader :name, :prefix, :partial, :virtual
-
2
alias_method :partial?, :partial
-
-
2
def self.build(name, prefix, partial)
-
6
virtual = ""
-
6
virtual << "#{prefix}/" unless prefix.empty?
-
6
virtual << (partial ? "_#{name}" : name)
-
6
new name, prefix, partial, virtual
-
end
-
-
2
def initialize(name, prefix, partial, virtual)
-
6
@name, @prefix, @partial = name, prefix, partial
-
6
super(virtual)
-
end
-
end
-
-
2
cattr_accessor :caching
-
2
self.caching = true
-
-
2
class << self
-
2
alias :caching? :caching
-
end
-
-
2
def initialize
-
15
@cached = Hash.new { |h1,k1| h1[k1] = Hash.new { |h2,k2|
-
15
h2[k2] = Hash.new { |h3,k3| h3[k3] = Hash.new { |h4,k4| h4[k4] = {} } } } }
-
end
-
-
2
def clear_cache
-
@cached.clear
-
end
-
-
# Normalizes the arguments and passes it on to find_template.
-
2
def find_all(name, prefix=nil, partial=false, details={}, key=nil, locals=[])
-
20
cached(key, [name, prefix, partial], details, locals) do
-
5
find_templates(name, prefix, partial, details)
-
end
-
end
-
-
2
private
-
-
2
delegate :caching?, :to => "self.class"
-
-
# This is what child classes implement. No defaults are needed
-
# because Resolver guarantees that the arguments are present and
-
# normalized.
-
2
def find_templates(name, prefix, partial, details)
-
raise NotImplementedError, "Subclasses must implement a find_templates(name, prefix, partial, details) method"
-
end
-
-
# Helpers that builds a path. Useful for building virtual paths.
-
2
def build_path(name, prefix, partial)
-
1
Path.build(name, prefix, partial)
-
end
-
-
# Handles templates caching. If a key is given and caching is on
-
# always check the cache before hitting the resolver. Otherwise,
-
# it always hits the resolver but check if the resolver is fresher
-
# before returning it.
-
2
def cached(key, path_info, details, locals) #:nodoc:
-
20
name, prefix, partial = path_info
-
20
locals = locals.map { |x| x.to_s }.sort!
-
-
20
if key && caching?
-
20
@cached[key][name][prefix][partial][locals] ||= decorate(yield, path_info, details, locals)
-
else
-
fresh = decorate(yield, path_info, details, locals)
-
return fresh unless key
-
-
scope = @cached[key][name][prefix][partial]
-
cache = scope[locals]
-
mtime = cache && cache.map(&:updated_at).max
-
-
if !mtime || fresh.empty? || fresh.any? { |t| t.updated_at > mtime }
-
scope[locals] = fresh
-
else
-
cache
-
end
-
end
-
end
-
-
# Ensures all the resolver information is set in the template.
-
2
def decorate(templates, path_info, details, locals) #:nodoc:
-
5
cached = nil
-
5
templates.each do |t|
-
1
t.locals = locals
-
1
t.formats = details[:formats] || [:html] if t.formats.empty?
-
1
t.virtual_path ||= (cached ||= build_path(*path_info))
-
end
-
end
-
end
-
-
# An abstract class that implements a Resolver with path semantics.
-
2
class PathResolver < Resolver #:nodoc:
-
2
EXTENSIONS = [:locale, :formats, :handlers]
-
2
DEFAULT_PATTERN = ":prefix/:action{.:locale,}{.:formats,}{.:handlers,}"
-
-
2
def initialize(pattern=nil)
-
12
@pattern = pattern || DEFAULT_PATTERN
-
12
super()
-
end
-
-
2
private
-
-
2
def find_templates(name, prefix, partial, details)
-
5
path = Path.build(name, prefix, partial)
-
5
query(path, details, details[:formats])
-
end
-
-
2
def query(path, details, formats)
-
5
query = build_query(path, details)
-
-
# deals with case-insensitive file systems.
-
6
sanitizer = Hash.new { |h,dir| h[dir] = Dir["#{dir}/*"] }
-
-
5
template_paths = Dir[query].reject { |filename|
-
File.directory?(filename) ||
-
1
!sanitizer[File.dirname(filename)].include?(filename)
-
}
-
-
5
template_paths.map { |template|
-
1
handler, format = extract_handler_and_format(template, formats)
-
1
contents = File.binread template
-
-
1
Template.new(contents, File.expand_path(template), handler,
-
:virtual_path => path.virtual,
-
:format => format,
-
:updated_at => mtime(template))
-
}
-
end
-
-
# Helper for building query glob string based on resolver's pattern.
-
2
def build_query(path, details)
-
query = @pattern.dup
-
-
prefix = path.prefix.empty? ? "" : "#{escape_entry(path.prefix)}\\1"
-
query.gsub!(/\:prefix(\/)?/, prefix)
-
-
partial = escape_entry(path.partial? ? "_#{path.name}" : path.name)
-
query.gsub!(/\:action/, partial)
-
-
details.each do |ext, variants|
-
query.gsub!(/\:#{ext}/, "{#{variants.compact.uniq.join(',')}}")
-
end
-
-
File.expand_path(query, @path)
-
end
-
-
2
def escape_entry(entry)
-
5
entry.gsub(/[*?{}\[\]]/, '\\\\\\&')
-
end
-
-
# Returns the file mtime from the filesystem.
-
2
def mtime(p)
-
1
File.mtime(p)
-
end
-
-
# Extract handler and formats from path. If a format cannot be a found neither
-
# from the path, or the handler, we should return the array of formats given
-
# to the resolver.
-
2
def extract_handler_and_format(path, default_formats)
-
1
pieces = File.basename(path).split(".")
-
1
pieces.shift
-
1
handler = Template.handler_for_extension(pieces.pop)
-
1
format = pieces.last && Mime[pieces.last]
-
1
[handler, format]
-
end
-
end
-
-
# A resolver that loads files from the filesystem. It allows to set your own
-
# resolving pattern. Such pattern can be a glob string supported by some variables.
-
#
-
# ==== Examples
-
#
-
# Default pattern, loads views the same way as previous versions of rails, eg. when you're
-
# looking for `users/new` it will produce query glob: `users/new{.{en},}{.{html,js},}{.{erb,haml},}`
-
#
-
# FileSystemResolver.new("/path/to/views", ":prefix/:action{.:locale,}{.:formats,}{.:handlers,}")
-
#
-
# This one allows you to keep files with different formats in seperated subdirectories,
-
# eg. `users/new.html` will be loaded from `users/html/new.erb` or `users/new.html.erb`,
-
# `users/new.js` from `users/js/new.erb` or `users/new.js.erb`, etc.
-
#
-
# FileSystemResolver.new("/path/to/views", ":prefix/{:formats/,}:action{.:locale,}{.:formats,}{.:handlers,}")
-
#
-
# If you don't specify pattern then the default will be used.
-
#
-
# In order to use any of the customized resolvers above in a Rails application, you just need
-
# to configure ActionController::Base.view_paths in an initializer, for example:
-
#
-
# ActionController::Base.view_paths = FileSystemResolver.new(
-
# Rails.root.join("app/views"),
-
# ":prefix{/:locale}/:action{.:formats,}{.:handlers,}"
-
# )
-
#
-
# ==== Pattern format and variables
-
#
-
# Pattern have to be a valid glob string, and it allows you to use the
-
# following variables:
-
#
-
# * <tt>:prefix</tt> - usualy the controller path
-
# * <tt>:action</tt> - name of the action
-
# * <tt>:locale</tt> - possible locale versions
-
# * <tt>:formats</tt> - possible request formats (for example html, json, xml...)
-
# * <tt>:handlers</tt> - possible handlers (for example erb, haml, builder...)
-
#
-
2
class FileSystemResolver < PathResolver
-
2
def initialize(path, pattern=nil)
-
12
raise ArgumentError, "path already is a Resolver class" if path.is_a?(Resolver)
-
12
super(pattern)
-
12
@path = File.expand_path(path)
-
end
-
-
2
def to_s
-
@path.to_s
-
end
-
2
alias :to_path :to_s
-
-
2
def eql?(resolver)
-
self.class.equal?(resolver.class) && to_path == resolver.to_path
-
end
-
2
alias :== :eql?
-
end
-
-
# An Optimized resolver for Rails' most common case.
-
2
class OptimizedFileSystemResolver < FileSystemResolver #:nodoc:
-
2
def build_query(path, details)
-
20
exts = EXTENSIONS.map { |ext| details[ext] }
-
5
query = escape_entry(File.join(@path, path))
-
-
query + exts.map { |ext|
-
60
"{#{ext.compact.uniq.map { |e| ".#{e}," }.join}}"
-
5
}.join
-
end
-
end
-
-
# The same as FileSystemResolver but does not allow templates to store
-
# a virtual path since it is invalid for such resolvers.
-
2
class FallbackFileSystemResolver < FileSystemResolver #:nodoc:
-
2
def self.instances
-
2
[new(""), new("/")]
-
end
-
-
2
def decorate(*)
-
super.each { |t| t.virtual_path = nil }
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'action_controller'
-
1
require 'action_controller/test_case'
-
1
require 'action_view'
-
-
1
module ActionView
-
# = Action View Test Case
-
1
class TestCase < ActiveSupport::TestCase
-
1
class TestController < ActionController::Base
-
1
include ActionDispatch::TestProcess
-
-
1
attr_accessor :request, :response, :params
-
-
1
class << self
-
1
attr_writer :controller_path
-
end
-
-
1
def controller_path=(path)
-
self.class.controller_path=(path)
-
end
-
-
1
def initialize
-
super
-
self.class.controller_path = ""
-
@request = ActionController::TestRequest.new
-
@response = ActionController::TestResponse.new
-
-
@request.env.delete('PATH_INFO')
-
@params = {}
-
end
-
end
-
-
1
module Behavior
-
1
extend ActiveSupport::Concern
-
-
1
include ActionDispatch::Assertions, ActionDispatch::TestProcess
-
1
include ActionController::TemplateAssertions
-
1
include ActionView::Context
-
-
1
include ActionDispatch::Routing::PolymorphicRoutes
-
1
include ActionController::RecordIdentifier
-
-
1
include AbstractController::Helpers
-
1
include ActionView::Helpers
-
-
1
delegate :lookup_context, :to => :controller
-
1
attr_accessor :controller, :output_buffer, :rendered
-
-
1
module ClassMethods
-
1
def tests(helper_class)
-
case helper_class
-
when String, Symbol
-
self.helper_class = "#{helper_class.to_s.underscore}_helper".camelize.safe_constantize
-
when Module
-
self.helper_class = helper_class
-
end
-
end
-
-
1
def determine_default_helper_class(name)
-
mod = name.sub(/Test$/, '').constantize
-
mod.is_a?(Class) ? nil : mod
-
rescue NameError
-
nil
-
end
-
-
1
def helper_method(*methods)
-
# Almost a duplicate from ActionController::Helpers
-
methods.flatten.each do |method|
-
_helpers.module_eval <<-end_eval
-
def #{method}(*args, &block) # def current_user(*args, &block)
-
_test_case.send(%(#{method}), *args, &block) # _test_case.send(%(current_user), *args, &block)
-
end # end
-
end_eval
-
end
-
end
-
-
1
attr_writer :helper_class
-
-
1
def helper_class
-
@helper_class ||= determine_default_helper_class(name)
-
end
-
-
1
def new(*)
-
include_helper_modules!
-
super
-
end
-
-
1
private
-
-
1
def include_helper_modules!
-
helper(helper_class) if helper_class
-
include _helpers
-
end
-
-
end
-
-
1
def setup_with_controller
-
@controller = ActionView::TestCase::TestController.new
-
@request = @controller.request
-
@output_buffer = ActiveSupport::SafeBuffer.new
-
@rendered = ''
-
-
make_test_case_available_to_view!
-
say_no_to_protect_against_forgery!
-
end
-
-
1
def config
-
@controller.config if @controller.respond_to?(:config)
-
end
-
-
1
def render(options = {}, local_assigns = {}, &block)
-
view.assign(view_assigns)
-
@rendered << output = view.render(options, local_assigns, &block)
-
output
-
end
-
-
1
def locals
-
@locals ||= {}
-
end
-
-
1
included do
-
1
setup :setup_with_controller
-
end
-
-
1
private
-
-
# Support the selector assertions
-
#
-
# Need to experiment if this priority is the best one: rendered => output_buffer
-
1
def response_from_page
-
HTML::Document.new(@rendered.blank? ? @output_buffer : @rendered).root
-
end
-
-
1
def say_no_to_protect_against_forgery!
-
_helpers.module_eval do
-
remove_possible_method :protect_against_forgery?
-
def protect_against_forgery?
-
false
-
end
-
end
-
end
-
-
1
def make_test_case_available_to_view!
-
test_case_instance = self
-
_helpers.module_eval do
-
unless private_method_defined?(:_test_case)
-
define_method(:_test_case) { test_case_instance }
-
private :_test_case
-
end
-
end
-
end
-
-
1
module Locals
-
1
attr_accessor :locals
-
-
1
def render(options = {}, local_assigns = {})
-
case options
-
when Hash
-
if block_given?
-
locals[options[:layout]] = options[:locals]
-
elsif options.key?(:partial)
-
locals[options[:partial]] = options[:locals]
-
end
-
else
-
locals[options] = local_assigns
-
end
-
-
super
-
end
-
end
-
-
# The instance of ActionView::Base that is used by +render+.
-
1
def view
-
@view ||= begin
-
view = @controller.view_context
-
view.singleton_class.send :include, _helpers
-
view.extend(Locals)
-
view.locals = self.locals
-
view.output_buffer = self.output_buffer
-
view
-
end
-
end
-
-
1
alias_method :_view, :view
-
-
1
INTERNAL_IVARS = %w{
-
@__name__
-
@__io__
-
@_assertion_wrapped
-
@_assertions
-
@_result
-
@_routes
-
@controller
-
@layouts
-
@locals
-
@method_name
-
@output_buffer
-
@partials
-
@passed
-
@rendered
-
@request
-
@routes
-
@templates
-
@options
-
@test_passed
-
@view
-
@view_context_class
-
}
-
-
1
def _user_defined_ivars
-
instance_variables.map(&:to_s) - INTERNAL_IVARS
-
end
-
-
# Returns a Hash of instance variables and their values, as defined by
-
# the user in the test case, which are then assigned to the view being
-
# rendered. This is generally intended for internal use and extension
-
# frameworks.
-
1
def view_assigns
-
Hash[_user_defined_ivars.map do |var|
-
[var[1, var.length].to_sym, instance_variable_get(var)]
-
end]
-
end
-
-
1
def _routes
-
@controller._routes if @controller.respond_to?(:_routes)
-
end
-
-
1
def method_missing(selector, *args)
-
if @controller.respond_to?(:_routes) &&
-
( @controller._routes.named_routes.helpers.include?(selector) ||
-
@controller._routes.mounted_helpers.method_defined?(selector) )
-
@controller.__send__(selector, *args)
-
else
-
super
-
end
-
end
-
-
end
-
-
1
include Behavior
-
-
end
-
end
-
2
module Sprockets
-
2
class Bootstrap
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
# TODO: Get rid of config.assets.enabled
-
2
def run
-
2
app, config = @app, @app.config
-
2
return unless app.assets
-
-
28
config.assets.paths.each { |path| app.assets.append_path(path) }
-
-
2
if config.assets.compress
-
# temporarily hardcode default JS compressor to uglify. Soon, it will work
-
# the same as SCSS, where a default plugin sets the default.
-
unless config.assets.js_compressor == false
-
app.assets.js_compressor = LazyCompressor.new { Sprockets::Compressors.registered_js_compressor(config.assets.js_compressor || :uglifier) }
-
end
-
-
unless config.assets.css_compressor == false
-
app.assets.css_compressor = LazyCompressor.new { Sprockets::Compressors.registered_css_compressor(config.assets.css_compressor) }
-
end
-
end
-
-
2
if config.assets.compile
-
2
app.routes.prepend do
-
2
mount app.assets => config.assets.prefix
-
end
-
end
-
-
2
if config.assets.digest
-
app.assets = app.assets.index
-
end
-
end
-
end
-
end
-
2
module Sprockets
-
2
module Helpers
-
2
autoload :RailsHelper, "sprockets/helpers/rails_helper"
-
2
autoload :IsolatedHelper, "sprockets/helpers/isolated_helper"
-
end
-
end
-
2
module Sprockets
-
2
module Helpers
-
2
module IsolatedHelper
-
2
def controller
-
nil
-
end
-
-
2
def config
-
Rails.application.config.action_controller
-
end
-
end
-
end
-
end
-
2
require "action_view"
-
-
2
module Sprockets
-
2
module Helpers
-
2
module RailsHelper
-
2
extend ActiveSupport::Concern
-
2
include ActionView::Helpers::AssetTagHelper
-
-
2
def asset_paths
-
@asset_paths ||= begin
-
paths = RailsHelper::AssetPaths.new(config, controller)
-
paths.asset_environment = asset_environment
-
paths.asset_digests = asset_digests
-
paths.compile_assets = compile_assets?
-
paths.digest_assets = digest_assets?
-
paths
-
end
-
end
-
-
2
def javascript_include_tag(*sources)
-
options = sources.extract_options!
-
debug = options.key?(:debug) ? options.delete(:debug) : debug_assets?
-
body = options.key?(:body) ? options.delete(:body) : false
-
digest = options.key?(:digest) ? options.delete(:digest) : digest_assets?
-
-
sources.collect do |source|
-
if debug && asset = asset_paths.asset_for(source, 'js')
-
asset.to_a.map { |dep|
-
super(dep.pathname.to_s, { :src => path_to_asset(dep, :ext => 'js', :body => true, :digest => digest) }.merge!(options))
-
}
-
else
-
super(source.to_s, { :src => path_to_asset(source, :ext => 'js', :body => body, :digest => digest) }.merge!(options))
-
end
-
end.flatten.uniq.join("\n").html_safe
-
end
-
-
2
def stylesheet_link_tag(*sources)
-
options = sources.extract_options!
-
debug = options.key?(:debug) ? options.delete(:debug) : debug_assets?
-
body = options.key?(:body) ? options.delete(:body) : false
-
digest = options.key?(:digest) ? options.delete(:digest) : digest_assets?
-
-
sources.collect do |source|
-
if debug && asset = asset_paths.asset_for(source, 'css')
-
asset.to_a.map { |dep|
-
super(dep.pathname.to_s, { :href => path_to_asset(dep, :ext => 'css', :body => true, :protocol => :request, :digest => digest) }.merge!(options))
-
}
-
else
-
super(source.to_s, { :href => path_to_asset(source, :ext => 'css', :body => body, :protocol => :request, :digest => digest) }.merge!(options))
-
end
-
end.flatten.uniq.join("\n").html_safe
-
end
-
-
2
def asset_path(source, options = {})
-
source = source.logical_path if source.respond_to?(:logical_path)
-
path = asset_paths.compute_public_path(source, asset_prefix, options.merge(:body => true))
-
options[:body] ? "#{path}?body=1" : path
-
end
-
2
alias_method :path_to_asset, :asset_path # aliased to avoid conflicts with an asset_path named route
-
-
2
def image_path(source)
-
path_to_asset(source)
-
end
-
2
alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
-
-
2
def font_path(source)
-
path_to_asset(source)
-
end
-
2
alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route
-
-
2
def javascript_path(source)
-
path_to_asset(source, :ext => 'js')
-
end
-
2
alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with an javascript_path named route
-
-
2
def stylesheet_path(source)
-
path_to_asset(source, :ext => 'css')
-
end
-
2
alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with an stylesheet_path named route
-
-
2
private
-
2
def debug_assets?
-
compile_assets? && (Rails.application.config.assets.debug || params[:debug_assets])
-
rescue NameError
-
false
-
end
-
-
# Override to specify an alternative prefix for asset path generation.
-
# When combined with a custom +asset_environment+, this can be used to
-
# implement themes that can take advantage of the asset pipeline.
-
#
-
# If you only want to change where the assets are mounted, refer to
-
# +config.assets.prefix+ instead.
-
2
def asset_prefix
-
Rails.application.config.assets.prefix
-
end
-
-
2
def asset_digests
-
Rails.application.config.assets.digests
-
end
-
-
2
def compile_assets?
-
Rails.application.config.assets.compile
-
end
-
-
2
def digest_assets?
-
Rails.application.config.assets.digest
-
end
-
-
# Override to specify an alternative asset environment for asset
-
# path generation. The environment should already have been mounted
-
# at the prefix returned by +asset_prefix+.
-
2
def asset_environment
-
Rails.application.assets
-
end
-
-
2
class AssetPaths < ::ActionView::AssetPaths #:nodoc:
-
2
attr_accessor :asset_environment, :asset_prefix, :asset_digests, :compile_assets, :digest_assets
-
-
2
class AssetNotPrecompiledError < StandardError; end
-
-
2
def asset_for(source, ext)
-
source = source.to_s
-
return nil if is_uri?(source)
-
source = rewrite_extension(source, nil, ext)
-
asset_environment[source]
-
rescue Sprockets::FileOutsidePaths
-
nil
-
end
-
-
2
def digest_for(logical_path)
-
if digest_assets && asset_digests && (digest = asset_digests[logical_path])
-
return digest
-
end
-
-
if compile_assets
-
if digest_assets && asset = asset_environment[logical_path]
-
return asset.digest_path
-
end
-
return logical_path
-
else
-
raise AssetNotPrecompiledError.new("#{logical_path} isn't precompiled")
-
end
-
end
-
-
2
def rewrite_asset_path(source, dir, options = {})
-
if source[0] == ?/
-
source
-
else
-
if digest_assets && options[:digest] != false
-
source = digest_for(source)
-
end
-
source = File.join(dir, source)
-
source = "/#{source}" unless source =~ /^\//
-
source
-
end
-
end
-
-
2
def rewrite_extension(source, dir, ext)
-
source_ext = File.extname(source)[1..-1]
-
-
if !ext || ext == source_ext
-
source
-
elsif source_ext.blank?
-
"#{source}.#{ext}"
-
elsif File.exists?(source) || exact_match_present?(source)
-
source
-
else
-
"#{source}.#{ext}"
-
end
-
end
-
-
2
def exact_match_present?(source)
-
pathname = asset_environment.resolve(source)
-
pathname.to_s =~ /#{Regexp.escape(source)}\Z/
-
rescue Sprockets::FileNotFound
-
false
-
end
-
end
-
end
-
end
-
end
-
2
require "action_controller/railtie"
-
-
2
module Sprockets
-
2
autoload :Bootstrap, "sprockets/bootstrap"
-
2
autoload :Helpers, "sprockets/helpers"
-
2
autoload :Compressors, "sprockets/compressors"
-
2
autoload :LazyCompressor, "sprockets/compressors"
-
2
autoload :NullCompressor, "sprockets/compressors"
-
2
autoload :StaticCompiler, "sprockets/static_compiler"
-
-
# TODO: Get rid of config.assets.enabled
-
2
class Railtie < ::Rails::Railtie
-
2
rake_tasks do
-
load "sprockets/assets.rake"
-
end
-
-
2
initializer "sprockets.environment", :group => :all do |app|
-
2
config = app.config
-
2
next unless config.assets.enabled
-
-
2
require 'sprockets'
-
-
2
app.assets = Sprockets::Environment.new(app.root.to_s) do |env|
-
2
env.version = ::Rails.env + "-#{config.assets.version}"
-
-
2
if config.assets.logger != false
-
2
env.logger = config.assets.logger || ::Rails.logger
-
end
-
-
2
if config.assets.cache_store != false
-
2
env.cache = ActiveSupport::Cache.lookup_store(config.assets.cache_store) || ::Rails.cache
-
end
-
end
-
-
2
if config.assets.manifest
-
path = File.join(config.assets.manifest, "manifest.yml")
-
else
-
2
path = File.join(Rails.public_path, config.assets.prefix, "manifest.yml")
-
end
-
-
2
if File.exist?(path)
-
config.assets.digests = YAML.load_file(path)
-
end
-
-
2
ActiveSupport.on_load(:action_view) do
-
2
include ::Sprockets::Helpers::RailsHelper
-
2
app.assets.context_class.instance_eval do
-
2
include ::Sprockets::Helpers::IsolatedHelper
-
2
include ::Sprockets::Helpers::RailsHelper
-
end
-
end
-
end
-
-
# We need to configure this after initialization to ensure we collect
-
# paths from all engines. This hook is invoked exactly before routes
-
# are compiled, and so that other Railties have an opportunity to
-
# register compressors.
-
2
config.after_initialize do |app|
-
2
Sprockets::Bootstrap.new(app).run
-
end
-
end
-
end
-
2
require 'active_support/log_subscriber'
-
-
2
module ActiveRecordQueryTrace
-
-
2
class << self
-
2
attr_accessor :enabled
-
2
attr_accessor :level
-
2
attr_accessor :lines
-
end
-
-
2
module ActiveRecord
-
2
class LogSubscriber < ActiveSupport::LogSubscriber
-
-
2
def initialize
-
2
super
-
2
ActiveRecordQueryTrace.enabled = false
-
2
ActiveRecordQueryTrace.level = :app
-
2
ActiveRecordQueryTrace.lines = 5
-
end
-
-
2
def sql(event)
-
1989
if ActiveRecordQueryTrace.enabled
-
index = begin
-
if ActiveRecordQueryTrace.lines == 0
-
0..-1
-
else
-
0..(ActiveRecordQueryTrace.lines - 1)
-
end
-
end
-
-
debug(color('Called from: ', MAGENTA, true) + clean_trace(caller)[index].join("\n "))
-
end
-
end
-
-
2
def clean_trace(trace)
-
case ActiveRecordQueryTrace.level
-
when :full
-
trace
-
when :rails
-
Rails.respond_to?(:backtrace_cleaner) ? Rails.backtrace_cleaner.clean(trace) : trace
-
when :app
-
Rails.backtrace_cleaner.add_silencer { |line| not line =~ /^app/ }
-
Rails.backtrace_cleaner.clean(trace)
-
end
-
end
-
-
2
attach_to :active_record
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2004-2011 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
-
2
$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-
2
require 'active_support'
-
2
require 'active_model/version'
-
-
2
module ActiveModel
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :AttributeMethods
-
2
autoload :BlockValidator, 'active_model/validator'
-
2
autoload :Callbacks
-
2
autoload :Conversion
-
2
autoload :Dirty
-
2
autoload :EachValidator, 'active_model/validator'
-
2
autoload :Errors
-
2
autoload :Lint
-
2
autoload :MassAssignmentSecurity
-
2
autoload :Name, 'active_model/naming'
-
2
autoload :Naming
-
2
autoload :Observer, 'active_model/observing'
-
2
autoload :Observing
-
2
autoload :SecurePassword
-
2
autoload :Serialization
-
2
autoload :TestCase
-
2
autoload :Translation
-
2
autoload :Validations
-
2
autoload :Validator
-
-
2
module Serializers
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :JSON
-
2
autoload :Xml
-
end
-
end
-
-
2
require 'active_support/i18n'
-
2
I18n.load_path << File.dirname(__FILE__) + '/active_model/locale/en.yml'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/deprecation'
-
-
2
module ActiveModel
-
2
class MissingAttributeError < NoMethodError
-
end
-
# == Active Model Attribute Methods
-
#
-
# <tt>ActiveModel::AttributeMethods</tt> provides a way to add prefixes and suffixes
-
# to your methods as well as handling the creation of Active Record like class methods
-
# such as +table_name+.
-
#
-
# The requirements to implement ActiveModel::AttributeMethods are to:
-
#
-
# * <tt>include ActiveModel::AttributeMethods</tt> in your object
-
# * Call each Attribute Method module method you want to add, such as
-
# attribute_method_suffix or attribute_method_prefix
-
# * Call <tt>define_attribute_methods</tt> after the other methods are
-
# called.
-
# * Define the various generic +_attribute+ methods that you have declared
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attribute_method_affix :prefix => 'reset_', :suffix => '_to_default!'
-
# attribute_method_suffix '_contrived?'
-
# attribute_method_prefix 'clear_'
-
# define_attribute_methods ['name']
-
#
-
# attr_accessor :name
-
#
-
# private
-
#
-
# def attribute_contrived?(attr)
-
# true
-
# end
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
#
-
# def reset_attribute_to_default!(attr)
-
# send("#{attr}=", "Default Name")
-
# end
-
# end
-
#
-
# Note that whenever you include ActiveModel::AttributeMethods in your class,
-
# it requires you to implement an <tt>attributes</tt> method which returns a hash
-
# with each attribute name in your model as hash key and the attribute value as
-
# hash value.
-
#
-
# Hash keys must be strings.
-
#
-
2
module AttributeMethods
-
2
extend ActiveSupport::Concern
-
-
2
NAME_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?=]?\z/
-
2
CALL_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?]?\z/
-
-
2
included do
-
2
class_attribute :attribute_method_matchers, :instance_writer => false
-
2
self.attribute_method_matchers = [ClassMethods::AttributeMethodMatcher.new]
-
end
-
-
2
module ClassMethods
-
2
def define_attr_method(name, value=nil, deprecation_warning = true, &block) #:nodoc:
-
# This deprecation_warning param is for internal use so that we can silence
-
# the warning from Active Record, because we are implementing more specific
-
# messages there instead.
-
#
-
# It doesn't apply to the original_#{name} method as we want to warn if
-
# people are calling that regardless.
-
if deprecation_warning
-
ActiveSupport::Deprecation.warn("define_attr_method is deprecated and will be removed without replacement.")
-
end
-
-
sing = singleton_class
-
sing.class_eval <<-eorb, __FILE__, __LINE__ + 1
-
remove_possible_method :'original_#{name}'
-
remove_possible_method :'_original_#{name}'
-
alias_method :'_original_#{name}', :'#{name}'
-
define_method :'original_#{name}' do
-
ActiveSupport::Deprecation.warn(
-
"This method is generated by ActiveModel::AttributeMethods::ClassMethods#define_attr_method, " \
-
"which is deprecated and will be removed."
-
)
-
send(:'_original_#{name}')
-
end
-
eorb
-
if block_given?
-
sing.send :define_method, name, &block
-
else
-
# If we can compile the method name, do it. Otherwise use define_method.
-
# This is an important *optimization*, please don't change it. define_method
-
# has slower dispatch and consumes more memory.
-
if name =~ NAME_COMPILABLE_REGEXP
-
sing.class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{name}; #{value.nil? ? 'nil' : value.to_s.inspect}; end
-
RUBY
-
else
-
value = value.to_s if value
-
sing.send(:define_method, name) { value }
-
end
-
end
-
end
-
-
# Declares a method available for all attributes with the given prefix.
-
# Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method.
-
#
-
# #{prefix}#{attr}(*args, &block)
-
#
-
# to
-
#
-
# #{prefix}attribute(#{attr}, *args, &block)
-
#
-
# An instance method <tt>#{prefix}attribute</tt> must exist and accept
-
# at least the +attr+ argument.
-
#
-
# For example:
-
#
-
# class Person
-
#
-
# include ActiveModel::AttributeMethods
-
# attr_accessor :name
-
# attribute_method_prefix 'clear_'
-
# define_attribute_methods [:name]
-
#
-
# private
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = "Bob"
-
# person.name # => "Bob"
-
# person.clear_name
-
# person.name # => nil
-
2
def attribute_method_prefix(*prefixes)
-
4
self.attribute_method_matchers += prefixes.map { |prefix| AttributeMethodMatcher.new :prefix => prefix }
-
2
undefine_attribute_methods
-
end
-
-
# Declares a method available for all attributes with the given suffix.
-
# Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method.
-
#
-
# #{attr}#{suffix}(*args, &block)
-
#
-
# to
-
#
-
# attribute#{suffix}(#{attr}, *args, &block)
-
#
-
# An <tt>attribute#{suffix}</tt> instance method must exist and accept at least
-
# the +attr+ argument.
-
#
-
# For example:
-
#
-
# class Person
-
#
-
# include ActiveModel::AttributeMethods
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_methods [:name]
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = "Bob"
-
# person.name # => "Bob"
-
# person.name_short? # => true
-
2
def attribute_method_suffix(*suffixes)
-
22
self.attribute_method_matchers += suffixes.map { |suffix| AttributeMethodMatcher.new :suffix => suffix }
-
8
undefine_attribute_methods
-
end
-
-
# Declares a method available for all attributes with the given prefix
-
# and suffix. Uses +method_missing+ and <tt>respond_to?</tt> to rewrite
-
# the method.
-
#
-
# #{prefix}#{attr}#{suffix}(*args, &block)
-
#
-
# to
-
#
-
# #{prefix}attribute#{suffix}(#{attr}, *args, &block)
-
#
-
# An <tt>#{prefix}attribute#{suffix}</tt> instance method must exist and
-
# accept at least the +attr+ argument.
-
#
-
# For example:
-
#
-
# class Person
-
#
-
# include ActiveModel::AttributeMethods
-
# attr_accessor :name
-
# attribute_method_affix :prefix => 'reset_', :suffix => '_to_default!'
-
# define_attribute_methods [:name]
-
#
-
# private
-
#
-
# def reset_attribute_to_default!(attr)
-
# ...
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name # => 'Gem'
-
# person.reset_name_to_default!
-
# person.name # => 'Gemma'
-
2
def attribute_method_affix(*affixes)
-
4
self.attribute_method_matchers += affixes.map { |affix| AttributeMethodMatcher.new :prefix => affix[:prefix], :suffix => affix[:suffix] }
-
2
undefine_attribute_methods
-
end
-
-
2
def alias_attribute(new_name, old_name)
-
attribute_method_matchers.each do |matcher|
-
matcher_new = matcher.method_name(new_name).to_s
-
matcher_old = matcher.method_name(old_name).to_s
-
define_optimized_call self, matcher_new, matcher_old
-
end
-
end
-
-
# Declares the attributes that should be prefixed and suffixed by
-
# ActiveModel::AttributeMethods.
-
#
-
# To use, pass in an array of attribute names (as strings or symbols),
-
# be sure to declare +define_attribute_methods+ after you define any
-
# prefix, suffix or affix methods, or they will not hook in.
-
#
-
# class Person
-
#
-
# include ActiveModel::AttributeMethods
-
# attr_accessor :name, :age, :address
-
# attribute_method_prefix 'clear_'
-
#
-
# # Call to define_attribute_methods must appear after the
-
# # attribute_method_prefix, attribute_method_suffix or
-
# # attribute_method_affix declares.
-
# define_attribute_methods [:name, :age, :address]
-
#
-
# private
-
#
-
# def clear_attribute(attr)
-
# ...
-
# end
-
# end
-
2
def define_attribute_methods(attr_names)
-
120
attr_names.each { |attr_name| define_attribute_method(attr_name) }
-
end
-
-
2
def define_attribute_method(attr_name)
-
107
attribute_method_matchers.each do |matcher|
-
1070
method_name = matcher.method_name(attr_name)
-
-
1070
unless instance_method_already_implemented?(method_name)
-
1070
generate_method = "define_method_#{matcher.method_missing_target}"
-
-
1070
if respond_to?(generate_method, true)
-
321
send(generate_method, attr_name)
-
else
-
749
define_optimized_call generated_attribute_methods, method_name, matcher.method_missing_target, attr_name.to_s
-
end
-
end
-
end
-
107
attribute_method_matchers_cache.clear
-
end
-
-
# Removes all the previously dynamically defined methods from the class
-
2
def undefine_attribute_methods
-
12
generated_attribute_methods.module_eval do
-
12
instance_methods.each { |m| undef_method(m) }
-
end
-
12
attribute_method_matchers_cache.clear
-
end
-
-
# Returns true if the attribute methods defined have been generated.
-
2
def generated_attribute_methods #:nodoc:
-
@generated_attribute_methods ||= begin
-
24
mod = Module.new
-
24
include mod
-
24
mod
-
2067
end
-
end
-
-
2
protected
-
2
def instance_method_already_implemented?(method_name)
-
1070
generated_attribute_methods.method_defined?(method_name)
-
end
-
-
2
private
-
# The methods +method_missing+ and +respond_to?+ of this module are
-
# invoked often in a typical rails, both of which invoke the method
-
# +match_attribute_method?+. The latter method iterates through an
-
# array doing regular expression matches, which results in a lot of
-
# object creations. Most of the times it returns a +nil+ match. As the
-
# match result is always the same given a +method_name+, this cache is
-
# used to alleviate the GC, which ultimately also speeds up the app
-
# significantly (in our case our test suite finishes 10% faster with
-
# this cache).
-
2
def attribute_method_matchers_cache #:nodoc:
-
1475
@attribute_method_matchers_cache ||= {}
-
end
-
-
2
def attribute_method_matcher(method_name) #:nodoc:
-
678
if attribute_method_matchers_cache.key?(method_name)
-
602
attribute_method_matchers_cache[method_name]
-
else
-
# Must try to match prefixes/suffixes first, or else the matcher with no prefix/suffix
-
# will match every time.
-
76
matchers = attribute_method_matchers.partition(&:plain?).reverse.flatten(1)
-
76
match = nil
-
774
matchers.detect { |method| match = method.match(method_name) }
-
76
attribute_method_matchers_cache[method_name] = match
-
end
-
end
-
-
# Define a method `name` in `mod` that dispatches to `send`
-
# using the given `extra` args. This fallbacks `define_method`
-
# and `send` if the given names cannot be compiled.
-
2
def define_optimized_call(mod, name, send, *extra) #:nodoc:
-
749
if name =~ NAME_COMPILABLE_REGEXP
-
749
defn = "def #{name}(*args)"
-
else
-
defn = "define_method(:'#{name}') do |*args|"
-
end
-
-
749
extra = (extra.map(&:inspect) << "*args").join(", ")
-
-
749
if send =~ CALL_COMPILABLE_REGEXP
-
749
target = "#{send}(#{extra})"
-
else
-
target = "send(:'#{send}', #{extra})"
-
end
-
-
749
mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
#{defn}
-
#{target}
-
end
-
RUBY
-
end
-
-
2
class AttributeMethodMatcher
-
2
attr_reader :prefix, :suffix, :method_missing_target
-
-
2
AttributeMethodMatch = Struct.new(:target, :attr_name, :method_name)
-
-
2
def initialize(options = {})
-
20
options.symbolize_keys!
-
-
20
if options[:prefix] == '' || options[:suffix] == ''
-
ActiveSupport::Deprecation.warn(
-
"Specifying an empty prefix/suffix for an attribute method is no longer " \
-
"necessary. If the un-prefixed/suffixed version of the method has not been " \
-
"defined when `define_attribute_methods` is called, it will be defined " \
-
"automatically."
-
)
-
end
-
-
20
@prefix, @suffix = options[:prefix] || '', options[:suffix] || ''
-
20
@regex = /\A(#{Regexp.escape(@prefix)})(.+?)(#{Regexp.escape(@suffix)})\z/
-
20
@method_missing_target = "#{@prefix}attribute#{@suffix}"
-
20
@method_name = "#{prefix}%s#{suffix}"
-
end
-
-
2
def match(method_name)
-
698
if @regex =~ method_name
-
76
AttributeMethodMatch.new(method_missing_target, $2, method_name)
-
else
-
nil
-
end
-
end
-
-
2
def method_name(attr_name)
-
1070
@method_name % attr_name
-
end
-
-
2
def plain?
-
760
prefix.empty? && suffix.empty?
-
end
-
end
-
end
-
-
# Allows access to the object attributes, which are held in the
-
# <tt>@attributes</tt> hash, as though they were first-class methods. So a
-
# Person class with a name attribute can use Person#name and Person#name=
-
# and never directly use the attributes hash -- except for multiple assigns
-
# with ActiveRecord#attributes=. A Milestone class can also ask
-
# Milestone#completed? to test that the completed attribute is not +nil+
-
# or 0.
-
#
-
# It's also possible to instantiate related objects, so a Client class
-
# belonging to the clients table with a +master_id+ foreign key can
-
# instantiate master through Client#master.
-
2
def method_missing(method, *args, &block)
-
if respond_to_without_attributes?(method, true)
-
super
-
else
-
match = match_attribute_method?(method.to_s)
-
match ? attribute_missing(match, *args, &block) : super
-
end
-
end
-
-
# attribute_missing is like method_missing, but for attributes. When method_missing is
-
# called we check to see if there is a matching attribute method. If so, we call
-
# attribute_missing to dispatch the attribute. This method can be overloaded to
-
# customise the behaviour.
-
2
def attribute_missing(match, *args, &block)
-
__send__(match.target, match.attr_name, *args, &block)
-
end
-
-
# A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
-
# <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
-
# which will all return +true+.
-
2
alias :respond_to_without_attributes? :respond_to?
-
2
def respond_to?(method, include_private_methods = false)
-
7543
if super
-
6865
true
-
678
elsif !include_private_methods && super(method, true)
-
# If we're here then we haven't found among non-private methods
-
# but found among all methods. Which means that the given method is private.
-
false
-
else
-
678
!match_attribute_method?(method.to_s).nil?
-
end
-
end
-
-
2
protected
-
2
def attribute_method?(attr_name)
-
respond_to_without_attributes?(:attributes) && attributes.include?(attr_name)
-
end
-
-
2
private
-
# Returns a struct representing the matching attribute method.
-
# The struct's attributes are prefix, base and suffix.
-
2
def match_attribute_method?(method_name)
-
678
match = self.class.send(:attribute_method_matcher, method_name)
-
678
match && attribute_method?(match.attr_name) ? match : nil
-
end
-
-
2
def missing_attribute(attr_name, stack)
-
raise ActiveModel::MissingAttributeError, "missing attribute: #{attr_name}", stack
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/callbacks'
-
-
2
module ActiveModel
-
# == Active Model Callbacks
-
#
-
# Provides an interface for any class to have Active Record like callbacks.
-
#
-
# Like the Active Record methods, the callback chain is aborted as soon as
-
# one of the methods in the chain returns false.
-
#
-
# First, extend ActiveModel::Callbacks from the class you are creating:
-
#
-
# class MyModel
-
# extend ActiveModel::Callbacks
-
# end
-
#
-
# Then define a list of methods that you want callbacks attached to:
-
#
-
# define_model_callbacks :create, :update
-
#
-
# This will provide all three standard callbacks (before, around and after) for
-
# both the :create and :update methods. To implement, you need to wrap the methods
-
# you want callbacks on in a block so that the callbacks get a chance to fire:
-
#
-
# def create
-
# run_callbacks :create do
-
# # Your create action methods here
-
# end
-
# end
-
#
-
# Then in your class, you can use the +before_create+, +after_create+ and +around_create+
-
# methods, just as you would in an Active Record module.
-
#
-
# before_create :action_before_create
-
#
-
# def action_before_create
-
# # Your code here
-
# end
-
#
-
# You can choose not to have all three callbacks by passing a hash to the
-
# define_model_callbacks method.
-
#
-
# define_model_callbacks :create, :only => [:after, :before]
-
#
-
# Would only create the after_create and before_create callback methods in your
-
# class.
-
2
module Callbacks
-
2
def self.extended(base)
-
2
base.class_eval do
-
2
include ActiveSupport::Callbacks
-
end
-
end
-
-
# define_model_callbacks accepts the same options define_callbacks does, in case
-
# you want to overwrite a default. Besides that, it also accepts an :only option,
-
# where you can choose if you want all types (before, around or after) or just some.
-
#
-
# define_model_callbacks :initializer, :only => :after
-
#
-
# Note, the <tt>:only => <type></tt> hash will apply to all callbacks defined on
-
# that method call. To get around this you can call the define_model_callbacks
-
# method as many times as you need.
-
#
-
# define_model_callbacks :create, :only => :after
-
# define_model_callbacks :update, :only => :before
-
# define_model_callbacks :destroy, :only => :around
-
#
-
# Would create +after_create+, +before_update+ and +around_destroy+ methods only.
-
#
-
# You can pass in a class to before_<type>, after_<type> and around_<type>, in which
-
# case the callback will call that class's <action>_<type> method passing the object
-
# that the callback is being called on.
-
#
-
# class MyModel
-
# extend ActiveModel::Callbacks
-
# define_model_callbacks :create
-
#
-
# before_create AnotherClass
-
# end
-
#
-
# class AnotherClass
-
# def self.before_create( obj )
-
# # obj is the MyModel instance that the callback is being called on
-
# end
-
# end
-
#
-
2
def define_model_callbacks(*callbacks)
-
4
options = callbacks.extract_options!
-
4
options = {
-
:terminator => "result == false",
-
:scope => [:kind, :name],
-
:only => [:before, :around, :after]
-
}.merge(options)
-
-
4
types = Array.wrap(options.delete(:only))
-
-
4
callbacks.each do |callback|
-
14
define_callbacks(callback, options)
-
-
14
types.each do |type|
-
30
send("_define_#{type}_model_callback", self, callback)
-
end
-
end
-
end
-
-
2
def _define_before_model_callback(klass, callback) #:nodoc:
-
8
klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1
-
def self.before_#{callback}(*args, &block)
-
set_callback(:#{callback}, :before, *args, &block)
-
end
-
CALLBACK
-
end
-
-
2
def _define_around_model_callback(klass, callback) #:nodoc:
-
8
klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1
-
def self.around_#{callback}(*args, &block)
-
set_callback(:#{callback}, :around, *args, &block)
-
end
-
CALLBACK
-
end
-
-
2
def _define_after_model_callback(klass, callback) #:nodoc:
-
14
klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1
-
def self.after_#{callback}(*args, &block)
-
options = args.extract_options!
-
options[:prepend] = true
-
options[:if] = Array.wrap(options[:if]) << "!halted && value != false"
-
set_callback(:#{callback}, :after, *(args << options), &block)
-
end
-
CALLBACK
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/inflector'
-
-
2
module ActiveModel
-
# == Active Model Conversions
-
#
-
# Handles default conversions: to_model, to_key, to_param, and to_partial_path.
-
#
-
# Let's take for example this non-persisted object.
-
#
-
# class ContactMessage
-
# include ActiveModel::Conversion
-
#
-
# # ContactMessage are never persisted in the DB
-
# def persisted?
-
# false
-
# end
-
# end
-
#
-
# cm = ContactMessage.new
-
# cm.to_model == self # => true
-
# cm.to_key # => nil
-
# cm.to_param # => nil
-
# cm.to_path # => "contact_messages/contact_message"
-
#
-
2
module Conversion
-
2
extend ActiveSupport::Concern
-
-
# If your object is already designed to implement all of the Active Model
-
# you can use the default <tt>:to_model</tt> implementation, which simply
-
# returns self.
-
#
-
# If your model does not act like an Active Model object, then you should
-
# define <tt>:to_model</tt> yourself returning a proxy object that wraps
-
# your object with Active Model compliant methods.
-
2
def to_model
-
self
-
end
-
-
# Returns an Enumerable of all key attributes if any is set, regardless
-
# if the object is persisted or not.
-
#
-
# Note the default implementation uses persisted? just because all objects
-
# in Ruby 1.8.x responds to <tt>:id</tt>.
-
2
def to_key
-
persisted? ? [id] : nil
-
end
-
-
# Returns a string representing the object's key suitable for use in URLs,
-
# or nil if <tt>persisted?</tt> is false.
-
2
def to_param
-
persisted? ? to_key.join('-') : nil
-
end
-
-
# Returns a string identifying the path associated with the object.
-
# ActionPack uses this to find a suitable partial to represent the object.
-
2
def to_partial_path
-
self.class._to_partial_path
-
end
-
-
2
module ClassMethods #:nodoc:
-
# Provide a class level cache for the to_path. This is an
-
# internal method and should not be accessed directly.
-
2
def _to_partial_path #:nodoc:
-
@_to_partial_path ||= begin
-
element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self))
-
collection = ActiveSupport::Inflector.tableize(self)
-
"#{collection}/#{element}".freeze
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_model/attribute_methods'
-
2
require 'active_support/hash_with_indifferent_access'
-
2
require 'active_support/core_ext/object/duplicable'
-
-
2
module ActiveModel
-
# == Active Model Dirty
-
#
-
# Provides a way to track changes in your object in the same way as
-
# Active Record does.
-
#
-
# The requirements for implementing ActiveModel::Dirty are:
-
#
-
# * <tt>include ActiveModel::Dirty</tt> in your object
-
# * Call <tt>define_attribute_methods</tt> passing each method you want to
-
# track
-
# * Call <tt>attr_name_will_change!</tt> before each change to the tracked
-
# attribute
-
#
-
# If you wish to also track previous changes on save or update, you need to
-
# add
-
#
-
# @previously_changed = changes
-
#
-
# inside of your save or update method.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
#
-
# include ActiveModel::Dirty
-
#
-
# define_attribute_methods [:name]
-
#
-
# def name
-
# @name
-
# end
-
#
-
# def name=(val)
-
# name_will_change! unless val == @name
-
# @name = val
-
# end
-
#
-
# def save
-
# @previously_changed = changes
-
# @changed_attributes.clear
-
# end
-
#
-
# end
-
#
-
# == Examples:
-
#
-
# A newly instantiated object is unchanged:
-
# person = Person.find_by_name('Uncle Bob')
-
# person.changed? # => false
-
#
-
# Change the name:
-
# person.name = 'Bob'
-
# person.changed? # => true
-
# person.name_changed? # => true
-
# person.name_was # => 'Uncle Bob'
-
# person.name_change # => ['Uncle Bob', 'Bob']
-
# person.name = 'Bill'
-
# person.name_change # => ['Uncle Bob', 'Bill']
-
#
-
# Save the changes:
-
# person.save
-
# person.changed? # => false
-
# person.name_changed? # => false
-
#
-
# Assigning the same value leaves the attribute unchanged:
-
# person.name = 'Bill'
-
# person.name_changed? # => false
-
# person.name_change # => nil
-
#
-
# Which attributes have changed?
-
# person.name = 'Bob'
-
# person.changed # => ['name']
-
# person.changes # => { 'name' => ['Bill', 'Bob'] }
-
#
-
# If an attribute is modified in-place then make use of <tt>[attribute_name]_will_change!</tt>
-
# to mark that the attribute is changing. Otherwise ActiveModel can't track changes to
-
# in-place attributes.
-
#
-
# person.name_will_change!
-
# person.name << 'y'
-
# person.name_change # => ['Bill', 'Billy']
-
2
module Dirty
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::AttributeMethods
-
-
2
included do
-
2
attribute_method_suffix '_changed?', '_change', '_will_change!', '_was'
-
2
attribute_method_affix :prefix => 'reset_', :suffix => '!'
-
end
-
-
# Returns true if any attribute have unsaved changes, false otherwise.
-
# person.changed? # => false
-
# person.name = 'bob'
-
# person.changed? # => true
-
2
def changed?
-
58
changed_attributes.any?
-
end
-
-
# List of attributes with unsaved changes.
-
# person.changed # => []
-
# person.name = 'bob'
-
# person.changed # => ['name']
-
2
def changed
-
423
changed_attributes.keys
-
end
-
-
# Map of changed attrs => [original value, new value].
-
# person.changes # => {}
-
# person.name = 'bob'
-
# person.changes # => { 'name' => ['bill', 'bob'] }
-
2
def changes
-
3418
HashWithIndifferentAccess[changed.map { |attr| [attr, attribute_change(attr)] }]
-
end
-
-
# Map of attributes that were changed when the model was saved.
-
# person.name # => 'bob'
-
# person.name = 'robert'
-
# person.save
-
# person.previous_changes # => {'name' => ['bob, 'robert']}
-
2
def previous_changes
-
@previously_changed
-
end
-
-
# Map of change <tt>attr => original value</tt>.
-
2
def changed_attributes
-
11241
@changed_attributes ||= {}
-
end
-
-
2
private
-
-
# Handle <tt>*_changed?</tt> for +method_missing+.
-
2
def attribute_changed?(attr)
-
7139
changed_attributes.include?(attr)
-
end
-
-
# Handle <tt>*_change</tt> for +method_missing+.
-
2
def attribute_change(attr)
-
3055
[changed_attributes[attr], __send__(attr)] if attribute_changed?(attr)
-
end
-
-
# Handle <tt>*_was</tt> for +method_missing+.
-
2
def attribute_was(attr)
-
attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
-
end
-
-
# Handle <tt>*_will_change!</tt> for +method_missing+.
-
2
def attribute_will_change!(attr)
-
566
begin
-
566
value = __send__(attr)
-
566
value = value.duplicable? ? value.clone : value
-
rescue TypeError, NoMethodError
-
end
-
-
566
changed_attributes[attr] = value unless changed_attributes.include?(attr)
-
end
-
-
# Handle <tt>reset_*!</tt> for +method_missing+.
-
2
def reset_attribute!(attr)
-
__send__("#{attr}=", changed_attributes[attr]) if attribute_changed?(attr)
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/array/conversions'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
2
require 'active_support/ordered_hash'
-
-
2
module ActiveModel
-
# == Active Model Errors
-
#
-
# Provides a modified +OrderedHash+ that you can include in your object
-
# for handling error messages and interacting with Action Pack helpers.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
#
-
# # Required dependency for ActiveModel::Errors
-
# extend ActiveModel::Naming
-
#
-
# def initialize
-
# @errors = ActiveModel::Errors.new(self)
-
# end
-
#
-
# attr_accessor :name
-
# attr_reader :errors
-
#
-
# def validate!
-
# errors.add(:name, "can not be nil") if name == nil
-
# end
-
#
-
# # The following methods are needed to be minimally implemented
-
#
-
# def read_attribute_for_validation(attr)
-
# send(attr)
-
# end
-
#
-
# def Person.human_attribute_name(attr, options = {})
-
# attr
-
# end
-
#
-
# def Person.lookup_ancestors
-
# [self]
-
# end
-
#
-
# end
-
#
-
# The last three methods are required in your object for Errors to be
-
# able to generate error messages correctly and also handle multiple
-
# languages. Of course, if you extend your object with ActiveModel::Translation
-
# you will not need to implement the last two. Likewise, using
-
# ActiveModel::Validations will handle the validation related methods
-
# for you.
-
#
-
# The above allows you to do:
-
#
-
# p = Person.new
-
# p.validate! # => ["can not be nil"]
-
# p.errors.full_messages # => ["name can not be nil"]
-
# # etc..
-
2
class Errors
-
2
include Enumerable
-
-
2
CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict]
-
-
2
attr_reader :messages
-
-
# Pass in the instance of the object that is using the errors object.
-
#
-
# class Person
-
# def initialize
-
# @errors = ActiveModel::Errors.new(self)
-
# end
-
# end
-
2
def initialize(base)
-
331
@base = base
-
331
@messages = ActiveSupport::OrderedHash.new
-
end
-
-
2
def initialize_dup(other)
-
@messages = other.messages.dup
-
end
-
-
# Backport dup from 1.9 so that #initialize_dup gets called
-
2
unless Object.respond_to?(:initialize_dup, true)
-
def dup # :nodoc:
-
copy = super
-
copy.initialize_dup(self)
-
copy
-
end
-
end
-
-
# Clear the messages
-
2
def clear
-
359
messages.clear
-
end
-
-
# Do the error messages include an error with key +error+?
-
2
def include?(error)
-
(v = messages[error]) && v.any?
-
end
-
2
alias :has_key? :include?
-
-
# Get messages for +key+
-
2
def get(key)
-
116
messages[key]
-
end
-
-
# Set messages for +key+ to +value+
-
2
def set(key, value)
-
32
messages[key] = value
-
end
-
-
# Delete messages for +key+
-
2
def delete(key)
-
messages.delete(key)
-
end
-
-
# When passed a symbol or a name of a method, returns an array of errors
-
# for the method.
-
#
-
# p.errors[:name] # => ["can not be nil"]
-
# p.errors['name'] # => ["can not be nil"]
-
2
def [](attribute)
-
112
get(attribute.to_sym) || set(attribute.to_sym, [])
-
end
-
-
# Adds to the supplied attribute the supplied error message.
-
#
-
# p.errors[:name] = "must be set"
-
# p.errors[:name] # => ['must be set']
-
2
def []=(attribute, error)
-
self[attribute] << error
-
end
-
-
# Iterates through each error key, value pair in the error messages hash.
-
# Yields the attribute and the error for that attribute. If the attribute
-
# has more than one error message, yields once for each error message.
-
#
-
# p.errors.add(:name, "can't be blank")
-
# p.errors.each do |attribute, errors_array|
-
# # Will yield :name and "can't be blank"
-
# end
-
#
-
# p.errors.add(:name, "must be specified")
-
# p.errors.each do |attribute, errors_array|
-
# # Will yield :name and "can't be blank"
-
# # then yield :name and "must be specified"
-
# end
-
2
def each
-
718
messages.each_key do |attribute|
-
128
self[attribute].each { |error| yield attribute, error }
-
end
-
end
-
-
# Returns the number of error messages.
-
#
-
# p.errors.add(:name, "can't be blank")
-
# p.errors.size # => 1
-
# p.errors.add(:name, "must be specified")
-
# p.errors.size # => 2
-
2
def size
-
values.flatten.size
-
end
-
-
# Returns all message values
-
2
def values
-
messages.values
-
end
-
-
# Returns all message keys
-
2
def keys
-
messages.keys
-
end
-
-
# Returns an array of error messages, with the attribute name included
-
#
-
# p.errors.add(:name, "can't be blank")
-
# p.errors.add(:name, "must be specified")
-
# p.errors.to_a # => ["name can't be blank", "name must be specified"]
-
2
def to_a
-
full_messages
-
end
-
-
# Returns the number of error messages.
-
# p.errors.add(:name, "can't be blank")
-
# p.errors.count # => 1
-
# p.errors.add(:name, "must be specified")
-
# p.errors.count # => 2
-
2
def count
-
to_a.size
-
end
-
-
# Returns true if no errors are found, false otherwise.
-
# If the error message is a string it can be empty.
-
2
def empty?
-
782
all? { |k, v| v && v.empty? && !v.is_a?(String) }
-
end
-
2
alias_method :blank?, :empty?
-
-
# Returns an xml formatted representation of the Errors hash.
-
#
-
# p.errors.add(:name, "can't be blank")
-
# p.errors.add(:name, "must be specified")
-
# p.errors.to_xml
-
# # =>
-
# # <?xml version=\"1.0\" encoding=\"UTF-8\"?>
-
# # <errors>
-
# # <error>name can't be blank</error>
-
# # <error>name must be specified</error>
-
# # </errors>
-
2
def to_xml(options={})
-
to_a.to_xml options.reverse_merge(:root => "errors", :skip_types => true)
-
end
-
-
# Returns an ActiveSupport::OrderedHash that can be used as the JSON representation for this object.
-
2
def as_json(options=nil)
-
to_hash
-
end
-
-
2
def to_hash
-
messages.dup
-
end
-
-
# Adds +message+ to the error messages on +attribute+. More than one error can be added to the same
-
# +attribute+.
-
# If no +message+ is supplied, <tt>:invalid</tt> is assumed.
-
#
-
# If +message+ is a symbol, it will be translated using the appropriate scope (see +translate_error+).
-
# If +message+ is a proc, it will be called, allowing for things like <tt>Time.now</tt> to be used within an error.
-
2
def add(attribute, message = nil, options = {})
-
48
message = normalize_message(attribute, message, options)
-
48
if options[:strict]
-
raise ActiveModel::StrictValidationFailed, full_message(attribute, message)
-
end
-
-
48
self[attribute] << message
-
end
-
-
# Will add an error message to each of the attributes in +attributes+ that is empty.
-
2
def add_on_empty(attributes, options = {})
-
[attributes].flatten.each do |attribute|
-
value = @base.send(:read_attribute_for_validation, attribute)
-
is_empty = value.respond_to?(:empty?) ? value.empty? : false
-
add(attribute, :empty, options) if value.nil? || is_empty
-
end
-
end
-
-
# Will add an error message to each of the attributes in +attributes+ that is blank (using Object#blank?).
-
2
def add_on_blank(attributes, options = {})
-
[attributes].flatten.each do |attribute|
-
value = @base.send(:read_attribute_for_validation, attribute)
-
add(attribute, :blank, options) if value.blank?
-
end
-
end
-
-
# Returns true if an error on the attribute with the given message is present, false otherwise.
-
# +message+ is treated the same as for +add+.
-
# p.errors.add :name, :blank
-
# p.errors.added? :name, :blank # => true
-
2
def added?(attribute, message = nil, options = {})
-
message = normalize_message(attribute, message, options)
-
self[attribute].include? message
-
end
-
-
# Returns all the full error messages in an array.
-
#
-
# class Company
-
# validates_presence_of :name, :address, :email
-
# validates_length_of :name, :in => 5..30
-
# end
-
#
-
# company = Company.create(:address => '123 First St.')
-
# company.errors.full_messages # =>
-
# ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Email can't be blank"]
-
2
def full_messages
-
map { |attribute, message| full_message(attribute, message) }
-
end
-
-
# Returns a full message for a given attribute.
-
#
-
# company.errors.full_message(:name, "is invalid") # =>
-
# "Name is invalid"
-
2
def full_message(attribute, message)
-
return message if attribute == :base
-
attr_name = attribute.to_s.gsub('.', '_').humanize
-
attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
-
I18n.t(:"errors.format", {
-
:default => "%{attribute} %{message}",
-
:attribute => attr_name,
-
:message => message
-
})
-
end
-
-
# Translates an error message in its default scope
-
# (<tt>activemodel.errors.messages</tt>).
-
#
-
# Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>,
-
# if it's not there, it's looked up in <tt>models.MODEL.MESSAGE</tt> and if that is not
-
# there also, it returns the translation of the default message
-
# (e.g. <tt>activemodel.errors.messages.MESSAGE</tt>). The translated model name,
-
# translated attribute name and the value are available for interpolation.
-
#
-
# When using inheritance in your models, it will check all the inherited
-
# models too, but only if the model itself hasn't been found. Say you have
-
# <tt>class Admin < User; end</tt> and you wanted the translation for
-
# the <tt>:blank</tt> error message for the <tt>title</tt> attribute,
-
# it looks for these translations:
-
#
-
# * <tt>activemodel.errors.models.admin.attributes.title.blank</tt>
-
# * <tt>activemodel.errors.models.admin.blank</tt>
-
# * <tt>activemodel.errors.models.user.attributes.title.blank</tt>
-
# * <tt>activemodel.errors.models.user.blank</tt>
-
# * any default you provided through the +options+ hash (in the <tt>activemodel.errors</tt> scope)
-
# * <tt>activemodel.errors.messages.blank</tt>
-
# * <tt>errors.attributes.title.blank</tt>
-
# * <tt>errors.messages.blank</tt>
-
#
-
2
def generate_message(attribute, type = :invalid, options = {})
-
type = options.delete(:message) if options[:message].is_a?(Symbol)
-
-
if @base.class.respond_to?(:i18n_scope)
-
defaults = @base.class.lookup_ancestors.map do |klass|
-
[ :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}",
-
:"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ]
-
end
-
else
-
defaults = []
-
end
-
-
defaults << options.delete(:message)
-
defaults << :"#{@base.class.i18n_scope}.errors.messages.#{type}" if @base.class.respond_to?(:i18n_scope)
-
defaults << :"errors.attributes.#{attribute}.#{type}"
-
defaults << :"errors.messages.#{type}"
-
-
defaults.compact!
-
defaults.flatten!
-
-
key = defaults.shift
-
value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil)
-
-
options = {
-
:default => defaults,
-
:model => @base.class.model_name.human,
-
:attribute => @base.class.human_attribute_name(attribute),
-
:value => value
-
}.merge(options)
-
-
I18n.translate(key, options)
-
end
-
-
2
private
-
2
def normalize_message(attribute, message, options)
-
48
message ||= :invalid
-
-
48
if message.is_a?(Symbol)
-
generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS))
-
48
elsif message.is_a?(Proc)
-
message.call
-
else
-
48
message
-
end
-
end
-
end
-
-
2
class StrictValidationFailed < StandardError
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_model/mass_assignment_security/permission_set'
-
2
require 'active_model/mass_assignment_security/sanitizer'
-
-
2
module ActiveModel
-
# = Active Model Mass-Assignment Security
-
2
module MassAssignmentSecurity
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :_accessible_attributes
-
2
class_attribute :_protected_attributes
-
2
class_attribute :_active_authorizer
-
-
2
class_attribute :_mass_assignment_sanitizer
-
2
self.mass_assignment_sanitizer = :logger
-
end
-
-
# Mass assignment security provides an interface for protecting attributes
-
# from end-user assignment. For more complex permissions, mass assignment security
-
# may be handled outside the model by extending a non-ActiveRecord class,
-
# such as a controller, with this behavior.
-
#
-
# For example, a logged in user may need to assign additional attributes depending
-
# on their role:
-
#
-
# class AccountsController < ApplicationController
-
# include ActiveModel::MassAssignmentSecurity
-
#
-
# attr_accessible :first_name, :last_name
-
# attr_accessible :first_name, :last_name, :plan_id, :as => :admin
-
#
-
# def update
-
# ...
-
# @account.update_attributes(account_params)
-
# ...
-
# end
-
#
-
# protected
-
#
-
# def account_params
-
# role = admin ? :admin : :default
-
# sanitize_for_mass_assignment(params[:account], role)
-
# end
-
#
-
# end
-
#
-
# = Configuration options
-
#
-
# * <tt>mass_assignment_sanitizer</tt> - Defines sanitize method. Possible values are:
-
# * <tt>:logger</tt> (default) - writes filtered attributes to logger
-
# * <tt>:strict</tt> - raise <tt>ActiveModel::MassAssignmentSecurity::Error</tt> on any protected attribute update
-
#
-
# You can specify your own sanitizer object eg. MySanitizer.new.
-
# See <tt>ActiveModel::MassAssignmentSecurity::LoggerSanitizer</tt> for example implementation.
-
#
-
#
-
2
module ClassMethods
-
# Attributes named in this macro are protected from mass-assignment
-
# whenever attributes are sanitized before assignment. A role for the
-
# attributes is optional, if no role is provided then :default is used.
-
# A role can be defined by using the :as option.
-
#
-
# Mass-assignment to these attributes will simply be ignored, to assign
-
# to them you can use direct writer methods. This is meant to protect
-
# sensitive attributes from being overwritten by malicious users
-
# tampering with URLs or forms. Example:
-
#
-
# class Customer
-
# include ActiveModel::MassAssignmentSecurity
-
#
-
# attr_accessor :name, :credit_rating
-
#
-
# attr_protected :credit_rating, :last_login
-
# attr_protected :last_login, :as => :admin
-
#
-
# def assign_attributes(values, options = {})
-
# sanitize_for_mass_assignment(values, options[:as]).each do |k, v|
-
# send("#{k}=", v)
-
# end
-
# end
-
# end
-
#
-
# When using the :default role:
-
#
-
# customer = Customer.new
-
# customer.assign_attributes({ "name" => "David", "credit_rating" => "Excellent", :last_login => 1.day.ago }, :as => :default)
-
# customer.name # => "David"
-
# customer.credit_rating # => nil
-
# customer.last_login # => nil
-
#
-
# customer.credit_rating = "Average"
-
# customer.credit_rating # => "Average"
-
#
-
# And using the :admin role:
-
#
-
# customer = Customer.new
-
# customer.assign_attributes({ "name" => "David", "credit_rating" => "Excellent", :last_login => 1.day.ago }, :as => :admin)
-
# customer.name # => "David"
-
# customer.credit_rating # => "Excellent"
-
# customer.last_login # => nil
-
#
-
# To start from an all-closed default and enable attributes as needed,
-
# have a look at +attr_accessible+.
-
#
-
# Note that using <tt>Hash#except</tt> or <tt>Hash#slice</tt> in place of
-
# +attr_protected+ to sanitize attributes provides basically the same
-
# functionality, but it makes a bit tricky to deal with nested attributes.
-
2
def attr_protected(*args)
-
options = args.extract_options!
-
role = options[:as] || :default
-
-
self._protected_attributes = protected_attributes_configs.dup
-
-
Array.wrap(role).each do |name|
-
self._protected_attributes[name] = self.protected_attributes(name) + args
-
end
-
-
self._active_authorizer = self._protected_attributes
-
end
-
-
# Specifies a white list of model attributes that can be set via
-
# mass-assignment.
-
#
-
# Like +attr_protected+, a role for the attributes is optional,
-
# if no role is provided then :default is used. A role can be defined by
-
# using the :as option.
-
#
-
# This is the opposite of the +attr_protected+ macro: Mass-assignment
-
# will only set attributes in this list, to assign to the rest of
-
# attributes you can use direct writer methods. This is meant to protect
-
# sensitive attributes from being overwritten by malicious users
-
# tampering with URLs or forms. If you'd rather start from an all-open
-
# default and restrict attributes as needed, have a look at
-
# +attr_protected+.
-
#
-
# class Customer
-
# include ActiveModel::MassAssignmentSecurity
-
#
-
# attr_accessor :name, :credit_rating
-
#
-
# attr_accessible :name
-
# attr_accessible :name, :credit_rating, :as => :admin
-
#
-
# def assign_attributes(values, options = {})
-
# sanitize_for_mass_assignment(values, options[:as]).each do |k, v|
-
# send("#{k}=", v)
-
# end
-
# end
-
# end
-
#
-
# When using the :default role:
-
#
-
# customer = Customer.new
-
# customer.assign_attributes({ "name" => "David", "credit_rating" => "Excellent", :last_login => 1.day.ago }, :as => :default)
-
# customer.name # => "David"
-
# customer.credit_rating # => nil
-
#
-
# customer.credit_rating = "Average"
-
# customer.credit_rating # => "Average"
-
#
-
# And using the :admin role:
-
#
-
# customer = Customer.new
-
# customer.assign_attributes({ "name" => "David", "credit_rating" => "Excellent", :last_login => 1.day.ago }, :as => :admin)
-
# customer.name # => "David"
-
# customer.credit_rating # => "Excellent"
-
#
-
# Note that using <tt>Hash#except</tt> or <tt>Hash#slice</tt> in place of
-
# +attr_accessible+ to sanitize attributes provides basically the same
-
# functionality, but it makes a bit tricky to deal with nested attributes.
-
2
def attr_accessible(*args)
-
32
options = args.extract_options!
-
32
role = options[:as] || :default
-
-
32
self._accessible_attributes = accessible_attributes_configs.dup
-
-
32
Array.wrap(role).each do |name|
-
32
self._accessible_attributes[name] = self.accessible_attributes(name) + args
-
end
-
-
32
self._active_authorizer = self._accessible_attributes
-
end
-
-
2
def protected_attributes(role = :default)
-
protected_attributes_configs[role]
-
end
-
-
2
def accessible_attributes(role = :default)
-
64
accessible_attributes_configs[role]
-
end
-
-
2
def active_authorizers
-
334
self._active_authorizer ||= protected_attributes_configs
-
end
-
2
alias active_authorizer active_authorizers
-
-
2
def attributes_protected_by_default
-
[]
-
end
-
-
2
def mass_assignment_sanitizer=(value)
-
4
self._mass_assignment_sanitizer = if value.is_a?(Symbol)
-
4
const_get(:"#{value.to_s.camelize}Sanitizer").new(self)
-
else
-
value
-
end
-
end
-
-
2
private
-
-
2
def protected_attributes_configs
-
self._protected_attributes ||= begin
-
Hash.new { |h,k| h[k] = BlackList.new(attributes_protected_by_default) }
-
end
-
end
-
-
2
def accessible_attributes_configs
-
96
self._accessible_attributes ||= begin
-
4
Hash.new { |h,k| h[k] = WhiteList.new }
-
end
-
end
-
end
-
-
2
protected
-
-
2
def sanitize_for_mass_assignment(attributes, role = nil)
-
334
_mass_assignment_sanitizer.sanitize(attributes, mass_assignment_authorizer(role))
-
end
-
-
2
def mass_assignment_authorizer(role)
-
334
self.class.active_authorizer[role || :default]
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module ActiveModel
-
2
module MassAssignmentSecurity
-
2
class PermissionSet < Set
-
-
2
def +(values)
-
32
super(values.map(&:to_s))
-
end
-
-
2
def include?(key)
-
2273
super(remove_multiparameter_id(key))
-
end
-
-
2
def deny?(key)
-
raise NotImplementedError, "#deny?(key) suppose to be overwritten"
-
end
-
-
2
protected
-
-
2
def remove_multiparameter_id(key)
-
2273
key.to_s.gsub(/\(.+/m, '')
-
end
-
end
-
-
2
class WhiteList < PermissionSet
-
-
2
def deny?(key)
-
2273
!include?(key)
-
end
-
end
-
-
2
class BlackList < PermissionSet
-
-
2
def deny?(key)
-
include?(key)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/delegation'
-
-
2
module ActiveModel
-
2
module MassAssignmentSecurity
-
2
class Sanitizer
-
2
def initialize(target=nil)
-
end
-
-
# Returns all attributes not denied by the authorizer.
-
2
def sanitize(attributes, authorizer)
-
2607
sanitized_attributes = attributes.reject { |key, value| authorizer.deny?(key) }
-
334
debug_protected_attribute_removal(attributes, sanitized_attributes)
-
334
sanitized_attributes
-
end
-
-
2
protected
-
-
2
def debug_protected_attribute_removal(attributes, sanitized_attributes)
-
334
removed_keys = attributes.keys - sanitized_attributes.keys
-
334
process_removed_attributes(removed_keys) if removed_keys.any?
-
end
-
-
2
def process_removed_attributes(attrs)
-
raise NotImplementedError, "#process_removed_attributes(attrs) suppose to be overwritten"
-
end
-
end
-
-
2
class LoggerSanitizer < Sanitizer
-
2
delegate :logger, :to => :@target
-
-
2
def initialize(target)
-
2
@target = target
-
2
super
-
end
-
-
2
def logger?
-
@target.respond_to?(:logger) && @target.logger
-
end
-
-
2
def process_removed_attributes(attrs)
-
logger.debug "WARNING: Can't mass-assign protected attributes: #{attrs.join(', ')}" if logger?
-
end
-
end
-
-
2
class StrictSanitizer < Sanitizer
-
2
def process_removed_attributes(attrs)
-
return if (attrs - insensitive_attributes).empty?
-
raise ActiveModel::MassAssignmentSecurity::Error, "Can't mass-assign protected attributes: #{attrs.join(', ')}"
-
end
-
-
2
def insensitive_attributes
-
['id']
-
end
-
end
-
-
2
class Error < StandardError
-
end
-
end
-
end
-
2
require 'active_support/inflector'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/module/introspection'
-
2
require 'active_support/deprecation'
-
-
2
module ActiveModel
-
2
class Name < String
-
2
attr_reader :singular, :plural, :element, :collection, :partial_path,
-
:singular_route_key, :route_key, :param_key, :i18n_key
-
-
2
alias_method :cache_key, :collection
-
-
2
deprecate :partial_path => "ActiveModel::Name#partial_path is deprecated. Call #to_partial_path on model instances directly instead."
-
-
2
def initialize(klass, namespace = nil, name = nil)
-
name ||= klass.name
-
-
raise ArgumentError, "Class name cannot be blank. You need to supply a name argument when anonymous class given" if name.blank?
-
-
super(name)
-
-
@unnamespaced = self.sub(/^#{namespace.name}::/, '') if namespace
-
@klass = klass
-
@singular = _singularize(self).freeze
-
@plural = ActiveSupport::Inflector.pluralize(@singular).freeze
-
@element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self)).freeze
-
@human = ActiveSupport::Inflector.humanize(@element).freeze
-
@collection = ActiveSupport::Inflector.tableize(self).freeze
-
@partial_path = "#{@collection}/#{@element}".freeze
-
@param_key = (namespace ? _singularize(@unnamespaced) : @singular).freeze
-
@i18n_key = self.underscore.to_sym
-
-
@route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key) : @plural.dup)
-
@singular_route_key = ActiveSupport::Inflector.singularize(@route_key).freeze
-
@route_key << "_index" if @plural == @singular
-
@route_key.freeze
-
end
-
-
# Transform the model name into a more humane format, using I18n. By default,
-
# it will underscore then humanize the class name
-
#
-
# BlogPost.model_name.human # => "Blog post"
-
#
-
# Specify +options+ with additional translating options.
-
2
def human(options={})
-
return @human unless @klass.respond_to?(:lookup_ancestors) &&
-
@klass.respond_to?(:i18n_scope)
-
-
defaults = @klass.lookup_ancestors.map do |klass|
-
klass.model_name.i18n_key
-
end
-
-
defaults << options[:default] if options[:default]
-
defaults << @human
-
-
options = {:scope => [@klass.i18n_scope, :models], :count => 1, :default => defaults}.merge(options.except(:default))
-
I18n.translate(defaults.shift, options)
-
end
-
-
2
private
-
-
2
def _singularize(string, replacement='_')
-
ActiveSupport::Inflector.underscore(string).tr('/', replacement)
-
end
-
end
-
-
# == Active Model Naming
-
#
-
# Creates a +model_name+ method on your object.
-
#
-
# To implement, just extend ActiveModel::Naming in your object:
-
#
-
# class BookCover
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BookCover.model_name # => "BookCover"
-
# BookCover.model_name.human # => "Book cover"
-
#
-
# BookCover.model_name.i18n_key # => :book_cover
-
# BookModule::BookCover.model_name.i18n_key # => :"book_module/book_cover"
-
#
-
# Providing the functionality that ActiveModel::Naming provides in your object
-
# is required to pass the Active Model Lint test. So either extending the provided
-
# method below, or rolling your own is required.
-
2
module Naming
-
# Returns an ActiveModel::Name object for module. It can be
-
# used to retrieve all kinds of naming-related information.
-
2
def model_name
-
@_model_name ||= begin
-
namespace = self.parents.detect do |n|
-
n.respond_to?(:use_relative_model_naming?) && n.use_relative_model_naming?
-
end
-
ActiveModel::Name.new(self, namespace)
-
end
-
end
-
-
# Returns the plural class name of a record or class. Examples:
-
#
-
# ActiveModel::Naming.plural(post) # => "posts"
-
# ActiveModel::Naming.plural(Highrise::Person) # => "highrise_people"
-
2
def self.plural(record_or_class)
-
model_name_from_record_or_class(record_or_class).plural
-
end
-
-
# Returns the singular class name of a record or class. Examples:
-
#
-
# ActiveModel::Naming.singular(post) # => "post"
-
# ActiveModel::Naming.singular(Highrise::Person) # => "highrise_person"
-
2
def self.singular(record_or_class)
-
model_name_from_record_or_class(record_or_class).singular
-
end
-
-
# Identifies whether the class name of a record or class is uncountable. Examples:
-
#
-
# ActiveModel::Naming.uncountable?(Sheep) # => true
-
# ActiveModel::Naming.uncountable?(Post) => false
-
2
def self.uncountable?(record_or_class)
-
plural(record_or_class) == singular(record_or_class)
-
end
-
-
# Returns string to use while generating route names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# For isolated engine:
-
# ActiveModel::Naming.route_key(Blog::Post) #=> post
-
#
-
# For shared engine:
-
# ActiveModel::Naming.route_key(Blog::Post) #=> blog_post
-
2
def self.singular_route_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).singular_route_key
-
end
-
-
# Returns string to use while generating route names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# For isolated engine:
-
# ActiveModel::Naming.route_key(Blog::Post) #=> posts
-
#
-
# For shared engine:
-
# ActiveModel::Naming.route_key(Blog::Post) #=> blog_posts
-
#
-
# The route key also considers if the noun is uncountable and, in
-
# such cases, automatically appends _index.
-
2
def self.route_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).route_key
-
end
-
-
# Returns string to use for params names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# For isolated engine:
-
# ActiveModel::Naming.param_key(Blog::Post) #=> post
-
#
-
# For shared engine:
-
# ActiveModel::Naming.param_key(Blog::Post) #=> blog_post
-
2
def self.param_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).param_key
-
end
-
-
2
private
-
2
def self.model_name_from_record_or_class(record_or_class)
-
(record_or_class.is_a?(Class) ? record_or_class : convert_to_model(record_or_class).class).model_name
-
end
-
-
2
def self.convert_to_model(object)
-
object.respond_to?(:to_model) ? object.to_model : object
-
end
-
end
-
-
end
-
2
require 'set'
-
-
2
module ActiveModel
-
# Stores the enabled/disabled state of individual observers for
-
# a particular model class.
-
2
class ObserverArray < Array
-
2
attr_reader :model_class
-
2
def initialize(model_class, *args)
-
2
@model_class = model_class
-
2
super(*args)
-
end
-
-
# Returns true if the given observer is disabled for the model class.
-
2
def disabled_for?(observer)
-
disabled_observers.include?(observer.class)
-
end
-
-
# Disables one or more observers. This supports multiple forms:
-
#
-
# ORM.observers.disable :user_observer
-
# # => disables the UserObserver
-
#
-
# User.observers.disable AuditTrail
-
# # => disables the AuditTrail observer for User notifications.
-
# # Other models will still notify the AuditTrail observer.
-
#
-
# ORM.observers.disable :observer_1, :observer_2
-
# # => disables Observer1 and Observer2 for all models.
-
#
-
# ORM.observers.disable :all
-
# # => disables all observers for all models.
-
#
-
# User.observers.disable :all do
-
# # all user observers are disabled for
-
# # just the duration of the block
-
# end
-
2
def disable(*observers, &block)
-
set_enablement(false, observers, &block)
-
end
-
-
# Enables one or more observers. This supports multiple forms:
-
#
-
# ORM.observers.enable :user_observer
-
# # => enables the UserObserver
-
#
-
# User.observers.enable AuditTrail
-
# # => enables the AuditTrail observer for User notifications.
-
# # Other models will not be affected (i.e. they will not
-
# # trigger notifications to AuditTrail if previously disabled)
-
#
-
# ORM.observers.enable :observer_1, :observer_2
-
# # => enables Observer1 and Observer2 for all models.
-
#
-
# ORM.observers.enable :all
-
# # => enables all observers for all models.
-
#
-
# User.observers.enable :all do
-
# # all user observers are enabled for
-
# # just the duration of the block
-
# end
-
#
-
# Note: all observers are enabled by default. This method is only
-
# useful when you have previously disabled one or more observers.
-
2
def enable(*observers, &block)
-
set_enablement(true, observers, &block)
-
end
-
-
2
protected
-
-
2
def disabled_observers
-
@disabled_observers ||= Set.new
-
end
-
-
2
def observer_class_for(observer)
-
return observer if observer.is_a?(Class)
-
-
if observer.respond_to?(:to_sym) # string/symbol
-
observer.to_s.camelize.constantize
-
else
-
raise ArgumentError, "#{observer} was not a class or a " +
-
"lowercase, underscored class name as expected."
-
end
-
end
-
-
2
def start_transaction
-
disabled_observer_stack.push(disabled_observers.dup)
-
each_subclass_array do |array|
-
array.start_transaction
-
end
-
end
-
-
2
def disabled_observer_stack
-
@disabled_observer_stack ||= []
-
end
-
-
2
def end_transaction
-
@disabled_observers = disabled_observer_stack.pop
-
each_subclass_array do |array|
-
array.end_transaction
-
end
-
end
-
-
2
def transaction
-
start_transaction
-
-
begin
-
yield
-
ensure
-
end_transaction
-
end
-
end
-
-
2
def each_subclass_array
-
model_class.descendants.each do |subclass|
-
yield subclass.observers
-
end
-
end
-
-
2
def set_enablement(enabled, observers)
-
if block_given?
-
transaction do
-
set_enablement(enabled, observers)
-
yield
-
end
-
else
-
observers = ActiveModel::Observer.descendants if observers == [:all]
-
observers.each do |obs|
-
klass = observer_class_for(obs)
-
-
unless klass < ActiveModel::Observer
-
raise ArgumentError.new("#{obs} does not refer to a valid observer")
-
end
-
-
if enabled
-
disabled_observers.delete(klass)
-
else
-
disabled_observers << klass
-
end
-
end
-
-
each_subclass_array do |array|
-
array.set_enablement(enabled, observers)
-
end
-
end
-
end
-
end
-
end
-
2
require 'singleton'
-
2
require 'active_model/observer_array'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/module/aliasing'
-
2
require 'active_support/core_ext/module/remove_method'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/core_ext/enumerable'
-
2
require 'active_support/descendants_tracker'
-
-
2
module ActiveModel
-
2
module Observing
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
extend ActiveSupport::DescendantsTracker
-
end
-
-
2
module ClassMethods
-
# == Active Model Observers Activation
-
#
-
# Activates the observers assigned. Examples:
-
#
-
# class ORM
-
# include ActiveModel::Observing
-
# end
-
#
-
# # Calls PersonObserver.instance
-
# ORM.observers = :person_observer
-
#
-
# # Calls Cacher.instance and GarbageCollector.instance
-
# ORM.observers = :cacher, :garbage_collector
-
#
-
# # Same as above, just using explicit class references
-
# ORM.observers = Cacher, GarbageCollector
-
#
-
# Note: Setting this does not instantiate the observers yet.
-
# +instantiate_observers+ is called during startup, and before
-
# each development request.
-
2
def observers=(*values)
-
observers.replace(values.flatten)
-
end
-
-
# Gets an array of observers observing this model.
-
# The array also provides +enable+ and +disable+ methods
-
# that allow you to selectively enable and disable observers.
-
# (see <tt>ActiveModel::ObserverArray.enable</tt> and
-
# <tt>ActiveModel::ObserverArray.disable</tt> for more on this)
-
2
def observers
-
2
@observers ||= ObserverArray.new(self)
-
end
-
-
# Gets the current observer instances.
-
2
def observer_instances
-
22
@observer_instances ||= []
-
end
-
-
# Instantiate the global observers.
-
2
def instantiate_observers
-
2
observers.each { |o| instantiate_observer(o) }
-
end
-
-
# Add a new observer to the pool.
-
# The new observer needs to respond to 'update', otherwise it
-
# raises an +ArgumentError+ exception.
-
2
def add_observer(observer)
-
unless observer.respond_to? :update
-
raise ArgumentError, "observer needs to respond to `update'"
-
end
-
observer_instances << observer
-
end
-
-
# Notify list of observers of a change.
-
2
def notify_observers(*arg)
-
22
observer_instances.each { |observer| observer.update(*arg) }
-
end
-
-
# Total number of observers.
-
2
def count_observers
-
observer_instances.size
-
end
-
-
2
protected
-
2
def instantiate_observer(observer) #:nodoc:
-
# string/symbol
-
if observer.respond_to?(:to_sym)
-
observer.to_s.camelize.constantize.instance
-
elsif observer.respond_to?(:instance)
-
observer.instance
-
else
-
raise ArgumentError,
-
"#{observer} must be a lowercase, underscored class name (or an " +
-
"instance of the class itself) responding to the instance " +
-
"method. Example: Person.observers = :big_brother # calls " +
-
"BigBrother.instance"
-
end
-
end
-
-
# Notify observers when the observed class is subclassed.
-
2
def inherited(subclass)
-
22
super
-
22
notify_observers :observed_class_inherited, subclass
-
end
-
end
-
-
2
private
-
# Fires notifications to model's observers
-
#
-
# def save
-
# notify_observers(:before_save)
-
# ...
-
# notify_observers(:after_save)
-
# end
-
2
def notify_observers(method)
-
self.class.notify_observers(method, self)
-
end
-
end
-
-
# == Active Model Observers
-
#
-
# Observer classes respond to life cycle callbacks to implement trigger-like
-
# behavior outside the original class. This is a great way to reduce the
-
# clutter that normally comes when the model class is burdened with
-
# functionality that doesn't pertain to the core responsibility of the
-
# class. Example:
-
#
-
# class CommentObserver < ActiveModel::Observer
-
# def after_save(comment)
-
# Notifications.comment("admin@do.com", "New comment was posted", comment).deliver
-
# end
-
# end
-
#
-
# This Observer sends an email when a Comment#save is finished.
-
#
-
# class ContactObserver < ActiveModel::Observer
-
# def after_create(contact)
-
# contact.logger.info('New contact added!')
-
# end
-
#
-
# def after_destroy(contact)
-
# contact.logger.warn("Contact with an id of #{contact.id} was destroyed!")
-
# end
-
# end
-
#
-
# This Observer uses logger to log when specific callbacks are triggered.
-
#
-
# == Observing a class that can't be inferred
-
#
-
# Observers will by default be mapped to the class with which they share a
-
# name. So CommentObserver will be tied to observing Comment, ProductManagerObserver
-
# to ProductManager, and so on. If you want to name your observer differently than
-
# the class you're interested in observing, you can use the <tt>Observer.observe</tt>
-
# class method which takes either the concrete class (Product) or a symbol for that
-
# class (:product):
-
#
-
# class AuditObserver < ActiveModel::Observer
-
# observe :account
-
#
-
# def after_update(account)
-
# AuditTrail.new(account, "UPDATED")
-
# end
-
# end
-
#
-
# If the audit observer needs to watch more than one kind of object, this can be
-
# specified with multiple arguments:
-
#
-
# class AuditObserver < ActiveModel::Observer
-
# observe :account, :balance
-
#
-
# def after_update(record)
-
# AuditTrail.new(record, "UPDATED")
-
# end
-
# end
-
#
-
# The AuditObserver will now act on both updates to Account and Balance by treating
-
# them both as records.
-
#
-
# If you're using an Observer in a Rails application with Active Record, be sure to
-
# read about the necessary configuration in the documentation for
-
# ActiveRecord::Observer.
-
#
-
2
class Observer
-
2
include Singleton
-
2
extend ActiveSupport::DescendantsTracker
-
-
2
class << self
-
# Attaches the observer to the supplied model classes.
-
2
def observe(*models)
-
models.flatten!
-
models.collect! { |model| model.respond_to?(:to_sym) ? model.to_s.camelize.constantize : model }
-
redefine_method(:observed_classes) { models }
-
end
-
-
# Returns an array of Classes to observe.
-
#
-
# You can override this instead of using the +observe+ helper.
-
#
-
# class AuditObserver < ActiveModel::Observer
-
# def self.observed_classes
-
# [Account, Balance]
-
# end
-
# end
-
2
def observed_classes
-
Array.wrap(observed_class)
-
end
-
-
# The class observed by default is inferred from the observer's class name:
-
# assert_equal Person, PersonObserver.observed_class
-
2
def observed_class
-
if observed_class_name = name[/(.*)Observer/, 1]
-
observed_class_name.constantize
-
else
-
nil
-
end
-
end
-
end
-
-
# Start observing the declared classes and their subclasses.
-
2
def initialize
-
observed_classes.each { |klass| add_observer!(klass) }
-
end
-
-
2
def observed_classes #:nodoc:
-
self.class.observed_classes
-
end
-
-
# Send observed_method(object) if the method exists and
-
# the observer is enabled for the given object's class.
-
2
def update(observed_method, object, &block) #:nodoc:
-
return unless respond_to?(observed_method)
-
return if disabled_for?(object)
-
send(observed_method, object, &block)
-
end
-
-
# Special method sent by the observed class when it is inherited.
-
# Passes the new subclass.
-
2
def observed_class_inherited(subclass) #:nodoc:
-
self.class.observe(observed_classes + [subclass])
-
add_observer!(subclass)
-
end
-
-
2
protected
-
2
def add_observer!(klass) #:nodoc:
-
klass.add_observer(self)
-
end
-
-
2
def disabled_for?(object)
-
klass = object.class
-
return false unless klass.respond_to?(:observers)
-
klass.observers.disabled_for?(self)
-
end
-
end
-
end
-
2
require "active_model"
-
2
require "rails"
-
2
module ActiveModel
-
2
module SecurePassword
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
# Adds methods to set and authenticate against a BCrypt password.
-
# This mechanism requires you to have a password_digest attribute.
-
#
-
# Validations for presence of password, confirmation of password (using
-
# a "password_confirmation" attribute) are automatically added.
-
# You can add more validations by hand if need be.
-
#
-
# You need to add bcrypt-ruby (~> 3.0.0) to Gemfile to use has_secure_password:
-
#
-
# gem 'bcrypt-ruby', '~> 3.0.0'
-
#
-
# Example using Active Record (which automatically includes ActiveModel::SecurePassword):
-
#
-
# # Schema: User(name:string, password_digest: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
-
2
def has_secure_password
-
# Load bcrypt-ruby only when has_secure_password is used.
-
# This is to avoid ActiveModel (and by extension the entire framework) being dependent on a binary library.
-
gem 'bcrypt-ruby', '~> 3.0.0'
-
require 'bcrypt'
-
-
attr_reader :password
-
-
validates_confirmation_of :password
-
validates_presence_of :password_digest
-
-
include InstanceMethodsOnActivation
-
-
if respond_to?(:attributes_protected_by_default)
-
def self.attributes_protected_by_default
-
super + ['password_digest']
-
end
-
end
-
end
-
end
-
-
2
module InstanceMethodsOnActivation
-
# Returns self if the password is correct, otherwise false.
-
2
def authenticate(unencrypted_password)
-
if BCrypt::Password.new(password_digest) == unencrypted_password
-
self
-
else
-
false
-
end
-
end
-
-
# Encrypts the password into the password_digest attribute.
-
2
def password=(unencrypted_password)
-
@password = unencrypted_password
-
unless unencrypted_password.blank?
-
self.password_digest = BCrypt::Password.create(unencrypted_password)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/array/wrap'
-
-
-
2
module ActiveModel
-
# == Active Model Serialization
-
#
-
# Provides a basic serialization to a serializable_hash for your object.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
#
-
# include ActiveModel::Serialization
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# {'name' => name}
-
# end
-
#
-
# end
-
#
-
# Which would provide you with:
-
#
-
# person = Person.new
-
# person.serializable_hash # => {"name"=>nil}
-
# person.name = "Bob"
-
# person.serializable_hash # => {"name"=>"Bob"}
-
#
-
# You need to declare some sort of attributes hash which contains the attributes
-
# you want to serialize and their current value.
-
#
-
# Most of the time though, you will want to include the JSON or XML
-
# serializations. Both of these modules automatically include the
-
# ActiveModel::Serialization module, so there is no need to explicitly
-
# include it.
-
#
-
# So a minimal implementation including XML and JSON would be:
-
#
-
# class Person
-
#
-
# include ActiveModel::Serializers::JSON
-
# include ActiveModel::Serializers::Xml
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# {'name' => name}
-
# end
-
#
-
# end
-
#
-
# Which would provide you with:
-
#
-
# person = Person.new
-
# person.serializable_hash # => {"name"=>nil}
-
# person.as_json # => {"name"=>nil}
-
# person.to_json # => "{\"name\":null}"
-
# person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
-
#
-
# person.name = "Bob"
-
# person.serializable_hash # => {"name"=>"Bob"}
-
# person.as_json # => {"name"=>"Bob"}
-
# person.to_json # => "{\"name\":\"Bob\"}"
-
# person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
-
#
-
# Valid options are <tt>:only</tt>, <tt>:except</tt> and <tt>:methods</tt> .
-
2
module Serialization
-
2
def serializable_hash(options = nil)
-
options ||= {}
-
-
attribute_names = attributes.keys.sort
-
if only = options[:only]
-
attribute_names &= Array.wrap(only).map(&:to_s)
-
elsif except = options[:except]
-
attribute_names -= Array.wrap(except).map(&:to_s)
-
end
-
-
hash = {}
-
attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) }
-
-
method_names = Array.wrap(options[:methods]).select { |n| respond_to?(n) }
-
method_names.each { |n| hash[n] = send(n) }
-
-
serializable_add_includes(options) do |association, records, opts|
-
hash[association] = if records.is_a?(Enumerable)
-
records.map { |a| a.serializable_hash(opts) }
-
else
-
records.serializable_hash(opts)
-
end
-
end
-
-
hash
-
end
-
-
2
private
-
-
# Hook method defining how an attribute value should be retrieved for
-
# serialization. By default this is assumed to be an instance named after
-
# the attribute. Override this method in subclasses should you need to
-
# retrieve the value for a given attribute differently:
-
#
-
# class MyClass
-
# include ActiveModel::Validations
-
#
-
# def initialize(data = {})
-
# @data = data
-
# end
-
#
-
# def read_attribute_for_serialization(key)
-
# @data[key]
-
# end
-
# end
-
#
-
2
alias :read_attribute_for_serialization :send
-
-
# Add associations specified via the <tt>:include</tt> option.
-
#
-
# Expects a block that takes as arguments:
-
# +association+ - name of the association
-
# +records+ - the association record(s) to be serialized
-
# +opts+ - options for the association records
-
2
def serializable_add_includes(options = {}) #:nodoc:
-
return unless include = options[:include]
-
-
unless include.is_a?(Hash)
-
include = Hash[Array.wrap(include).map { |n| n.is_a?(Hash) ? n.to_a.first : [n, {}] }]
-
end
-
-
include.each do |association, opts|
-
if records = send(association)
-
yield association, records, opts
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/json'
-
2
require 'active_support/core_ext/class/attribute'
-
-
2
module ActiveModel
-
2
module Serializers
-
# == Active Model JSON Serializer
-
2
module JSON
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::Serialization
-
-
2
included do
-
2
extend ActiveModel::Naming
-
-
2
class_attribute :include_root_in_json
-
2
self.include_root_in_json = true
-
end
-
-
# Returns a hash representing the model. Some configuration can be
-
# passed through +options+.
-
#
-
# The option <tt>include_root_in_json</tt> controls the top-level behavior
-
# of +as_json+. If true (the default) +as_json+ will emit a single root
-
# node named after the object's type. For example:
-
#
-
# user = User.find(1)
-
# user.as_json
-
# # => { "user": {"id": 1, "name": "Konata Izumi", "age": 16,
-
# "created_at": "2006/08/01", "awesome": true} }
-
#
-
# ActiveRecord::Base.include_root_in_json = false
-
# user.as_json
-
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
-
# "created_at": "2006/08/01", "awesome": true}
-
#
-
# This behavior can also be achieved by setting the <tt>:root</tt> option to +false+ as in:
-
#
-
# user = User.find(1)
-
# user.as_json(root: false)
-
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
-
# "created_at": "2006/08/01", "awesome": true}
-
#
-
# The remainder of the examples in this section assume include_root_in_json is set to
-
# <tt>false</tt>.
-
#
-
# Without any +options+, the returned Hash will include all the model's
-
# attributes. For example:
-
#
-
# user = User.find(1)
-
# user.as_json
-
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
-
# "created_at": "2006/08/01", "awesome": true}
-
#
-
# The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the attributes
-
# included, and work similar to the +attributes+ method. For example:
-
#
-
# user.as_json(:only => [ :id, :name ])
-
# # => {"id": 1, "name": "Konata Izumi"}
-
#
-
# user.as_json(:except => [ :id, :created_at, :age ])
-
# # => {"name": "Konata Izumi", "awesome": true}
-
#
-
# To include the result of some method calls on the model use <tt>:methods</tt>:
-
#
-
# user.as_json(:methods => :permalink)
-
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
-
# "created_at": "2006/08/01", "awesome": true,
-
# "permalink": "1-konata-izumi"}
-
#
-
# To include associations use <tt>:include</tt>:
-
#
-
# user.as_json(:include => :posts)
-
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
-
# "created_at": "2006/08/01", "awesome": true,
-
# "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
-
# {"id": 2, author_id: 1, "title": "So I was thinking"}]}
-
#
-
# Second level and higher order associations work as well:
-
#
-
# user.as_json(:include => { :posts => {
-
# :include => { :comments => {
-
# :only => :body } },
-
# :only => :title } })
-
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
-
# "created_at": "2006/08/01", "awesome": true,
-
# "posts": [{"comments": [{"body": "1st post!"}, {"body": "Second!"}],
-
# "title": "Welcome to the weblog"},
-
# {"comments": [{"body": "Don't think too hard"}],
-
# "title": "So I was thinking"}]}
-
2
def as_json(options = nil)
-
root = include_root_in_json
-
root = options[:root] if options.try(:key?, :root)
-
if root
-
root = self.class.model_name.element if root == true
-
{ root => serializable_hash(options) }
-
else
-
serializable_hash(options)
-
end
-
end
-
-
2
def from_json(json, include_root=include_root_in_json)
-
hash = ActiveSupport::JSON.decode(json)
-
hash = hash.values.first if include_root
-
self.attributes = hash
-
self
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/class/attribute_accessors'
-
2
require 'active_support/core_ext/array/conversions'
-
2
require 'active_support/core_ext/hash/conversions'
-
2
require 'active_support/core_ext/hash/slice'
-
-
2
module ActiveModel
-
2
module Serializers
-
# == Active Model XML Serializer
-
2
module Xml
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::Serialization
-
-
2
included do
-
2
extend ActiveModel::Naming
-
end
-
-
2
class Serializer #:nodoc:
-
2
class Attribute #:nodoc:
-
2
attr_reader :name, :value, :type
-
-
2
def initialize(name, serializable, value)
-
@name, @serializable = name, serializable
-
value = value.in_time_zone if value.respond_to?(:in_time_zone)
-
@value = value
-
@type = compute_type
-
end
-
-
2
def decorations
-
decorations = {}
-
decorations[:encoding] = 'base64' if type == :binary
-
decorations[:type] = (type == :string) ? nil : type
-
decorations[:nil] = true if value.nil?
-
decorations
-
end
-
-
2
protected
-
-
2
def compute_type
-
return if value.nil?
-
type = ActiveSupport::XmlMini::TYPE_NAMES[value.class.name]
-
type ||= :string if value.respond_to?(:to_str)
-
type ||= :yaml
-
type
-
end
-
end
-
-
2
class MethodAttribute < Attribute #:nodoc:
-
end
-
-
2
attr_reader :options
-
-
2
def initialize(serializable, options = nil)
-
@serializable = serializable
-
@options = options ? options.dup : {}
-
end
-
-
2
def serializable_hash
-
@serializable.serializable_hash(@options.except(:include))
-
end
-
-
2
def serializable_collection
-
methods = Array.wrap(options[:methods]).map(&:to_s)
-
serializable_hash.map do |name, value|
-
name = name.to_s
-
if methods.include?(name)
-
self.class::MethodAttribute.new(name, @serializable, value)
-
else
-
self.class::Attribute.new(name, @serializable, value)
-
end
-
end
-
end
-
-
2
def serialize
-
require 'builder' unless defined? ::Builder
-
-
options[:indent] ||= 2
-
options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent])
-
-
@builder = options[:builder]
-
@builder.instruct! unless options[:skip_instruct]
-
-
root = (options[:root] || @serializable.class.model_name.element).to_s
-
root = ActiveSupport::XmlMini.rename_key(root, options)
-
-
args = [root]
-
args << {:xmlns => options[:namespace]} if options[:namespace]
-
args << {:type => options[:type]} if options[:type] && !options[:skip_types]
-
-
@builder.tag!(*args) do
-
add_attributes_and_methods
-
add_includes
-
add_extra_behavior
-
add_procs
-
yield @builder if block_given?
-
end
-
end
-
-
2
private
-
-
2
def add_extra_behavior
-
end
-
-
2
def add_attributes_and_methods
-
serializable_collection.each do |attribute|
-
key = ActiveSupport::XmlMini.rename_key(attribute.name, options)
-
ActiveSupport::XmlMini.to_tag(key, attribute.value,
-
options.merge(attribute.decorations))
-
end
-
end
-
-
2
def add_includes
-
@serializable.send(:serializable_add_includes, options) do |association, records, opts|
-
add_associations(association, records, opts)
-
end
-
end
-
-
# TODO This can likely be cleaned up to simple use ActiveSupport::XmlMini.to_tag as well.
-
2
def add_associations(association, records, opts)
-
merged_options = opts.merge(options.slice(:builder, :indent))
-
merged_options[:skip_instruct] = true
-
-
if records.is_a?(Enumerable)
-
tag = ActiveSupport::XmlMini.rename_key(association.to_s, options)
-
type = options[:skip_types] ? { } : {:type => "array"}
-
association_name = association.to_s.singularize
-
merged_options[:root] = association_name
-
-
if records.empty?
-
@builder.tag!(tag, type)
-
else
-
@builder.tag!(tag, type) do
-
records.each do |record|
-
if options[:skip_types]
-
record_type = {}
-
else
-
record_class = (record.class.to_s.underscore == association_name) ? nil : record.class.name
-
record_type = {:type => record_class}
-
end
-
-
record.to_xml merged_options.merge(record_type)
-
end
-
end
-
end
-
else
-
merged_options[:root] = association.to_s
-
-
unless records.class.to_s.underscore == association.to_s
-
merged_options[:type] = records.class.name
-
end
-
-
records.to_xml merged_options
-
end
-
end
-
-
2
def add_procs
-
if procs = options.delete(:procs)
-
Array.wrap(procs).each do |proc|
-
if proc.arity == 1
-
proc.call(options)
-
else
-
proc.call(options, @serializable)
-
end
-
end
-
end
-
end
-
end
-
-
# Returns XML representing the model. Configuration can be
-
# passed through +options+.
-
#
-
# Without any +options+, the returned XML string will include all the model's
-
# attributes. For example:
-
#
-
# user = User.find(1)
-
# user.to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <user>
-
# <id type="integer">1</id>
-
# <name>David</name>
-
# <age type="integer">16</age>
-
# <created-at type="datetime">2011-01-30T22:29:23Z</created-at>
-
# </user>
-
#
-
# The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the attributes
-
# included, and work similar to the +attributes+ method.
-
#
-
# To include the result of some method calls on the model use <tt>:methods</tt>.
-
#
-
# To include associations use <tt>:include</tt>.
-
#
-
# For further documentation see activerecord/lib/active_record/serializers/xml_serializer.xml.
-
2
def to_xml(options = {}, &block)
-
Serializer.new(self, options).serialize(&block)
-
end
-
-
2
def from_xml(xml)
-
self.attributes = Hash.from_xml(xml).values.first
-
self
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
-
2
module ActiveModel
-
-
# == Active Model Translation
-
#
-
# Provides integration between your object and the Rails internationalization
-
# (i18n) framework.
-
#
-
# A minimal implementation could be:
-
#
-
# class TranslatedPerson
-
# extend ActiveModel::Translation
-
# end
-
#
-
# TranslatedPerson.human_attribute_name('my_attribute')
-
# # => "My attribute"
-
#
-
# This also provides the required class methods for hooking into the
-
# Rails internationalization API, including being able to define a
-
# class based +i18n_scope+ and +lookup_ancestors+ to find translations in
-
# parent classes.
-
2
module Translation
-
2
include ActiveModel::Naming
-
-
# Returns the +i18n_scope+ for the class. Overwrite if you want custom lookup.
-
2
def i18n_scope
-
:activemodel
-
end
-
-
# When localizing a string, it goes through the lookup returned by this
-
# method, which is used in ActiveModel::Name#human,
-
# ActiveModel::Errors#full_messages and
-
# ActiveModel::Translation#human_attribute_name.
-
2
def lookup_ancestors
-
self.ancestors.select { |x| x.respond_to?(:model_name) }
-
end
-
-
# Transforms attribute names into a more human format, such as "First name"
-
# instead of "first_name".
-
#
-
# Person.human_attribute_name("first_name") # => "First name"
-
#
-
# Specify +options+ with additional translating options.
-
2
def human_attribute_name(attribute, options = {})
-
defaults = []
-
parts = attribute.to_s.split(".")
-
attribute = parts.pop
-
namespace = parts.join("/") unless parts.empty?
-
-
if namespace
-
lookup_ancestors.each do |klass|
-
defaults << :"#{self.i18n_scope}.attributes.#{klass.model_name.i18n_key}/#{namespace}.#{attribute}"
-
end
-
defaults << :"#{self.i18n_scope}.attributes.#{namespace}.#{attribute}"
-
else
-
lookup_ancestors.each do |klass|
-
defaults << :"#{self.i18n_scope}.attributes.#{klass.model_name.i18n_key}.#{attribute}"
-
end
-
end
-
-
defaults << :"attributes.#{attribute}"
-
defaults << options.delete(:default) if options[:default]
-
defaults << attribute.humanize
-
-
options.reverse_merge! :count => 1, :default => defaults
-
I18n.translate(defaults.shift, options)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_model/errors'
-
2
require 'active_model/validations/callbacks'
-
2
require 'active_model/validator'
-
-
2
module ActiveModel
-
-
# == Active Model Validations
-
#
-
# Provides a full validation framework to your objects.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :first_name, :last_name
-
#
-
# validates_each :first_name, :last_name do |record, attr, value|
-
# record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
-
# end
-
# end
-
#
-
# Which provides you with the full standard validation stack that you
-
# know from Active Record:
-
#
-
# person = Person.new
-
# person.valid? # => true
-
# person.invalid? # => false
-
#
-
# person.first_name = 'zoolander'
-
# person.valid? # => false
-
# person.invalid? # => true
-
# person.errors # => #<OrderedHash {:first_name=>["starts with z."]}>
-
#
-
# Note that <tt>ActiveModel::Validations</tt> automatically adds an +errors+ method
-
# to your instances initialized with a new <tt>ActiveModel::Errors</tt> object, so
-
# there is no need for you to do this manually.
-
#
-
2
module Validations
-
2
extend ActiveSupport::Concern
-
2
include ActiveSupport::Callbacks
-
-
2
included do
-
2
extend ActiveModel::Translation
-
-
2
extend HelperMethods
-
2
include HelperMethods
-
-
2
attr_accessor :validation_context
-
2
define_callbacks :validate, :scope => :name
-
-
2
class_attribute :_validators
-
14
self._validators = Hash.new { |h,k| h[k] = [] }
-
end
-
-
2
module ClassMethods
-
# Validates each attribute against a block.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :first_name, :last_name
-
#
-
# validates_each :first_name, :last_name do |record, attr, value|
-
# record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
-
# end
-
# end
-
#
-
# Options:
-
# * <tt>:on</tt> - Specifies the context where this validation is active
-
# (e.g. <tt>:on => :create</tt> or <tt>:on => :custom_validation_context</tt>)
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
-
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
-
# or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a true or false value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or
-
# <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a true or false value.
-
2
def validates_each(*attr_names, &block)
-
options = attr_names.extract_options!.symbolize_keys
-
validates_with BlockValidator, options.merge(:attributes => attr_names.flatten), &block
-
end
-
-
# Adds a validation method or block to the class. This is useful when
-
# overriding the +validate+ instance method becomes too unwieldy and
-
# you're looking for more descriptive declaration of your validations.
-
#
-
# This can be done with a symbol pointing to a method:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate :must_be_friends
-
#
-
# def must_be_friends
-
# errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# With a block which is passed with the current record to be validated:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate do |comment|
-
# comment.must_be_friends
-
# end
-
#
-
# def must_be_friends
-
# errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# Or with a block where self points to the current record to be validated:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate do
-
# errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
2
def validate(*args, &block)
-
62
options = args.extract_options!
-
62
if options.key?(:on)
-
6
options = options.dup
-
6
options[:if] = Array.wrap(options[:if])
-
6
options[:if].unshift("validation_context == :#{options[:on]}")
-
end
-
62
args << options
-
62
set_callback(:validate, *args, &block)
-
end
-
-
# List all validators that are being used to validate the model using
-
# +validates_with+ method.
-
2
def validators
-
_validators.values.flatten.uniq
-
end
-
-
# List all validators that being used to validate a specific attribute.
-
2
def validators_on(*attributes)
-
attributes.map do |attribute|
-
_validators[attribute.to_sym]
-
end.flatten
-
end
-
-
# Check if method is an attribute method or not.
-
2
def attribute_method?(attribute)
-
method_defined?(attribute)
-
end
-
-
# Copy validators on inheritance.
-
2
def inherited(base)
-
22
dup = _validators.dup
-
22
base._validators = dup.each { |k, v| dup[k] = v.dup }
-
22
super
-
end
-
end
-
-
# Clean the +Errors+ object if instance is duped
-
2
def initialize_dup(other) # :nodoc:
-
@errors = nil
-
super if defined?(super)
-
end
-
-
# Backport dup from 1.9 so that #initialize_dup gets called
-
2
unless Object.respond_to?(:initialize_dup, true)
-
def dup # :nodoc:
-
copy = super
-
copy.initialize_dup(self)
-
copy
-
end
-
end
-
-
# Returns the +Errors+ object that holds all information about attribute error messages.
-
2
def errors
-
1151
@errors ||= Errors.new(self)
-
end
-
-
# Runs all the specified validations and returns true if no errors were added
-
# otherwise false. Context can optionally be supplied to define which callbacks
-
# to test against (the context is defined on the validations using :on).
-
2
def valid?(context = nil)
-
359
current_context, self.validation_context = validation_context, context
-
359
errors.clear
-
359
run_validations!
-
ensure
-
359
self.validation_context = current_context
-
end
-
-
# Performs the opposite of <tt>valid?</tt>. Returns true if errors were added,
-
# false otherwise.
-
2
def invalid?(context = nil)
-
!valid?(context)
-
end
-
-
# Hook method defining how an attribute value should be retrieved. By default
-
# this is assumed to be an instance named after the attribute. Override this
-
# method in subclasses should you need to retrieve the value for a given
-
# attribute differently:
-
#
-
# class MyClass
-
# include ActiveModel::Validations
-
#
-
# def initialize(data = {})
-
# @data = data
-
# end
-
#
-
# def read_attribute_for_validation(key)
-
# @data[key]
-
# end
-
# end
-
#
-
2
alias :read_attribute_for_validation :send
-
-
2
protected
-
-
2
def run_validations!
-
359
run_callbacks :validate
-
359
errors.empty?
-
end
-
end
-
end
-
-
2
Dir[File.dirname(__FILE__) + "/validations/*.rb"].sort.each do |path|
-
22
filename = File.basename(path)
-
22
require "active_model/validations/#{filename}"
-
end
-
2
module ActiveModel
-
# == Active Model Acceptance Validator
-
2
module Validations
-
2
class AcceptanceValidator < EachValidator
-
2
def initialize(options)
-
super(options.reverse_merge(:allow_nil => true, :accept => "1"))
-
end
-
-
2
def validate_each(record, attribute, value)
-
unless value == options[:accept]
-
record.errors.add(attribute, :accepted, options.except(:accept, :allow_nil))
-
end
-
end
-
-
2
def setup(klass)
-
attr_readers = attributes.reject { |name| klass.attribute_method?(name) }
-
attr_writers = attributes.reject { |name| klass.attribute_method?("#{name}=") }
-
klass.send(:attr_reader, *attr_readers)
-
klass.send(:attr_writer, *attr_writers)
-
end
-
end
-
-
2
module HelperMethods
-
# Encapsulates the pattern of wanting to validate the acceptance of a
-
# terms of service check box (or similar agreement). Example:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_acceptance_of :terms_of_service
-
# validates_acceptance_of :eula, :message => "must be abided"
-
# end
-
#
-
# If the database column does not exist, the +terms_of_service+ attribute
-
# is entirely virtual. This check is performed only if +terms_of_service+
-
# is not +nil+ and by default on save.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "must be
-
# accepted").
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default
-
# is true).
-
# * <tt>:accept</tt> - Specifies value that is considered accepted.
-
# The default value is a string "1", which makes it easy to relate to
-
# an HTML checkbox. This should be set to +true+ if you are validating
-
# a database column, since the attribute is typecast from "1" to +true+
-
# before validation.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
-
# or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
-
# method, proc or string should return or evaluate to a true or false
-
# value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (for example,
-
# <tt>:unless => :skip_validation</tt>, or
-
# <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).
-
# The method, proc or string should return or evaluate to a true or
-
# false value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
2
def validates_acceptance_of(*attr_names)
-
validates_with AcceptanceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
require 'active_support/callbacks'
-
-
2
module ActiveModel
-
2
module Validations
-
2
module Callbacks
-
# == Active Model Validation callbacks
-
#
-
# Provides an interface for any class to have <tt>before_validation</tt> and
-
# <tt>after_validation</tt> callbacks.
-
#
-
# First, extend ActiveModel::Callbacks from the class you are creating:
-
#
-
# class MyModel
-
# include ActiveModel::Validations::Callbacks
-
#
-
# before_validation :do_stuff_before_validation
-
# after_validation :do_stuff_after_validation
-
# end
-
#
-
# Like other before_* callbacks if <tt>before_validation</tt> returns false
-
# then <tt>valid?</tt> will not be called.
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
include ActiveSupport::Callbacks
-
2
define_callbacks :validation, :terminator => "result == false", :scope => [:kind, :name]
-
end
-
-
2
module ClassMethods
-
2
def before_validation(*args, &block)
-
2
options = args.last
-
2
if options.is_a?(Hash) && options[:on]
-
options[:if] = Array.wrap(options[:if])
-
options[:if].unshift("self.validation_context == :#{options[:on]}")
-
end
-
2
set_callback(:validation, :before, *args, &block)
-
end
-
-
2
def after_validation(*args, &block)
-
options = args.extract_options!
-
options[:prepend] = true
-
options[:if] = Array.wrap(options[:if])
-
options[:if] << "!halted"
-
options[:if].unshift("self.validation_context == :#{options[:on]}") if options[:on]
-
set_callback(:validation, :after, *(args << options), &block)
-
end
-
end
-
-
2
protected
-
-
# Overwrite run validations to include callbacks.
-
2
def run_validations!
-
718
run_callbacks(:validation) { super }
-
end
-
end
-
end
-
end
-
2
module ActiveModel
-
# == Active Model Confirmation Validator
-
2
module Validations
-
2
class ConfirmationValidator < EachValidator
-
2
def validate_each(record, attribute, value)
-
if (confirmed = record.send("#{attribute}_confirmation")) && (value != confirmed)
-
record.errors.add(attribute, :confirmation, options)
-
end
-
end
-
-
2
def setup(klass)
-
klass.send(:attr_accessor, *attributes.map do |attribute|
-
:"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation")
-
end.compact)
-
end
-
end
-
-
2
module HelperMethods
-
# Encapsulates the pattern of wanting to validate a password or email
-
# address field with a confirmation. For example:
-
#
-
# Model:
-
# class Person < ActiveRecord::Base
-
# validates_confirmation_of :user_name, :password
-
# validates_confirmation_of :email_address,
-
# :message => "should match confirmation"
-
# end
-
#
-
# View:
-
# <%= password_field "person", "password" %>
-
# <%= password_field "person", "password_confirmation" %>
-
#
-
# The added +password_confirmation+ attribute is virtual; it exists only
-
# as an in-memory attribute for validating the password. To achieve this,
-
# the validation adds accessors to the model for the confirmation
-
# attribute.
-
#
-
# NOTE: This check is performed only if +password_confirmation+ is not
-
# +nil+, and by default only on save. To require confirmation, make sure
-
# to add a presence check for the confirmation attribute:
-
#
-
# validates_presence_of :password_confirmation, :if => :password_changed?
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "doesn't match
-
# confirmation").
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
-
# or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
-
# method, proc or string should return or evaluate to a true or false
-
# value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g.
-
# <tt>:unless => :skip_validation</tt>, or
-
# <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a true or false value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
2
def validates_confirmation_of(*attr_names)
-
validates_with ConfirmationValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/range'
-
-
2
module ActiveModel
-
# == Active Model Exclusion Validator
-
2
module Validations
-
2
class ExclusionValidator < EachValidator
-
2
ERROR_MESSAGE = "An object with the method #include? or a proc or lambda is required, " <<
-
"and must be supplied as the :in (or :within) option of the configuration hash"
-
-
2
def check_validity!
-
unless [:include?, :call].any? { |method| delimiter.respond_to?(method) }
-
raise ArgumentError, ERROR_MESSAGE
-
end
-
end
-
-
2
def validate_each(record, attribute, value)
-
exclusions = delimiter.respond_to?(:call) ? delimiter.call(record) : delimiter
-
if exclusions.send(inclusion_method(exclusions), value)
-
record.errors.add(attribute, :exclusion, options.except(:in, :within).merge!(:value => value))
-
end
-
end
-
-
2
private
-
-
2
def delimiter
-
@delimiter ||= options[:in] || options[:within]
-
end
-
-
# In Ruby 1.9 <tt>Range#include?</tt> on non-numeric ranges checks all possible
-
# values in the range for equality, so it may be slow for large ranges. The new
-
# <tt>Range#cover?</tt> uses the previous logic of comparing a value with the
-
# range endpoints.
-
2
def inclusion_method(enumerable)
-
enumerable.is_a?(Range) ? :cover? : :include?
-
end
-
end
-
-
2
module HelperMethods
-
# Validates that the value of the specified attribute is not in a particular
-
# enumerable object.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_exclusion_of :username, :in => %w( admin superuser ), :message => "You don't belong here"
-
# validates_exclusion_of :age, :in => 30..60, :message => "This site is only for under 30 and over 60"
-
# validates_exclusion_of :format, :in => %w( mov avi ), :message => "extension %{value} is not allowed"
-
# validates_exclusion_of :password, :in => lambda { |p| [p.username, p.first_name] },
-
# :message => "should not be the same as your username or first name"
-
# end
-
#
-
# Configuration options:
-
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't be
-
# part of. This can be supplied as a proc or lambda which returns an enumerable.
-
# If the enumerable is a range the test is performed with <tt>Range#cover?</tt>
-
# (backported in Active Support for 1.8), otherwise with <tt>include?</tt>.
-
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved").
-
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute
-
# is +nil+ (default is +false+).
-
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the
-
# attribute is blank (default is +false+).
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the
-
# validation should occur (e.g. <tt>:if => :allow_validation</tt>, or
-
# <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
-
# or string should return or evaluate to a true or false value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if
-
# the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
-
# or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
-
# proc or string should return or evaluate to a true or false value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
2
def validates_exclusion_of(*attr_names)
-
validates_with ExclusionValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
module ActiveModel
-
# == Active Model Format Validator
-
2
module Validations
-
2
class FormatValidator < EachValidator
-
2
def validate_each(record, attribute, value)
-
if options[:with]
-
regexp = option_call(record, :with)
-
record_error(record, attribute, :with, value) if value.to_s !~ regexp
-
elsif options[:without]
-
regexp = option_call(record, :without)
-
record_error(record, attribute, :without, value) if value.to_s =~ regexp
-
end
-
end
-
-
2
def check_validity!
-
unless options.include?(:with) ^ options.include?(:without) # ^ == xor, or "exclusive or"
-
raise ArgumentError, "Either :with or :without must be supplied (but not both)"
-
end
-
-
check_options_validity(options, :with)
-
check_options_validity(options, :without)
-
end
-
-
2
private
-
-
2
def option_call(record, name)
-
option = options[name]
-
option.respond_to?(:call) ? option.call(record) : option
-
end
-
-
2
def record_error(record, attribute, name, value)
-
record.errors.add(attribute, :invalid, options.except(name).merge!(:value => value))
-
end
-
-
2
def check_options_validity(options, name)
-
option = options[name]
-
if option && !option.is_a?(Regexp) && !option.respond_to?(:call)
-
raise ArgumentError, "A regular expression or a proc or lambda must be supplied as :#{name}"
-
end
-
end
-
end
-
-
2
module HelperMethods
-
# Validates whether the value of the specified attribute is of the correct form,
-
# going by the regular expression provided. You can require that the attribute
-
# matches the regular expression:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
-
# end
-
#
-
# Alternatively, you can require that the specified attribute does _not_ match
-
# the regular expression:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_format_of :email, :without => /NOSPAM/
-
# end
-
#
-
# You can also provide a proc or lambda which will determine the regular
-
# expression that will be used to validate the attribute.
-
#
-
# class Person < ActiveRecord::Base
-
# # Admin can have number as a first letter in their screen name
-
# validates_format_of :screen_name,
-
# :with => lambda{ |person| person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\Z/i : /\A[a-z][a-z0-9_\-]*\Z/i }
-
# end
-
#
-
# Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string,
-
# <tt>^</tt> and <tt>$</tt> match the start/end of a line.
-
#
-
# You must pass either <tt>:with</tt> or <tt>:without</tt> as an option. In
-
# addition, both must be a regular expression or a proc or lambda, or else an
-
# exception will be raised.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
-
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute
-
# is +nil+ (default is +false+).
-
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the
-
# attribute is blank (default is +false+).
-
# * <tt>:with</tt> - Regular expression that if the attribute matches will
-
# result in a successful validation. This can be provided as a proc or lambda
-
# returning regular expression which will be called at runtime.
-
# * <tt>:without</tt> - Regular expression that if the attribute does not match
-
# will result in a successful validation. This can be provided as a proc or
-
# lambda returning regular expression which will be called at runtime.
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the
-
# validation should occur (e.g. <tt>:if => :allow_validation</tt>, or
-
# <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
-
# or string should return or evaluate to a true or false value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if
-
# the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
-
# or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
-
# proc or string should return or evaluate to a true or false value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
2
def validates_format_of(*attr_names)
-
validates_with FormatValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/range'
-
-
2
module ActiveModel
-
# == Active Model Inclusion Validator
-
2
module Validations
-
2
class InclusionValidator < EachValidator
-
2
ERROR_MESSAGE = "An object with the method #include? or a proc or lambda is required, " <<
-
"and must be supplied as the :in (or :within) option of the configuration hash"
-
-
2
def check_validity!
-
unless [:include?, :call].any?{ |method| delimiter.respond_to?(method) }
-
raise ArgumentError, ERROR_MESSAGE
-
end
-
end
-
-
2
def validate_each(record, attribute, value)
-
exclusions = delimiter.respond_to?(:call) ? delimiter.call(record) : delimiter
-
unless exclusions.send(inclusion_method(exclusions), value)
-
record.errors.add(attribute, :inclusion, options.except(:in, :within).merge!(:value => value))
-
end
-
end
-
-
2
private
-
-
2
def delimiter
-
@delimiter ||= options[:in] || options[:within]
-
end
-
-
# In Ruby 1.9 <tt>Range#include?</tt> on non-numeric ranges checks all possible
-
# values in the range for equality, so it may be slow for large ranges. The new
-
# <tt>Range#cover?</tt> uses the previous logic of comparing a value with the
-
# range endpoints.
-
2
def inclusion_method(enumerable)
-
enumerable.is_a?(Range) ? :cover? : :include?
-
end
-
end
-
-
2
module HelperMethods
-
# Validates whether the value of the specified attribute is available in a
-
# particular enumerable object.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_inclusion_of :gender, :in => %w( m f )
-
# validates_inclusion_of :age, :in => 0..99
-
# validates_inclusion_of :format, :in => %w( jpg gif png ), :message => "extension %{value} is not included in the list"
-
# validates_inclusion_of :states, :in => lambda{ |person| STATES[person.country] }
-
# end
-
#
-
# Configuration options:
-
# * <tt>:in</tt> - An enumerable object of available items. This can be
-
# supplied as a proc or lambda which returns an enumerable. If the enumerable
-
# is a range the test is performed with <tt>Range#cover?</tt>
-
# (backported in Active Support for 1.8), otherwise with <tt>include?</tt>.
-
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "is not
-
# included in the list").
-
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute
-
# is +nil+ (default is +false+).
-
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the
-
# attribute is blank (default is +false+).
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
-
# the validation should occur (e.g. <tt>:if => :allow_validation</tt>, or
-
# <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
-
# or string should return or evaluate to a true or false value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
-
# or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
-
# proc or string should return or evaluate to a true or false value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
2
def validates_inclusion_of(*attr_names)
-
validates_with InclusionValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
require "active_support/core_ext/string/encoding"
-
-
2
module ActiveModel
-
# == Active Model Length Validator
-
2
module Validations
-
2
class LengthValidator < EachValidator
-
2
MESSAGES = { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }.freeze
-
2
CHECKS = { :is => :==, :minimum => :>=, :maximum => :<= }.freeze
-
-
2
RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long]
-
-
2
def initialize(options)
-
if range = (options.delete(:in) || options.delete(:within))
-
raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
-
options[:minimum], options[:maximum] = range.begin, range.end
-
options[:maximum] -= 1 if range.exclude_end?
-
end
-
-
super
-
end
-
-
2
def check_validity!
-
keys = CHECKS.keys & options.keys
-
-
if keys.empty?
-
raise ArgumentError, 'Range unspecified. Specify the :in, :within, :maximum, :minimum, or :is option.'
-
end
-
-
keys.each do |key|
-
value = options[key]
-
-
unless value.is_a?(Integer) && value >= 0
-
raise ArgumentError, ":#{key} must be a nonnegative Integer"
-
end
-
end
-
end
-
-
2
def validate_each(record, attribute, value)
-
value = tokenize(value)
-
value_length = value.respond_to?(:length) ? value.length : value.to_s.length
-
-
CHECKS.each do |key, validity_check|
-
next unless check_value = options[key]
-
next if value_length.send(validity_check, check_value)
-
-
errors_options = options.except(*RESERVED_OPTIONS)
-
errors_options[:count] = check_value
-
-
default_message = options[MESSAGES[key]]
-
errors_options[:message] ||= default_message if default_message
-
-
record.errors.add(attribute, MESSAGES[key], errors_options)
-
end
-
end
-
-
2
private
-
-
2
def tokenize(value)
-
if value.kind_of?(String)
-
if options[:tokenizer]
-
options[:tokenizer].call(value)
-
elsif !value.encoding_aware?
-
value.mb_chars
-
end
-
end || value
-
end
-
end
-
-
2
module HelperMethods
-
# Validates that the specified attribute matches the length restrictions supplied.
-
# Only one option can be used at a time:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_length_of :first_name, :maximum => 30
-
# validates_length_of :last_name, :maximum => 30, :message => "less than 30 if you don't mind"
-
# validates_length_of :fax, :in => 7..32, :allow_nil => true
-
# validates_length_of :phone, :in => 7..32, :allow_blank => true
-
# validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
-
# validates_length_of :zip_code, :minimum => 5, :too_short => "please enter at least 5 characters"
-
# validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with 4 characters... don't play me."
-
# validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least 100 words.",
-
# :tokenizer => lambda { |str| str.scan(/\w+/) }
-
# end
-
#
-
# Configuration options:
-
# * <tt>:minimum</tt> - The minimum size of the attribute.
-
# * <tt>:maximum</tt> - The maximum size of the attribute.
-
# * <tt>:is</tt> - The exact size of the attribute.
-
# * <tt>:within</tt> - A range specifying the minimum and maximum size of the
-
# attribute.
-
# * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
-
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
-
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
-
# * <tt>:too_long</tt> - The error message if the attribute goes over the
-
# maximum (default is: "is too long (maximum is %{count} characters)").
-
# * <tt>:too_short</tt> - The error message if the attribute goes under the
-
# minimum (default is: "is too short (min is %{count} characters)").
-
# * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method
-
# and the attribute is the wrong size (default is: "is the wrong length
-
# should be %{count} characters)").
-
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>,
-
# <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate
-
# <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
-
# the validation should occur (e.g. <tt>:if => :allow_validation</tt>, or
-
# <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
-
# or string should return or evaluate to a true or false value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
-
# or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a true or false value.
-
# * <tt>:tokenizer</tt> - Specifies how to split up the attribute string.
-
# (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to count words
-
# as in above example). Defaults to <tt>lambda{ |value| value.split(//) }</tt> which counts individual characters.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
2
def validates_length_of(*attr_names)
-
validates_with LengthValidator, _merge_attributes(attr_names)
-
end
-
-
2
alias_method :validates_size_of, :validates_length_of
-
end
-
end
-
end
-
2
module ActiveModel
-
# == Active Model Numericality Validator
-
2
module Validations
-
2
class NumericalityValidator < EachValidator
-
2
CHECKS = { :greater_than => :>, :greater_than_or_equal_to => :>=,
-
:equal_to => :==, :less_than => :<, :less_than_or_equal_to => :<=,
-
:odd => :odd?, :even => :even? }.freeze
-
-
2
RESERVED_OPTIONS = CHECKS.keys + [:only_integer]
-
-
2
def check_validity!
-
4
keys = CHECKS.keys - [:odd, :even]
-
4
options.slice(*keys).each do |option, value|
-
4
next if value.is_a?(Numeric) || value.is_a?(Proc) || value.is_a?(Symbol)
-
raise ArgumentError, ":#{option} must be a number, a symbol or a proc"
-
end
-
end
-
-
2
def validate_each(record, attr_name, value)
-
17
before_type_cast = "#{attr_name}_before_type_cast"
-
-
17
raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast.to_sym)
-
17
raw_value ||= value
-
-
17
return if options[:allow_nil] && raw_value.nil?
-
-
17
unless value = parse_raw_value_as_a_number(raw_value)
-
record.errors.add(attr_name, :not_a_number, filtered_options(raw_value))
-
return
-
end
-
-
17
if options[:only_integer]
-
17
unless value = parse_raw_value_as_an_integer(raw_value)
-
record.errors.add(attr_name, :not_an_integer, filtered_options(raw_value))
-
return
-
end
-
end
-
-
17
options.slice(*CHECKS.keys).each do |option, option_value|
-
17
case option
-
when :odd, :even
-
unless value.to_i.send(CHECKS[option])
-
record.errors.add(attr_name, option, filtered_options(value))
-
end
-
else
-
17
option_value = option_value.call(record) if option_value.is_a?(Proc)
-
17
option_value = record.send(option_value) if option_value.is_a?(Symbol)
-
-
17
unless value.send(CHECKS[option], option_value)
-
record.errors.add(attr_name, option, filtered_options(value).merge(:count => option_value))
-
end
-
end
-
end
-
end
-
-
2
protected
-
-
2
def parse_raw_value_as_a_number(raw_value)
-
17
case raw_value
-
when /\A0[xX]/
-
nil
-
else
-
17
begin
-
17
Kernel.Float(raw_value)
-
rescue ArgumentError, TypeError
-
nil
-
end
-
end
-
end
-
-
2
def parse_raw_value_as_an_integer(raw_value)
-
17
raw_value.to_i if raw_value.to_s =~ /\A[+-]?\d+\Z/
-
end
-
-
2
def filtered_options(value)
-
options.except(*RESERVED_OPTIONS).merge!(:value => value)
-
end
-
end
-
-
2
module HelperMethods
-
# Validates whether the value of the specified attribute is numeric by trying to convert it to
-
# a float with Kernel.Float (if <tt>only_integer</tt> is false) or applying it to the regular expression
-
# <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>only_integer</tt> is set to true).
-
#
-
# class Person < ActiveRecord::Base
-
# validates_numericality_of :value, :on => :create
-
# end
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "is not a number").
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:only_integer</tt> - Specifies whether the value has to be an integer, e.g. an integral value (default is +false+).
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is
-
# +false+). Notice that for fixnum and float columns empty strings are
-
# converted to +nil+.
-
# * <tt>:greater_than</tt> - Specifies the value must be greater than the
-
# supplied value.
-
# * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be greater
-
# than or equal the supplied value.
-
# * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied value.
-
# * <tt>:less_than</tt> - Specifies the value must be less than the supplied
-
# value.
-
# * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less than
-
# or equal the supplied value.
-
# * <tt>:odd</tt> - Specifies the value must be an odd number.
-
# * <tt>:even</tt> - Specifies the value must be an even number.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
-
# or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a true or false value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
-
# or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
-
# proc or string should return or evaluate to a true or false value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
#
-
# The following checks can also be supplied with a proc or a symbol which corresponds to a method:
-
# * <tt>:greater_than</tt>
-
# * <tt>:greater_than_or_equal_to</tt>
-
# * <tt>:equal_to</tt>
-
# * <tt>:less_than</tt>
-
# * <tt>:less_than_or_equal_to</tt>
-
#
-
# For example:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_numericality_of :width, :less_than => Proc.new { |person| person.height }
-
# validates_numericality_of :width, :greater_than => :minimum_weight
-
# end
-
2
def validates_numericality_of(*attr_names)
-
validates_with NumericalityValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActiveModel
-
# == Active Model Presence Validator
-
2
module Validations
-
2
class PresenceValidator < EachValidator
-
2
def validate(record)
-
record.errors.add_on_blank(attributes, options)
-
end
-
end
-
-
2
module HelperMethods
-
# Validates that the specified attributes are not blank (as defined by
-
# Object#blank?). Happens by default on save. Example:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_presence_of :first_name
-
# end
-
#
-
# The first_name attribute must be in the object and it cannot be blank.
-
#
-
# If you want to validate the presence of a boolean field (where the real values
-
# are true and false), you will want to use <tt>validates_inclusion_of :field_name,
-
# :in => [true, false]</tt>.
-
#
-
# This is due to the way Object#blank? handles boolean values:
-
# <tt>false.blank? # => true</tt>.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "can't be blank").
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
-
# the validation should occur (e.g. <tt>:if => :allow_validation</tt>, or
-
# <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
-
# or string should return or evaluate to a true or false value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
-
# or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
-
# proc or string should return or evaluate to a true or false value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
2
def validates_presence_of(*attr_names)
-
validates_with PresenceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/slice'
-
-
2
module ActiveModel
-
# == Active Model validates method
-
2
module Validations
-
2
module ClassMethods
-
# This method is a shortcut to all default validators and any custom
-
# validator classes ending in 'Validator'. Note that Rails default
-
# validators can be overridden inside specific classes by creating
-
# custom validator classes in their place such as PresenceValidator.
-
#
-
# Examples of using the default rails validators:
-
#
-
# validates :terms, :acceptance => true
-
# validates :password, :confirmation => true
-
# validates :username, :exclusion => { :in => %w(admin superuser) }
-
# validates :email, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create }
-
# validates :age, :inclusion => { :in => 0..9 }
-
# validates :first_name, :length => { :maximum => 30 }
-
# validates :age, :numericality => true
-
# validates :username, :presence => true
-
# validates :username, :uniqueness => true
-
#
-
# The power of the +validates+ method comes when using custom validators
-
# and default validators in one call for a given attribute e.g.
-
#
-
# class EmailValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, (options[:message] || "is not an email") unless
-
# value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
-
# end
-
# end
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# attr_accessor :name, :email
-
#
-
# validates :name, :presence => true, :uniqueness => true, :length => { :maximum => 100 }
-
# validates :email, :presence => true, :email => true
-
# end
-
#
-
# Validator classes may also exist within the class being validated
-
# allowing custom modules of validators to be included as needed e.g.
-
#
-
# class Film
-
# include ActiveModel::Validations
-
#
-
# class TitleValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/i
-
# end
-
# end
-
#
-
# validates :name, :title => true
-
# end
-
#
-
# Additionally validator classes may be in another namespace and still used within any class.
-
#
-
# validates :name, :'film/title' => true
-
#
-
# The validators hash can also handle regular expressions, ranges,
-
# arrays and strings in shortcut form, e.g.
-
#
-
# validates :email, :format => /@/
-
# validates :gender, :inclusion => %w(male female)
-
# validates :password, :length => 6..20
-
#
-
# When using shortcut form, ranges and arrays are passed to your
-
# validator's initializer as +options[:in]+ while other types including
-
# regular expressions and strings are passed as +options[:with]+
-
#
-
# Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+, +:allow_nil+ and +:strict+
-
# can be given to one specific validator, as a hash:
-
#
-
# validates :password, :presence => { :if => :password_required? }, :confirmation => true
-
#
-
# Or to all at the same time:
-
#
-
# validates :password, :presence => true, :confirmation => true, :if => :password_required?
-
#
-
2
def validates(*attributes)
-
16
defaults = attributes.extract_options!
-
16
validations = defaults.slice!(*_validates_default_keys)
-
-
16
raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?
-
16
raise ArgumentError, "You need to supply at least one validation" if validations.empty?
-
-
16
defaults.merge!(:attributes => attributes)
-
-
16
validations.each do |key, options|
-
18
key = "#{key.to_s.camelize}Validator"
-
-
18
begin
-
18
validator = key.include?('::') ? key.constantize : const_get(key)
-
rescue NameError
-
raise ArgumentError, "Unknown validator: '#{key}'"
-
end
-
-
18
validates_with(validator, defaults.merge(_parse_validates_options(options)))
-
end
-
end
-
-
# This method is used to define validation that cannot be corrected by end
-
# user and is considered exceptional. So each validator defined with bang
-
# or <tt>:strict</tt> option set to <tt>true</tt> will always raise
-
# <tt>ActiveModel::StrictValidationFailed</tt> instead of adding error
-
# when validation fails.
-
# See <tt>validates</tt> for more information about validation itself.
-
2
def validates!(*attributes)
-
options = attributes.extract_options!
-
options[:strict] = true
-
validates(*(attributes << options))
-
end
-
-
2
protected
-
-
# When creating custom validators, it might be useful to be able to specify
-
# additional default keys. This can be done by overwriting this method.
-
2
def _validates_default_keys
-
16
[:if, :unless, :on, :allow_blank, :allow_nil , :strict]
-
end
-
-
2
def _parse_validates_options(options) #:nodoc:
-
18
case options
-
when TrueClass
-
14
{}
-
when Hash
-
4
options
-
when Range, Array
-
{ :in => options }
-
else
-
{ :with => options }
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveModel
-
2
module Validations
-
2
module HelperMethods
-
2
private
-
2
def _merge_attributes(attr_names)
-
options = attr_names.extract_options!
-
options.merge(:attributes => attr_names.flatten)
-
end
-
end
-
-
2
class WithValidator < EachValidator
-
2
def validate_each(record, attr, val)
-
method_name = options[:with]
-
-
if record.method(method_name).arity == 0
-
record.send method_name
-
else
-
record.send method_name, attr
-
end
-
end
-
end
-
-
2
module ClassMethods
-
# Passes the record off to the class or classes specified and allows them
-
# to add errors based on more complex conditions.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# if some_complex_logic
-
# record.errors.add :base, "This record is invalid"
-
# end
-
# end
-
#
-
# private
-
# def some_complex_logic
-
# # ...
-
# end
-
# end
-
#
-
# You may also pass it multiple classes, like so:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator, MyOtherValidator, :on => :create
-
# end
-
#
-
# Configuration options:
-
# * <tt>:on</tt> - Specifies when this validation is active
-
# (<tt>:create</tt> or <tt>:update</tt>
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
-
# or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a true or false value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>:unless => :skip_validation</tt>,
-
# or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
-
# proc or string should return or evaluate to a true or false value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
-
# If you pass any additional configuration options, they will be passed
-
# to the class and available as <tt>options</tt>:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator, :my_custom_key => "my custom value"
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# options[:my_custom_key] # => "my custom value"
-
# end
-
# end
-
2
def validates_with(*args, &block)
-
18
options = args.extract_options!
-
18
args.each do |klass|
-
18
validator = klass.new(options, &block)
-
18
validator.setup(self) if validator.respond_to?(:setup)
-
-
18
if validator.respond_to?(:attributes) && !validator.attributes.empty?
-
18
validator.attributes.each do |attribute|
-
18
_validators[attribute.to_sym] << validator
-
end
-
else
-
_validators[nil] << validator
-
end
-
-
18
validate(validator, options)
-
end
-
end
-
end
-
-
# Passes the record off to the class or classes specified and allows them
-
# to add errors based on more complex conditions.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validate :instance_validations
-
#
-
# def instance_validations
-
# validates_with MyValidator
-
# end
-
# end
-
#
-
# Please consult the class method documentation for more information on
-
# creating your own validator.
-
#
-
# You may also pass it multiple classes, like so:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validate :instance_validations, :on => :create
-
#
-
# def instance_validations
-
# validates_with MyValidator, MyOtherValidator
-
# end
-
# end
-
#
-
# Standard configuration options (:on, :if and :unless), which are
-
# available on the class version of validates_with, should instead be
-
# placed on the <tt>validates</tt> method as these are applied and tested
-
# in the callback.
-
#
-
# If you pass any additional configuration options, they will be passed
-
# to the class and available as <tt>options</tt>, please refer to the
-
# class version of this method for more information.
-
2
def validates_with(*args, &block)
-
options = args.extract_options!
-
args.each do |klass|
-
validator = klass.new(options, &block)
-
validator.validate(self)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
2
require "active_support/core_ext/module/anonymous"
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/object/inclusion'
-
-
2
module ActiveModel #:nodoc:
-
-
# == Active Model Validator
-
#
-
# A simple base class that can be used along with
-
# ActiveModel::Validations::ClassMethods.validates_with
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# if some_complex_logic
-
# record.errors[:base] = "This record is invalid"
-
# end
-
# end
-
#
-
# private
-
# def some_complex_logic
-
# # ...
-
# end
-
# end
-
#
-
# Any class that inherits from ActiveModel::Validator must implement a method
-
# called <tt>validate</tt> which accepts a <tt>record</tt>.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# record # => The person instance being validated
-
# options # => Any non-standard options passed to validates_with
-
# end
-
# end
-
#
-
# To cause a validation error, you must add to the <tt>record</tt>'s errors directly
-
# from within the validators message
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# record.errors.add :base, "This is some custom error message"
-
# record.errors.add :first_name, "This is some complex validation"
-
# # etc...
-
# end
-
# end
-
#
-
# To add behavior to the initialize method, use the following signature:
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def initialize(options)
-
# super
-
# @my_custom_field = options[:field_name] || :first_name
-
# end
-
# end
-
#
-
# The easiest way to add custom validators for validating individual attributes
-
# is with the convenient <tt>ActiveModel::EachValidator</tt>. For example:
-
#
-
# class TitleValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, 'must be Mr. Mrs. or Dr.' unless value.in?(['Mr.', 'Mrs.', 'Dr.'])
-
# end
-
# end
-
#
-
# This can now be used in combination with the +validates+ method
-
# (see <tt>ActiveModel::Validations::ClassMethods.validates</tt> for more on this)
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# attr_accessor :title
-
#
-
# validates :title, :presence => true
-
# end
-
#
-
# Validator may also define a +setup+ instance method which will get called
-
# with the class that using that validator as its argument. This can be
-
# useful when there are prerequisites such as an +attr_accessor+ being present
-
# for example:
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def setup(klass)
-
# klass.send :attr_accessor, :custom_attribute
-
# end
-
# end
-
#
-
# This setup method is only called when used with validation macros or the
-
# class level <tt>validates_with</tt> method.
-
#
-
2
class Validator
-
2
attr_reader :options
-
-
# Returns the kind of the validator. Examples:
-
#
-
# PresenceValidator.kind # => :presence
-
# UniquenessValidator.kind # => :uniqueness
-
#
-
2
def self.kind
-
@kind ||= name.split('::').last.underscore.sub(/_validator$/, '').to_sym unless anonymous?
-
end
-
-
# Accepts options that will be made available through the +options+ reader.
-
2
def initialize(options)
-
18
@options = options.freeze
-
end
-
-
# Return the kind for this validator.
-
2
def kind
-
self.class.kind
-
end
-
-
# Override this method in subclasses with validation logic, adding errors
-
# to the records +errors+ array where necessary.
-
2
def validate(record)
-
raise NotImplementedError, "Subclasses must implement a validate(record) method."
-
end
-
end
-
-
# +EachValidator+ is a validator which iterates through the attributes given
-
# in the options hash invoking the <tt>validate_each</tt> method passing in the
-
# record, attribute and value.
-
#
-
# All Active Model validations are built on top of this validator.
-
2
class EachValidator < Validator
-
2
attr_reader :attributes
-
-
# Returns a new validator instance. All options will be available via the
-
# +options+ reader, however the <tt>:attributes</tt> option will be removed
-
# and instead be made available through the +attributes+ reader.
-
2
def initialize(options)
-
18
@attributes = Array.wrap(options.delete(:attributes))
-
18
raise ":attributes cannot be blank" if @attributes.empty?
-
18
super
-
18
check_validity!
-
end
-
-
# Performs validation on the supplied record. By default this will call
-
# +validates_each+ to determine validity therefore subclasses should
-
# override +validates_each+ with validation logic.
-
2
def validate(record)
-
17
attributes.each do |attribute|
-
17
value = record.read_attribute_for_validation(attribute)
-
17
next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
-
17
validate_each(record, attribute, value)
-
end
-
end
-
-
# Override this method in subclasses with the validation logic, adding
-
# errors to the records +errors+ array where necessary.
-
2
def validate_each(record, attribute, value)
-
raise NotImplementedError, "Subclasses must implement a validate_each(record, attribute, value) method"
-
end
-
-
# Hook method that gets called by the initializer allowing verification
-
# that the arguments supplied are valid. You could for example raise an
-
# +ArgumentError+ when invalid options are supplied.
-
2
def check_validity!
-
end
-
end
-
-
# +BlockValidator+ is a special +EachValidator+ which receives a block on initialization
-
# and call this block for each attribute being validated. +validates_each+ uses this validator.
-
2
class BlockValidator < EachValidator
-
2
def initialize(options, &block)
-
@block = block
-
super
-
end
-
-
2
private
-
-
2
def validate_each(record, attribute, value)
-
@block.call(record, attribute, value)
-
end
-
end
-
end
-
2
module ActiveModel
-
2
module VERSION #:nodoc:
-
2
MAJOR = 3
-
2
MINOR = 2
-
2
TINY = 16
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
-
end
-
end
-
#--
-
# Copyright (c) 2004-2011 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
require 'active_support'
-
2
require 'active_support/i18n'
-
2
require 'active_model'
-
2
require 'arel'
-
-
2
require 'active_record/version'
-
-
2
module ActiveRecord
-
2
extend ActiveSupport::Autoload
-
-
# ActiveRecord::SessionStore depends on the abstract store in Action Pack.
-
# Eager loading this class would break client code that eager loads Active
-
# Record standalone.
-
#
-
# Note that the Rails application generator creates an initializer specific
-
# for setting the session store. Thus, albeit in theory this autoload would
-
# not be thread-safe, in practice it is because if the application uses this
-
# session store its autoload happens at boot time.
-
2
autoload :SessionStore
-
-
2
eager_autoload do
-
2
autoload :ActiveRecordError, 'active_record/errors'
-
2
autoload :ConnectionNotEstablished, 'active_record/errors'
-
2
autoload :ConnectionAdapters, 'active_record/connection_adapters/abstract_adapter'
-
-
2
autoload :Aggregations
-
2
autoload :Associations
-
2
autoload :AttributeMethods
-
2
autoload :AttributeAssignment
-
2
autoload :AutosaveAssociation
-
-
2
autoload :Relation
-
-
2
autoload_under 'relation' do
-
2
autoload :QueryMethods
-
2
autoload :FinderMethods
-
2
autoload :Calculations
-
2
autoload :PredicateBuilder
-
2
autoload :SpawnMethods
-
2
autoload :Batches
-
2
autoload :Explain
-
2
autoload :Delegation
-
end
-
-
2
autoload :Base
-
2
autoload :Callbacks
-
2
autoload :CounterCache
-
2
autoload :DynamicMatchers
-
2
autoload :DynamicFinderMatch
-
2
autoload :DynamicScopeMatch
-
2
autoload :Explain
-
2
autoload :IdentityMap
-
2
autoload :Inheritance
-
2
autoload :Integration
-
2
autoload :Migration
-
2
autoload :Migrator, 'active_record/migration'
-
2
autoload :ModelSchema
-
2
autoload :NestedAttributes
-
2
autoload :Observer
-
2
autoload :Persistence
-
2
autoload :QueryCache
-
2
autoload :Querying
-
2
autoload :ReadonlyAttributes
-
2
autoload :Reflection
-
2
autoload :Result
-
2
autoload :Sanitization
-
2
autoload :Schema
-
2
autoload :SchemaDumper
-
2
autoload :Scoping
-
2
autoload :Serialization
-
2
autoload :Store
-
2
autoload :Timestamp
-
2
autoload :Transactions
-
2
autoload :Translation
-
2
autoload :Validations
-
end
-
-
2
module Coders
-
2
autoload :YAMLColumn, 'active_record/coders/yaml_column'
-
end
-
-
2
module AttributeMethods
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :BeforeTypeCast
-
2
autoload :Dirty
-
2
autoload :PrimaryKey
-
2
autoload :Query
-
2
autoload :Read
-
2
autoload :TimeZoneConversion
-
2
autoload :Write
-
2
autoload :Serialization
-
2
autoload :DeprecatedUnderscoreRead
-
end
-
end
-
-
2
module Locking
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :Optimistic
-
2
autoload :Pessimistic
-
end
-
end
-
-
2
module ConnectionAdapters
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :AbstractAdapter
-
2
autoload :ConnectionManagement, "active_record/connection_adapters/abstract/connection_pool"
-
end
-
end
-
-
2
module Scoping
-
2
extend ActiveSupport::Autoload
-
-
2
eager_autoload do
-
2
autoload :Named
-
2
autoload :Default
-
end
-
end
-
-
2
autoload :TestCase
-
2
autoload :TestFixtures, 'active_record/fixtures'
-
end
-
-
2
ActiveSupport.on_load(:active_record) do
-
2
Arel::Table.engine = self
-
end
-
-
2
I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
-
2
module ActiveRecord
-
# = Active Record Aggregations
-
2
module Aggregations # :nodoc:
-
2
extend ActiveSupport::Concern
-
-
2
def clear_aggregation_cache #:nodoc:
-
4
@aggregation_cache.clear if persisted?
-
end
-
-
# Active Record implements aggregation through a macro-like class method called +composed_of+
-
# for representing attributes as value objects. It expresses relationships like "Account [is]
-
# composed of Money [among other things]" or "Person [is] composed of [an] address". Each call
-
# to the macro adds a description of how the value objects are created from the attributes of
-
# the entity object (when the entity is initialized either as a new object or from finding an
-
# existing object) and how it can be turned back into attributes (when the entity is saved to
-
# the database).
-
#
-
# class Customer < ActiveRecord::Base
-
# composed_of :balance, :class_name => "Money", :mapping => %w(balance amount)
-
# composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
-
# end
-
#
-
# The customer class now has the following methods to manipulate the value objects:
-
# * <tt>Customer#balance, Customer#balance=(money)</tt>
-
# * <tt>Customer#address, Customer#address=(address)</tt>
-
#
-
# These methods will operate with value objects like the ones described below:
-
#
-
# class Money
-
# include Comparable
-
# attr_reader :amount, :currency
-
# EXCHANGE_RATES = { "USD_TO_DKK" => 6 }
-
#
-
# def initialize(amount, currency = "USD")
-
# @amount, @currency = amount, currency
-
# end
-
#
-
# def exchange_to(other_currency)
-
# exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor
-
# Money.new(exchanged_amount, other_currency)
-
# end
-
#
-
# def ==(other_money)
-
# amount == other_money.amount && currency == other_money.currency
-
# end
-
#
-
# def <=>(other_money)
-
# if currency == other_money.currency
-
# amount <=> other_money.amount
-
# else
-
# amount <=> other_money.exchange_to(currency).amount
-
# end
-
# end
-
# end
-
#
-
# class Address
-
# attr_reader :street, :city
-
# def initialize(street, city)
-
# @street, @city = street, city
-
# end
-
#
-
# def close_to?(other_address)
-
# city == other_address.city
-
# end
-
#
-
# def ==(other_address)
-
# city == other_address.city && street == other_address.street
-
# end
-
# end
-
#
-
# Now it's possible to access attributes from the database through the value objects instead. If
-
# you choose to name the composition the same as the attribute's name, it will be the only way to
-
# access that attribute. That's the case with our +balance+ attribute. You interact with the value
-
# objects just like you would any other attribute, though:
-
#
-
# customer.balance = Money.new(20) # sets the Money value object and the attribute
-
# customer.balance # => Money value object
-
# customer.balance.exchange_to("DKK") # => Money.new(120, "DKK")
-
# customer.balance > Money.new(10) # => true
-
# customer.balance == Money.new(20) # => true
-
# customer.balance < Money.new(5) # => false
-
#
-
# Value objects can also be composed of multiple attributes, such as the case of Address. The order
-
# of the mappings will determine the order of the parameters.
-
#
-
# customer.address_street = "Hyancintvej"
-
# customer.address_city = "Copenhagen"
-
# customer.address # => Address.new("Hyancintvej", "Copenhagen")
-
# customer.address = Address.new("May Street", "Chicago")
-
# customer.address_street # => "May Street"
-
# customer.address_city # => "Chicago"
-
#
-
# == Writing value objects
-
#
-
# Value objects are immutable and interchangeable objects that represent a given value, such as
-
# a Money object representing $5. Two Money objects both representing $5 should be equal (through
-
# methods such as <tt>==</tt> and <tt><=></tt> from Comparable if ranking makes sense). This is
-
# unlike entity objects where equality is determined by identity. An entity class such as Customer can
-
# easily have two different objects that both have an address on Hyancintvej. Entity identity is
-
# determined by object or relational unique identifiers (such as primary keys). Normal
-
# ActiveRecord::Base classes are entity objects.
-
#
-
# It's also important to treat the value objects as immutable. Don't allow the Money object to have
-
# its amount changed after creation. Create a new Money object with the new value instead. This
-
# is exemplified by the Money#exchange_to method that returns a new value object instead of changing
-
# its own values. Active Record won't persist value objects that have been changed through means
-
# other than the writer method.
-
#
-
# The immutable requirement is enforced by Active Record by freezing any object assigned as a value
-
# object. Attempting to change it afterwards will result in a ActiveSupport::FrozenObjectError.
-
#
-
# Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not
-
# keeping value objects immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
-
#
-
# == Custom constructors and converters
-
#
-
# By default value objects are initialized by calling the <tt>new</tt> constructor of the value
-
# class passing each of the mapped attributes, in the order specified by the <tt>:mapping</tt>
-
# option, as arguments. If the value class doesn't support this convention then +composed_of+ allows
-
# a custom constructor to be specified.
-
#
-
# When a new value is assigned to the value object the default assumption is that the new value
-
# is an instance of the value class. Specifying a custom converter allows the new value to be automatically
-
# converted to an instance of value class if necessary.
-
#
-
# For example, the NetworkResource model has +network_address+ and +cidr_range+ attributes that
-
# should be aggregated using the NetAddr::CIDR value class (http://netaddr.rubyforge.org). The constructor
-
# for the value class is called +create+ and it expects a CIDR address string as a parameter. New
-
# values can be assigned to the value object using either another NetAddr::CIDR object, a string
-
# or an array. The <tt>:constructor</tt> and <tt>:converter</tt> options can be used to meet
-
# these requirements:
-
#
-
# class NetworkResource < ActiveRecord::Base
-
# composed_of :cidr,
-
# :class_name => 'NetAddr::CIDR',
-
# :mapping => [ %w(network_address network), %w(cidr_range bits) ],
-
# :allow_nil => true,
-
# :constructor => Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") },
-
# :converter => Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) }
-
# end
-
#
-
# # This calls the :constructor
-
# network_resource = NetworkResource.new(:network_address => '192.168.0.1', :cidr_range => 24)
-
#
-
# # These assignments will both use the :converter
-
# network_resource.cidr = [ '192.168.2.1', 8 ]
-
# network_resource.cidr = '192.168.0.1/24'
-
#
-
# # This assignment won't use the :converter as the value is already an instance of the value class
-
# network_resource.cidr = NetAddr::CIDR.create('192.168.2.1/8')
-
#
-
# # Saving and then reloading will use the :constructor on reload
-
# network_resource.save
-
# network_resource.reload
-
#
-
# == Finding records by a value object
-
#
-
# Once a +composed_of+ relationship is specified for a model, records can be loaded from the database
-
# by specifying an instance of the value object in the conditions hash. The following example
-
# finds all customers with +balance_amount+ equal to 20 and +balance_currency+ equal to "USD":
-
#
-
# Customer.where(:balance => Money.new(20, "USD")).all
-
#
-
2
module ClassMethods
-
# Adds reader and writer methods for manipulating a value object:
-
# <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods.
-
#
-
# Options are:
-
# * <tt>:class_name</tt> - Specifies the class name of the association. Use it only if that name
-
# can't be inferred from the part id. So <tt>composed_of :address</tt> will by default be linked
-
# to the Address class, but if the real class name is CompanyAddress, you'll have to specify it
-
# with this option.
-
# * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value
-
# object. Each mapping is represented as an array where the first item is the name of the
-
# entity attribute and the second item is the name of the attribute in the value object. The
-
# order in which mappings are defined determines the order in which attributes are sent to the
-
# value class constructor.
-
# * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped
-
# attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all
-
# mapped attributes.
-
# This defaults to +false+.
-
# * <tt>:constructor</tt> - A symbol specifying the name of the constructor method or a Proc that
-
# is called to initialize the value object. The constructor is passed all of the mapped attributes,
-
# in the order that they are defined in the <tt>:mapping option</tt>, as arguments and uses them
-
# to instantiate a <tt>:class_name</tt> object.
-
# The default is <tt>:new</tt>.
-
# * <tt>:converter</tt> - A symbol specifying the name of a class method of <tt>:class_name</tt>
-
# or a Proc that is called when a new value is assigned to the value object. The converter is
-
# passed the single value that is used in the assignment and is only called if the new value is
-
# not an instance of <tt>:class_name</tt>.
-
#
-
# Option examples:
-
# composed_of :temperature, :mapping => %w(reading celsius)
-
# composed_of :balance, :class_name => "Money", :mapping => %w(balance amount),
-
# :converter => Proc.new { |balance| balance.to_money }
-
# composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
-
# composed_of :gps_location
-
# composed_of :gps_location, :allow_nil => true
-
# composed_of :ip_address,
-
# :class_name => 'IPAddr',
-
# :mapping => %w(ip to_i),
-
# :constructor => Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) },
-
# :converter => Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) }
-
#
-
2
def composed_of(part_id, options = {})
-
options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter)
-
-
name = part_id.id2name
-
class_name = options[:class_name] || name.camelize
-
mapping = options[:mapping] || [ name, name ]
-
mapping = [ mapping ] unless mapping.first.is_a?(Array)
-
allow_nil = options[:allow_nil] || false
-
constructor = options[:constructor] || :new
-
converter = options[:converter]
-
-
reader_method(name, class_name, mapping, allow_nil, constructor)
-
writer_method(name, class_name, mapping, allow_nil, converter)
-
-
create_reflection(:composed_of, part_id, options, self)
-
end
-
-
2
private
-
2
def reader_method(name, class_name, mapping, allow_nil, constructor)
-
define_method(name) do
-
if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|pair| !read_attribute(pair.first).nil? })
-
attrs = mapping.collect {|pair| read_attribute(pair.first)}
-
object = constructor.respond_to?(:call) ?
-
constructor.call(*attrs) :
-
class_name.constantize.send(constructor, *attrs)
-
@aggregation_cache[name] = object
-
end
-
@aggregation_cache[name]
-
end
-
end
-
-
2
def writer_method(name, class_name, mapping, allow_nil, converter)
-
define_method("#{name}=") do |part|
-
if part.nil? && allow_nil
-
mapping.each { |pair| self[pair.first] = nil }
-
@aggregation_cache[name] = nil
-
else
-
unless part.is_a?(class_name.constantize) || converter.nil?
-
part = converter.respond_to?(:call) ?
-
converter.call(part) :
-
class_name.constantize.send(converter, part)
-
end
-
-
mapping.each { |pair| self[pair.first] = part.send(pair.last) }
-
@aggregation_cache[name] = part.freeze
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/enumerable'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/string/conversions'
-
2
require 'active_support/core_ext/module/remove_method'
-
2
require 'active_support/core_ext/class/attribute'
-
-
2
module ActiveRecord
-
2
class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc:
-
2
def initialize(reflection, associated_class = nil)
-
super("Could not find the inverse association for #{reflection.name} (#{reflection.options[:inverse_of].inspect} in #{associated_class.nil? ? reflection.class_name : associated_class.name})")
-
end
-
end
-
-
2
class HasManyThroughAssociationNotFoundError < ActiveRecordError #:nodoc:
-
2
def initialize(owner_class_name, reflection)
-
super("Could not find the association #{reflection.options[:through].inspect} in model #{owner_class_name}")
-
end
-
end
-
-
2
class HasManyThroughAssociationPolymorphicSourceError < ActiveRecordError #:nodoc:
-
2
def initialize(owner_class_name, reflection, source_reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}'.")
-
end
-
end
-
-
2
class HasManyThroughAssociationPolymorphicThroughError < ActiveRecordError #:nodoc:
-
2
def initialize(owner_class_name, reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.")
-
end
-
end
-
-
2
class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc:
-
2
def initialize(owner_class_name, reflection, source_reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.")
-
end
-
end
-
-
2
class HasOneThroughCantAssociateThroughCollection < ActiveRecordError #:nodoc:
-
2
def initialize(owner_class_name, reflection, through_reflection)
-
super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' where the :through association '#{owner_class_name}##{through_reflection.name}' is a collection. Specify a has_one or belongs_to association in the :through option instead.")
-
end
-
end
-
-
2
class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc:
-
2
def initialize(reflection)
-
through_reflection = reflection.through_reflection
-
source_reflection_names = reflection.source_reflection_names
-
source_associations = reflection.through_reflection.klass.reflect_on_all_associations.collect { |a| a.name.inspect }
-
super("Could not find the source association(s) #{source_reflection_names.collect{ |a| a.inspect }.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?")
-
end
-
end
-
-
2
class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ActiveRecordError #:nodoc:
-
2
def initialize(owner, reflection)
-
super("Cannot modify association '#{owner.class.name}##{reflection.name}' because the source reflection class '#{reflection.source_reflection.class_name}' is associated to '#{reflection.through_reflection.class_name}' via :#{reflection.source_reflection.macro}.")
-
end
-
end
-
-
2
class HasManyThroughCantAssociateNewRecords < ActiveRecordError #:nodoc:
-
2
def initialize(owner, reflection)
-
super("Cannot associate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to create the has_many :through record associating them.")
-
end
-
end
-
-
2
class HasManyThroughCantDissociateNewRecords < ActiveRecordError #:nodoc:
-
2
def initialize(owner, reflection)
-
super("Cannot dissociate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to delete the has_many :through record associating them.")
-
end
-
end
-
-
2
class HasManyThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc:
-
2
def initialize(owner, reflection)
-
super("Cannot modify association '#{owner.class.name}##{reflection.name}' because it goes through more than one other association.")
-
end
-
end
-
-
2
class HasAndBelongsToManyAssociationForeignKeyNeeded < ActiveRecordError #:nodoc:
-
2
def initialize(reflection)
-
super("Cannot create self referential has_and_belongs_to_many association on '#{reflection.class_name rescue nil}##{reflection.name rescue nil}'. :association_foreign_key cannot be the same as the :foreign_key.")
-
end
-
end
-
-
2
class EagerLoadPolymorphicError < ActiveRecordError #:nodoc:
-
2
def initialize(reflection)
-
super("Can not eagerly load the polymorphic association #{reflection.name.inspect}")
-
end
-
end
-
-
2
class ReadOnlyAssociation < ActiveRecordError #:nodoc:
-
2
def initialize(reflection)
-
super("Can not add to a has_many :through association. Try adding to #{reflection.through_reflection.name.inspect}.")
-
end
-
end
-
-
# This error is raised when trying to destroy a parent instance in N:1 or 1:1 associations
-
# (has_many, has_one) when there is at least 1 child associated instance.
-
# ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project
-
2
class DeleteRestrictionError < ActiveRecordError #:nodoc:
-
2
def initialize(name)
-
super("Cannot delete record because of dependent #{name}")
-
end
-
end
-
-
# See ActiveRecord::Associations::ClassMethods for documentation.
-
2
module Associations # :nodoc:
-
2
extend ActiveSupport::Autoload
-
2
extend ActiveSupport::Concern
-
-
# These classes will be loaded when associations are created.
-
# So there is no need to eager load them.
-
2
autoload :Association, 'active_record/associations/association'
-
2
autoload :SingularAssociation, 'active_record/associations/singular_association'
-
2
autoload :CollectionAssociation, 'active_record/associations/collection_association'
-
2
autoload :CollectionProxy, 'active_record/associations/collection_proxy'
-
-
2
autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
-
2
autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association'
-
2
autoload :HasAndBelongsToManyAssociation, 'active_record/associations/has_and_belongs_to_many_association'
-
2
autoload :HasManyAssociation, 'active_record/associations/has_many_association'
-
2
autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
-
2
autoload :HasOneAssociation, 'active_record/associations/has_one_association'
-
2
autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
-
2
autoload :ThroughAssociation, 'active_record/associations/through_association'
-
-
2
module Builder #:nodoc:
-
2
autoload :Association, 'active_record/associations/builder/association'
-
2
autoload :SingularAssociation, 'active_record/associations/builder/singular_association'
-
2
autoload :CollectionAssociation, 'active_record/associations/builder/collection_association'
-
-
2
autoload :BelongsTo, 'active_record/associations/builder/belongs_to'
-
2
autoload :HasOne, 'active_record/associations/builder/has_one'
-
2
autoload :HasMany, 'active_record/associations/builder/has_many'
-
2
autoload :HasAndBelongsToMany, 'active_record/associations/builder/has_and_belongs_to_many'
-
end
-
-
2
eager_autoload do
-
2
autoload :Preloader, 'active_record/associations/preloader'
-
2
autoload :JoinDependency, 'active_record/associations/join_dependency'
-
2
autoload :AssociationScope, 'active_record/associations/association_scope'
-
2
autoload :AliasTracker, 'active_record/associations/alias_tracker'
-
2
autoload :JoinHelper, 'active_record/associations/join_helper'
-
end
-
-
# Clears out the association cache.
-
2
def clear_association_cache #:nodoc:
-
4
@association_cache.clear if persisted?
-
end
-
-
# :nodoc:
-
2
attr_reader :association_cache
-
-
# Returns the association instance for the given name, instantiating it if it doesn't already exist
-
2
def association(name) #:nodoc:
-
1045
association = association_instance_get(name)
-
-
1045
if association.nil?
-
293
reflection = self.class.reflect_on_association(name)
-
293
association = reflection.association_class.new(self, reflection)
-
293
association_instance_set(name, association)
-
end
-
-
1045
association
-
end
-
-
2
private
-
# Returns the specified association instance if it responds to :loaded?, nil otherwise.
-
2
def association_instance_get(name)
-
2675
@association_cache[name.to_sym]
-
end
-
-
# Set the specified association instance.
-
2
def association_instance_set(name, association)
-
293
@association_cache[name] = association
-
end
-
-
# Associations are a set of macro-like class methods for tying objects together through
-
# foreign keys. They express relationships like "Project has one Project Manager"
-
# or "Project belongs to a Portfolio". Each macro adds a number of methods to the
-
# class which are specialized according to the collection or association symbol and the
-
# options hash. It works much the same way as Ruby's own <tt>attr*</tt>
-
# methods.
-
#
-
# class Project < ActiveRecord::Base
-
# belongs_to :portfolio
-
# has_one :project_manager
-
# has_many :milestones
-
# has_and_belongs_to_many :categories
-
# end
-
#
-
# The project class now has the following methods (and more) to ease the traversal and
-
# manipulation of its relationships:
-
# * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
-
# * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
-
# * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
-
# <tt>Project#milestones.delete(milestone), Project#milestones.find(milestone_id), Project#milestones.all(options),</tt>
-
# <tt>Project#milestones.build, Project#milestones.create</tt>
-
# * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
-
# <tt>Project#categories.delete(category1)</tt>
-
#
-
# === Overriding generated methods
-
#
-
# Association methods are generated in a module that is included into the model class,
-
# which allows you to easily override with your own methods and call the original
-
# generated method with +super+. For example:
-
#
-
# class Car < ActiveRecord::Base
-
# belongs_to :owner
-
# belongs_to :old_owner
-
# def owner=(new_owner)
-
# self.old_owner = self.owner
-
# super
-
# end
-
# end
-
#
-
# If your model class is <tt>Project</tt>, the module is
-
# named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is
-
# included in the model class immediately after the (anonymous) generated attributes methods
-
# module, meaning an association will override the methods for an attribute with the same name.
-
#
-
# === A word of warning
-
#
-
# Don't create associations that have the same name as instance methods of
-
# <tt>ActiveRecord::Base</tt>. Since the association adds a method with that name to
-
# its model, it will override the inherited method and break things.
-
# For instance, +attributes+ and +connection+ would be bad choices for association names.
-
#
-
# == Auto-generated methods
-
#
-
# === Singular associations (one-to-one)
-
# | | belongs_to |
-
# generated methods | belongs_to | :polymorphic | has_one
-
# ----------------------------------+------------+--------------+---------
-
# other | X | X | X
-
# other=(other) | X | X | X
-
# build_other(attributes={}) | X | | X
-
# create_other(attributes={}) | X | | X
-
# create_other!(attributes={}) | X | | X
-
#
-
# ===Collection associations (one-to-many / many-to-many)
-
# | | | has_many
-
# generated methods | habtm | has_many | :through
-
# ----------------------------------+-------+----------+----------
-
# others | X | X | X
-
# others=(other,other,...) | X | X | X
-
# other_ids | X | X | X
-
# other_ids=(id,id,...) | X | X | X
-
# others<< | X | X | X
-
# others.push | X | X | X
-
# others.concat | X | X | X
-
# others.build(attributes={}) | X | X | X
-
# others.create(attributes={}) | X | X | X
-
# others.create!(attributes={}) | X | X | X
-
# others.size | X | X | X
-
# others.length | X | X | X
-
# others.count | X | X | X
-
# others.sum(args*,&block) | X | X | X
-
# others.empty? | X | X | X
-
# others.clear | X | X | X
-
# others.delete(other,other,...) | X | X | X
-
# others.delete_all | X | X | X
-
# others.destroy_all | X | X | X
-
# others.find(*args) | X | X | X
-
# others.exists? | X | X | X
-
# others.uniq | X | X | X
-
# others.reset | X | X | X
-
#
-
# == Cardinality and associations
-
#
-
# Active Record associations can be used to describe one-to-one, one-to-many and many-to-many
-
# relationships between models. Each model uses an association to describe its role in
-
# the relation. The +belongs_to+ association is always used in the model that has
-
# the foreign key.
-
#
-
# === One-to-one
-
#
-
# Use +has_one+ in the base, and +belongs_to+ in the associated model.
-
#
-
# class Employee < ActiveRecord::Base
-
# has_one :office
-
# end
-
# class Office < ActiveRecord::Base
-
# belongs_to :employee # foreign key - employee_id
-
# end
-
#
-
# === One-to-many
-
#
-
# Use +has_many+ in the base, and +belongs_to+ in the associated model.
-
#
-
# class Manager < ActiveRecord::Base
-
# has_many :employees
-
# end
-
# class Employee < ActiveRecord::Base
-
# belongs_to :manager # foreign key - manager_id
-
# end
-
#
-
# === Many-to-many
-
#
-
# There are two ways to build a many-to-many relationship.
-
#
-
# The first way uses a +has_many+ association with the <tt>:through</tt> option and a join model, so
-
# there are two stages of associations.
-
#
-
# class Assignment < ActiveRecord::Base
-
# belongs_to :programmer # foreign key - programmer_id
-
# belongs_to :project # foreign key - project_id
-
# end
-
# class Programmer < ActiveRecord::Base
-
# has_many :assignments
-
# has_many :projects, :through => :assignments
-
# end
-
# class Project < ActiveRecord::Base
-
# has_many :assignments
-
# has_many :programmers, :through => :assignments
-
# end
-
#
-
# For the second way, use +has_and_belongs_to_many+ in both models. This requires a join table
-
# that has no corresponding model or primary key.
-
#
-
# class Programmer < ActiveRecord::Base
-
# has_and_belongs_to_many :projects # foreign keys in the join table
-
# end
-
# class Project < ActiveRecord::Base
-
# has_and_belongs_to_many :programmers # foreign keys in the join table
-
# end
-
#
-
# Choosing which way to build a many-to-many relationship is not always simple.
-
# If you need to work with the relationship model as its own entity,
-
# use <tt>has_many :through</tt>. Use +has_and_belongs_to_many+ when working with legacy schemas or when
-
# you never work directly with the relationship itself.
-
#
-
# == Is it a +belongs_to+ or +has_one+ association?
-
#
-
# Both express a 1-1 relationship. The difference is mostly where to place the foreign
-
# key, which goes on the table for the class declaring the +belongs_to+ relationship.
-
#
-
# class User < ActiveRecord::Base
-
# # I reference an account.
-
# belongs_to :account
-
# end
-
#
-
# class Account < ActiveRecord::Base
-
# # One user references me.
-
# has_one :user
-
# end
-
#
-
# The tables for these classes could look something like:
-
#
-
# CREATE TABLE users (
-
# id int(11) NOT NULL auto_increment,
-
# account_id int(11) default NULL,
-
# name varchar default NULL,
-
# PRIMARY KEY (id)
-
# )
-
#
-
# CREATE TABLE accounts (
-
# id int(11) NOT NULL auto_increment,
-
# name varchar default NULL,
-
# PRIMARY KEY (id)
-
# )
-
#
-
# == Unsaved objects and associations
-
#
-
# You can manipulate objects and associations before they are saved to the database, but
-
# there is some special behavior you should be aware of, mostly involving the saving of
-
# associated objects.
-
#
-
# You can set the :autosave option on a <tt>has_one</tt>, <tt>belongs_to</tt>,
-
# <tt>has_many</tt>, or <tt>has_and_belongs_to_many</tt> association. Setting it
-
# to +true+ will _always_ save the members, whereas setting it to +false+ will
-
# _never_ save the members. More details about :autosave option is available at
-
# autosave_association.rb .
-
#
-
# === One-to-one associations
-
#
-
# * Assigning an object to a +has_one+ association automatically saves that object and
-
# the object being replaced (if there is one), in order to update their foreign
-
# keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
-
# * If either of these saves fail (due to one of the objects being invalid), an
-
# <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
-
# cancelled.
-
# * If you wish to assign an object to a +has_one+ association without saving it,
-
# use the <tt>build_association</tt> method (documented below). The object being
-
# replaced will still be saved to update its foreign key.
-
# * Assigning an object to a +belongs_to+ association does not save the object, since
-
# the foreign key field belongs on the parent. It does not save the parent either.
-
#
-
# === Collections
-
#
-
# * Adding an object to a collection (+has_many+ or +has_and_belongs_to_many+) automatically
-
# saves that object, except if the parent object (the owner of the collection) is not yet
-
# stored in the database.
-
# * If saving any of the objects being added to a collection (via <tt>push</tt> or similar)
-
# fails, then <tt>push</tt> returns +false+.
-
# * If saving fails while replacing the collection (via <tt>association=</tt>), an
-
# <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
-
# cancelled.
-
# * You can add an object to a collection without automatically saving it by using the
-
# <tt>collection.build</tt> method (documented below).
-
# * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically
-
# saved when the parent is saved.
-
#
-
# === Association callbacks
-
#
-
# Similar to the normal callbacks that hook into the life cycle of an Active Record object,
-
# you can also define callbacks that get triggered when you add an object to or remove an
-
# object from an association collection.
-
#
-
# class Project
-
# has_and_belongs_to_many :developers, :after_add => :evaluate_velocity
-
#
-
# def evaluate_velocity(developer)
-
# ...
-
# end
-
# end
-
#
-
# It's possible to stack callbacks by passing them as an array. Example:
-
#
-
# class Project
-
# has_and_belongs_to_many :developers,
-
# :after_add => [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
-
# end
-
#
-
# Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+.
-
#
-
# Should any of the +before_add+ callbacks throw an exception, the object does not get
-
# added to the collection. Same with the +before_remove+ callbacks; if an exception is
-
# thrown the object doesn't get removed.
-
#
-
# === Association extensions
-
#
-
# The proxy objects that control the access to associations can be extended through anonymous
-
# modules. This is especially beneficial for adding new finders, creators, and other
-
# factory-type methods that are only used as part of this association.
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :people do
-
# def find_or_create_by_name(name)
-
# first_name, last_name = name.split(" ", 2)
-
# find_or_create_by_first_name_and_last_name(first_name, last_name)
-
# end
-
# end
-
# end
-
#
-
# person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson")
-
# person.first_name # => "David"
-
# person.last_name # => "Heinemeier Hansson"
-
#
-
# If you need to share the same extensions between many associations, you can use a named
-
# extension module.
-
#
-
# module FindOrCreateByNameExtension
-
# def find_or_create_by_name(name)
-
# first_name, last_name = name.split(" ", 2)
-
# find_or_create_by_first_name_and_last_name(first_name, last_name)
-
# end
-
# end
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :people, :extend => FindOrCreateByNameExtension
-
# end
-
#
-
# class Company < ActiveRecord::Base
-
# has_many :people, :extend => FindOrCreateByNameExtension
-
# end
-
#
-
# If you need to use multiple named extension modules, you can specify an array of modules
-
# with the <tt>:extend</tt> option.
-
# In the case of name conflicts between methods in the modules, methods in modules later
-
# in the array supercede those earlier in the array.
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
-
# end
-
#
-
# Some extensions can only be made to work with knowledge of the association's internals.
-
# Extensions can access relevant state using the following methods (where +items+ is the
-
# name of the association):
-
#
-
# * <tt>record.association(:items).owner</tt> - Returns the object the association is part of.
-
# * <tt>record.association(:items).reflection</tt> - Returns the reflection object that describes the association.
-
# * <tt>record.association(:items).target</tt> - Returns the associated object for +belongs_to+ and +has_one+, or
-
# the collection of associated objects for +has_many+ and +has_and_belongs_to_many+.
-
#
-
# However, inside the actual extension code, you will not have access to the <tt>record</tt> as
-
# above. In this case, you can access <tt>proxy_association</tt>. For example,
-
# <tt>record.association(:items)</tt> and <tt>record.items.proxy_association</tt> will return
-
# the same object, allowing you to make calls like <tt>proxy_association.owner</tt> inside
-
# association extensions.
-
#
-
# === Association Join Models
-
#
-
# Has Many associations can be configured with the <tt>:through</tt> option to use an
-
# explicit join model to retrieve the data. This operates similarly to a
-
# +has_and_belongs_to_many+ association. The advantage is that you're able to add validations,
-
# callbacks, and extra attributes on the join model. Consider the following schema:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :authorships
-
# has_many :books, :through => :authorships
-
# end
-
#
-
# class Authorship < ActiveRecord::Base
-
# belongs_to :author
-
# belongs_to :book
-
# end
-
#
-
# @author = Author.first
-
# @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to
-
# @author.books # selects all books by using the Authorship join model
-
#
-
# You can also go through a +has_many+ association on the join model:
-
#
-
# class Firm < ActiveRecord::Base
-
# has_many :clients
-
# has_many :invoices, :through => :clients
-
# end
-
#
-
# class Client < ActiveRecord::Base
-
# belongs_to :firm
-
# has_many :invoices
-
# end
-
#
-
# class Invoice < ActiveRecord::Base
-
# belongs_to :client
-
# end
-
#
-
# @firm = Firm.first
-
# @firm.clients.collect { |c| c.invoices }.flatten # select all invoices for all clients of the firm
-
# @firm.invoices # selects all invoices by going through the Client join model
-
#
-
# Similarly you can go through a +has_one+ association on the join model:
-
#
-
# class Group < ActiveRecord::Base
-
# has_many :users
-
# has_many :avatars, :through => :users
-
# end
-
#
-
# class User < ActiveRecord::Base
-
# belongs_to :group
-
# has_one :avatar
-
# end
-
#
-
# class Avatar < ActiveRecord::Base
-
# belongs_to :user
-
# end
-
#
-
# @group = Group.first
-
# @group.users.collect { |u| u.avatar }.flatten # select all avatars for all users in the group
-
# @group.avatars # selects all avatars by going through the User join model.
-
#
-
# An important caveat with going through +has_one+ or +has_many+ associations on the
-
# join model is that these associations are *read-only*. For example, the following
-
# would not work following the previous example:
-
#
-
# @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around
-
# @group.avatars.delete(@group.avatars.last) # so would this
-
#
-
# If you are using a +belongs_to+ on the join model, it is a good idea to set the
-
# <tt>:inverse_of</tt> option on the +belongs_to+, which will mean that the following example
-
# works correctly (where <tt>tags</tt> is a +has_many+ <tt>:through</tt> association):
-
#
-
# @post = Post.first
-
# @tag = @post.tags.build :name => "ruby"
-
# @tag.save
-
#
-
# The last line ought to save the through record (a <tt>Taggable</tt>). This will only work if the
-
# <tt>:inverse_of</tt> is set:
-
#
-
# class Taggable < ActiveRecord::Base
-
# belongs_to :post
-
# belongs_to :tag, :inverse_of => :taggings
-
# end
-
#
-
# === Nested Associations
-
#
-
# You can actually specify *any* association with the <tt>:through</tt> option, including an
-
# association which has a <tt>:through</tt> option itself. For example:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# has_many :comments, :through => :posts
-
# has_many :commenters, :through => :comments
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# end
-
#
-
# class Comment < ActiveRecord::Base
-
# belongs_to :commenter
-
# end
-
#
-
# @author = Author.first
-
# @author.commenters # => People who commented on posts written by the author
-
#
-
# An equivalent way of setting up this association this would be:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# has_many :commenters, :through => :posts
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# has_many :commenters, :through => :comments
-
# end
-
#
-
# class Comment < ActiveRecord::Base
-
# belongs_to :commenter
-
# end
-
#
-
# When using nested association, you will not be able to modify the association because there
-
# is not enough information to know what modification to make. For example, if you tried to
-
# add a <tt>Commenter</tt> in the example above, there would be no way to tell how to set up the
-
# intermediate <tt>Post</tt> and <tt>Comment</tt> objects.
-
#
-
# === Polymorphic Associations
-
#
-
# Polymorphic associations on models are not restricted on what types of models they
-
# can be associated with. Rather, they specify an interface that a +has_many+ association
-
# must adhere to.
-
#
-
# class Asset < ActiveRecord::Base
-
# belongs_to :attachable, :polymorphic => true
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :assets, :as => :attachable # The :as option specifies the polymorphic interface to use.
-
# end
-
#
-
# @asset.attachable = @post
-
#
-
# This works by using a type column in addition to a foreign key to specify the associated
-
# record. In the Asset example, you'd need an +attachable_id+ integer column and an
-
# +attachable_type+ string column.
-
#
-
# Using polymorphic associations in combination with single table inheritance (STI) is
-
# a little tricky. In order for the associations to work as expected, ensure that you
-
# store the base model for the STI models in the type column of the polymorphic
-
# association. To continue with the asset example above, suppose there are guest posts
-
# and member posts that use the posts table for STI. In this case, there must be a +type+
-
# column in the posts table.
-
#
-
# class Asset < ActiveRecord::Base
-
# belongs_to :attachable, :polymorphic => true
-
#
-
# def attachable_type=(sType)
-
# super(sType.to_s.classify.constantize.base_class.to_s)
-
# end
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# # because we store "Post" in attachable_type now :dependent => :destroy will work
-
# has_many :assets, :as => :attachable, :dependent => :destroy
-
# end
-
#
-
# class GuestPost < Post
-
# end
-
#
-
# class MemberPost < Post
-
# end
-
#
-
# == Caching
-
#
-
# All of the methods are built on a simple caching principle that will keep the result
-
# of the last query around unless specifically instructed not to. The cache is even
-
# shared across methods to make it even cheaper to use the macro-added methods without
-
# worrying too much about performance at the first go.
-
#
-
# project.milestones # fetches milestones from the database
-
# project.milestones.size # uses the milestone cache
-
# project.milestones.empty? # uses the milestone cache
-
# project.milestones(true).size # fetches milestones from the database
-
# project.milestones # uses the milestone cache
-
#
-
# == Eager loading of associations
-
#
-
# Eager loading is a way to find objects of a certain class and a number of named associations.
-
# This is one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100
-
# posts that each need to display their author triggers 101 database queries. Through the
-
# use of eager loading, the 101 queries can be reduced to 2.
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :author
-
# has_many :comments
-
# end
-
#
-
# Consider the following loop using the class above:
-
#
-
# Post.all.each do |post|
-
# puts "Post: " + post.title
-
# puts "Written by: " + post.author.name
-
# puts "Last comment on: " + post.comments.first.created_on
-
# end
-
#
-
# To iterate over these one hundred posts, we'll generate 201 database queries. Let's
-
# first just optimize it for retrieving the author:
-
#
-
# Post.includes(:author).each do |post|
-
#
-
# This references the name of the +belongs_to+ association that also used the <tt>:author</tt>
-
# symbol. After loading the posts, find will collect the +author_id+ from each one and load
-
# all the referenced authors with one query. Doing so will cut down the number of queries
-
# from 201 to 102.
-
#
-
# We can improve upon the situation further by referencing both associations in the finder with:
-
#
-
# Post.includes(:author, :comments).each do |post|
-
#
-
# This will load all comments with a single query. This reduces the total number of queries
-
# to 3. More generally the number of queries will be 1 plus the number of associations
-
# named (except if some of the associations are polymorphic +belongs_to+ - see below).
-
#
-
# To include a deep hierarchy of associations, use a hash:
-
#
-
# Post.includes(:author, {:comments => {:author => :gravatar}}).each do |post|
-
#
-
# That'll grab not only all the comments but all their authors and gravatar pictures.
-
# You can mix and match symbols, arrays and hashes in any combination to describe the
-
# associations you want to load.
-
#
-
# All of this power shouldn't fool you into thinking that you can pull out huge amounts
-
# of data with no performance penalty just because you've reduced the number of queries.
-
# The database still needs to send all the data to Active Record and it still needs to
-
# be processed. So it's no catch-all for performance problems, but it's a great way to
-
# cut down on the number of queries in a situation as the one described above.
-
#
-
# Since only one table is loaded at a time, conditions or orders cannot reference tables
-
# other than the main one. If this is the case Active Record falls back to the previously
-
# used LEFT OUTER JOIN based strategy. For example
-
#
-
# Post.includes([:author, :comments]).where(['comments.approved = ?', true]).all
-
#
-
# This will result in a single SQL query with joins along the lines of:
-
# <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
-
# <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions
-
# like this can have unintended consequences.
-
# In the above example posts with no approved comments are not returned at all, because
-
# the conditions apply to the SQL statement as a whole and not just to the association.
-
# You must disambiguate column references for this fallback to happen, for example
-
# <tt>:order => "author.name DESC"</tt> will work but <tt>:order => "name DESC"</tt> will not.
-
#
-
# If you do want eager load only some members of an association it is usually more natural
-
# to include an association which has conditions defined on it:
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :approved_comments, :class_name => 'Comment', :conditions => ['approved = ?', true]
-
# end
-
#
-
# Post.includes(:approved_comments)
-
#
-
# This will load posts and eager load the +approved_comments+ association, which contains
-
# only those comments that have been approved.
-
#
-
# If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored,
-
# returning all the associated objects:
-
#
-
# class Picture < ActiveRecord::Base
-
# has_many :most_recent_comments, :class_name => 'Comment', :order => 'id DESC', :limit => 10
-
# end
-
#
-
# Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments.
-
#
-
# When eager loaded, conditions are interpolated in the context of the model class, not
-
# the model instance. Conditions are lazily interpolated before the actual model exists.
-
#
-
# Eager loading is supported with polymorphic associations.
-
#
-
# class Address < ActiveRecord::Base
-
# belongs_to :addressable, :polymorphic => true
-
# end
-
#
-
# A call that tries to eager load the addressable model
-
#
-
# Address.includes(:addressable)
-
#
-
# This will execute one query to load the addresses and load the addressables with one
-
# query per addressable type.
-
# For example if all the addressables are either of class Person or Company then a total
-
# of 3 queries will be executed. The list of addressable types to load is determined on
-
# the back of the addresses loaded. This is not supported if Active Record has to fallback
-
# to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError.
-
# The reason is that the parent model's type is a column value so its corresponding table
-
# name cannot be put in the +FROM+/+JOIN+ clauses of that query.
-
#
-
# == Table Aliasing
-
#
-
# Active Record uses table aliasing in the case that a table is referenced multiple times
-
# in a join. If a table is referenced only once, the standard table name is used. The
-
# second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>.
-
# Indexes are appended for any more successive uses of the table name.
-
#
-
# Post.joins(:comments)
-
# # => SELECT ... FROM posts INNER JOIN comments ON ...
-
# Post.joins(:special_comments) # STI
-
# # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment'
-
# Post.joins(:comments, :special_comments) # special_comments is the reflection name, posts is the parent table name
-
# # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts
-
#
-
# Acts as tree example:
-
#
-
# TreeMixin.joins(:children)
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# TreeMixin.joins(:children => :parent)
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# INNER JOIN parents_mixins ...
-
# TreeMixin.joins(:children => {:parent => :children})
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# INNER JOIN parents_mixins ...
-
# INNER JOIN mixins childrens_mixins_2
-
#
-
# Has and Belongs to Many join tables use the same idea, but add a <tt>_join</tt> suffix:
-
#
-
# Post.joins(:categories)
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# Post.joins(:categories => :posts)
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
-
# Post.joins(:categories => {:posts => :categories})
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
-
# INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
-
#
-
# If you wish to specify your own custom joins using <tt>joins</tt> method, those table
-
# names will take precedence over the eager associations:
-
#
-
# Post.joins(:comments).joins("inner join comments ...")
-
# # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...
-
# Post.joins(:comments, :special_comments).joins("inner join comments ...")
-
# # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ...
-
# INNER JOIN comments special_comments_posts ...
-
# INNER JOIN comments ...
-
#
-
# Table aliases are automatically truncated according to the maximum length of table identifiers
-
# according to the specific database.
-
#
-
# == Modules
-
#
-
# By default, associations will look for objects within the current module scope. Consider:
-
#
-
# module MyApplication
-
# module Business
-
# class Firm < ActiveRecord::Base
-
# has_many :clients
-
# end
-
#
-
# class Client < ActiveRecord::Base; end
-
# end
-
# end
-
#
-
# When <tt>Firm#clients</tt> is called, it will in turn call
-
# <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>.
-
# If you want to associate with a class in another module scope, this can be done by
-
# specifying the complete class name.
-
#
-
# module MyApplication
-
# module Business
-
# class Firm < ActiveRecord::Base; end
-
# end
-
#
-
# module Billing
-
# class Account < ActiveRecord::Base
-
# belongs_to :firm, :class_name => "MyApplication::Business::Firm"
-
# end
-
# end
-
# end
-
#
-
# == Bi-directional associations
-
#
-
# When you specify an association there is usually an association on the associated model
-
# that specifies the same relationship in reverse. For example, with the following models:
-
#
-
# class Dungeon < ActiveRecord::Base
-
# has_many :traps
-
# has_one :evil_wizard
-
# end
-
#
-
# class Trap < ActiveRecord::Base
-
# belongs_to :dungeon
-
# end
-
#
-
# class EvilWizard < ActiveRecord::Base
-
# belongs_to :dungeon
-
# end
-
#
-
# The +traps+ association on +Dungeon+ and the +dungeon+ association on +Trap+ are
-
# the inverse of each other and the inverse of the +dungeon+ association on +EvilWizard+
-
# is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
-
# Active Record doesn't know anything about these inverse relationships and so no object
-
# loading optimization is possible. For example:
-
#
-
# d = Dungeon.first
-
# t = d.traps.first
-
# d.level == t.dungeon.level # => true
-
# d.level = 10
-
# d.level == t.dungeon.level # => false
-
#
-
# The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to
-
# the same object data from the database, but are actually different in-memory copies
-
# of that data. Specifying the <tt>:inverse_of</tt> option on associations lets you tell
-
# Active Record about inverse relationships and it will optimise object loading. For
-
# example, if we changed our model definitions to:
-
#
-
# class Dungeon < ActiveRecord::Base
-
# has_many :traps, :inverse_of => :dungeon
-
# has_one :evil_wizard, :inverse_of => :dungeon
-
# end
-
#
-
# class Trap < ActiveRecord::Base
-
# belongs_to :dungeon, :inverse_of => :traps
-
# end
-
#
-
# class EvilWizard < ActiveRecord::Base
-
# belongs_to :dungeon, :inverse_of => :evil_wizard
-
# end
-
#
-
# Then, from our code snippet above, +d+ and <tt>t.dungeon</tt> are actually the same
-
# in-memory instance and our final <tt>d.level == t.dungeon.level</tt> will return +true+.
-
#
-
# There are limitations to <tt>:inverse_of</tt> support:
-
#
-
# * does not work with <tt>:through</tt> associations.
-
# * does not work with <tt>:polymorphic</tt> associations.
-
# * for +belongs_to+ associations +has_many+ inverse associations are ignored.
-
#
-
# == Deleting from associations
-
#
-
# === Dependent associations
-
#
-
# +has_many+, +has_one+ and +belongs_to+ associations support the <tt>:dependent</tt> option.
-
# This allows you to specify that associated records should be deleted when the owner is
-
# deleted.
-
#
-
# For example:
-
#
-
# class Author
-
# has_many :posts, :dependent => :destroy
-
# end
-
# Author.find(1).destroy # => Will destroy all of the author's posts, too
-
#
-
# The <tt>:dependent</tt> option can have different values which specify how the deletion
-
# is done. For more information, see the documentation for this option on the different
-
# specific association types.
-
#
-
# === Delete or destroy?
-
#
-
# +has_many+ and +has_and_belongs_to_many+ associations have the methods <tt>destroy</tt>,
-
# <tt>delete</tt>, <tt>destroy_all</tt> and <tt>delete_all</tt>.
-
#
-
# For +has_and_belongs_to_many+, <tt>delete</tt> and <tt>destroy</tt> are the same: they
-
# cause the records in the join table to be removed.
-
#
-
# For +has_many+, <tt>destroy</tt> will always call the <tt>destroy</tt> method of the
-
# record(s) being removed so that callbacks are run. However <tt>delete</tt> will either
-
# do the deletion according to the strategy specified by the <tt>:dependent</tt> option, or
-
# if no <tt>:dependent</tt> option is given, then it will follow the default strategy.
-
# The default strategy is <tt>:nullify</tt> (set the foreign keys to <tt>nil</tt>), except for
-
# +has_many+ <tt>:through</tt>, where the default strategy is <tt>delete_all</tt> (delete
-
# the join records, without running their callbacks).
-
#
-
# There is also a <tt>clear</tt> method which is the same as <tt>delete_all</tt>, except that
-
# it returns the association rather than the records which have been deleted.
-
#
-
# === What gets deleted?
-
#
-
# There is a potential pitfall here: +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>
-
# associations have records in join tables, as well as the associated records. So when we
-
# call one of these deletion methods, what exactly should be deleted?
-
#
-
# The answer is that it is assumed that deletion on an association is about removing the
-
# <i>link</i> between the owner and the associated object(s), rather than necessarily the
-
# associated objects themselves. So with +has_and_belongs_to_many+ and +has_many+
-
# <tt>:through</tt>, the join records will be deleted, but the associated records won't.
-
#
-
# This makes sense if you think about it: if you were to call <tt>post.tags.delete(Tag.find_by_name('food'))</tt>
-
# you would want the 'food' tag to be unlinked from the post, rather than for the tag itself
-
# to be removed from the database.
-
#
-
# However, there are examples where this strategy doesn't make sense. For example, suppose
-
# a person has many projects, and each project has many tasks. If we deleted one of a person's
-
# tasks, we would probably not want the project to be deleted. In this scenario, the delete method
-
# won't actually work: it can only be used if the association on the join model is a
-
# +belongs_to+. In other situations you are expected to perform operations directly on
-
# either the associated records or the <tt>:through</tt> association.
-
#
-
# With a regular +has_many+ there is no distinction between the "associated records"
-
# and the "link", so there is only one choice for what gets deleted.
-
#
-
# With +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>, if you want to delete the
-
# associated records themselves, you can always do something along the lines of
-
# <tt>person.tasks.each(&:destroy)</tt>.
-
#
-
# == Type safety with <tt>ActiveRecord::AssociationTypeMismatch</tt>
-
#
-
# If you attempt to assign an object to an association that doesn't match the inferred
-
# or specified <tt>:class_name</tt>, you'll get an <tt>ActiveRecord::AssociationTypeMismatch</tt>.
-
#
-
# == Options
-
#
-
# All of the association macros can be specialized through options. This makes cases
-
# more complex than the simple and guessable ones possible.
-
2
module ClassMethods
-
# Specifies a one-to-many association. The following methods for retrieval and query of
-
# collections of associated objects will be added:
-
#
-
# [collection(force_reload = false)]
-
# Returns an array of all the associated objects.
-
# An empty array is returned if none are found.
-
# [collection<<(object, ...)]
-
# Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
-
# Note that this operation instantly fires update sql without waiting for the save or update call on the
-
# parent object.
-
# [collection.delete(object, ...)]
-
# Removes one or more objects from the collection by setting their foreign keys to +NULL+.
-
# Objects will be in addition destroyed if they're associated with <tt>:dependent => :destroy</tt>,
-
# and deleted if they're associated with <tt>:dependent => :delete_all</tt>.
-
#
-
# If the <tt>:through</tt> option is used, then the join records are deleted (rather than
-
# nullified) by default, but you can specify <tt>:dependent => :destroy</tt> or
-
# <tt>:dependent => :nullify</tt> to override this.
-
# [collection=objects]
-
# Replaces the collections content by deleting and adding objects as appropriate. If the <tt>:through</tt>
-
# option is true callbacks in the join models are triggered except destroy callbacks, since deletion is
-
# direct.
-
# [collection_singular_ids]
-
# Returns an array of the associated objects' ids
-
# [collection_singular_ids=ids]
-
# Replace the collection with the objects identified by the primary keys in +ids+. This
-
# method loads the models and calls <tt>collection=</tt>. See above.
-
# [collection.clear]
-
# Removes every object from the collection. This destroys the associated objects if they
-
# are associated with <tt>:dependent => :destroy</tt>, deletes them directly from the
-
# database if <tt>:dependent => :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
-
# If the <tt>:through</tt> option is true no destroy callbacks are invoked on the join models.
-
# Join models are directly deleted.
-
# [collection.empty?]
-
# Returns +true+ if there are no associated objects.
-
# [collection.size]
-
# Returns the number of associated objects.
-
# [collection.find(...)]
-
# Finds an associated object according to the same rules as ActiveRecord::Base.find.
-
# [collection.exists?(...)]
-
# Checks whether an associated object with the given conditions exists.
-
# Uses the same rules as ActiveRecord::Base.exists?.
-
# [collection.build(attributes = {}, ...)]
-
# Returns one or more new objects of the collection type that have been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but have not yet
-
# been saved.
-
# [collection.create(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that has already
-
# been saved (if it passed the validation). *Note*: This only works if the base model
-
# already exists in the DB, not if it is a new (unsaved) record!
-
#
-
# (*Note*: +collection+ is replaced with the symbol passed as the first argument, so
-
# <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.)
-
#
-
# === Example
-
#
-
# Example: A Firm class declares <tt>has_many :clients</tt>, which will add:
-
# * <tt>Firm#clients</tt> (similar to <tt>Clients.all :conditions => ["firm_id = ?", id]</tt>)
-
# * <tt>Firm#clients<<</tt>
-
# * <tt>Firm#clients.delete</tt>
-
# * <tt>Firm#clients=</tt>
-
# * <tt>Firm#client_ids</tt>
-
# * <tt>Firm#client_ids=</tt>
-
# * <tt>Firm#clients.clear</tt>
-
# * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
-
# * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
-
# * <tt>Firm#clients.find</tt> (similar to <tt>Client.find(id, :conditions => "firm_id = #{id}")</tt>)
-
# * <tt>Firm#clients.exists?(:name => 'ACME')</tt> (similar to <tt>Client.exists?(:name => 'ACME', :firm_id => firm.id)</tt>)
-
# * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
-
# * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
-
# The declaration can also include an options hash to specialize the behavior of the association.
-
#
-
# === Options
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_many :products</tt> will by default be linked
-
# to the Product class, but if the real class name is SpecialProduct, you'll have to
-
# specify it with this option.
-
# [:conditions]
-
# Specify the conditions that the associated objects must meet in order to be included as a +WHERE+
-
# SQL fragment, such as <tt>price > 5 AND name LIKE 'B%'</tt>. Record creations from
-
# the association are scoped if a hash is used.
-
# <tt>has_many :posts, :conditions => {:published => true}</tt> will create published
-
# posts with <tt>@blog.posts.create</tt> or <tt>@blog.posts.build</tt>.
-
# [:order]
-
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
-
# such as <tt>last_name, first_name DESC</tt>.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+
-
# association will use "person_id" as the default <tt>:foreign_key</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key used for the association. By default this is +id+.
-
# [:dependent]
-
# If set to <tt>:destroy</tt> all the associated objects are destroyed
-
# alongside this object by calling their +destroy+ method. If set to <tt>:delete_all</tt> all associated
-
# objects are deleted *without* calling their +destroy+ method. If set to <tt>:nullify</tt> all associated
-
# objects' foreign keys are set to +NULL+ *without* calling their +save+ callbacks. If set to
-
# <tt>:restrict</tt> this object raises an <tt>ActiveRecord::DeleteRestrictionError</tt> exception and
-
# cannot be deleted if it has any associated objects.
-
#
-
# If using with the <tt>:through</tt> option, the association on the join model must be
-
# a +belongs_to+, and the records which get deleted are the join records, rather than
-
# the associated records.
-
#
-
# [:finder_sql]
-
# Specify a complete SQL statement to fetch the association. This is a good way to go for complex
-
# associations that depend on multiple tables. May be supplied as a string or a proc where interpolation is
-
# required. Note: When this option is used, +find_in_collection+
-
# is _not_ added.
-
# [:counter_sql]
-
# Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
-
# specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by
-
# replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
-
# [:extend]
-
# Specify a named module for extending the proxy. See "Association extensions".
-
# [:include]
-
# Specify second-order associations that should be eager loaded when the collection is loaded.
-
# [:group]
-
# An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
-
# [:having]
-
# Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt>
-
# returns. Uses the <tt>HAVING</tt> SQL-clause.
-
# [:limit]
-
# An integer determining the limit on the number of rows that should be returned.
-
# [:offset]
-
# An integer determining the offset from where the rows should be fetched. So at 5,
-
# it would skip the first 4 rows.
-
# [:select]
-
# By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if
-
# you, for example, want to do a join but not include the joined columns. Do not forget
-
# to include the primary and foreign keys, otherwise it will raise an error.
-
# [:as]
-
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
-
# [:through]
-
# Specifies an association through which to perform the query. This can be any other type
-
# of association, including other <tt>:through</tt> associations. Options for <tt>:class_name</tt>,
-
# <tt>:primary_key</tt> and <tt>:foreign_key</tt> are ignored, as the association uses the
-
# source reflection.
-
#
-
# If the association on the join model is a +belongs_to+, the collection can be modified
-
# and the records on the <tt>:through</tt> model will be automatically created and removed
-
# as appropriate. Otherwise, the collection is read-only, so you should manipulate the
-
# <tt>:through</tt> association directly.
-
#
-
# If you are going to modify the association (rather than just read from it), then it is
-
# a good idea to set the <tt>:inverse_of</tt> option on the source association on the
-
# join model. This allows associated records to be built which will automatically create
-
# the appropriate join model records when they are saved. (See the 'Association Join Models'
-
# section above.)
-
# [:source]
-
# Specifies the source association name used by <tt>has_many :through</tt> queries.
-
# Only use it if the name cannot be inferred from the association.
-
# <tt>has_many :subscribers, :through => :subscriptions</tt> will look for either <tt>:subscribers</tt> or
-
# <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
-
# [:source_type]
-
# Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
-
# association is a polymorphic +belongs_to+.
-
# [:uniq]
-
# If true, duplicates will be omitted from the collection. Useful in conjunction with <tt>:through</tt>.
-
# [:readonly]
-
# If true, all the associated objects are readonly through the association.
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. true by default.
-
# [:autosave]
-
# If true, always save the associated objects or destroy them if marked for destruction,
-
# when saving the parent object. If false, never save or destroy the associated objects.
-
# By default, only save associated objects that are new records.
-
# [:inverse_of]
-
# Specifies the name of the <tt>belongs_to</tt> association on the associated object
-
# that is the inverse of this <tt>has_many</tt> association. Does not work in combination
-
# with <tt>:through</tt> or <tt>:as</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# has_many :comments, :order => "posted_on"
-
# has_many :comments, :include => :author
-
# has_many :people, :class_name => "Person", :conditions => "deleted = 0", :order => "name"
-
# has_many :tracks, :order => "position", :dependent => :destroy
-
# has_many :comments, :dependent => :nullify
-
# has_many :tags, :as => :taggable
-
# has_many :reports, :readonly => true
-
# has_many :subscribers, :through => :subscriptions, :source => :user
-
# has_many :subscribers, :class_name => "Person", :finder_sql => Proc.new {
-
# %Q{
-
# SELECT DISTINCT *
-
# FROM people p, post_subscriptions ps
-
# WHERE ps.post_id = #{id} AND ps.person_id = p.id
-
# ORDER BY p.first_name
-
# }
-
# }
-
2
def has_many(name, options = {}, &extension)
-
22
Builder::HasMany.build(self, name, options, &extension)
-
end
-
-
# Specifies a one-to-one association with another class. This method should only be used
-
# if the other class contains the foreign key. If the current class contains the foreign key,
-
# then you should use +belongs_to+ instead. See also ActiveRecord::Associations::ClassMethods's overview
-
# on when to use has_one and when to use belongs_to.
-
#
-
# The following methods for retrieval and query of a single associated object will be added:
-
#
-
# [association(force_reload = false)]
-
# Returns the associated object. +nil+ is returned if none is found.
-
# [association=(associate)]
-
# Assigns the associate object, extracts the primary key, sets it as the foreign key,
-
# and saves the associate object.
-
# [build_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but has not
-
# yet been saved.
-
# [create_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that
-
# has already been saved (if it passed the validation).
-
# [create_association!(attributes = {})]
-
# Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# (+association+ is replaced with the symbol passed as the first argument, so
-
# <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.)
-
#
-
# === Example
-
#
-
# An Account class declares <tt>has_one :beneficiary</tt>, which will add:
-
# * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.first(:conditions => "account_id = #{id}")</tt>)
-
# * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
-
# * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
-
# * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
-
# * <tt>Account#create_beneficiary!</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save!; b</tt>)
-
#
-
# === Options
-
#
-
# The declaration can also include an options hash to specialize the behavior of the association.
-
#
-
# Options are:
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
-
# if the real class name is Person, you'll have to specify it with this option.
-
# [:conditions]
-
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
-
# SQL fragment, such as <tt>rank = 5</tt>. Record creation from the association is scoped if a hash
-
# is used. <tt>has_one :account, :conditions => {:enabled => true}</tt> will create
-
# an enabled account with <tt>@company.create_account</tt> or <tt>@company.build_account</tt>.
-
# [:order]
-
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
-
# such as <tt>last_name, first_name DESC</tt>.
-
# [:dependent]
-
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
-
# <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
-
# If set to <tt>:nullify</tt>, the associated object's foreign key is set to +NULL+.
-
# Also, association is assigned. If set to <tt>:restrict</tt> this object raises an
-
# <tt>ActiveRecord::DeleteRestrictionError</tt> exception and cannot be deleted if it has any associated object.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association
-
# will use "person_id" as the default <tt>:foreign_key</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key used for the association. By default this is +id+.
-
# [:include]
-
# Specify second-order associations that should be eager loaded when this object is loaded.
-
# [:as]
-
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
-
# [:select]
-
# By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example,
-
# you want to do a join but not include the joined columns. Do not forget to include the
-
# primary and foreign keys, otherwise it will raise an error.
-
# [:through]
-
# Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>,
-
# <tt>:primary_key</tt>, and <tt>:foreign_key</tt> are ignored, as the association uses the
-
# source reflection. You can only use a <tt>:through</tt> query through a <tt>has_one</tt>
-
# or <tt>belongs_to</tt> association on the join model.
-
# [:source]
-
# Specifies the source association name used by <tt>has_one :through</tt> queries.
-
# Only use it if the name cannot be inferred from the association.
-
# <tt>has_one :favorite, :through => :favorites</tt> will look for a
-
# <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
-
# [:source_type]
-
# Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
-
# association is a polymorphic +belongs_to+.
-
# [:readonly]
-
# If true, the associated object is readonly through the association.
-
# [:validate]
-
# If +false+, don't validate the associated object when saving the parent object. +false+ by default.
-
# [:autosave]
-
# If true, always save the associated object or destroy it if marked for destruction,
-
# when saving the parent object. If false, never save or destroy the associated object.
-
# By default, only save the associated object if it's a new record.
-
# [:inverse_of]
-
# Specifies the name of the <tt>belongs_to</tt> association on the associated object
-
# that is the inverse of this <tt>has_one</tt> association. Does not work in combination
-
# with <tt>:through</tt> or <tt>:as</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# has_one :credit_card, :dependent => :destroy # destroys the associated credit card
-
# has_one :credit_card, :dependent => :nullify # updates the associated records foreign
-
# # key value to NULL rather than destroying it
-
# has_one :last_comment, :class_name => "Comment", :order => "posted_on"
-
# has_one :project_manager, :class_name => "Person", :conditions => "role = 'project_manager'"
-
# has_one :attachment, :as => :attachable
-
# has_one :boss, :readonly => :true
-
# has_one :club, :through => :membership
-
# has_one :primary_address, :through => :addressables, :conditions => ["addressable.primary = ?", true], :source => :addressable
-
2
def has_one(name, options = {})
-
10
Builder::HasOne.build(self, name, options)
-
end
-
-
# Specifies a one-to-one association with another class. This method should only be used
-
# if this class contains the foreign key. If the other class contains the foreign key,
-
# then you should use +has_one+ instead. See also ActiveRecord::Associations::ClassMethods's overview
-
# on when to use +has_one+ and when to use +belongs_to+.
-
#
-
# Methods will be added for retrieval and query for a single associated object, for which
-
# this object holds an id:
-
#
-
# [association(force_reload = false)]
-
# Returns the associated object. +nil+ is returned if none is found.
-
# [association=(associate)]
-
# Assigns the associate object, extracts the primary key, and sets it as the foreign key.
-
# [build_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
-
# [create_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that
-
# has already been saved (if it passed the validation).
-
# [create_association!(attributes = {})]
-
# Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# (+association+ is replaced with the symbol passed as the first argument, so
-
# <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.)
-
#
-
# === Example
-
#
-
# A Post class declares <tt>belongs_to :author</tt>, which will add:
-
# * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
-
# * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
-
# * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
-
# * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
-
# * <tt>Post#create_author!</tt> (similar to <tt>post.author = Author.new; post.author.save!; post.author</tt>)
-
# The declaration can also include an options hash to specialize the behavior of the association.
-
#
-
# === Options
-
#
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>belongs_to :author</tt> will by default be linked to the Author class, but
-
# if the real class name is Person, you'll have to specify it with this option.
-
# [:conditions]
-
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
-
# SQL fragment, such as <tt>authorized = 1</tt>.
-
# [:select]
-
# By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed
-
# if, for example, you want to do a join but not include the joined columns. Do not
-
# forget to include the primary and foreign keys, otherwise it will raise an error.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
-
# association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly,
-
# <tt>belongs_to :favorite_person, :class_name => "Person"</tt> will use a foreign key
-
# of "favorite_person_id".
-
# [:foreign_type]
-
# Specify the column used to store the associated object's type, if this is a polymorphic
-
# association. By default this is guessed to be the name of the association with a "_type"
-
# suffix. So a class that defines a <tt>belongs_to :taggable, :polymorphic => true</tt>
-
# association will use "taggable_type" as the default <tt>:foreign_type</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key of associated object used for the association.
-
# By default this is id.
-
# [:dependent]
-
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
-
# <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
-
# This option should not be specified when <tt>belongs_to</tt> is used in conjunction with
-
# a <tt>has_many</tt> relationship on another class because of the potential to leave
-
# orphaned records behind.
-
# [:counter_cache]
-
# Caches the number of belonging objects on the associate class through the use of +increment_counter+
-
# and +decrement_counter+. The counter cache is incremented when an object of this
-
# class is created and decremented when it's destroyed. This requires that a column
-
# named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
-
# is used on the associate class (such as a Post class). You can also specify a custom counter
-
# cache column by providing a column name instead of a +true+/+false+ value to this
-
# option (e.g., <tt>:counter_cache => :my_custom_counter</tt>.)
-
# Note: Specifying a counter cache will add it to that model's list of readonly attributes
-
# using +attr_readonly+.
-
# [:include]
-
# Specify second-order associations that should be eager loaded when this object is loaded.
-
# [:polymorphic]
-
# Specify this association is a polymorphic association by passing +true+.
-
# Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
-
# to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
-
# [:readonly]
-
# If true, the associated object is readonly through the association.
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. +false+ by default.
-
# [:autosave]
-
# If true, always save the associated object or destroy it if marked for destruction, when
-
# saving the parent object.
-
# If false, never save or destroy the associated object.
-
# By default, only save the associated object if it's a new record.
-
# [:touch]
-
# If true, the associated object will be touched (the updated_at/on attributes set to now)
-
# when this record is either saved or destroyed. If you specify a symbol, that attribute
-
# will be updated with the current time in addition to the updated_at/on attribute.
-
# [:inverse_of]
-
# Specifies the name of the <tt>has_one</tt> or <tt>has_many</tt> association on the associated
-
# object that is the inverse of this <tt>belongs_to</tt> association. Does not work in
-
# combination with the <tt>:polymorphic</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# belongs_to :firm, :foreign_key => "client_of"
-
# belongs_to :person, :primary_key => "name", :foreign_key => "person_name"
-
# belongs_to :author, :class_name => "Person", :foreign_key => "author_id"
-
# belongs_to :valid_coupon, :class_name => "Coupon", :foreign_key => "coupon_id",
-
# :conditions => 'discounts > #{payments_count}'
-
# belongs_to :attachable, :polymorphic => true
-
# belongs_to :project, :readonly => true
-
# belongs_to :post, :counter_cache => true
-
# belongs_to :company, :touch => true
-
# belongs_to :company, :touch => :employees_last_updated_at
-
2
def belongs_to(name, options = {})
-
32
Builder::BelongsTo.build(self, name, options)
-
end
-
-
# Specifies a many-to-many relationship with another class. This associates two classes via an
-
# intermediate join table. Unless the join table is explicitly specified as an option, it is
-
# guessed using the lexical order of the class names. So a join between Developer and Project
-
# will give the default join table name of "developers_projects" because "D" outranks "P".
-
# Note that this precedence is calculated using the <tt><</tt> operator for String. This
-
# means that if the strings are of different lengths, and the strings are equal when compared
-
# up to the shortest length, then the longer string is considered of higher
-
# lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers"
-
# to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes",
-
# but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the
-
# custom <tt>:join_table</tt> option if you need to.
-
#
-
# The join table should not have a primary key or a model associated with it. You must manually generate the
-
# join table with a migration such as this:
-
#
-
# class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
-
# def change
-
# create_table :developers_projects, :id => false do |t|
-
# t.integer :developer_id
-
# t.integer :project_id
-
# end
-
# end
-
# end
-
#
-
# It's also a good idea to add indexes to each of those columns to speed up the joins process.
-
# However, in MySQL it is advised to add a compound index for both of the columns as MySQL only
-
# uses one index per table during the lookup.
-
#
-
# Adds the following methods for retrieval and query:
-
#
-
# [collection(force_reload = false)]
-
# Returns an array of all the associated objects.
-
# An empty array is returned if none are found.
-
# [collection<<(object, ...)]
-
# Adds one or more objects to the collection by creating associations in the join table
-
# (<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to this method).
-
# Note that this operation instantly fires update sql without waiting for the save or update call on the
-
# parent object.
-
# [collection.delete(object, ...)]
-
# Removes one or more objects from the collection by removing their associations from the join table.
-
# This does not destroy the objects.
-
# [collection=objects]
-
# Replaces the collection's content by deleting and adding objects as appropriate.
-
# [collection_singular_ids]
-
# Returns an array of the associated objects' ids.
-
# [collection_singular_ids=ids]
-
# Replace the collection by the objects identified by the primary keys in +ids+.
-
# [collection.clear]
-
# Removes every object from the collection. This does not destroy the objects.
-
# [collection.empty?]
-
# Returns +true+ if there are no associated objects.
-
# [collection.size]
-
# Returns the number of associated objects.
-
# [collection.find(id)]
-
# Finds an associated object responding to the +id+ and that
-
# meets the condition that it has to be associated with this object.
-
# Uses the same rules as ActiveRecord::Base.find.
-
# [collection.exists?(...)]
-
# Checks whether an associated object with the given conditions exists.
-
# Uses the same rules as ActiveRecord::Base.exists?.
-
# [collection.build(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+ and linked to this object through the join table, but has not yet been saved.
-
# [collection.create(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+, linked to this object through the join table, and that has already been
-
# saved (if it passed the validation).
-
#
-
# (+collection+ is replaced with the symbol passed as the first argument, so
-
# <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.)
-
#
-
# === Example
-
#
-
# A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
-
# * <tt>Developer#projects</tt>
-
# * <tt>Developer#projects<<</tt>
-
# * <tt>Developer#projects.delete</tt>
-
# * <tt>Developer#projects=</tt>
-
# * <tt>Developer#project_ids</tt>
-
# * <tt>Developer#project_ids=</tt>
-
# * <tt>Developer#projects.clear</tt>
-
# * <tt>Developer#projects.empty?</tt>
-
# * <tt>Developer#projects.size</tt>
-
# * <tt>Developer#projects.find(id)</tt>
-
# * <tt>Developer#projects.exists?(...)</tt>
-
# * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("developer_id" => id)</tt>)
-
# * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("developer_id" => id); c.save; c</tt>)
-
# The declaration may include an options hash to specialize the behavior of the association.
-
#
-
# === Options
-
#
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
-
# Project class, but if the real class name is SuperProject, you'll have to specify it with this option.
-
# [:join_table]
-
# Specify the name of the join table if the default based on lexical order isn't what you want.
-
# <b>WARNING:</b> If you're overwriting the table name of either class, the +table_name+ method
-
# MUST be declared underneath any +has_and_belongs_to_many+ declaration in order to work.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes
-
# a +has_and_belongs_to_many+ association to Project will use "person_id" as the
-
# default <tt>:foreign_key</tt>.
-
# [:association_foreign_key]
-
# Specify the foreign key used for the association on the receiving side of the association.
-
# By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
-
# So if a Person class makes a +has_and_belongs_to_many+ association to Project,
-
# the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
-
# [:conditions]
-
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
-
# SQL fragment, such as <tt>authorized = 1</tt>. Record creations from the association are
-
# scoped if a hash is used.
-
# <tt>has_many :posts, :conditions => {:published => true}</tt> will create published posts with <tt>@blog.posts.create</tt>
-
# or <tt>@blog.posts.build</tt>.
-
# [:order]
-
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
-
# such as <tt>last_name, first_name DESC</tt>
-
# [:uniq]
-
# If true, duplicate associated objects will be ignored by accessors and query methods.
-
# [:finder_sql]
-
# Overwrite the default generated SQL statement used to fetch the association with a manual statement
-
# [:counter_sql]
-
# Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
-
# specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by
-
# replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
-
# [:delete_sql]
-
# Overwrite the default generated SQL statement used to remove links between the associated
-
# classes with a manual statement.
-
# [:insert_sql]
-
# Overwrite the default generated SQL statement used to add links between the associated classes
-
# with a manual statement.
-
# [:extend]
-
# Anonymous module for extending the proxy, see "Association extensions".
-
# [:include]
-
# Specify second-order associations that should be eager loaded when the collection is loaded.
-
# [:group]
-
# An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
-
# [:having]
-
# Combined with +:group+ this can be used to filter the records that a <tt>GROUP BY</tt> returns.
-
# Uses the <tt>HAVING</tt> SQL-clause.
-
# [:limit]
-
# An integer determining the limit on the number of rows that should be returned.
-
# [:offset]
-
# An integer determining the offset from where the rows should be fetched. So at 5,
-
# it would skip the first 4 rows.
-
# [:select]
-
# By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example,
-
# you want to do a join but not include the joined columns. Do not forget to include the primary
-
# and foreign keys, otherwise it will raise an error.
-
# [:readonly]
-
# If true, all the associated objects are readonly through the association.
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. +true+ by default.
-
# [:autosave]
-
# If true, always save the associated objects or destroy them if marked for destruction, when
-
# saving the parent object.
-
# If false, never save or destroy the associated objects.
-
# By default, only save associated objects that are new records.
-
#
-
# Option examples:
-
# has_and_belongs_to_many :projects
-
# has_and_belongs_to_many :projects, :include => [ :milestones, :manager ]
-
# has_and_belongs_to_many :nations, :class_name => "Country"
-
# has_and_belongs_to_many :categories, :join_table => "prods_cats"
-
# has_and_belongs_to_many :categories, :readonly => true
-
# has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>
-
# "DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}"
-
2
def has_and_belongs_to_many(name, options = {}, &extension)
-
Builder::HasAndBelongsToMany.build(self, name, options, &extension)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/string/conversions'
-
-
1
module ActiveRecord
-
1
module Associations
-
# Keeps track of table aliases for ActiveRecord::Associations::ClassMethods::JoinDependency and
-
# ActiveRecord::Associations::ThroughAssociationScope
-
1
class AliasTracker # :nodoc:
-
1
attr_reader :aliases, :table_joins, :connection
-
-
# table_joins is an array of arel joins which might conflict with the aliases we assign here
-
1
def initialize(connection = ActiveRecord::Model.connection, table_joins = [])
-
526
@aliases = Hash.new { |h,k| h[k] = initial_count_for(k) }
-
263
@table_joins = table_joins
-
263
@connection = connection
-
end
-
-
1
def aliased_table_for(table_name, aliased_name = nil)
-
263
table_alias = aliased_name_for(table_name, aliased_name)
-
-
263
if table_alias == table_name
-
263
Arel::Table.new(table_name)
-
else
-
Arel::Table.new(table_name).alias(table_alias)
-
end
-
end
-
-
1
def aliased_name_for(table_name, aliased_name = nil)
-
263
aliased_name ||= table_name
-
-
263
if aliases[table_name].zero?
-
# If it's zero, we can have our table_name
-
263
aliases[table_name] = 1
-
263
table_name
-
else
-
# Otherwise, we need to use an alias
-
aliased_name = connection.table_alias_for(aliased_name)
-
-
# Update the count
-
aliases[aliased_name] += 1
-
-
if aliases[aliased_name] > 1
-
"#{truncate(aliased_name)}_#{aliases[aliased_name]}"
-
else
-
aliased_name
-
end
-
end
-
end
-
-
1
private
-
-
1
def initial_count_for(name)
-
263
return 0 if Arel::Table === table_joins
-
-
# quoted_name should be downcased as some database adapters (Oracle) return quoted name in uppercase
-
263
quoted_name = connection.quote_table_name(name).downcase
-
-
263
counts = table_joins.map do |join|
-
if join.is_a?(Arel::Nodes::StringJoin)
-
# Table names + table aliases
-
join.left.downcase.scan(
-
/join(?:\s+\w+)?\s+(\S+\s+)?#{quoted_name}\son/
-
).size
-
else
-
join.left.table_name == name ? 1 : 0
-
end
-
end
-
-
263
counts.sum
-
end
-
-
1
def truncate(name)
-
name.slice(0, connection.table_alias_length - 2)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/core_ext/object/inclusion'
-
-
1
module ActiveRecord
-
1
module Associations
-
# = Active Record Associations
-
#
-
# This is the root class of all associations ('+ Foo' signifies an included module Foo):
-
#
-
# Association
-
# SingularAssociation
-
# HasOneAssociation
-
# HasOneThroughAssociation + ThroughAssociation
-
# BelongsToAssociation
-
# BelongsToPolymorphicAssociation
-
# CollectionAssociation
-
# HasAndBelongsToManyAssociation
-
# HasManyAssociation
-
# HasManyThroughAssociation + ThroughAssociation
-
1
class Association #:nodoc:
-
1
attr_reader :owner, :target, :reflection
-
-
1
delegate :options, :to => :reflection
-
-
1
def initialize(owner, reflection)
-
293
reflection.check_validity!
-
-
293
@target = nil
-
293
@owner, @reflection = owner, reflection
-
293
@updated = false
-
-
293
reset
-
293
reset_scope
-
end
-
-
# Returns the name of the table of the related class:
-
#
-
# post.comments.aliased_table_name # => "comments"
-
#
-
1
def aliased_table_name
-
reflection.klass.table_name
-
end
-
-
# Resets the \loaded flag to +false+ and sets the \target to +nil+.
-
1
def reset
-
448
@loaded = false
-
448
IdentityMap.remove(target) if IdentityMap.enabled? && target
-
448
@target = nil
-
448
@stale_state = nil
-
end
-
-
# Reloads the \target and returns +self+ on success.
-
1
def reload
-
221
reset
-
221
reset_scope
-
221
load_target
-
221
self unless target.nil?
-
end
-
-
# Has the \target been already \loaded?
-
1
def loaded?
-
2535
@loaded
-
end
-
-
# Asserts the \target has been loaded setting the \loaded flag to +true+.
-
1
def loaded!
-
506
@loaded = true
-
506
@stale_state = stale_state
-
end
-
-
# The target is stale if the target no longer points to the record(s) that the
-
# relevant foreign_key(s) refers to. If stale, the association accessor method
-
# on the owner will reload the target. It's up to subclasses to implement the
-
# state_state method if relevant.
-
#
-
# Note that if the target has not been loaded, it is not considered stale.
-
1
def stale_target?
-
900
loaded? && @stale_state != stale_state
-
end
-
-
# Sets the target of this association to <tt>\target</tt>, and the \loaded flag to +true+.
-
1
def target=(target)
-
7
@target = target
-
7
loaded!
-
end
-
-
1
def scoped
-
280
target_scope.merge(association_scope)
-
end
-
-
# The scope for this association.
-
#
-
# Note that the association_scope is merged into the target_scope only when the
-
# scoped method is called. This is because at that point the call may be surrounded
-
# by scope.scoping { ... } or with_scope { ... } etc, which affects the scope which
-
# actually gets built.
-
1
def association_scope
-
280
if klass
-
280
@association_scope ||= AssociationScope.new(self).scope
-
end
-
end
-
-
1
def reset_scope
-
552
@association_scope = nil
-
end
-
-
# Set the inverse association, if possible
-
1
def set_inverse_instance(record)
-
279
if record && invertible_for?(record)
-
inverse = record.association(inverse_reflection_for(record).name)
-
inverse.target = owner
-
end
-
end
-
-
# This class of the target. belongs_to polymorphic overrides this to look at the
-
# polymorphic_type field on the owner.
-
1
def klass
-
1601
reflection.klass
-
end
-
-
# Can be overridden (i.e. in ThroughAssociation) to merge in other scopes (i.e. the
-
# through association's scope)
-
1
def target_scope
-
280
klass.scoped
-
end
-
-
# Loads the \target if needed and returns it.
-
#
-
# This method is abstract in the sense that it relies on +find_target+,
-
# which is expected to be provided by descendants.
-
#
-
# If the \target is stale(the target no longer points to the record(s) that the
-
# relevant foreign_key(s) refers to.), force reload the \target.
-
#
-
# Otherwise if the \target is already \loaded it is just returned. Thus, you can
-
# call +load_target+ unconditionally to get the \target.
-
#
-
# ActiveRecord::RecordNotFound is rescued within the method, and it is
-
# not reraised. The proxy is \reset and +nil+ is the return value.
-
1
def load_target
-
311
if (@stale_state && stale_target?) || find_target?
-
221
begin
-
221
if IdentityMap.enabled? && association_class && association_class.respond_to?(:base_class)
-
@target = IdentityMap.get(association_class, owner[reflection.foreign_key])
-
elsif @stale_state && stale_target?
-
@target = find_target
-
end
-
rescue NameError
-
nil
-
ensure
-
221
@target ||= find_target
-
end
-
end
-
311
loaded! unless loaded?
-
311
target
-
rescue ActiveRecord::RecordNotFound
-
reset
-
end
-
-
1
def interpolate(sql, record = nil)
-
if sql.respond_to?(:to_proc)
-
owner.send(:instance_exec, record, &sql)
-
else
-
sql
-
end
-
end
-
-
1
private
-
-
1
def find_target?
-
379
!loaded? && (!owner.new_record? || foreign_key_present?) && klass
-
end
-
-
1
def creation_attributes
-
8
attributes = {}
-
-
8
if reflection.macro.in?([:has_one, :has_many]) && !options[:through]
-
8
attributes[reflection.foreign_key] = owner[reflection.active_record_primary_key]
-
-
8
if reflection.options[:as]
-
attributes[reflection.type] = owner.class.base_class.name
-
end
-
end
-
-
8
attributes
-
end
-
-
# Sets the owner attributes on the given record
-
1
def set_owner_attributes(record)
-
16
creation_attributes.each { |key, value| record[key] = value }
-
end
-
-
# Should be true if there is a foreign key present on the owner which
-
# references the target. This is used to determine whether we can load
-
# the target if the owner is currently a new record (and therefore
-
# without a key).
-
#
-
# Currently implemented by belongs_to (vanilla and polymorphic) and
-
# has_one/has_many :through associations which go through a belongs_to
-
1
def foreign_key_present?
-
5
false
-
end
-
-
# Raises ActiveRecord::AssociationTypeMismatch unless +record+ is of
-
# the kind of the class of the associated objects. Meant to be used as
-
# a sanity check when you are about to assign an associated record.
-
1
def raise_on_type_mismatch(record)
-
10
unless record.is_a?(reflection.klass) || record.is_a?(reflection.class_name.constantize)
-
message = "#{reflection.class_name}(##{reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
-
raise ActiveRecord::AssociationTypeMismatch, message
-
end
-
end
-
-
# Can be redefined by subclasses, notably polymorphic belongs_to
-
# The record parameter is necessary to support polymorphic inverses as we must check for
-
# the association in the specific class of the record.
-
1
def inverse_reflection_for(record)
-
241
reflection.inverse_of
-
end
-
-
# Is this association invertible? Can be redefined by subclasses.
-
1
def invertible_for?(record)
-
110
inverse_reflection_for(record)
-
end
-
-
# This should be implemented to return the values of the relevant key(s) on the owner,
-
# so that when state_state is different from the value stored on the last find_target,
-
# the target is stale.
-
#
-
# This is only relevant to certain associations, which is why it returns nil by default.
-
1
def stale_state
-
end
-
-
1
def association_class
-
@reflection.klass
-
end
-
-
1
def build_record(attributes, options)
-
5
reflection.build_association(attributes, options) do |record|
-
5
skip_assign = [reflection.foreign_key, reflection.type].compact
-
5
attributes = create_scope.except(*(record.changed - skip_assign))
-
5
record.assign_attributes(attributes, :without_protection => true)
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Associations
-
1
class AssociationScope #:nodoc:
-
1
include JoinHelper
-
-
1
attr_reader :association, :alias_tracker
-
-
1
delegate :klass, :owner, :reflection, :interpolate, :to => :association
-
1
delegate :chain, :conditions, :options, :source_options, :active_record, :to => :reflection
-
-
1
def initialize(association)
-
263
@association = association
-
263
@alias_tracker = AliasTracker.new klass.connection
-
end
-
-
1
def scope
-
263
scope = klass.unscoped
-
263
scope = scope.extending(*Array.wrap(options[:extend]))
-
-
# It's okay to just apply all these like this. The options will only be present if the
-
# association supports that option; this is enforced by the association builder.
-
263
scope = scope.apply_finder_options(options.slice(
-
:readonly, :include, :order, :limit, :joins, :group, :having, :offset, :select))
-
-
263
if options[:through] && !options[:include]
-
scope = scope.includes(source_options[:include])
-
end
-
-
263
scope = scope.uniq if options[:uniq]
-
-
263
add_constraints(scope)
-
end
-
-
1
private
-
-
1
def add_constraints(scope)
-
263
tables = construct_tables
-
-
263
chain.each_with_index do |reflection, i|
-
263
table, foreign_table = tables.shift, tables.first
-
-
263
if reflection.source_macro == :has_and_belongs_to_many
-
join_table = tables.shift
-
-
scope = scope.joins(join(
-
join_table,
-
table[reflection.association_primary_key].
-
eq(join_table[reflection.association_foreign_key])
-
))
-
-
table, foreign_table = join_table, tables.first
-
end
-
-
263
if reflection.source_macro == :belongs_to
-
129
if reflection.options[:polymorphic]
-
key = reflection.association_primary_key(klass)
-
else
-
129
key = reflection.association_primary_key
-
end
-
-
129
foreign_key = reflection.foreign_key
-
else
-
134
key = reflection.foreign_key
-
134
foreign_key = reflection.active_record_primary_key
-
end
-
-
263
conditions = self.conditions[i]
-
-
263
if reflection == chain.last
-
263
scope = scope.where(table[key].eq(owner[foreign_key]))
-
-
263
if reflection.type
-
scope = scope.where(table[reflection.type].eq(owner.class.base_class.name))
-
end
-
-
263
conditions.each do |condition|
-
if options[:through] && condition.is_a?(Hash)
-
condition = disambiguate_condition(table, condition)
-
end
-
-
scope = scope.where(interpolate(condition))
-
end
-
else
-
constraint = table[key].eq(foreign_table[foreign_key])
-
-
if reflection.type
-
type = chain[i + 1].klass.base_class.name
-
constraint = constraint.and(table[reflection.type].eq(type))
-
end
-
-
scope = scope.joins(join(foreign_table, constraint))
-
-
unless conditions.empty?
-
scope = scope.where(sanitize(conditions, table))
-
end
-
end
-
end
-
-
263
scope
-
end
-
-
1
def alias_suffix
-
263
reflection.name
-
end
-
-
1
def table_name_for(reflection)
-
263
if reflection == self.reflection
-
# If this is a polymorphic belongs_to, we want to get the klass from the
-
# association because it depends on the polymorphic_type attribute of
-
# the owner
-
263
klass.table_name
-
else
-
reflection.table_name
-
end
-
end
-
-
1
def disambiguate_condition(table, condition)
-
if condition.is_a?(Hash)
-
Hash[
-
condition.map do |k, v|
-
if v.is_a?(Hash)
-
[k, v]
-
else
-
[table.table_alias || table.name, { k => v }]
-
end
-
end
-
]
-
else
-
condition
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Belongs To Associations
-
1
module Associations
-
1
class BelongsToAssociation < SingularAssociation #:nodoc:
-
1
def replace(record)
-
2
raise_on_type_mismatch(record) if record
-
-
2
update_counters(record)
-
2
replace_keys(record)
-
2
set_inverse_instance(record)
-
-
2
@updated = true if record
-
-
2
self.target = record
-
end
-
-
1
def updated?
-
75
@updated
-
end
-
-
1
private
-
-
1
def find_target?
-
204
!loaded? && foreign_key_present? && klass
-
end
-
-
1
def update_counters(record)
-
2
counter_cache_name = reflection.counter_cache_column
-
-
2
if counter_cache_name && owner.persisted? && different_target?(record)
-
if record
-
record.class.increment_counter(counter_cache_name, record.id)
-
end
-
-
if foreign_key_present?
-
klass.decrement_counter(counter_cache_name, target_id)
-
end
-
end
-
end
-
-
# Checks whether record is different to the current target, without loading it
-
1
def different_target?(record)
-
record.nil? && owner[reflection.foreign_key] ||
-
record && record.id != owner[reflection.foreign_key]
-
end
-
-
1
def replace_keys(record)
-
2
if record
-
2
owner[reflection.foreign_key] = record[reflection.association_primary_key(record.class)]
-
else
-
owner[reflection.foreign_key] = nil
-
end
-
end
-
-
1
def foreign_key_present?
-
129
owner[reflection.foreign_key]
-
end
-
-
# NOTE - for now, we're only supporting inverse setting from belongs_to back onto
-
# has_one associations.
-
1
def invertible_for?(record)
-
131
inverse = inverse_reflection_for(record)
-
131
inverse && inverse.macro == :has_one
-
end
-
-
1
def target_id
-
if options[:primary_key]
-
owner.send(reflection.name).try(:id)
-
else
-
owner[reflection.foreign_key]
-
end
-
end
-
-
1
def stale_state
-
671
owner[reflection.foreign_key] && owner[reflection.foreign_key].to_s
-
end
-
end
-
end
-
end
-
2
module ActiveRecord::Associations::Builder
-
2
class Association #:nodoc:
-
2
class_attribute :valid_options
-
2
self.valid_options = [:class_name, :foreign_key, :select, :conditions, :include, :extend, :readonly, :validate]
-
-
# Set by subclasses
-
2
class_attribute :macro
-
-
2
attr_reader :model, :name, :options, :reflection
-
-
2
def self.build(model, name, options)
-
42
new(model, name, options).build
-
end
-
-
2
def initialize(model, name, options)
-
64
@model, @name, @options = model, name, options
-
end
-
-
2
def mixin
-
298
@model.generated_feature_methods
-
end
-
-
2
def build
-
64
validate_options
-
64
reflection = model.create_reflection(self.class.macro, name, options, model)
-
64
define_accessors
-
64
reflection
-
end
-
-
2
private
-
-
2
def validate_options
-
54
options.assert_valid_keys(self.class.valid_options)
-
end
-
-
2
def define_accessors
-
64
define_readers
-
64
define_writers
-
end
-
-
2
def define_readers
-
64
name = self.name
-
64
mixin.redefine_method(name) do |*params|
-
1038
association(name).reader(*params)
-
end
-
end
-
-
2
def define_writers
-
64
name = self.name
-
64
mixin.redefine_method("#{name}=") do |value|
-
2
association(name).writer(value)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/inclusion'
-
-
2
module ActiveRecord::Associations::Builder
-
2
class BelongsTo < SingularAssociation #:nodoc:
-
2
self.macro = :belongs_to
-
-
2
self.valid_options += [:foreign_type, :polymorphic, :touch]
-
-
2
def constructable?
-
32
!options[:polymorphic]
-
end
-
-
2
def build
-
32
reflection = super
-
32
add_counter_cache_callbacks(reflection) if options[:counter_cache]
-
32
add_touch_callbacks(reflection) if options[:touch]
-
32
configure_dependency
-
32
reflection
-
end
-
-
2
private
-
-
2
def add_counter_cache_callbacks(reflection)
-
cache_column = reflection.counter_cache_column
-
name = self.name
-
-
method_name = "belongs_to_counter_cache_after_create_for_#{name}"
-
mixin.redefine_method(method_name) do
-
record = send(name)
-
record.class.increment_counter(cache_column, record.id) unless record.nil?
-
end
-
model.after_create(method_name)
-
-
method_name = "belongs_to_counter_cache_before_destroy_for_#{name}"
-
mixin.redefine_method(method_name) do
-
record = send(name)
-
-
if record && !self.destroyed?
-
record.class.decrement_counter(cache_column, record.id)
-
end
-
end
-
model.before_destroy(method_name)
-
-
model.send(:module_eval,
-
"#{reflection.class_name}.send(:attr_readonly,\"#{cache_column}\".intern) if defined?(#{reflection.class_name}) && #{reflection.class_name}.respond_to?(:attr_readonly)", __FILE__, __LINE__
-
)
-
end
-
-
2
def add_touch_callbacks(reflection)
-
name = self.name
-
method_name = "belongs_to_touch_after_save_or_destroy_for_#{name}"
-
touch = options[:touch]
-
-
mixin.redefine_method(method_name) do
-
record = send(name)
-
-
unless record.nil?
-
if touch == true
-
record.touch
-
else
-
record.touch(touch)
-
end
-
end
-
end
-
-
model.after_save(method_name)
-
model.after_touch(method_name)
-
model.after_destroy(method_name)
-
end
-
-
2
def configure_dependency
-
32
if options[:dependent]
-
4
unless options[:dependent].in?([:destroy, :delete])
-
raise ArgumentError, "The :dependent option expects either :destroy or :delete (#{options[:dependent].inspect})"
-
end
-
-
4
method_name = "belongs_to_dependent_#{options[:dependent]}_for_#{name}"
-
4
model.send(:class_eval, <<-eoruby, __FILE__, __LINE__ + 1)
-
def #{method_name}
-
association = #{name}
-
association.#{options[:dependent]} if association
-
end
-
eoruby
-
4
model.after_destroy method_name
-
end
-
end
-
end
-
end
-
2
module ActiveRecord::Associations::Builder
-
2
class CollectionAssociation < Association #:nodoc:
-
2
CALLBACKS = [:before_add, :after_add, :before_remove, :after_remove]
-
-
2
self.valid_options += [
-
:table_name, :order, :group, :having, :limit, :offset, :uniq, :finder_sql,
-
:counter_sql, :before_add, :after_add, :before_remove, :after_remove
-
]
-
-
2
attr_reader :block_extension
-
-
2
def self.build(model, name, options, &extension)
-
22
new(model, name, options, &extension).build
-
end
-
-
2
def initialize(model, name, options, &extension)
-
22
super(model, name, options)
-
22
@block_extension = extension
-
end
-
-
2
def build
-
22
wrap_block_extension
-
22
reflection = super
-
110
CALLBACKS.each { |callback_name| define_callback(callback_name) }
-
22
reflection
-
end
-
-
2
def writable?
-
true
-
end
-
-
2
private
-
-
2
def wrap_block_extension
-
22
options[:extend] = Array.wrap(options[:extend])
-
-
22
if block_extension
-
silence_warnings do
-
model.parent.const_set(extension_module_name, Module.new(&block_extension))
-
end
-
options[:extend].push("#{model.parent}::#{extension_module_name}".constantize)
-
end
-
end
-
-
2
def extension_module_name
-
@extension_module_name ||= "#{model.to_s.demodulize}#{name.to_s.camelize}AssociationExtension"
-
end
-
-
2
def define_callback(callback_name)
-
88
full_callback_name = "#{callback_name}_for_#{name}"
-
-
# TODO : why do i need method_defined? I think its because of the inheritance chain
-
88
model.class_attribute full_callback_name.to_sym unless model.method_defined?(full_callback_name)
-
88
model.send("#{full_callback_name}=", Array.wrap(options[callback_name.to_sym]))
-
end
-
-
2
def define_readers
-
22
super
-
-
22
name = self.name
-
22
mixin.redefine_method("#{name.to_s.singularize}_ids") do
-
association(name).ids_reader
-
end
-
end
-
-
2
def define_writers
-
22
super
-
-
22
name = self.name
-
22
mixin.redefine_method("#{name.to_s.singularize}_ids=") do |ids|
-
association(name).ids_writer(ids)
-
end
-
end
-
end
-
end
-
2
module ActiveRecord::Associations::Builder
-
2
class HasAndBelongsToMany < CollectionAssociation #:nodoc:
-
2
self.macro = :has_and_belongs_to_many
-
-
2
self.valid_options += [:join_table, :association_foreign_key, :delete_sql, :insert_sql]
-
-
2
def build
-
reflection = super
-
check_validity(reflection)
-
define_destroy_hook
-
reflection
-
end
-
-
2
private
-
-
2
def define_destroy_hook
-
name = self.name
-
model.send(:include, Module.new {
-
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def destroy_associations
-
association(#{name.to_sym.inspect}).delete_all_on_destroy
-
super
-
end
-
RUBY
-
})
-
end
-
-
# TODO: These checks should probably be moved into the Reflection, and we should not be
-
# redefining the options[:join_table] value - instead we should define a
-
# reflection.join_table method.
-
2
def check_validity(reflection)
-
if reflection.association_foreign_key == reflection.foreign_key
-
raise ActiveRecord::HasAndBelongsToManyAssociationForeignKeyNeeded.new(reflection)
-
end
-
-
reflection.options[:join_table] ||= join_table_name(
-
model.send(:undecorated_table_name, model.to_s),
-
model.send(:undecorated_table_name, reflection.class_name)
-
)
-
end
-
-
# Generates a join table name from two provided table names.
-
# The names in the join table names end up in lexicographic order.
-
#
-
# join_table_name("members", "clubs") # => "clubs_members"
-
# join_table_name("members", "special_clubs") # => "members_special_clubs"
-
2
def join_table_name(first_table_name, second_table_name)
-
if first_table_name < second_table_name
-
join_table = "#{first_table_name}_#{second_table_name}"
-
else
-
join_table = "#{second_table_name}_#{first_table_name}"
-
end
-
-
model.table_name_prefix + join_table + model.table_name_suffix
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/inclusion'
-
-
2
module ActiveRecord::Associations::Builder
-
2
class HasMany < CollectionAssociation #:nodoc:
-
2
self.macro = :has_many
-
-
2
self.valid_options += [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of]
-
-
2
def build
-
22
reflection = super
-
22
configure_dependency
-
22
reflection
-
end
-
-
2
private
-
-
2
def configure_dependency
-
22
if options[:dependent]
-
unless options[:dependent].in?([:destroy, :delete_all, :nullify, :restrict])
-
raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, " \
-
":nullify or :restrict (#{options[:dependent].inspect})"
-
end
-
-
send("define_#{options[:dependent]}_dependency_method")
-
model.before_destroy dependency_method_name
-
end
-
end
-
-
2
def define_destroy_dependency_method
-
name = self.name
-
mixin.redefine_method(dependency_method_name) do
-
send(name).each do |o|
-
# No point in executing the counter update since we're going to destroy the parent anyway
-
counter_method = ('belongs_to_counter_cache_before_destroy_for_' + self.class.name.downcase).to_sym
-
if o.respond_to?(counter_method)
-
class << o
-
self
-
end.send(:define_method, counter_method, Proc.new {})
-
end
-
end
-
-
send(name).delete_all
-
end
-
end
-
-
2
def define_delete_all_dependency_method
-
name = self.name
-
mixin.redefine_method(dependency_method_name) do
-
association(name).delete_all_on_destroy
-
end
-
end
-
-
2
def define_nullify_dependency_method
-
name = self.name
-
mixin.redefine_method(dependency_method_name) do
-
send(name).delete_all
-
end
-
end
-
-
2
def define_restrict_dependency_method
-
name = self.name
-
mixin.redefine_method(dependency_method_name) do
-
raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).empty?
-
end
-
end
-
-
2
def dependency_method_name
-
"has_many_dependent_for_#{name}"
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/inclusion'
-
-
2
module ActiveRecord::Associations::Builder
-
2
class HasOne < SingularAssociation #:nodoc:
-
2
self.macro = :has_one
-
-
2
self.valid_options += [:order, :as]
-
-
2
class_attribute :through_options
-
2
self.through_options = [:through, :source, :source_type]
-
-
2
def constructable?
-
10
!options[:through]
-
end
-
-
2
def build
-
10
reflection = super
-
10
configure_dependency unless options[:through]
-
10
reflection
-
end
-
-
2
private
-
-
2
def validate_options
-
10
valid_options = self.class.valid_options
-
10
valid_options += self.class.through_options if options[:through]
-
10
options.assert_valid_keys(valid_options)
-
end
-
-
2
def configure_dependency
-
10
if options[:dependent]
-
unless options[:dependent].in?([:destroy, :delete, :nullify, :restrict])
-
raise ArgumentError, "The :dependent option expects either :destroy, :delete, " \
-
":nullify or :restrict (#{options[:dependent].inspect})"
-
end
-
-
send("define_#{options[:dependent]}_dependency_method")
-
model.before_destroy dependency_method_name
-
end
-
end
-
-
2
def dependency_method_name
-
"has_one_dependent_#{options[:dependent]}_for_#{name}"
-
end
-
-
2
def define_destroy_dependency_method
-
name = self.name
-
mixin.redefine_method(dependency_method_name) do
-
association(name).delete
-
end
-
end
-
2
alias :define_delete_dependency_method :define_destroy_dependency_method
-
2
alias :define_nullify_dependency_method :define_destroy_dependency_method
-
-
2
def define_restrict_dependency_method
-
name = self.name
-
mixin.redefine_method(dependency_method_name) do
-
raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).nil?
-
end
-
end
-
end
-
end
-
2
module ActiveRecord::Associations::Builder
-
2
class SingularAssociation < Association #:nodoc:
-
2
self.valid_options += [:remote, :dependent, :counter_cache, :primary_key, :inverse_of]
-
-
2
def constructable?
-
true
-
end
-
-
2
def define_accessors
-
42
super
-
42
define_constructors if constructable?
-
end
-
-
2
private
-
-
2
def define_constructors
-
42
name = self.name
-
-
42
mixin.redefine_method("build_#{name}") do |*params, &block|
-
5
association(name).build(*params, &block)
-
end
-
-
42
mixin.redefine_method("create_#{name}") do |*params, &block|
-
association(name).create(*params, &block)
-
end
-
-
42
mixin.redefine_method("create_#{name}!") do |*params, &block|
-
association(name).create!(*params, &block)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/wrap'
-
-
1
module ActiveRecord
-
1
module Associations
-
# = Active Record Association Collection
-
#
-
# CollectionAssociation is an abstract class that provides common stuff to
-
# ease the implementation of association proxies that represent
-
# collections. See the class hierarchy in AssociationProxy.
-
#
-
# You need to be careful with assumptions regarding the target: The proxy
-
# does not fetch records from the database until it needs them, but new
-
# ones created with +build+ are added to the target. So, the target may be
-
# non-empty and still lack children waiting to be read from the database.
-
# If you look directly to the database you cannot assume that's the entire
-
# collection because new records may have been added to the target, etc.
-
#
-
# If you need to work on all current children, new and existing records,
-
# +load_target+ and the +loaded+ flag are your friends.
-
1
class CollectionAssociation < Association #:nodoc:
-
1
attr_reader :proxy
-
-
1
def initialize(owner, reflection)
-
66
super
-
66
@proxy = CollectionProxy.new(self)
-
end
-
-
# Implements the reader method, e.g. foo.items for Foo.has_many :items
-
1
def reader(force_reload = false)
-
314
if force_reload
-
klass.uncached { reload }
-
elsif stale_target?
-
reload
-
end
-
-
314
proxy
-
end
-
-
# Implements the writer method, e.g. foo.items= for Foo.has_many :items
-
1
def writer(records)
-
replace(records)
-
end
-
-
# Implements the ids reader method, e.g. foo.item_ids for Foo.has_many :items
-
1
def ids_reader
-
if owner.new_record? || loaded? || options[:finder_sql]
-
load_target.map do |record|
-
record.send(reflection.association_primary_key)
-
end
-
else
-
column = "#{reflection.quoted_table_name}.#{reflection.association_primary_key}"
-
relation = scoped
-
-
including = (relation.eager_load_values + relation.includes_values).uniq
-
-
if including.any?
-
join_dependency = ActiveRecord::Associations::JoinDependency.new(reflection.klass, including, [])
-
relation = join_dependency.join_associations.inject(relation) do |r, association|
-
association.join_relation(r)
-
end
-
end
-
-
relation.pluck(column)
-
end
-
end
-
-
# Implements the ids writer method, e.g. foo.item_ids= for Foo.has_many :items
-
1
def ids_writer(ids)
-
pk_column = reflection.primary_key_column
-
ids = Array.wrap(ids).reject { |id| id.blank? }
-
ids.map! { |i| pk_column.type_cast(i) }
-
replace(klass.find(ids).index_by { |r| r.id }.values_at(*ids))
-
end
-
-
1
def reset
-
66
@loaded = false
-
66
@target = []
-
end
-
-
1
def select(select = nil)
-
if block_given?
-
load_target.select.each { |e| yield e }
-
else
-
scoped.select(select)
-
end
-
end
-
-
1
def find(*args)
-
if block_given?
-
load_target.find(*args) { |*block_args| yield(*block_args) }
-
else
-
if options[:finder_sql]
-
find_by_scan(*args)
-
else
-
scoped.find(*args)
-
end
-
end
-
end
-
-
1
def first(*args)
-
7
first_or_last(:first, *args)
-
end
-
-
1
def last(*args)
-
2
first_or_last(:last, *args)
-
end
-
-
1
def build(attributes = {}, options = {}, &block)
-
if attributes.is_a?(Array)
-
attributes.collect { |attr| build(attr, options, &block) }
-
else
-
add_to_target(build_record(attributes, options)) do |record|
-
yield(record) if block_given?
-
end
-
end
-
end
-
-
1
def create(attributes = {}, options = {}, &block)
-
create_record(attributes, options, &block)
-
end
-
-
1
def create!(attributes = {}, options = {}, &block)
-
create_record(attributes, options, true, &block)
-
end
-
-
# Add +records+ to this association. Returns +self+ so method calls may be chained.
-
# Since << flattens its argument list and inserts each record, +push+ and +concat+ behave identically.
-
1
def concat(*records)
-
3
load_target if owner.new_record?
-
-
3
if owner.new_record?
-
3
concat_records(records)
-
else
-
transaction { concat_records(records) }
-
end
-
end
-
-
# Starts a transaction in the association class's database connection.
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :books
-
# end
-
#
-
# Author.first.books.transaction do
-
# # same effect as calling Book.transaction
-
# end
-
1
def transaction(*args)
-
reflection.klass.transaction(*args) do
-
yield
-
end
-
end
-
-
# Remove all records from this association
-
#
-
# See delete for more info.
-
1
def delete_all
-
delete(load_target).tap do
-
reset
-
loaded!
-
end
-
end
-
-
# Called when the association is declared as :dependent => :delete_all. This is
-
# an optimised version which avoids loading the records into memory. Not really
-
# for public consumption.
-
1
def delete_all_on_destroy
-
scoped.delete_all
-
end
-
-
# Destroy all the records from this association.
-
#
-
# See destroy for more info.
-
1
def destroy_all
-
destroy(load_target).tap do
-
reset
-
loaded!
-
end
-
end
-
-
# Calculate sum using SQL, not Enumerable
-
1
def sum(*args)
-
if block_given?
-
scoped.sum(*args) { |*block_args| yield(*block_args) }
-
else
-
scoped.sum(*args)
-
end
-
end
-
-
# Count all records using SQL. If the +:counter_sql+ or +:finder_sql+ option is set for the
-
# association, it will be used for the query. Otherwise, construct options and pass them with
-
# scope to the target class's +count+.
-
1
def count(column_name = nil, count_options = {})
-
14
return 0 if owner.new_record?
-
-
14
column_name, count_options = nil, column_name if column_name.is_a?(Hash)
-
-
14
if options[:counter_sql] || options[:finder_sql]
-
unless count_options.blank?
-
raise ArgumentError, "If finder_sql/counter_sql is used then options cannot be passed"
-
end
-
-
reflection.klass.count_by_sql(custom_counter_sql)
-
else
-
14
if options[:uniq]
-
# This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
-
column_name ||= reflection.klass.primary_key
-
count_options.merge!(:distinct => true)
-
end
-
-
14
value = scoped.count(column_name, count_options)
-
-
14
limit = options[:limit]
-
14
offset = options[:offset]
-
-
14
if limit || offset
-
[ [value - offset.to_i, 0].max, limit.to_i ].min
-
else
-
14
value
-
end
-
end
-
end
-
-
# Removes +records+ from this association calling +before_remove+ and
-
# +after_remove+ callbacks.
-
#
-
# This method is abstract in the sense that +delete_records+ has to be
-
# provided by descendants. Note this method does not imply the records
-
# are actually removed from the database, that depends precisely on
-
# +delete_records+. They are in any case removed from the collection.
-
1
def delete(*records)
-
delete_or_destroy(records, options[:dependent])
-
end
-
-
# Destroy +records+ and remove them from this association calling
-
# +before_remove+ and +after_remove+ callbacks.
-
#
-
# Note that this method will _always_ remove records from the database
-
# ignoring the +:dependent+ option.
-
1
def destroy(*records)
-
records = find(records) if records.any? { |record| record.kind_of?(Fixnum) || record.kind_of?(String) }
-
delete_or_destroy(records, :destroy)
-
end
-
-
# Returns the size of the collection by executing a SELECT COUNT(*)
-
# query if the collection hasn't been loaded, and calling
-
# <tt>collection.size</tt> if it has.
-
#
-
# If the collection has been already loaded +size+ and +length+ are
-
# equivalent. If not and you are going to need the records anyway
-
# +length+ will take one less query. Otherwise +size+ is more efficient.
-
#
-
# This method is abstract in the sense that it relies on
-
# +count_records+, which is a method descendants have to provide.
-
1
def size
-
if !find_target? || (loaded? && !options[:uniq])
-
target.size
-
elsif !loaded? && options[:group]
-
load_target.size
-
elsif !loaded? && !options[:uniq] && target.is_a?(Array)
-
unsaved_records = target.select { |r| r.new_record? }
-
unsaved_records.size + count_records
-
else
-
count_records
-
end
-
end
-
-
# Returns the size of the collection calling +size+ on the target.
-
#
-
# If the collection has been already loaded +length+ and +size+ are
-
# equivalent. If not and you are going to need the records anyway this
-
# method will take one less query. Otherwise +size+ is more efficient.
-
1
def length
-
load_target.size
-
end
-
-
# Equivalent to <tt>collection.size.zero?</tt>. If the collection has
-
# not been already loaded and you are going to fetch the records anyway
-
# it is better to check <tt>collection.length.zero?</tt>.
-
1
def empty?
-
size.zero?
-
end
-
-
1
def any?
-
if block_given?
-
load_target.any? { |*block_args| yield(*block_args) }
-
else
-
!empty?
-
end
-
end
-
-
# Returns true if the collection has more than 1 record. Equivalent to collection.size > 1.
-
1
def many?
-
if block_given?
-
load_target.many? { |*block_args| yield(*block_args) }
-
else
-
size > 1
-
end
-
end
-
-
1
def uniq(collection = load_target)
-
seen = {}
-
collection.find_all do |record|
-
seen[record.id] = true unless seen.key?(record.id)
-
end
-
end
-
-
# Replace this collection with +other_array+
-
# This will perform a diff and delete/add only records that have changed.
-
1
def replace(other_array)
-
other_array.each { |val| raise_on_type_mismatch(val) }
-
original_target = load_target.dup
-
-
if owner.new_record?
-
replace_records(other_array, original_target)
-
else
-
transaction { replace_records(other_array, original_target) }
-
end
-
end
-
-
1
def include?(record)
-
if record.is_a?(reflection.klass)
-
if record.new_record?
-
include_in_memory?(record)
-
else
-
load_target if options[:finder_sql]
-
loaded? ? target.include?(record) : scoped.exists?(record)
-
end
-
else
-
false
-
end
-
end
-
-
1
def load_target
-
272
if find_target?
-
12
@target = merge_target_lists(find_target, target)
-
end
-
-
272
loaded!
-
272
target
-
end
-
-
1
def add_to_target(record)
-
3
callback(:before_add, record)
-
3
yield(record) if block_given?
-
-
3
if options[:uniq] && index = @target.index(record)
-
@target[index] = record
-
else
-
3
@target << record
-
end
-
-
3
callback(:after_add, record)
-
3
set_inverse_instance(record)
-
-
3
record
-
end
-
-
1
private
-
-
1
def custom_counter_sql
-
if options[:counter_sql]
-
interpolate(options[:counter_sql])
-
else
-
# replace the SELECT clause with COUNT(SELECTS), preserving any hints within /* ... */
-
interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) do
-
count_with = $2.to_s
-
count_with = '*' if count_with.blank? || count_with =~ /,/ || count_with =~ /\.\*/
-
"SELECT #{$1}COUNT(#{count_with}) FROM"
-
end
-
end
-
end
-
-
1
def custom_finder_sql
-
interpolate(options[:finder_sql])
-
end
-
-
1
def find_target
-
12
records =
-
if options[:finder_sql]
-
reflection.klass.find_by_sql(custom_finder_sql)
-
else
-
12
scoped.all
-
end
-
-
12
records = options[:uniq] ? uniq(records) : records
-
48
records.each { |record| set_inverse_instance(record) }
-
12
records
-
end
-
-
# We have some records loaded from the database (persisted) and some that are
-
# in-memory (memory). The same record may be represented in the persisted array
-
# and in the memory array.
-
#
-
# So the task of this method is to merge them according to the following rules:
-
#
-
# * The final array must not have duplicates
-
# * The order of the persisted array is to be preserved
-
# * Any changes made to attributes on objects in the memory array are to be preserved
-
# * Otherwise, attributes should have the value found in the database
-
1
def merge_target_lists(persisted, memory)
-
12
return persisted if memory.empty?
-
return memory if persisted.empty?
-
-
persisted.map! do |record|
-
# Unfortunately we cannot simply do memory.delete(record) since on 1.8 this returns
-
# record rather than memory.at(memory.index(record)). The behavior is fixed in 1.9.
-
mem_index = memory.index(record)
-
-
if mem_index
-
mem_record = memory.delete_at(mem_index)
-
-
((record.attribute_names & mem_record.attribute_names) - mem_record.changes.keys).each do |name|
-
mem_record[name] = record[name]
-
end
-
-
mem_record
-
else
-
record
-
end
-
end
-
-
persisted + memory
-
end
-
-
1
def create_record(attributes, options, raise = false, &block)
-
unless owner.persisted?
-
raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
-
end
-
-
if attributes.is_a?(Array)
-
attributes.collect { |attr| create_record(attr, options, raise, &block) }
-
else
-
transaction do
-
add_to_target(build_record(attributes, options)) do |record|
-
yield(record) if block_given?
-
insert_record(record, true, raise)
-
end
-
end
-
end
-
end
-
-
# Do the relevant stuff to insert the given record into the association collection.
-
1
def insert_record(record, validate = true, raise = false)
-
raise NotImplementedError
-
end
-
-
1
def create_scope
-
scoped.scope_for_create.stringify_keys
-
end
-
-
1
def delete_or_destroy(records, method)
-
records = records.flatten
-
records.each { |record| raise_on_type_mismatch(record) }
-
existing_records = records.reject { |r| r.new_record? }
-
-
if existing_records.empty?
-
remove_records(existing_records, records, method)
-
else
-
transaction { remove_records(existing_records, records, method) }
-
end
-
end
-
-
1
def remove_records(existing_records, records, method)
-
records.each { |record| callback(:before_remove, record) }
-
-
delete_records(existing_records, method) if existing_records.any?
-
records.each { |record| target.delete(record) }
-
-
records.each { |record| callback(:after_remove, record) }
-
end
-
-
# Delete the given records from the association, using one of the methods :destroy,
-
# :delete_all or :nullify (or nil, in which case a default is used).
-
1
def delete_records(records, method)
-
raise NotImplementedError
-
end
-
-
1
def replace_records(new_target, original_target)
-
delete(target - new_target)
-
-
unless concat(new_target - target)
-
@target = original_target
-
raise RecordNotSaved, "Failed to replace #{reflection.name} because one or more of the " \
-
"new records could not be saved."
-
end
-
-
target
-
end
-
-
1
def concat_records(records)
-
3
result = true
-
-
3
records.flatten.each do |record|
-
3
raise_on_type_mismatch(record)
-
3
add_to_target(record) do |r|
-
3
result &&= insert_record(record) unless owner.new_record?
-
end
-
end
-
-
3
result && records
-
end
-
-
1
def callback(method, record)
-
6
callbacks_for(method).each do |callback|
-
case callback
-
when Symbol
-
owner.send(callback, record)
-
when Proc
-
callback.call(owner, record)
-
else
-
callback.send(method, owner, record)
-
end
-
end
-
end
-
-
1
def callbacks_for(callback_name)
-
6
full_callback_name = "#{callback_name}_for_#{reflection.name}"
-
6
owner.class.send(full_callback_name.to_sym) || []
-
end
-
-
# Should we deal with assoc.first or assoc.last by issuing an independent query to
-
# the database, or by getting the target, and then taking the first/last item from that?
-
#
-
# If the args is just a non-empty options hash, go to the database.
-
#
-
# Otherwise, go to the database only if none of the following are true:
-
# * target already loaded
-
# * owner is new record
-
# * custom :finder_sql exists
-
# * target contains new or changed record(s)
-
# * the first arg is an integer (which indicates the number of records to be returned)
-
1
def fetch_first_or_last_using_find?(args)
-
9
if args.first.is_a?(Hash)
-
true
-
else
-
!(loaded? ||
-
9
owner.new_record? ||
-
options[:finder_sql] ||
-
target.any? { |record| record.new_record? || record.changed? } ||
-
9
args.first.kind_of?(Integer))
-
end
-
end
-
-
1
def include_in_memory?(record)
-
if reflection.is_a?(ActiveRecord::Reflection::ThroughReflection)
-
owner.send(reflection.through_reflection.name).any? { |source|
-
target = source.send(reflection.source_reflection.name)
-
target.respond_to?(:include?) ? target.include?(record) : target == record
-
} || target.include?(record)
-
else
-
target.include?(record)
-
end
-
end
-
-
# If using a custom finder_sql, #find scans the entire collection.
-
1
def find_by_scan(*args)
-
expects_array = args.first.kind_of?(Array)
-
ids = args.flatten.compact.uniq.map { |arg| arg.to_i }
-
-
if ids.size == 1
-
id = ids.first
-
record = load_target.detect { |r| id == r.id }
-
expects_array ? [ record ] : record
-
else
-
load_target.select { |r| ids.include?(r.id) }
-
end
-
end
-
-
# Fetches the first/last using SQL if possible, otherwise from the target array.
-
1
def first_or_last(type, *args)
-
9
args.shift if args.first.is_a?(Hash) && args.first.empty?
-
-
9
collection = fetch_first_or_last_using_find?(args) ? scoped : load_target
-
9
collection.send(type, *args).tap do |record|
-
9
set_inverse_instance record if record.is_a? ActiveRecord::Base
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Associations
-
# Association proxies in Active Record are middlemen between the object that
-
# holds the association, known as the <tt>@owner</tt>, and the actual associated
-
# object, known as the <tt>@target</tt>. The kind of association any proxy is
-
# about is available in <tt>@reflection</tt>. That's an instance of the class
-
# ActiveRecord::Reflection::AssociationReflection.
-
#
-
# For example, given
-
#
-
# class Blog < ActiveRecord::Base
-
# has_many :posts
-
# end
-
#
-
# blog = Blog.first
-
#
-
# the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
-
# <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
-
# the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
-
#
-
# This class has most of the basic instance methods removed, and delegates
-
# unknown methods to <tt>@target</tt> via <tt>method_missing</tt>. As a
-
# corner case, it even removes the +class+ method and that's why you get
-
#
-
# blog.posts.class # => Array
-
#
-
# though the object behind <tt>blog.posts</tt> is not an Array, but an
-
# ActiveRecord::Associations::HasManyAssociation.
-
#
-
# The <tt>@target</tt> object is not \loaded until needed. For example,
-
#
-
# blog.posts.count
-
#
-
# is computed directly through SQL and does not trigger by itself the
-
# instantiation of the actual post records.
-
2
class CollectionProxy # :nodoc:
-
2
alias :proxy_extend :extend
-
-
210
instance_methods.each { |m| undef_method m unless m.to_s =~ /^(?:nil\?|send|object_id|to_a)$|^__|^respond_to|proxy_/ }
-
-
2
delegate :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from,
-
:lock, :readonly, :having, :pluck, :to => :scoped
-
-
2
delegate :target, :load_target, :loaded?, :to => :@association
-
-
2
delegate :select, :find, :first, :last,
-
:build, :create, :create!,
-
:concat, :replace, :delete_all, :destroy_all, :delete, :destroy, :uniq,
-
:sum, :count, :size, :length, :empty?,
-
:any?, :many?, :include?,
-
:to => :@association
-
-
2
def initialize(association)
-
66
@association = association
-
66
Array.wrap(association.options[:extend]).each { |ext| proxy_extend(ext) }
-
end
-
-
2
alias_method :new, :build
-
-
2
def proxy_association
-
17
@association
-
end
-
-
2
def scoped
-
20
association = @association
-
20
association.scoped.extending do
-
20
define_method(:proxy_association) { association }
-
end
-
end
-
-
2
def respond_to?(name, include_private = false)
-
super ||
-
(load_target && target.respond_to?(name, include_private)) ||
-
proxy_association.klass.respond_to?(name, include_private)
-
end
-
-
2
def method_missing(method, *args, &block)
-
282
match = DynamicFinderMatch.match(method)
-
282
if match && match.instantiator?
-
send(:find_or_instantiator_by_attributes, match, match.attribute_names, *args) do |record|
-
proxy_association.send :set_owner_attributes, record
-
proxy_association.send :add_to_target, record
-
yield(record) if block_given?
-
end.tap do |record|
-
proxy_association.send :set_inverse_instance, record
-
end
-
-
282
elsif target.respond_to?(method) || (!proxy_association.klass.respond_to?(method) && Class.respond_to?(method))
-
268
if load_target
-
268
if target.respond_to?(method)
-
268
target.send(method, *args, &block)
-
else
-
begin
-
super
-
rescue NoMethodError => e
-
raise e, e.message.sub(/ for #<.*$/, " via proxy for #{target}")
-
end
-
end
-
end
-
-
else
-
14
scoped.readonly(nil).send(method, *args, &block)
-
end
-
end
-
-
# Forwards <tt>===</tt> explicitly to the \target because the instance method
-
# removal above doesn't catch it. Loads the \target if needed.
-
2
def ===(other)
-
other === load_target
-
end
-
-
2
def to_ary
-
load_target.dup
-
end
-
2
alias_method :to_a, :to_ary
-
-
2
def <<(*records)
-
3
proxy_association.concat(records) && self
-
end
-
2
alias_method :push, :<<
-
-
2
def clear
-
delete_all
-
self
-
end
-
-
2
def reload
-
proxy_association.reload
-
self
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Has Many Association
-
1
module Associations
-
# This is the proxy that handles a has many association.
-
#
-
# If the association has a <tt>:through</tt> option further specialization
-
# is provided by its child HasManyThroughAssociation.
-
1
class HasManyAssociation < CollectionAssociation #:nodoc:
-
-
1
def insert_record(record, validate = true, raise = false)
-
3
set_owner_attributes(record)
-
3
set_inverse_instance(record)
-
-
3
if raise
-
record.save!(:validate => validate)
-
else
-
3
record.save(:validate => validate)
-
end
-
end
-
-
1
private
-
-
# Returns the number of records in this collection.
-
#
-
# If the association has a counter cache it gets that value. Otherwise
-
# it will attempt to do a count via SQL, bounded to <tt>:limit</tt> if
-
# there's one. Some configuration options like :group make it impossible
-
# to do an SQL count, in those cases the array count will be used.
-
#
-
# That does not depend on whether the collection has already been loaded
-
# or not. The +size+ method is the one that takes the loaded flag into
-
# account and delegates to +count_records+ if needed.
-
#
-
# If the collection is empty the target is set to an empty array and
-
# the loaded flag is set to true as well.
-
1
def count_records
-
count = if has_cached_counter?
-
owner.send(:read_attribute, cached_counter_attribute_name)
-
elsif options[:counter_sql] || options[:finder_sql]
-
reflection.klass.count_by_sql(custom_counter_sql)
-
else
-
scoped.count
-
end
-
-
# If there's nothing in the database and @target has no new records
-
# we are certain the current target is an empty array. This is a
-
# documented side-effect of the method that may avoid an extra SELECT.
-
@target ||= [] and loaded! if count == 0
-
-
[options[:limit], count].compact.min
-
end
-
-
1
def has_cached_counter?(reflection = reflection)
-
owner.attribute_present?(cached_counter_attribute_name(reflection))
-
end
-
-
1
def cached_counter_attribute_name(reflection = reflection)
-
"#{reflection.name}_count"
-
end
-
-
1
def update_counter(difference, reflection = reflection)
-
if has_cached_counter?(reflection)
-
counter = cached_counter_attribute_name(reflection)
-
owner.class.update_counters(owner.id, counter => difference)
-
owner[counter] += difference
-
owner.changed_attributes.delete(counter) # eww
-
end
-
end
-
-
# This shit is nasty. We need to avoid the following situation:
-
#
-
# * An associated record is deleted via record.destroy
-
# * Hence the callbacks run, and they find a belongs_to on the record with a
-
# :counter_cache options which points back at our owner. So they update the
-
# counter cache.
-
# * In which case, we must make sure to *not* update the counter cache, or else
-
# it will be decremented twice.
-
#
-
# Hence this method.
-
1
def inverse_updates_counter_cache?(reflection = reflection)
-
counter_name = cached_counter_attribute_name(reflection)
-
reflection.klass.reflect_on_all_associations(:belongs_to).any? { |inverse_reflection|
-
inverse_reflection.counter_cache_column == counter_name
-
}
-
end
-
-
# Deletes the records according to the <tt>:dependent</tt> option.
-
1
def delete_records(records, method)
-
if method == :destroy
-
records.each { |r| r.destroy }
-
update_counter(-records.length) unless inverse_updates_counter_cache?
-
else
-
scope = self.scoped.where(reflection.klass.primary_key => records)
-
-
if method == :delete_all
-
update_counter(-scope.delete_all)
-
else
-
update_counter(-scope.update_all(reflection.foreign_key => nil))
-
end
-
end
-
end
-
-
1
def foreign_key_present?
-
30
owner.attribute_present?(reflection.association_primary_key)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/inclusion'
-
-
1
module ActiveRecord
-
# = Active Record Belongs To Has One Association
-
1
module Associations
-
1
class HasOneAssociation < SingularAssociation #:nodoc:
-
1
def replace(record, save = true)
-
5
raise_on_type_mismatch(record) if record
-
5
load_target
-
-
# If target and record are nil, or target is equal to record,
-
# we don't need to have transaction.
-
5
if (target || record) && target != record
-
5
transaction_if(save) do
-
5
remove_target!(options[:dependent]) if target && !target.destroyed?
-
-
5
if record
-
5
set_owner_attributes(record)
-
5
set_inverse_instance(record)
-
-
5
if owner.persisted? && save && !record.save
-
nullify_owner_attributes(record)
-
set_owner_attributes(target) if target
-
raise RecordNotSaved, "Failed to save the new associated #{reflection.name}."
-
end
-
end
-
end
-
end
-
-
5
self.target = record
-
end
-
-
1
def delete(method = options[:dependent])
-
if load_target
-
case method
-
when :delete
-
target.delete
-
when :destroy
-
target.destroy
-
when :nullify
-
target.update_attribute(reflection.foreign_key, nil)
-
end
-
end
-
end
-
-
1
private
-
-
# The reason that the save param for replace is false, if for create (not just build),
-
# is because the setting of the foreign keys is actually handled by the scoping when
-
# the record is instantiated, and so they are set straight away and do not need to be
-
# updated within replace.
-
1
def set_new_record(record)
-
5
replace(record, false)
-
end
-
-
1
def remove_target!(method)
-
if method.in?([:delete, :destroy])
-
target.send(method)
-
else
-
nullify_owner_attributes(target)
-
-
if target.persisted? && owner.persisted? && !target.save
-
set_owner_attributes(target)
-
raise RecordNotSaved, "Failed to remove the existing associated #{reflection.name}. " +
-
"The record failed to save when after its foreign key was set to nil."
-
end
-
end
-
end
-
-
1
def nullify_owner_attributes(record)
-
record[reflection.foreign_key] = nil
-
end
-
-
1
def transaction_if(value)
-
5
if value
-
reflection.klass.transaction { yield }
-
else
-
5
yield
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Associations
-
# Helper class module which gets mixed into JoinDependency::JoinAssociation and AssociationScope
-
1
module JoinHelper #:nodoc:
-
-
1
def join_type
-
Arel::InnerJoin
-
end
-
-
1
private
-
-
1
def construct_tables
-
263
tables = []
-
263
chain.each do |reflection|
-
tables << alias_tracker.aliased_table_for(
-
table_name_for(reflection),
-
table_alias_for(reflection, reflection != self.reflection)
-
263
)
-
-
263
if reflection.source_macro == :has_and_belongs_to_many
-
tables << alias_tracker.aliased_table_for(
-
(reflection.source_reflection || reflection).options[:join_table],
-
table_alias_for(reflection, true)
-
)
-
end
-
end
-
263
tables
-
end
-
-
1
def table_name_for(reflection)
-
reflection.table_name
-
end
-
-
1
def table_alias_for(reflection, join = false)
-
263
name = "#{reflection.plural_name}_#{alias_suffix}"
-
263
name << "_join" if join
-
263
name
-
end
-
-
1
def join(table, constraint)
-
table.create_join(table, table.create_on(constraint), join_type)
-
end
-
-
1
def sanitize(conditions, table)
-
conditions = conditions.map do |condition|
-
condition = active_record.send(:sanitize_sql, interpolate(condition), table.table_alias || table.name)
-
condition = Arel.sql(condition) unless condition.is_a?(Arel::Node)
-
condition
-
end
-
-
conditions.length == 1 ? conditions.first : Arel::Nodes::And.new(conditions)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Associations
-
1
class SingularAssociation < Association #:nodoc:
-
# Implements the reader method, e.g. foo.bar for Foo.has_one :bar
-
1
def reader(force_reload = false)
-
732
if force_reload
-
klass.uncached { reload }
-
elsif !loaded? || stale_target?
-
221
reload
-
end
-
-
732
target
-
end
-
-
# Implements the writer method, e.g. foo.items= for Foo.has_many :items
-
1
def writer(record)
-
2
replace(record)
-
end
-
-
1
def create(attributes = {}, options = {}, &block)
-
create_record(attributes, options, &block)
-
end
-
-
1
def create!(attributes = {}, options = {}, &block)
-
create_record(attributes, options, true, &block)
-
end
-
-
1
def build(attributes = {}, options = {})
-
5
record = build_record(attributes, options)
-
5
yield(record) if block_given?
-
5
set_new_record(record)
-
5
record
-
end
-
-
1
private
-
-
1
def create_scope
-
5
scoped.scope_for_create.stringify_keys.except(klass.primary_key)
-
end
-
-
1
def find_target
-
442
scoped.first.tap { |record| set_inverse_instance(record) }
-
end
-
-
# Implemented by subclasses
-
1
def replace(record)
-
raise NotImplementedError, "Subclasses must implement a replace(record) method"
-
end
-
-
1
def set_new_record(record)
-
replace(record)
-
end
-
-
1
def create_record(attributes, options, raise_error = false)
-
record = build_record(attributes, options)
-
yield(record) if block_given?
-
saved = record.save
-
set_new_record(record)
-
raise RecordInvalid.new(record) if !saved && raise_error
-
record
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
-
2
module ActiveRecord
-
2
module AttributeAssignment
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::MassAssignmentSecurity
-
-
2
module ClassMethods
-
2
private
-
-
# The primary key and inheritance column can never be set by mass-assignment for security reasons.
-
2
def attributes_protected_by_default
-
default = [ primary_key, inheritance_column ]
-
default << 'id' unless primary_key.eql? 'id'
-
default
-
end
-
end
-
-
# Allows you to set all the attributes at once by passing in a hash with keys
-
# matching the attribute names (which again matches the column names).
-
#
-
# If any attributes are protected by either +attr_protected+ or
-
# +attr_accessible+ then only settable attributes will be assigned.
-
#
-
# class User < ActiveRecord::Base
-
# attr_protected :is_admin
-
# end
-
#
-
# user = User.new
-
# user.attributes = { :username => 'Phusion', :is_admin => true }
-
# user.username # => "Phusion"
-
# user.is_admin? # => false
-
2
def attributes=(new_attributes)
-
return unless new_attributes.is_a?(Hash)
-
-
assign_attributes(new_attributes)
-
end
-
-
# Allows you to set all the attributes for a particular mass-assignment
-
# security role by passing in a hash of attributes with keys matching
-
# the attribute names (which again matches the column names) and the role
-
# name using the :as option.
-
#
-
# To bypass mass-assignment security you can use the :without_protection => true
-
# option.
-
#
-
# class User < ActiveRecord::Base
-
# attr_accessible :name
-
# attr_accessible :name, :is_admin, :as => :admin
-
# end
-
#
-
# user = User.new
-
# user.assign_attributes({ :name => 'Josh', :is_admin => true })
-
# user.name # => "Josh"
-
# user.is_admin? # => false
-
#
-
# user = User.new
-
# user.assign_attributes({ :name => 'Josh', :is_admin => true }, :as => :admin)
-
# user.name # => "Josh"
-
# user.is_admin? # => true
-
#
-
# user = User.new
-
# user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true)
-
# user.name # => "Josh"
-
# user.is_admin? # => true
-
2
def assign_attributes(new_attributes, options = {})
-
344
return if new_attributes.blank?
-
-
339
attributes = new_attributes.stringify_keys
-
339
multi_parameter_attributes = []
-
339
nested_parameter_attributes = []
-
339
@mass_assignment_options = options
-
-
339
unless options[:without_protection]
-
334
attributes = sanitize_for_mass_assignment(attributes, mass_assignment_role)
-
end
-
-
339
attributes.each do |k, v|
-
2278
if k.include?("(")
-
multi_parameter_attributes << [ k, v ]
-
elsif respond_to?("#{k}=")
-
2278
if v.is_a?(Hash)
-
nested_parameter_attributes << [ k, v ]
-
else
-
2278
send("#{k}=", v)
-
end
-
else
-
raise(UnknownAttributeError, "unknown attribute: #{k}")
-
end
-
end
-
-
# assign any deferred nested attributes after the base attributes have been set
-
339
nested_parameter_attributes.each do |k,v|
-
send("#{k}=", v)
-
end
-
-
339
@mass_assignment_options = nil
-
339
assign_multiparameter_attributes(multi_parameter_attributes)
-
end
-
-
2
protected
-
-
2
def mass_assignment_options
-
334
@mass_assignment_options ||= {}
-
end
-
-
2
def mass_assignment_role
-
334
mass_assignment_options[:as] || :default
-
end
-
-
2
private
-
-
# Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
-
# by calling new on the column type or aggregation type (through composed_of) object with these parameters.
-
# So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
-
# written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
-
# parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum,
-
# f for Float, s for String, and a for Array. If all the values for a given attribute are empty, the
-
# attribute will be set to nil.
-
2
def assign_multiparameter_attributes(pairs)
-
execute_callstack_for_multiparameter_attributes(
-
339
extract_callstack_for_multiparameter_attributes(pairs)
-
)
-
end
-
-
2
def instantiate_time_object(name, values)
-
if self.class.send(:create_time_zone_conversion_attribute?, name, column_for_attribute(name))
-
Time.zone.local(*values)
-
else
-
Time.time_with_datetime_fallback(self.class.default_timezone, *values)
-
end
-
end
-
-
2
def execute_callstack_for_multiparameter_attributes(callstack)
-
339
errors = []
-
339
callstack.each do |name, values_with_empty_parameters|
-
begin
-
send(name + "=", read_value_from_parameter(name, values_with_empty_parameters))
-
rescue => ex
-
errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name}", ex, name)
-
end
-
end
-
339
unless errors.empty?
-
raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes"
-
end
-
end
-
-
2
def read_value_from_parameter(name, values_hash_from_param)
-
klass = (self.class.reflect_on_aggregation(name.to_sym) || column_for_attribute(name)).klass
-
if values_hash_from_param.values.all?{|v|v.nil?}
-
nil
-
elsif klass == Time
-
read_time_parameter_value(name, values_hash_from_param)
-
elsif klass == Date
-
read_date_parameter_value(name, values_hash_from_param)
-
else
-
read_other_parameter_value(klass, name, values_hash_from_param)
-
end
-
end
-
-
2
def read_time_parameter_value(name, values_hash_from_param)
-
# If Date bits were not provided, error
-
raise "Missing Parameter" if [1,2,3].any?{|position| !values_hash_from_param.has_key?(position)}
-
max_position = extract_max_param_for_multiparameter_attributes(values_hash_from_param, 6)
-
# If Date bits were provided but blank, then return nil
-
return nil if (1..3).any? {|position| values_hash_from_param[position].blank?}
-
-
set_values = (1..max_position).collect{|position| values_hash_from_param[position] }
-
# If Time bits are not there, then default to 0
-
(3..5).each {|i| set_values[i] = set_values[i].blank? ? 0 : set_values[i]}
-
instantiate_time_object(name, set_values)
-
end
-
-
2
def read_date_parameter_value(name, values_hash_from_param)
-
return nil if (1..3).any? {|position| values_hash_from_param[position].blank?}
-
set_values = [values_hash_from_param[1], values_hash_from_param[2], values_hash_from_param[3]]
-
begin
-
Date.new(*set_values)
-
rescue ArgumentError # if Date.new raises an exception on an invalid date
-
instantiate_time_object(name, set_values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates
-
end
-
end
-
-
2
def read_other_parameter_value(klass, name, values_hash_from_param)
-
max_position = extract_max_param_for_multiparameter_attributes(values_hash_from_param)
-
values = (1..max_position).collect do |position|
-
raise "Missing Parameter" if !values_hash_from_param.has_key?(position)
-
values_hash_from_param[position]
-
end
-
klass.new(*values)
-
end
-
-
2
def extract_max_param_for_multiparameter_attributes(values_hash_from_param, upper_cap = 100)
-
[values_hash_from_param.keys.max,upper_cap].min
-
end
-
-
2
def extract_callstack_for_multiparameter_attributes(pairs)
-
339
attributes = { }
-
-
339
pairs.each do |pair|
-
multiparameter_name, value = pair
-
attribute_name = multiparameter_name.split("(").first
-
attributes[attribute_name] = {} unless attributes.include?(attribute_name)
-
-
parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value)
-
attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value
-
end
-
-
339
attributes
-
end
-
-
2
def type_cast_attribute_value(multiparameter_name, value)
-
multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value
-
end
-
-
2
def find_parameter_position(multiparameter_name)
-
multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i
-
end
-
-
end
-
end
-
2
require 'active_support/core_ext/enumerable'
-
2
require 'active_support/deprecation'
-
-
2
module ActiveRecord
-
# = Active Record Attribute Methods
-
2
module AttributeMethods #:nodoc:
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::AttributeMethods
-
-
2
included do
-
2
include Read
-
2
include Write
-
2
include BeforeTypeCast
-
2
include Query
-
2
include PrimaryKey
-
2
include TimeZoneConversion
-
2
include Dirty
-
2
include Serialization
-
2
include DeprecatedUnderscoreRead
-
-
# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
-
# "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
-
# (Alias for the protected read_attribute method).
-
2
def [](attr_name)
-
1754
read_attribute(attr_name)
-
end
-
-
# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
-
# (Alias for the protected write_attribute method).
-
2
def []=(attr_name, value)
-
14
write_attribute(attr_name, value)
-
end
-
end
-
-
2
module ClassMethods
-
# Generates all the attribute related methods for columns in the database
-
# accessors, mutators and query methods.
-
2
def define_attribute_methods
-
13
unless defined?(@attribute_methods_mutex)
-
msg = "It looks like something (probably a gem/plugin) is overriding the " \
-
"ActiveRecord::Base.inherited method. It is important that this hook executes so " \
-
"that your models are set up correctly. A workaround has been added to stop this " \
-
"causing an error in 3.2, but future versions will simply not work if the hook is " \
-
"overridden. If you are using Kaminari, please upgrade as it is known to have had " \
-
"this problem.\n\n"
-
msg << "The following may help track down the problem:"
-
-
meth = method(:inherited)
-
if meth.respond_to?(:source_location)
-
msg << " #{meth.source_location.inspect}"
-
else
-
msg << " #{meth.inspect}"
-
end
-
msg << "\n\n"
-
-
ActiveSupport::Deprecation.warn(msg)
-
-
@attribute_methods_mutex = Mutex.new
-
end
-
-
# Use a mutex; we don't want two thread simaltaneously trying to define
-
# attribute methods.
-
13
@attribute_methods_mutex.synchronize do
-
13
return if attribute_methods_generated?
-
13
superclass.define_attribute_methods unless self == base_class
-
13
super(column_names)
-
120
column_names.each { |name| define_external_attribute_method(name) }
-
13
@attribute_methods_generated = true
-
end
-
end
-
-
2
def attribute_methods_generated?
-
7556
@attribute_methods_generated ||= false
-
end
-
-
# We will define the methods as instance methods, but will call them as singleton
-
# methods. This allows us to use method_defined? to check if the method exists,
-
# which is fast and won't give any false positives from the ancestors (because
-
# there are no ancestors).
-
2
def generated_external_attribute_methods
-
21664
@generated_external_attribute_methods ||= Module.new { extend self }
-
end
-
-
2
def undefine_attribute_methods
-
12
super
-
12
@attribute_methods_generated = false
-
end
-
-
2
def instance_method_already_implemented?(method_name)
-
1070
if dangerous_attribute_method?(method_name)
-
raise DangerousAttributeError, "#{method_name} is defined by ActiveRecord"
-
end
-
-
1070
if superclass == Base
-
1070
super
-
else
-
# If B < A and A defines its own attribute method, then we don't want to overwrite that.
-
defined = method_defined_within?(method_name, superclass, superclass.generated_attribute_methods)
-
defined && !ActiveRecord::Base.method_defined?(method_name) || super
-
end
-
end
-
-
# A method name is 'dangerous' if it is already defined by Active Record, but
-
# not by any ancestors. (So 'puts' is not dangerous but 'save' is.)
-
2
def dangerous_attribute_method?(name)
-
1070
method_defined_within?(name, Base)
-
end
-
-
2
def method_defined_within?(name, klass, sup = klass.superclass)
-
1070
if klass.method_defined?(name) || klass.private_method_defined?(name)
-
39
if sup.method_defined?(name) || sup.private_method_defined?(name)
-
klass.instance_method(name).owner != sup.instance_method(name).owner
-
else
-
39
true
-
end
-
else
-
1031
false
-
end
-
end
-
-
2
def attribute_method?(attribute)
-
super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
-
end
-
-
# Returns an array of column names as strings if it's not
-
# an abstract class and table exists.
-
# Otherwise it returns an empty array.
-
2
def attribute_names
-
@attribute_names ||= if !abstract_class? && table_exists?
-
column_names
-
else
-
[]
-
end
-
end
-
end
-
-
# If we haven't generated any methods yet, generate them, then
-
# see if we've created the method we're looking for.
-
2
def method_missing(method, *args, &block)
-
unless self.class.attribute_methods_generated?
-
self.class.define_attribute_methods
-
-
if respond_to_without_attributes?(method)
-
send(method, *args, &block)
-
else
-
super
-
end
-
else
-
super
-
end
-
end
-
-
2
def attribute_missing(match, *args, &block)
-
if self.class.columns_hash[match.attr_name]
-
ActiveSupport::Deprecation.warn(
-
"The method `#{match.method_name}', matching the attribute `#{match.attr_name}' has " \
-
"dispatched through method_missing. This shouldn't happen, because `#{match.attr_name}' " \
-
"is a column of the table. If this error has happened through normal usage of Active " \
-
"Record (rather than through your own code or external libraries), please report it as " \
-
"a bug."
-
)
-
end
-
-
super
-
end
-
-
2
def respond_to?(name, include_private = false)
-
7543
self.class.define_attribute_methods unless self.class.attribute_methods_generated?
-
7543
super
-
end
-
-
# Returns true if the given attribute is in the attributes hash
-
2
def has_attribute?(attr_name)
-
955
@attributes.has_key?(attr_name.to_s)
-
end
-
-
# Returns an array of names for the attributes available on this object.
-
2
def attribute_names
-
106
@attributes.keys
-
end
-
-
# Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
-
2
def attributes
-
106
attrs = {}
-
1359
attribute_names.each { |name| attrs[name] = read_attribute(name) }
-
106
attrs
-
end
-
-
# Returns an <tt>#inspect</tt>-like string for the value of the
-
# attribute +attr_name+. String attributes are truncated upto 50
-
# characters, and Date and Time attributes are returned in the
-
# <tt>:db</tt> format. Other attributes return the value of
-
# <tt>#inspect</tt> without modification.
-
#
-
# person = Person.create!(:name => "David Heinemeier Hansson " * 3)
-
#
-
# person.attribute_for_inspect(:name)
-
# # => '"David Heinemeier Hansson David Heinemeier Hansson D..."'
-
#
-
# person.attribute_for_inspect(:created_at)
-
# # => '"2009-01-12 04:48:57"'
-
2
def attribute_for_inspect(attr_name)
-
182
value = read_attribute(attr_name)
-
-
182
if value.is_a?(String) && value.length > 50
-
"#{value[0..50]}...".inspect
-
182
elsif value.is_a?(Date) || value.is_a?(Time)
-
56
%("#{value.to_s(:db)}")
-
else
-
126
value.inspect
-
end
-
end
-
-
# Returns true if the specified +attribute+ has been set by the user or by a database load and is neither
-
# nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings).
-
2
def attribute_present?(attribute)
-
30
value = read_attribute(attribute)
-
30
!value.nil? && !(value.respond_to?(:empty?) && value.empty?)
-
end
-
-
# Returns the column object for the named attribute.
-
2
def column_for_attribute(name)
-
10770
self.class.columns_hash[name.to_s]
-
end
-
-
2
protected
-
-
2
def clone_attributes(reader_method = :read_attribute, attributes = {})
-
attribute_names.each do |name|
-
attributes[name] = clone_attribute_value(reader_method, name)
-
end
-
attributes
-
end
-
-
2
def clone_attribute_value(reader_method, attribute_name)
-
3418
value = send(reader_method, attribute_name)
-
3418
value.duplicable? ? value.clone : value
-
rescue TypeError, NoMethodError
-
value
-
end
-
-
# Returns a copy of the attributes hash where all the values have been safely quoted for use in
-
# an Arel insert/update method.
-
2
def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
-
363
attrs = {}
-
363
klass = self.class
-
363
arel_table = klass.arel_table
-
-
363
attribute_names.each do |name|
-
3862
if (column = column_for_attribute(name)) && (include_primary_key || !column.primary)
-
-
3554
if include_readonly_attributes || !self.class.readonly_attributes.include?(name)
-
-
3554
value = if klass.serialized_attributes.include?(name)
-
@attributes[name].serialized_value
-
else
-
# FIXME: we need @attributes to be used consistently.
-
# If the values stored in @attributes were already type
-
# casted, this code could be simplified
-
3554
read_attribute(name)
-
end
-
-
3554
attrs[arel_table[name]] = value
-
end
-
end
-
end
-
-
363
attrs
-
end
-
-
2
def attribute_method?(attr_name)
-
678
attr_name == 'id' || (defined?(@attributes) && @attributes.include?(attr_name))
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module BeforeTypeCast
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
attribute_method_suffix "_before_type_cast"
-
end
-
-
2
def read_attribute_before_type_cast(attr_name)
-
17
@attributes[attr_name]
-
end
-
-
# Returns a hash of attributes before typecasting and deserialization.
-
2
def attributes_before_type_cast
-
@attributes
-
end
-
-
2
private
-
-
# Handle *_before_type_cast for method_missing.
-
2
def attribute_before_type_cast(attribute_name)
-
17
if attribute_name == 'id'
-
read_attribute_before_type_cast(self.class.primary_key)
-
else
-
17
read_attribute_before_type_cast(attribute_name)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/deprecation'
-
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module DeprecatedUnderscoreRead
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
attribute_method_prefix "_"
-
end
-
-
2
module ClassMethods
-
2
protected
-
-
2
def define_method__attribute(attr_name)
-
# Do nothing, let it hit method missing instead.
-
end
-
end
-
-
2
protected
-
-
2
def _attribute(attr_name)
-
ActiveSupport::Deprecation.warn(
-
"You have called '_#{attr_name}'. This is deprecated. Please use " \
-
"either '#{attr_name}' or read_attribute('#{attr_name}')."
-
)
-
read_attribute(attr_name)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module Dirty
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::Dirty
-
2
include AttributeMethods::Write
-
-
2
included do
-
2
if self < ::ActiveRecord::Timestamp
-
raise "You cannot include Dirty after Timestamp"
-
end
-
-
2
class_attribute :partial_updates
-
2
self.partial_updates = true
-
end
-
-
# Attempts to +save+ the record and clears changed attributes if successful.
-
2
def save(*) #:nodoc:
-
356
if status = super
-
332
@previously_changed = changes
-
332
@changed_attributes.clear
-
elsif IdentityMap.enabled?
-
IdentityMap.remove(self)
-
end
-
356
status
-
end
-
-
# Attempts to <tt>save!</tt> the record and clears changed attributes if successful.
-
2
def save!(*) #:nodoc:
-
31
super.tap do
-
31
@previously_changed = changes
-
31
@changed_attributes.clear
-
end
-
rescue
-
IdentityMap.remove(self) if IdentityMap.enabled?
-
raise
-
end
-
-
# <tt>reload</tt> the record and clears changed attributes.
-
2
def reload(*) #:nodoc:
-
4
super.tap do
-
4
@previously_changed.clear
-
4
@changed_attributes.clear
-
end
-
end
-
-
2
private
-
# Wrap write_attribute to remember original attribute value.
-
2
def write_attribute(attr, value)
-
3432
attr = attr.to_s
-
-
# The attribute already has an unsaved change.
-
3432
if attribute_changed?(attr)
-
14
old = @changed_attributes[attr]
-
14
@changed_attributes.delete(attr) unless _field_changed?(attr, old, value)
-
else
-
3418
old = clone_attribute_value(:read_attribute, attr)
-
# Save Time objects as TimeWithZone if time_zone_aware_attributes == true
-
3418
old = old.in_time_zone if clone_with_time_zone_conversion_attribute?(attr, old)
-
3418
@changed_attributes[attr] = old if _field_changed?(attr, old, value)
-
end
-
-
# Carry on.
-
3432
super(attr, value)
-
end
-
-
2
def update(*)
-
55
if partial_updates?
-
# Serialized attributes should always be written in case they've been
-
# changed in place.
-
55
super(changed | (attributes.keys & self.class.serialized_attributes.keys))
-
else
-
super
-
end
-
end
-
-
2
def _field_changed?(attr, old, value)
-
3432
if column = column_for_attribute(attr)
-
if column.number? && (changes_from_nil_to_empty_string?(column, old, value) ||
-
3432
changes_from_zero_to_string?(old, value))
-
251
value = nil
-
else
-
3181
value = column.type_cast(value)
-
end
-
end
-
-
3432
old != value
-
end
-
-
2
def clone_with_time_zone_conversion_attribute?(attr, old)
-
3418
old.class.name == "Time" && time_zone_aware_attributes && !self.skip_time_zone_conversion_for_attributes.include?(attr.to_sym)
-
end
-
-
2
def changes_from_nil_to_empty_string?(column, old, value)
-
# For nullable numeric columns, NULL gets stored in database for blank (i.e. '') values.
-
# Hence we don't record it as a change if the value changes from nil to ''.
-
# If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll
-
# be typecast back to 0 (''.to_i => 0)
-
1210
column.null && (old.nil? || old == 0) && value.blank?
-
end
-
-
2
def changes_from_zero_to_string?(old, value)
-
# For columns with old 0 and value non-empty string
-
959
old == 0 && value.is_a?(String) && value.present? && value != '0'
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module PrimaryKey
-
2
extend ActiveSupport::Concern
-
-
# Returns this record's primary key value wrapped in an Array if one is available
-
2
def to_key
-
key = self.id
-
[key] if key
-
end
-
-
# Returns the primary key value
-
2
def id
-
read_attribute(self.class.primary_key)
-
end
-
-
# Sets the primary key value
-
2
def id=(value)
-
write_attribute(self.class.primary_key, value)
-
end
-
-
# Queries the primary key value
-
2
def id?
-
query_attribute(self.class.primary_key)
-
end
-
-
2
module ClassMethods
-
2
def define_method_attribute(attr_name)
-
107
super
-
-
107
if attr_name == primary_key && attr_name != 'id'
-
generated_attribute_methods.send(:alias_method, :id, primary_key)
-
generated_external_attribute_methods.module_eval <<-CODE, __FILE__, __LINE__
-
def id(v, attributes, attributes_cache, attr_name)
-
attr_name = '#{primary_key}'
-
send(attr_name, attributes[attr_name], attributes, attributes_cache, attr_name)
-
end
-
CODE
-
end
-
end
-
-
2
def dangerous_attribute_method?(method_name)
-
1070
super && !['id', 'id=', 'id?'].include?(method_name)
-
end
-
-
# Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
-
# primary_key_prefix_type setting, though.
-
2
def primary_key
-
8216
@primary_key = reset_primary_key unless defined? @primary_key
-
8216
@primary_key
-
end
-
-
# Returns a quoted version of the primary key name, used to construct SQL statements.
-
2
def quoted_primary_key
-
2
@quoted_primary_key ||= connection.quote_column_name(primary_key)
-
end
-
-
2
def reset_primary_key #:nodoc:
-
17
if self == base_class
-
17
self.primary_key = get_primary_key(base_class.name)
-
else
-
self.primary_key = base_class.primary_key
-
end
-
end
-
-
2
def get_primary_key(base_name) #:nodoc:
-
17
return 'id' unless base_name && !base_name.blank?
-
-
17
case primary_key_prefix_type
-
when :table_name
-
base_name.foreign_key(false)
-
when :table_name_with_underscore
-
base_name.foreign_key
-
else
-
17
if ActiveRecord::Base != self && table_exists?
-
17
connection.schema_cache.primary_keys[table_name]
-
else
-
'id'
-
end
-
end
-
end
-
-
2
def original_primary_key #:nodoc:
-
deprecated_original_property_getter :primary_key
-
end
-
-
# Sets the name of the primary key column.
-
#
-
# class Project < ActiveRecord::Base
-
# self.primary_key = "sysid"
-
# end
-
#
-
# You can also define the primary_key method yourself:
-
#
-
# class Project < ActiveRecord::Base
-
# def self.primary_key
-
# "foo_" + super
-
# end
-
# end
-
# Project.primary_key # => "foo_id"
-
2
def primary_key=(value)
-
17
@original_primary_key = @primary_key if defined?(@primary_key)
-
17
@primary_key = value && value.to_s
-
17
@quoted_primary_key = nil
-
end
-
-
2
def set_primary_key(value = nil, &block) #:nodoc:
-
deprecated_property_setter :primary_key, value, block
-
@quoted_primary_key = nil
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module Query
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
attribute_method_suffix "?"
-
end
-
-
2
def query_attribute(attr_name)
-
8
unless value = read_attribute(attr_name)
-
false
-
else
-
8
column = self.class.columns_hash[attr_name]
-
8
if column.nil?
-
if Numeric === value || value !~ /[^0-9]/
-
!value.to_i.zero?
-
else
-
return false if ActiveRecord::ConnectionAdapters::Column::FALSE_VALUES.include?(value)
-
!value.blank?
-
end
-
8
elsif column.number?
-
!value.zero?
-
else
-
8
!value.blank?
-
end
-
end
-
end
-
-
2
private
-
# Handle *? for method_missing.
-
2
def attribute?(attribute_name)
-
8
query_attribute(attribute_name)
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module Read
-
2
extend ActiveSupport::Concern
-
-
2
ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date]
-
-
2
included do
-
2
cattr_accessor :attribute_types_cached_by_default, :instance_writer => false
-
2
self.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
-
end
-
-
2
module ClassMethods
-
# +cache_attributes+ allows you to declare which converted attribute values should
-
# be cached. Usually caching only pays off for attributes with expensive conversion
-
# methods, like time related columns (e.g. +created_at+, +updated_at+).
-
2
def cache_attributes(*attribute_names)
-
cached_attributes.merge attribute_names.map { |attr| attr.to_s }
-
end
-
-
# Returns the attributes which are cached. By default time related columns
-
# with datatype <tt>:datetime, :timestamp, :time, :date</tt> are cached.
-
2
def cached_attributes
-
360
@cached_attributes ||= columns.select { |c| cacheable_column?(c) }.map { |col| col.name }.to_set
-
end
-
-
# Returns +true+ if the provided attribute is being cached.
-
2
def cache_attribute?(attr_name)
-
214
cached_attributes.include?(attr_name)
-
end
-
-
2
def undefine_attribute_methods
-
12
generated_external_attribute_methods.module_eval do
-
12
instance_methods.each { |m| undef_method(m) }
-
end
-
-
12
super
-
end
-
-
2
def type_cast_attribute(attr_name, attributes, cache = {}) #:nodoc:
-
10765
return unless attr_name
-
10765
attr_name = attr_name.to_s
-
-
10765
if generated_external_attribute_methods.method_defined?(attr_name)
-
10765
if attributes.has_key?(attr_name) || attr_name == 'id'
-
10765
generated_external_attribute_methods.send(attr_name, attributes[attr_name], attributes, cache, attr_name)
-
end
-
elsif !attribute_methods_generated?
-
# If we haven't generated the caster methods yet, do that and
-
# then try again
-
define_attribute_methods
-
type_cast_attribute(attr_name, attributes, cache)
-
else
-
# If we get here, the attribute has no associated DB column, so
-
# just return it verbatim.
-
attributes[attr_name]
-
end
-
end
-
-
2
protected
-
# We want to generate the methods via module_eval rather than define_method,
-
# because define_method is slower on dispatch and uses more memory (because it
-
# creates a closure).
-
#
-
# But sometimes the database might return columns with characters that are not
-
# allowed in normal method names (like 'my_column(omg)'. So to work around this
-
# we first define with the __temp__ identifier, and then use alias method to
-
# rename it to what we want.
-
2
def define_method_attribute(attr_name)
-
107
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
-
def __temp__
-
#{internal_attribute_access_code(attr_name, attribute_cast_code(attr_name))}
-
end
-
alias_method '#{attr_name}', :__temp__
-
undef_method :__temp__
-
STR
-
end
-
-
2
private
-
-
2
def define_external_attribute_method(attr_name)
-
107
generated_external_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
-
def __temp__(v, attributes, attributes_cache, attr_name)
-
#{external_attribute_access_code(attr_name, attribute_cast_code(attr_name))}
-
end
-
alias_method '#{attr_name}', :__temp__
-
undef_method :__temp__
-
STR
-
end
-
-
2
def cacheable_column?(column)
-
107
attribute_types_cached_by_default.include?(column.type)
-
end
-
-
2
def internal_attribute_access_code(attr_name, cast_code)
-
107
access_code = "(v=@attributes[attr_name]) && #{cast_code}"
-
-
107
unless attr_name == primary_key
-
94
access_code.insert(0, "missing_attribute(attr_name, caller) unless @attributes.has_key?(attr_name); ")
-
end
-
-
107
if cache_attribute?(attr_name)
-
39
access_code = "@attributes_cache[attr_name] ||= (#{access_code})"
-
end
-
-
107
"attr_name = '#{attr_name}'; #{access_code}"
-
end
-
-
2
def external_attribute_access_code(attr_name, cast_code)
-
107
access_code = "v && #{cast_code}"
-
-
107
if cache_attribute?(attr_name)
-
39
access_code = "attributes_cache[attr_name] ||= (#{access_code})"
-
end
-
-
107
access_code
-
end
-
-
2
def attribute_cast_code(attr_name)
-
214
columns_hash[attr_name].type_cast_code('v')
-
end
-
end
-
-
# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
-
# "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
-
2
def read_attribute(attr_name)
-
10765
self.class.type_cast_attribute(attr_name, @attributes, @attributes_cache)
-
end
-
-
2
private
-
2
def attribute(attribute_name)
-
read_attribute(attribute_name)
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module Serialization
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
# Returns a hash of all the attributes that have been specified for serialization as
-
# keys and their class restriction as values.
-
2
class_attribute :serialized_attributes
-
2
self.serialized_attributes = {}
-
end
-
-
2
class Attribute < Struct.new(:coder, :value, :state)
-
2
def unserialized_value
-
state == :serialized ? unserialize : value
-
end
-
-
2
def serialized_value
-
state == :unserialized ? serialize : value
-
end
-
-
2
def unserialize
-
self.state = :unserialized
-
self.value = coder.load(value)
-
end
-
-
2
def serialize
-
self.state = :serialized
-
self.value = coder.dump(value)
-
end
-
end
-
-
2
module ClassMethods
-
# If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
-
# then specify the name of that attribute using this method and it will be handled automatically.
-
# The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
-
# class on retrieval or SerializationTypeMismatch will be raised.
-
#
-
# ==== Parameters
-
#
-
# * +attr_name+ - The field name that should be serialized.
-
# * +class_name+ - Optional, class name that the object type should be equal to.
-
#
-
# ==== Example
-
# # Serialize a preferences attribute
-
# class User < ActiveRecord::Base
-
# serialize :preferences
-
# end
-
2
def serialize(attr_name, class_name = Object)
-
coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) }
-
class_name
-
else
-
Coders::YAMLColumn.new(class_name)
-
end
-
-
# merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
-
# has its own hash of own serialized attributes
-
self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
-
end
-
-
2
def initialize_attributes(attributes, options = {}) #:nodoc:
-
2120
serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized
-
1060
super(attributes, options)
-
-
1060
serialized_attributes.each do |key, coder|
-
if attributes.key?(key)
-
attributes[key] = Attribute.new(coder, attributes[key], serialized)
-
end
-
end
-
-
1060
attributes
-
end
-
-
2
private
-
-
2
def attribute_cast_code(attr_name)
-
214
if serialized_attributes.include?(attr_name)
-
"v.unserialized_value"
-
else
-
214
super
-
end
-
end
-
end
-
-
2
def type_cast_attribute_for_write(column, value)
-
3476
if column && coder = self.class.serialized_attributes[column.name]
-
Attribute.new(coder, value, :unserialized)
-
else
-
3476
super
-
end
-
end
-
-
2
def _field_changed?(attr, old, value)
-
3432
if self.class.serialized_attributes.include?(attr)
-
old != value
-
else
-
3432
super
-
end
-
end
-
-
2
def read_attribute_before_type_cast(attr_name)
-
17
if serialized_attributes.include?(attr_name)
-
super.unserialized_value
-
else
-
17
super
-
end
-
end
-
-
2
def attributes_before_type_cast
-
super.dup.tap do |attributes|
-
self.class.serialized_attributes.each_key do |key|
-
if attributes.key?(key)
-
attributes[key] = attributes[key].unserialized_value
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/object/inclusion'
-
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module TimeZoneConversion
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
cattr_accessor :time_zone_aware_attributes, :instance_writer => false
-
2
self.time_zone_aware_attributes = false
-
-
2
class_attribute :skip_time_zone_conversion_for_attributes, :instance_writer => false
-
2
self.skip_time_zone_conversion_for_attributes = []
-
end
-
-
2
module ClassMethods
-
2
protected
-
# The enhanced read method automatically converts the UTC time stored in the database to the time
-
# zone stored in Time.zone.
-
2
def attribute_cast_code(attr_name)
-
214
column = columns_hash[attr_name]
-
-
214
if create_time_zone_conversion_attribute?(attr_name, column)
-
60
typecast = "v = #{super}"
-
60
time_zone_conversion = "v.acts_like?(:time) ? v.in_time_zone : v"
-
-
60
"((#{typecast}) && (#{time_zone_conversion}))"
-
else
-
154
super
-
end
-
end
-
-
# Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled.
-
# This enhanced write method will automatically convert the time passed to it to the zone stored in Time.zone.
-
2
def define_method_attribute=(attr_name)
-
107
if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name])
-
30
method_body, line = <<-EOV, __LINE__ + 1
-
def #{attr_name}=(original_time)
-
original_time = nil if original_time.blank?
-
time = original_time
-
unless time.acts_like?(:time)
-
time = time.is_a?(String) ? Time.zone.parse(time) : time.to_time rescue time
-
end
-
time = time.in_time_zone rescue nil if time
-
previous_time = attribute_changed?("#{attr_name}") ? changed_attributes["#{attr_name}"] : read_attribute(:#{attr_name})
-
write_attribute(:#{attr_name}, original_time)
-
#{attr_name}_will_change! if previous_time != time
-
@attributes_cache["#{attr_name}"] = time
-
end
-
EOV
-
30
generated_attribute_methods.module_eval(method_body, __FILE__, line)
-
else
-
77
super
-
end
-
end
-
-
2
private
-
2
def create_time_zone_conversion_attribute?(name, column)
-
321
time_zone_aware_attributes && !self.skip_time_zone_conversion_for_attributes.include?(name.to_sym) && column.type.in?([:datetime, :timestamp])
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module AttributeMethods
-
2
module Write
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
attribute_method_suffix "="
-
end
-
-
2
module ClassMethods
-
2
protected
-
2
def define_method_attribute=(attr_name)
-
77
if attr_name =~ ActiveModel::AttributeMethods::NAME_COMPILABLE_REGEXP
-
77
generated_attribute_methods.module_eval("def #{attr_name}=(new_value); write_attribute('#{attr_name}', new_value); end", __FILE__, __LINE__)
-
else
-
generated_attribute_methods.send(:define_method, "#{attr_name}=") do |new_value|
-
write_attribute(attr_name, new_value)
-
end
-
end
-
end
-
end
-
-
# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+. Empty strings
-
# for fixnum and float columns are turned into +nil+.
-
2
def write_attribute(attr_name, value)
-
3476
attr_name = attr_name.to_s
-
3476
attr_name = self.class.primary_key if attr_name == 'id' && self.class.primary_key
-
3476
@attributes_cache.delete(attr_name)
-
3476
column = column_for_attribute(attr_name)
-
-
3476
unless column || @attributes.has_key?(attr_name)
-
ActiveSupport::Deprecation.warn(
-
"You're trying to create an attribute `#{attr_name}'. Writing arbitrary " \
-
"attributes on a model is deprecated. Please just use `attr_writer` etc."
-
)
-
end
-
-
3476
@attributes[attr_name] = type_cast_attribute_for_write(column, value)
-
end
-
2
alias_method :raw_write_attribute, :write_attribute
-
-
2
private
-
# Handle *= for method_missing.
-
2
def attribute=(attribute_name, value)
-
write_attribute(attribute_name, value)
-
end
-
-
2
def type_cast_attribute_for_write(column, value)
-
3476
if column && column.number?
-
1210
convert_number_column_value(value)
-
else
-
2266
value
-
end
-
end
-
-
2
def convert_number_column_value(value)
-
1210
case value
-
when FalseClass
-
0
-
when TrueClass
-
1
-
when String
-
value.presence
-
else
-
1210
value
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
-
2
module ActiveRecord
-
# = Active Record Autosave Association
-
#
-
# +AutosaveAssociation+ is a module that takes care of automatically saving
-
# associated records when their parent is saved. In addition to saving, it
-
# also destroys any associated records that were marked for destruction.
-
# (See +mark_for_destruction+ and <tt>marked_for_destruction?</tt>).
-
#
-
# Saving of the parent, its associations, and the destruction of marked
-
# associations, all happen inside a transaction. This should never leave the
-
# database in an inconsistent state.
-
#
-
# If validations for any of the associations fail, their error messages will
-
# be applied to the parent.
-
#
-
# Note that it also means that associations marked for destruction won't
-
# be destroyed directly. They will however still be marked for destruction.
-
#
-
# Note that <tt>:autosave => false</tt> is not same as not declaring <tt>:autosave</tt>.
-
# When the <tt>:autosave</tt> option is not present new associations are saved.
-
#
-
# == Validation
-
#
-
# Children records are validated unless <tt>:validate</tt> is +false+.
-
#
-
# == Callbacks
-
#
-
# Association with autosave option defines several callbacks on your
-
# model (before_save, after_create, after_update). Please note that
-
# callbacks are executed in the order they were defined in
-
# model. You should avoid modyfing the association content, before
-
# autosave callbacks are executed. Placing your callbacks after
-
# associations is usually a good practice.
-
#
-
# == Examples
-
#
-
# === One-to-one Example
-
#
-
# class Post
-
# has_one :author, :autosave => true
-
# end
-
#
-
# Saving changes to the parent and its associated model can now be performed
-
# automatically _and_ atomically:
-
#
-
# post = Post.find(1)
-
# post.title # => "The current global position of migrating ducks"
-
# post.author.name # => "alloy"
-
#
-
# post.title = "On the migration of ducks"
-
# post.author.name = "Eloy Duran"
-
#
-
# post.save
-
# post.reload
-
# post.title # => "On the migration of ducks"
-
# post.author.name # => "Eloy Duran"
-
#
-
# Destroying an associated model, as part of the parent's save action, is as
-
# simple as marking it for destruction:
-
#
-
# post.author.mark_for_destruction
-
# post.author.marked_for_destruction? # => true
-
#
-
# Note that the model is _not_ yet removed from the database:
-
#
-
# id = post.author.id
-
# Author.find_by_id(id).nil? # => false
-
#
-
# post.save
-
# post.reload.author # => nil
-
#
-
# Now it _is_ removed from the database:
-
#
-
# Author.find_by_id(id).nil? # => true
-
#
-
# === One-to-many Example
-
#
-
# When <tt>:autosave</tt> is not declared new children are saved when their parent is saved:
-
#
-
# class Post
-
# has_many :comments # :autosave option is no declared
-
# end
-
#
-
# post = Post.new(:title => 'ruby rocks')
-
# post.comments.build(:body => 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# post = Post.create(:title => 'ruby rocks')
-
# post.comments.build(:body => 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# post = Post.create(:title => 'ruby rocks')
-
# post.comments.create(:body => 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# When <tt>:autosave</tt> is true all children is saved, no matter whether they are new records:
-
#
-
# class Post
-
# has_many :comments, :autosave => true
-
# end
-
#
-
# post = Post.create(:title => 'ruby rocks')
-
# post.comments.create(:body => 'hello world')
-
# post.comments[0].body = 'hi everyone'
-
# post.save # => saves both post and comment, with 'hi everyone' as body
-
#
-
# Destroying one of the associated models as part of the parent's save action
-
# is as simple as marking it for destruction:
-
#
-
# post.comments.last.mark_for_destruction
-
# post.comments.last.marked_for_destruction? # => true
-
# post.comments.length # => 2
-
#
-
# Note that the model is _not_ yet removed from the database:
-
#
-
# id = post.comments.last.id
-
# Comment.find_by_id(id).nil? # => false
-
#
-
# post.save
-
# post.reload.comments.length # => 1
-
#
-
# Now it _is_ removed from the database:
-
#
-
# Comment.find_by_id(id).nil? # => true
-
-
2
module AutosaveAssociation
-
2
extend ActiveSupport::Concern
-
-
2
ASSOCIATION_TYPES = %w{ HasOne HasMany BelongsTo HasAndBelongsToMany }
-
-
2
module AssociationBuilderExtension #:nodoc:
-
2
def self.included(base)
-
8
base.valid_options << :autosave
-
end
-
-
2
def build
-
64
reflection = super
-
64
model.send(:add_autosave_association_callbacks, reflection)
-
64
reflection
-
end
-
end
-
-
2
included do
-
2
ASSOCIATION_TYPES.each do |type|
-
8
Associations::Builder.const_get(type).send(:include, AssociationBuilderExtension)
-
end
-
end
-
-
2
module ClassMethods
-
2
private
-
-
2
def define_non_cyclic_method(name, reflection, &block)
-
78
define_method(name) do |*args|
-
1545
result = true; @_already_called ||= {}
-
# Loop prevention for validation of associations
-
1545
unless @_already_called[[name, reflection.name]]
-
1545
begin
-
1545
@_already_called[[name, reflection.name]]=true
-
1545
result = instance_eval(&block)
-
ensure
-
1545
@_already_called[[name, reflection.name]]=false
-
end
-
end
-
-
1545
result
-
end
-
end
-
-
# Adds validation and save callbacks for the association as specified by
-
# the +reflection+.
-
#
-
# For performance reasons, we don't check whether to validate at runtime.
-
# However the validation and callback methods are lazy and those methods
-
# get created when they are invoked for the very first time. However,
-
# this can change, for instance, when using nested attributes, which is
-
# called _after_ the association has been defined. Since we don't want
-
# the callbacks to get defined multiple times, there are guards that
-
# check if the save or validation methods have already been defined
-
# before actually defining them.
-
2
def add_autosave_association_callbacks(reflection)
-
68
save_method = :"autosave_associated_records_for_#{reflection.name}"
-
68
validation_method = :"validate_associated_records_for_#{reflection.name}"
-
68
collection = reflection.collection?
-
-
68
unless method_defined?(save_method)
-
64
if collection
-
22
before_save :before_save_collection_association
-
-
145
define_non_cyclic_method(save_method, reflection) { save_collection_association(reflection) }
-
# Doesn't use after_save as that would save associations added in after_create/after_update twice
-
22
after_create save_method
-
22
after_update save_method
-
else
-
42
if reflection.macro == :has_one
-
95
define_method(save_method) { save_has_one_association(reflection) }
-
# Configures two callbacks instead of a single after_save so that
-
# the model may rely on their execution order relative to its
-
# own callbacks.
-
#
-
# For example, given that after_creates run before after_saves, if
-
# we configured instead an after_save there would be no way to fire
-
# a custom after_create callback after the child association gets
-
# created.
-
10
after_create save_method
-
10
after_update save_method
-
else
-
1239
define_non_cyclic_method(save_method, reflection) { save_belongs_to_association(reflection) }
-
32
before_save save_method
-
end
-
end
-
end
-
-
68
if reflection.validate? && !method_defined?(validation_method)
-
24
method = (collection ? :validate_collection_association : :validate_single_association)
-
239
define_non_cyclic_method(validation_method, reflection) { send(method, reflection) }
-
24
validate validation_method
-
end
-
end
-
end
-
-
# Reloads the attributes of the object as usual and clears <tt>marked_for_destruction</tt> flag.
-
2
def reload(options = nil)
-
4
@marked_for_destruction = false
-
4
super
-
end
-
-
# Marks this record to be destroyed as part of the parents save transaction.
-
# This does _not_ actually destroy the record instantly, rather child record will be destroyed
-
# when <tt>parent.save</tt> is called.
-
#
-
# Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
-
2
def mark_for_destruction
-
1
@marked_for_destruction = true
-
end
-
-
# Returns whether or not this record will be destroyed as part of the parents save transaction.
-
#
-
# Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
-
2
def marked_for_destruction?
-
29
@marked_for_destruction
-
end
-
-
# Returns whether or not this record has been changed in any way (including whether
-
# any of its nested autosave associations are likewise changed)
-
2
def changed_for_autosave?
-
3
new_record? || changed? || marked_for_destruction? || nested_records_changed_for_autosave?
-
end
-
-
2
private
-
-
# Returns the record for an association collection that should be validated
-
# or saved. If +autosave+ is +false+ only new records will be returned,
-
# unless the parent is/was a new record itself.
-
2
def associated_records_to_validate_or_save(association, new_record, autosave)
-
70
if new_record
-
33
association && association.target
-
37
elsif autosave
-
15
association.target.find_all { |record| record.changed_for_autosave? }
-
else
-
25
association.target.find_all { |record| record.new_record? }
-
end
-
end
-
-
# go through nested autosave associations that are loaded in memory (without loading
-
# any new ones), and return true if is changed for autosave
-
2
def nested_records_changed_for_autosave?
-
1
self.class.reflect_on_all_autosave_associations.any? do |reflection|
-
association = association_instance_get(reflection.name)
-
association && Array.wrap(association.target).any? { |a| a.changed_for_autosave? }
-
end
-
end
-
-
# Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is
-
# turned on for the association.
-
2
def validate_single_association(reflection)
-
48
association = association_instance_get(reflection.name)
-
48
record = association && association.reader
-
48
association_valid?(reflection, record) if record
-
end
-
-
# Validate the associated records if <tt>:validate</tt> or
-
# <tt>:autosave</tt> is turned on for the association specified by
-
# +reflection+.
-
2
def validate_collection_association(reflection)
-
167
if association = association_instance_get(reflection.name)
-
32
if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave])
-
37
records.each { |record| association_valid?(reflection, record) }
-
end
-
end
-
end
-
-
# Returns whether or not the association is valid and applies any errors to
-
# the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt>
-
# enabled records if they're marked_for_destruction? or destroyed.
-
2
def association_valid?(reflection, record)
-
13
return true if record.destroyed? || record.marked_for_destruction?
-
-
11
unless valid = record.valid?
-
if reflection.options[:autosave]
-
record.errors.each do |attribute, message|
-
attribute = "#{reflection.name}.#{attribute}"
-
errors[attribute] << message
-
errors[attribute].uniq!
-
end
-
else
-
errors.add(reflection.name)
-
end
-
end
-
11
valid
-
end
-
-
# Is used as a before_save callback to check while saving a collection
-
# association whether or not the parent was a new record before saving.
-
2
def before_save_collection_association
-
46
@new_record_before_save = new_record?
-
46
true
-
end
-
-
# Saves any new associated records, or all loaded autosave associations if
-
# <tt>:autosave</tt> is enabled on the association.
-
#
-
# In addition, it destroys all children that were marked for destruction
-
# with mark_for_destruction.
-
#
-
# This all happens inside a transaction, _if_ the Transactions module is included into
-
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
-
2
def save_collection_association(reflection)
-
123
if association = association_instance_get(reflection.name)
-
38
autosave = reflection.options[:autosave]
-
-
38
if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave)
-
38
begin
-
38
if autosave
-
24
records_to_destroy = records.select(&:marked_for_destruction?)
-
24
records_to_destroy.each { |record| association.proxy.destroy(record) }
-
24
records -= records_to_destroy
-
end
-
-
38
records.each do |record|
-
3
next if record.destroyed?
-
-
3
saved = true
-
-
3
if autosave != false && (@new_record_before_save || record.new_record?)
-
3
if autosave
-
3
saved = association.insert_record(record, false)
-
else
-
association.insert_record(record) unless reflection.nested?
-
end
-
elsif autosave
-
saved = record.save(:validate => false)
-
end
-
-
3
raise ActiveRecord::Rollback unless saved
-
end
-
rescue
-
records.each {|x| IdentityMap.remove(x) } if IdentityMap.enabled?
-
raise
-
end
-
end
-
-
# reconstruct the scope now that we know the owner's id
-
38
association.reset_scope if association.respond_to?(:reset_scope)
-
end
-
end
-
-
# Saves the associated record if it's new or <tt>:autosave</tt> is enabled
-
# on the association.
-
#
-
# In addition, it will destroy the association if it was marked for
-
# destruction with mark_for_destruction.
-
#
-
# This all happens inside a transaction, _if_ the Transactions module is included into
-
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
-
2
def save_has_one_association(reflection)
-
85
association = association_instance_get(reflection.name)
-
85
record = association && association.load_target
-
85
if record && !record.destroyed?
-
10
autosave = reflection.options[:autosave]
-
-
10
if autosave && record.marked_for_destruction?
-
record.destroy
-
else
-
10
key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id
-
10
if autosave != false && (new_record? || record.new_record? || record[reflection.foreign_key] != key || autosave)
-
3
unless reflection.through_reflection
-
3
record[reflection.foreign_key] = key
-
end
-
-
3
saved = record.save(:validate => !autosave)
-
3
raise ActiveRecord::Rollback if !saved && autosave
-
3
saved
-
end
-
end
-
end
-
end
-
-
# Saves the associated record if it's new or <tt>:autosave</tt> is enabled.
-
#
-
# In addition, it will destroy the association if it was marked for destruction.
-
2
def save_belongs_to_association(reflection)
-
1207
association = association_instance_get(reflection.name)
-
1207
record = association && association.load_target
-
1207
if record && !record.destroyed?
-
75
autosave = reflection.options[:autosave]
-
-
75
if autosave && record.marked_for_destruction?
-
record.destroy
-
75
elsif autosave != false
-
75
saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
-
-
75
if association.updated?
-
1
association_id = record.send(reflection.options[:primary_key] || :id)
-
1
self[reflection.foreign_key] = association_id
-
1
association.loaded!
-
end
-
-
75
saved if autosave
-
end
-
end
-
end
-
end
-
end
-
2
begin
-
2
require 'psych'
-
rescue LoadError
-
end
-
-
2
require 'yaml'
-
2
require 'set'
-
2
require 'thread'
-
2
require 'active_support/benchmarkable'
-
2
require 'active_support/dependencies'
-
2
require 'active_support/descendants_tracker'
-
2
require 'active_support/time'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/class/attribute_accessors'
-
2
require 'active_support/core_ext/class/delegating_attributes'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/hash/deep_merge'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/string/behavior'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/module/introspection'
-
2
require 'active_support/core_ext/object/duplicable'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/deprecation'
-
2
require 'arel'
-
2
require 'active_record/errors'
-
2
require 'active_record/log_subscriber'
-
2
require 'active_record/explain_subscriber'
-
-
2
module ActiveRecord #:nodoc:
-
# = Active Record
-
#
-
# Active Record objects don't specify their attributes directly, but rather infer them from
-
# the table definition with which they're linked. Adding, removing, and changing attributes
-
# and their type is done directly in the database. Any change is instantly reflected in the
-
# Active Record objects. The mapping that binds a given Active Record class to a certain
-
# database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
-
#
-
# See the mapping rules in table_name and the full example in link:files/activerecord/README_rdoc.html for more insight.
-
#
-
# == Creation
-
#
-
# Active Records accept constructor parameters either in a hash or as a block. The hash
-
# method is especially useful when you're receiving the data from somewhere else, like an
-
# HTTP request. It works like this:
-
#
-
# user = User.new(:name => "David", :occupation => "Code Artist")
-
# user.name # => "David"
-
#
-
# You can also use block initialization:
-
#
-
# user = User.new do |u|
-
# u.name = "David"
-
# u.occupation = "Code Artist"
-
# end
-
#
-
# And of course you can just create a bare object and specify the attributes after the fact:
-
#
-
# user = User.new
-
# user.name = "David"
-
# user.occupation = "Code Artist"
-
#
-
# == Conditions
-
#
-
# Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
-
# The array form is to be used when the condition input is tainted and requires sanitization. The string form can
-
# be used for statements that don't involve tainted data. The hash form works much like the array form, except
-
# only equality and range is possible. Examples:
-
#
-
# class User < ActiveRecord::Base
-
# def self.authenticate_unsafely(user_name, password)
-
# where("user_name = '#{user_name}' AND password = '#{password}'").first
-
# end
-
#
-
# def self.authenticate_safely(user_name, password)
-
# where("user_name = ? AND password = ?", user_name, password).first
-
# end
-
#
-
# def self.authenticate_safely_simply(user_name, password)
-
# where(:user_name => user_name, :password => password).first
-
# end
-
# end
-
#
-
# The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query
-
# and is thus susceptible to SQL-injection attacks if the <tt>user_name</tt> and +password+
-
# parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
-
# <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+
-
# before inserting them in the query, which will ensure that an attacker can't escape the
-
# query and fake the login (or worse).
-
#
-
# When using multiple parameters in the conditions, it can easily become hard to read exactly
-
# what the fourth or fifth question mark is supposed to represent. In those cases, you can
-
# resort to named bind variables instead. That's done by replacing the question marks with
-
# symbols and supplying a hash with values for the matching symbol keys:
-
#
-
# Company.where(
-
# "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
-
# { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
-
# ).first
-
#
-
# Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
-
# operator. For instance:
-
#
-
# Student.where(:first_name => "Harvey", :status => 1)
-
# Student.where(params[:student])
-
#
-
# A range may be used in the hash to use the SQL BETWEEN operator:
-
#
-
# Student.where(:grade => 9..12)
-
#
-
# An array may be used in the hash to use the SQL IN operator:
-
#
-
# Student.where(:grade => [9,11,12])
-
#
-
# When joining tables, nested hashes or keys written in the form 'table_name.column_name'
-
# can be used to qualify the table name of a particular condition. For instance:
-
#
-
# Student.joins(:schools).where(:schools => { :category => 'public' })
-
# Student.joins(:schools).where('schools.category' => 'public' )
-
#
-
# == Overwriting default accessors
-
#
-
# All column values are automatically available through basic accessors on the Active Record
-
# object, but sometimes you want to specialize this behavior. This can be done by overwriting
-
# the default accessors (using the same name as the attribute) and calling
-
# <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually
-
# change things.
-
#
-
# class Song < ActiveRecord::Base
-
# # Uses an integer of seconds to hold the length of the song
-
#
-
# def length=(minutes)
-
# write_attribute(:length, minutes.to_i * 60)
-
# end
-
#
-
# def length
-
# read_attribute(:length) / 60
-
# end
-
# end
-
#
-
# You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
-
# instead of <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
-
#
-
# == Attribute query methods
-
#
-
# In addition to the basic accessors, query methods are also automatically available on the Active Record object.
-
# Query methods allow you to test whether an attribute value is present.
-
#
-
# For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
-
# to determine whether the user has a name:
-
#
-
# user = User.new(:name => "David")
-
# user.name? # => true
-
#
-
# anonymous = User.new(:name => "")
-
# anonymous.name? # => false
-
#
-
# == Accessing attributes before they have been typecasted
-
#
-
# Sometimes you want to be able to read the raw attribute data without having the column-determined
-
# typecast run its course first. That can be done by using the <tt><attribute>_before_type_cast</tt>
-
# accessors that all attributes have. For example, if your Account model has a <tt>balance</tt> attribute,
-
# you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
-
#
-
# This is especially useful in validation situations where the user might supply a string for an
-
# integer field and you want to display the original string back in an error message. Accessing the
-
# attribute normally would typecast the string to 0, which isn't what you want.
-
#
-
# == Dynamic attribute-based finders
-
#
-
# Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects
-
# by simple queries without turning to SQL. They work by appending the name of an attribute
-
# to <tt>find_by_</tt>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt> and thus produces finders
-
# like <tt>Person.find_by_user_name</tt>, <tt>Person.find_all_by_last_name</tt>, and
-
# <tt>Payment.find_by_transaction_id</tt>. Instead of writing
-
# <tt>Person.where(:user_name => user_name).first</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
-
# And instead of writing <tt>Person.where(:last_name => last_name).all</tt>, you just do
-
# <tt>Person.find_all_by_last_name(last_name)</tt>.
-
#
-
# It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an
-
# <tt>ActiveRecord::RecordNotFound</tt> error if they do not return any records,
-
# like <tt>Person.find_by_last_name!</tt>.
-
#
-
# It's also possible to use multiple attributes in the same find by separating them with "_and_".
-
#
-
# Person.where(:user_name => user_name, :password => password).first
-
# Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
-
#
-
# It's even possible to call these dynamic finder methods on relations and named scopes.
-
#
-
# Payment.order("created_on").find_all_by_amount(50)
-
# Payment.pending.find_last_by_amount(100)
-
#
-
# The same dynamic finder style can be used to create the object if it doesn't already exist.
-
# This dynamic finder is called with <tt>find_or_create_by_</tt> and will return the object if
-
# it already exists and otherwise creates it, then returns it. Protected attributes won't be set
-
# unless they are given in a block.
-
#
-
# # No 'Summer' tag exists
-
# Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
-
#
-
# # Now the 'Summer' tag does exist
-
# Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
-
#
-
# # Now 'Bob' exist and is an 'admin'
-
# User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
-
#
-
# Adding an exclamation point (!) on to the end of <tt>find_or_create_by_</tt> will
-
# raise an <tt>ActiveRecord::RecordInvalid</tt> error if the new record is invalid.
-
#
-
# Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without
-
# saving it first. Protected attributes won't be set unless they are given in a block.
-
#
-
# # No 'Winter' tag exists
-
# winter = Tag.find_or_initialize_by_name("Winter")
-
# winter.persisted? # false
-
#
-
# To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
-
# a list of parameters.
-
#
-
# Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
-
#
-
# That will either find an existing tag named "rails", or create a new one while setting the
-
# user that created it.
-
#
-
# Just like <tt>find_by_*</tt>, you can also use <tt>scoped_by_*</tt> to retrieve data. The good thing about
-
# using this feature is that the very first time result is returned using <tt>method_missing</tt> technique
-
# but after that the method is declared on the class. Henceforth <tt>method_missing</tt> will not be hit.
-
#
-
# User.scoped_by_user_name('David')
-
#
-
# == Saving arrays, hashes, and other non-mappable objects in text columns
-
#
-
# Active Record can serialize any object in text columns using YAML. To do so, you must
-
# specify this with a call to the class method +serialize+.
-
# This makes it possible to store arrays, hashes, and other non-mappable objects without doing
-
# any additional work.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences
-
# end
-
#
-
# user = User.create(:preferences => { "background" => "black", "display" => large })
-
# User.find(user.id).preferences # => { "background" => "black", "display" => large }
-
#
-
# You can also specify a class option as the second parameter that'll raise an exception
-
# if a serialized object is retrieved as a descendant of a class not in the hierarchy.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences, Hash
-
# end
-
#
-
# user = User.create(:preferences => %w( one two three ))
-
# User.find(user.id).preferences # raises SerializationTypeMismatch
-
#
-
# When you specify a class option, the default value for that attribute will be a new
-
# instance of that class.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences, OpenStruct
-
# end
-
#
-
# user = User.new
-
# user.preferences.theme_color = "red"
-
#
-
#
-
# == Single table inheritance
-
#
-
# Active Record allows inheritance by storing the name of the class in a column that by
-
# default is named "type" (can be changed by overwriting <tt>Base.inheritance_column</tt>).
-
# This means that an inheritance looking like this:
-
#
-
# class Company < ActiveRecord::Base; end
-
# class Firm < Company; end
-
# class Client < Company; end
-
# class PriorityClient < Client; end
-
#
-
# When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in
-
# the companies table with type = "Firm". You can then fetch this row again using
-
# <tt>Company.where(:name => '37signals').first</tt> and it will return a Firm object.
-
#
-
# If you don't have a type column defined in your table, single-table inheritance won't
-
# be triggered. In that case, it'll work just like normal subclasses with no special magic
-
# for differentiating between them or reloading the right type with find.
-
#
-
# Note, all the attributes for all the cases are kept in the same table. Read more:
-
# http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
-
#
-
# == Connection to multiple databases in different models
-
#
-
# Connections are usually created through ActiveRecord::Base.establish_connection and retrieved
-
# by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this
-
# connection. But you can also set a class-specific connection. For example, if Course is an
-
# ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
-
# and Course and all of its subclasses will use this connection instead.
-
#
-
# This feature is implemented by keeping a connection pool in ActiveRecord::Base that is
-
# a Hash indexed by the class. If a connection is requested, the retrieve_connection method
-
# will go up the class-hierarchy until a connection is found in the connection pool.
-
#
-
# == Exceptions
-
#
-
# * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
-
# * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
-
# <tt>:adapter</tt> key.
-
# * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a
-
# non-existent adapter
-
# (or a bad spelling of an existing one).
-
# * AssociationTypeMismatch - The object assigned to the association wasn't of the type
-
# specified in the association definition.
-
# * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
-
# * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt>
-
# before querying.
-
# * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
-
# or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
-
# nothing was found, please check its documentation for further details.
-
# * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
-
# * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
-
# <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of
-
# AttributeAssignmentError
-
# objects that should be inspected to determine which attributes triggered the errors.
-
# * AttributeAssignmentError - An error occurred while doing a mass assignment through the
-
# <tt>attributes=</tt> method.
-
# You can inspect the +attribute+ property of the exception object to determine which attribute
-
# triggered the error.
-
#
-
# *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
-
# So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
-
# instances in the current object space.
-
2
class Base
-
##
-
# :singleton-method:
-
# Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class,
-
# which is then passed on to any new database connections made and which can be retrieved on both
-
# a class and instance level by calling +logger+.
-
2
cattr_accessor :logger, :instance_writer => false
-
-
##
-
# :singleton-method:
-
# Contains the database configuration - as is typically stored in config/database.yml -
-
# as a Hash.
-
#
-
# For example, the following database.yml...
-
#
-
# development:
-
# adapter: sqlite3
-
# database: db/development.sqlite3
-
#
-
# production:
-
# adapter: sqlite3
-
# database: db/production.sqlite3
-
#
-
# ...would result in ActiveRecord::Base.configurations to look like this:
-
#
-
# {
-
# 'development' => {
-
# 'adapter' => 'sqlite3',
-
# 'database' => 'db/development.sqlite3'
-
# },
-
# 'production' => {
-
# 'adapter' => 'sqlite3',
-
# 'database' => 'db/production.sqlite3'
-
# }
-
# }
-
2
cattr_accessor :configurations, :instance_writer => false
-
2
@@configurations = {}
-
-
##
-
# :singleton-method:
-
# Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling
-
# dates and times from the database. This is set to :local by default.
-
2
cattr_accessor :default_timezone, :instance_writer => false
-
2
@@default_timezone = :local
-
-
##
-
# :singleton-method:
-
# Specifies the format to use when dumping the database schema with Rails'
-
# Rakefile. If :sql, the schema is dumped as (potentially database-
-
# specific) SQL statements. If :ruby, the schema is dumped as an
-
# ActiveRecord::Schema file which can be loaded into any database that
-
# supports migrations. Use :ruby if you want to have different database
-
# adapters for, e.g., your development and test environments.
-
2
cattr_accessor :schema_format , :instance_writer => false
-
2
@@schema_format = :ruby
-
-
##
-
# :singleton-method:
-
# Specify whether or not to use timestamps for migration versions
-
2
cattr_accessor :timestamped_migrations , :instance_writer => false
-
2
@@timestamped_migrations = true
-
-
2
class << self # Class methods
-
2
def inherited(child_class) #:nodoc:
-
22
child_class.initialize_generated_modules
-
22
super
-
end
-
-
2
def initialize_generated_modules #:nodoc:
-
22
@attribute_methods_mutex = Mutex.new
-
-
# force attribute methods to be higher in inheritance hierarchy than other generated methods
-
22
generated_attribute_methods
-
22
generated_feature_methods
-
end
-
-
2
def generated_feature_methods
-
@generated_feature_methods ||= begin
-
22
mod = const_set(:GeneratedFeatureMethods, Module.new)
-
22
include mod
-
22
mod
-
320
end
-
end
-
-
# Returns a string like 'Post(id:integer, title:string, body:text)'
-
2
def inspect
-
6
if self == Base
-
6
super
-
elsif abstract_class?
-
"#{super}(abstract)"
-
elsif table_exists?
-
attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
-
"#{super}(#{attr_list})"
-
else
-
"#{super}(Table doesn't exist)"
-
end
-
end
-
-
# Overwrite the default class equality method to provide support for association proxies.
-
2
def ===(object)
-
200
object.is_a?(self)
-
end
-
-
2
def arel_table
-
3296
@arel_table ||= Arel::Table.new(table_name, arel_engine)
-
end
-
-
2
def arel_engine
-
@arel_engine ||= begin
-
20
if self == ActiveRecord::Base
-
ActiveRecord::Base
-
else
-
20
connection_handler.retrieve_connection_pool(self) ? self : superclass.arel_engine
-
end
-
26
end
-
end
-
-
2
private
-
-
2
def relation #:nodoc:
-
1564
relation = Relation.new(self, arel_table)
-
-
1564
if finder_needs_type_condition?
-
relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name)
-
else
-
1564
relation
-
end
-
end
-
end
-
-
2
public
-
# New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
-
# attributes but not yet saved (pass a hash with key names matching the associated table column names).
-
# In both instances, valid attribute keys are determined by the column names of the associated table --
-
# hence you can't have attributes that aren't part of the table columns.
-
#
-
# +initialize+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options
-
# in the +options+ parameter.
-
#
-
# ==== Examples
-
# # Instantiates a single new object
-
# User.new(:first_name => 'Jamie')
-
#
-
# # Instantiates a single new object using the :admin mass-assignment security role
-
# User.new({ :first_name => 'Jamie', :is_admin => true }, :as => :admin)
-
#
-
# # Instantiates a single new object bypassing mass-assignment security
-
# User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
-
2
def initialize(attributes = nil, options = {})
-
4565
defaults = Hash[self.class.column_defaults.map { |k, v| [k, v.duplicable? ? v.dup : v] }]
-
359
@attributes = self.class.initialize_attributes(defaults)
-
359
@association_cache = {}
-
359
@aggregation_cache = {}
-
359
@attributes_cache = {}
-
359
@new_record = true
-
359
@readonly = false
-
359
@destroyed = false
-
359
@marked_for_destruction = false
-
359
@previously_changed = {}
-
359
@changed_attributes = {}
-
-
359
ensure_proper_type
-
-
359
populate_with_current_scope_attributes
-
-
359
assign_attributes(attributes, options) if attributes
-
-
359
yield self if block_given?
-
359
run_callbacks :initialize
-
end
-
-
# Initialize an empty model object from +coder+. +coder+ must contain
-
# the attributes necessary for initializing an empty model object. For
-
# example:
-
#
-
# class Post < ActiveRecord::Base
-
# end
-
#
-
# post = Post.allocate
-
# post.init_with('attributes' => { 'title' => 'hello world' })
-
# post.title # => 'hello world'
-
2
def init_with(coder)
-
701
@attributes = self.class.initialize_attributes(coder['attributes'])
-
701
@relation = nil
-
-
701
@attributes_cache, @previously_changed, @changed_attributes = {}, {}, {}
-
701
@association_cache = {}
-
701
@aggregation_cache = {}
-
701
@readonly = @destroyed = @marked_for_destruction = false
-
701
@new_record = false
-
701
run_callbacks :find
-
701
run_callbacks :initialize
-
-
701
self
-
end
-
-
# Duped objects have no id assigned and are treated as new records. Note
-
# that this is a "shallow" copy as it copies the object's attributes
-
# only, not its associations. The extent of a "deep" copy is application
-
# specific and is therefore left to the application to implement according
-
# to its need.
-
# The dup method does not preserve the timestamps (created|updated)_(at|on).
-
2
def initialize_dup(other)
-
cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
-
self.class.initialize_attributes(cloned_attributes, :serialized => false)
-
-
cloned_attributes.delete(self.class.primary_key)
-
-
@attributes = cloned_attributes
-
-
_run_after_initialize_callbacks if respond_to?(:_run_after_initialize_callbacks)
-
-
@changed_attributes = {}
-
self.class.column_defaults.each do |attr, orig_value|
-
@changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value, @attributes[attr])
-
end
-
-
@aggregation_cache = {}
-
@association_cache = {}
-
@attributes_cache = {}
-
@new_record = true
-
-
ensure_proper_type
-
super
-
end
-
-
# Backport dup from 1.9 so that initialize_dup() gets called
-
2
unless Object.respond_to?(:initialize_dup, true)
-
def dup # :nodoc:
-
copy = super
-
copy.initialize_dup(self)
-
copy
-
end
-
end
-
-
# Populate +coder+ with attributes about this record that should be
-
# serialized. The structure of +coder+ defined in this method is
-
# guaranteed to match the structure of +coder+ passed to the +init_with+
-
# method.
-
#
-
# Example:
-
#
-
# class Post < ActiveRecord::Base
-
# end
-
# coder = {}
-
# Post.new.encode_with(coder)
-
# coder # => { 'id' => nil, ... }
-
2
def encode_with(coder)
-
50
coder['attributes'] = attributes
-
end
-
-
# Returns true if +comparison_object+ is the same exact object, or +comparison_object+
-
# is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
-
#
-
# Note that new records are different from any other record by definition, unless the
-
# other record is the receiver itself. Besides, if you fetch existing records with
-
# +select+ and leave the ID out, you're on your own, this predicate will return false.
-
#
-
# Note also that destroying a record preserves its ID in the model instance, so deleted
-
# models are still comparable.
-
2
def ==(comparison_object)
-
super ||
-
comparison_object.instance_of?(self.class) &&
-
id.present? &&
-
1
comparison_object.id == id
-
end
-
2
alias :eql? :==
-
-
# Delegates to id in order to allow two records of the same type and id to work with something like:
-
# [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
-
2
def hash
-
11
id.hash
-
end
-
-
# Freeze the attributes hash such that associations are still accessible, even on destroyed records.
-
2
def freeze
-
21
@attributes.freeze; self
-
end
-
-
# Returns +true+ if the attributes hash has been frozen.
-
2
def frozen?
-
@attributes.frozen?
-
end
-
-
# Allows sort on objects
-
2
def <=>(other_object)
-
if other_object.is_a?(self.class)
-
self.to_key <=> other_object.to_key
-
else
-
nil
-
end
-
end
-
-
# Returns +true+ if the record is read only. Records loaded through joins with piggy-back
-
# attributes will be marked as read only since they cannot be saved.
-
2
def readonly?
-
363
@readonly
-
end
-
-
# Marks this record as read only.
-
2
def readonly!
-
@readonly = true
-
end
-
-
# Returns the contents of the record as a nicely formatted string.
-
2
def inspect
-
14
inspection = if @attributes
-
14
self.class.column_names.collect { |name|
-
182
if has_attribute?(name)
-
182
"#{name}: #{attribute_for_inspect(name)}"
-
end
-
}.compact.join(", ")
-
else
-
"not initialized"
-
end
-
14
"#<#{self.class} #{inspection}>"
-
end
-
-
# Hackery to accomodate Syck. Remove for 4.0.
-
2
def to_yaml(opts = {}) #:nodoc:
-
10
if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck?
-
10
super
-
else
-
coder = {}
-
encode_with(coder)
-
YAML.quick_emit(self, opts) do |out|
-
out.map(taguri, to_yaml_style) do |map|
-
coder.each { |k, v| map.add(k, v) }
-
end
-
end
-
end
-
end
-
-
# Hackery to accomodate Syck. Remove for 4.0.
-
2
def yaml_initialize(tag, coder) #:nodoc:
-
init_with(coder)
-
end
-
-
2
private
-
-
# Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements
-
# of the array, and then rescues from the possible NoMethodError. If those elements are
-
# ActiveRecord::Base's, then this triggers the various method_missing's that we have,
-
# which significantly impacts upon performance.
-
#
-
# So we can avoid the method_missing hit by explicitly defining #to_ary as nil here.
-
#
-
# See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary/
-
2
def to_ary # :nodoc:
-
nil
-
end
-
-
2
include ActiveRecord::Persistence
-
2
extend ActiveModel::Naming
-
2
extend QueryCache::ClassMethods
-
2
extend ActiveSupport::Benchmarkable
-
2
extend ActiveSupport::DescendantsTracker
-
-
2
extend Querying
-
2
include ReadonlyAttributes
-
2
include ModelSchema
-
2
extend Translation
-
2
include Inheritance
-
2
include Scoping
-
2
extend DynamicMatchers
-
2
include Sanitization
-
2
include AttributeAssignment
-
2
include ActiveModel::Conversion
-
2
include Integration
-
2
include Validations
-
2
extend CounterCache
-
2
include Locking::Optimistic, Locking::Pessimistic
-
2
include AttributeMethods
-
2
include Callbacks, ActiveModel::Observing, Timestamp
-
2
include Associations
-
2
include IdentityMap
-
2
include ActiveModel::SecurePassword
-
2
extend Explain
-
-
# AutosaveAssociation needs to be included before Transactions, because we want
-
# #save_with_autosave_associations to be wrapped inside a transaction.
-
2
include AutosaveAssociation, NestedAttributes
-
2
include Aggregations, Transactions, Reflection, Serialization, Store
-
end
-
end
-
-
2
require 'active_record/connection_adapters/abstract/connection_specification'
-
2
ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
-
2
require 'active_support/core_ext/array/wrap'
-
-
2
module ActiveRecord
-
# = Active Record Callbacks
-
#
-
# Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic
-
# before or after an alteration of the object state. This can be used to make sure that associated and
-
# dependent objects are deleted when +destroy+ is called (by overwriting +before_destroy+) or to massage attributes
-
# before they're validated (by overwriting +before_validation+). As an example of the callbacks initiated, consider
-
# the <tt>Base#save</tt> call for a new record:
-
#
-
# * (-) <tt>save</tt>
-
# * (-) <tt>valid</tt>
-
# * (1) <tt>before_validation</tt>
-
# * (-) <tt>validate</tt>
-
# * (2) <tt>after_validation</tt>
-
# * (3) <tt>before_save</tt>
-
# * (4) <tt>before_create</tt>
-
# * (-) <tt>create</tt>
-
# * (5) <tt>after_create</tt>
-
# * (6) <tt>after_save</tt>
-
# * (7) <tt>after_commit</tt>
-
#
-
# Also, an <tt>after_rollback</tt> callback can be configured to be triggered whenever a rollback is issued.
-
# Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and
-
# <tt>after_rollback</tt>.
-
#
-
# Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that
-
# is found and instantiated by a finder, with <tt>after_initialize</tt> being triggered after new objects
-
# are instantiated as well.
-
#
-
# That's a total of twelve callbacks, which gives you immense power to react and prepare for each state in the
-
# Active Record life cycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
-
# except that each <tt>_create</tt> callback is replaced by the corresponding <tt>_update</tt> callback.
-
#
-
# Examples:
-
# class CreditCard < ActiveRecord::Base
-
# # Strip everything but digits, so the user can specify "555 234 34" or
-
# # "5552-3434" or both will mean "55523434"
-
# before_validation(:on => :create) do
-
# self.number = number.gsub(/[^0-9]/, "") if attribute_present?("number")
-
# end
-
# end
-
#
-
# class Subscription < ActiveRecord::Base
-
# before_create :record_signup
-
#
-
# private
-
# def record_signup
-
# self.signed_up_on = Date.today
-
# end
-
# end
-
#
-
# class Firm < ActiveRecord::Base
-
# # Destroys the associated clients and people when the firm is destroyed
-
# before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
-
# before_destroy { |record| Client.destroy_all "client_of = #{record.id}" }
-
# end
-
#
-
# == Inheritable callback queues
-
#
-
# Besides the overwritable callback methods, it's also possible to register callbacks through the
-
# use of the callback macros. Their main advantage is that the macros add behavior into a callback
-
# queue that is kept intact down through an inheritance hierarchy.
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy :destroy_author
-
# end
-
#
-
# class Reply < Topic
-
# before_destroy :destroy_readers
-
# end
-
#
-
# Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is
-
# run, both +destroy_author+ and +destroy_readers+ are called. Contrast this to the following situation
-
# where the +before_destroy+ method is overridden:
-
#
-
# class Topic < ActiveRecord::Base
-
# def before_destroy() destroy_author end
-
# end
-
#
-
# class Reply < Topic
-
# def before_destroy() destroy_readers end
-
# end
-
#
-
# In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+.
-
# So, use the callback macros when you want to ensure that a certain callback is called for the entire
-
# hierarchy, and use the regular overwriteable methods when you want to leave it up to each descendant
-
# to decide whether they want to call +super+ and trigger the inherited callbacks.
-
#
-
# *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the
-
# callbacks before specifying the associations. Otherwise, you might trigger the loading of a
-
# child before the parent has registered the callbacks and they won't be inherited.
-
#
-
# == Types of callbacks
-
#
-
# There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects,
-
# inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects
-
# are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for
-
# creating mix-ins), and inline eval methods are deprecated.
-
#
-
# The method reference callbacks work by specifying a protected or private method available in the object, like this:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy :delete_parents
-
#
-
# private
-
# def delete_parents
-
# self.class.delete_all "parent_id = #{id}"
-
# end
-
# end
-
#
-
# The callback objects have methods named after the callback called with the record as the only parameter, such as:
-
#
-
# class BankAccount < ActiveRecord::Base
-
# before_save EncryptionWrapper.new
-
# after_save EncryptionWrapper.new
-
# after_initialize EncryptionWrapper.new
-
# end
-
#
-
# class EncryptionWrapper
-
# def before_save(record)
-
# record.credit_card_number = encrypt(record.credit_card_number)
-
# end
-
#
-
# def after_save(record)
-
# record.credit_card_number = decrypt(record.credit_card_number)
-
# end
-
#
-
# alias_method :after_find, :after_save
-
#
-
# private
-
# def encrypt(value)
-
# # Secrecy is committed
-
# end
-
#
-
# def decrypt(value)
-
# # Secrecy is unveiled
-
# end
-
# end
-
#
-
# So you specify the object you want messaged on a given callback. When that callback is triggered, the object has
-
# a method by the name of the callback messaged. You can make these callbacks more flexible by passing in other
-
# initialization data such as the name of the attribute to work with:
-
#
-
# class BankAccount < ActiveRecord::Base
-
# before_save EncryptionWrapper.new("credit_card_number")
-
# after_save EncryptionWrapper.new("credit_card_number")
-
# after_initialize EncryptionWrapper.new("credit_card_number")
-
# end
-
#
-
# class EncryptionWrapper
-
# def initialize(attribute)
-
# @attribute = attribute
-
# end
-
#
-
# def before_save(record)
-
# record.send("#{@attribute}=", encrypt(record.send("#{@attribute}")))
-
# end
-
#
-
# def after_save(record)
-
# record.send("#{@attribute}=", decrypt(record.send("#{@attribute}")))
-
# end
-
#
-
# alias_method :after_find, :after_save
-
#
-
# private
-
# def encrypt(value)
-
# # Secrecy is committed
-
# end
-
#
-
# def decrypt(value)
-
# # Secrecy is unveiled
-
# end
-
# end
-
#
-
# The callback macros usually accept a symbol for the method they're supposed to run, but you can also
-
# pass a "method string", which will then be evaluated within the binding of the callback. Example:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy 'self.class.delete_all "parent_id = #{id}"'
-
# end
-
#
-
# Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback
-
# is triggered. Also note that these inline callbacks can be stacked just like the regular ones:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy 'self.class.delete_all "parent_id = #{id}"',
-
# 'puts "Evaluated after parents are destroyed"'
-
# end
-
#
-
# == <tt>before_validation*</tt> returning statements
-
#
-
# If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be
-
# aborted and <tt>Base#save</tt> will return +false+. If Base#save! is called it will raise a
-
# ActiveRecord::RecordInvalid exception. Nothing will be appended to the errors object.
-
#
-
# == Canceling callbacks
-
#
-
# If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are
-
# cancelled. If an <tt>after_*</tt> callback returns +false+, all the later callbacks are cancelled.
-
# Callbacks are generally run in the order they are defined, with the exception of callbacks defined as
-
# methods on the model, which are called last.
-
#
-
# == Transactions
-
#
-
# The entire callback chain of a +save+, <tt>save!</tt>, or +destroy+ call runs
-
# within a transaction. That includes <tt>after_*</tt> hooks. If everything
-
# goes fine a COMMIT is executed once the chain has been completed.
-
#
-
# If a <tt>before_*</tt> callback cancels the action a ROLLBACK is issued. You
-
# can also trigger a ROLLBACK raising an exception in any of the callbacks,
-
# including <tt>after_*</tt> hooks. Note, however, that in that case the client
-
# needs to be aware of it because an ordinary +save+ will raise such exception
-
# instead of quietly returning +false+.
-
#
-
# == Debugging callbacks
-
#
-
# The callback chain is accessible via the <tt>_*_callbacks</tt> method on an object. ActiveModel Callbacks support
-
# <tt>:before</tt>, <tt>:after</tt> and <tt>:around</tt> as values for the <tt>kind</tt> property. The <tt>kind</tt> property
-
# defines what part of the chain the callback runs in.
-
#
-
# To find all callbacks in the before_save callback chain:
-
#
-
# Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }
-
#
-
# Returns an array of callback objects that form the before_save chain.
-
#
-
# To further check if the before_save chain contains a proc defined as <tt>rest_when_dead</tt> use the <tt>filter</tt> property of the callback object:
-
#
-
# Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }.collect(&:filter).include?(:rest_when_dead)
-
#
-
# Returns true or false depending on whether the proc is contained in the before_save callback chain on a Topic model.
-
#
-
2
module Callbacks
-
2
extend ActiveSupport::Concern
-
-
2
CALLBACKS = [
-
:after_initialize, :after_find, :after_touch, :before_validation, :after_validation,
-
:before_save, :around_save, :after_save, :before_create, :around_create,
-
:after_create, :before_update, :around_update, :after_update,
-
:before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback
-
]
-
-
2
included do
-
2
extend ActiveModel::Callbacks
-
2
include ActiveModel::Validations::Callbacks
-
-
2
define_model_callbacks :initialize, :find, :touch, :only => :after
-
2
define_model_callbacks :save, :create, :update, :destroy
-
end
-
-
2
def destroy #:nodoc:
-
42
run_callbacks(:destroy) { super }
-
end
-
-
2
def touch(*) #:nodoc:
-
run_callbacks(:touch) { super }
-
end
-
-
2
private
-
-
2
def create_or_update #:nodoc:
-
726
run_callbacks(:save) { super }
-
end
-
-
2
def create #:nodoc:
-
616
run_callbacks(:create) { super }
-
end
-
-
2
def update(*) #:nodoc:
-
110
run_callbacks(:update) { super }
-
end
-
end
-
end
-
2
require 'thread'
-
2
require 'monitor'
-
2
require 'set'
-
2
require 'active_support/core_ext/module/deprecation'
-
-
2
module ActiveRecord
-
# Raised when a connection could not be obtained within the connection
-
# acquisition timeout period.
-
2
class ConnectionTimeoutError < ConnectionNotEstablished
-
end
-
-
2
module ConnectionAdapters
-
# Connection pool base class for managing Active Record database
-
# connections.
-
#
-
# == Introduction
-
#
-
# A connection pool synchronizes thread access to a limited number of
-
# database connections. The basic idea is that each thread checks out a
-
# database connection from the pool, uses that connection, and checks the
-
# connection back in. ConnectionPool is completely thread-safe, and will
-
# ensure that a connection cannot be used by two threads at the same time,
-
# as long as ConnectionPool's contract is correctly followed. It will also
-
# handle cases in which there are more threads than connections: if all
-
# connections have been checked out, and a thread tries to checkout a
-
# connection anyway, then ConnectionPool will wait until some other thread
-
# has checked in a connection.
-
#
-
# == Obtaining (checking out) a connection
-
#
-
# Connections can be obtained and used from a connection pool in several
-
# ways:
-
#
-
# 1. Simply use ActiveRecord::Base.connection as with Active Record 2.1 and
-
# earlier (pre-connection-pooling). Eventually, when you're done with
-
# the connection(s) and wish it to be returned to the pool, you call
-
# ActiveRecord::Base.clear_active_connections!. This will be the
-
# default behavior for Active Record when used in conjunction with
-
# Action Pack's request handling cycle.
-
# 2. Manually check out a connection from the pool with
-
# ActiveRecord::Base.connection_pool.checkout. You are responsible for
-
# returning this connection to the pool when finished by calling
-
# ActiveRecord::Base.connection_pool.checkin(connection).
-
# 3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which
-
# obtains a connection, yields it as the sole argument to the block,
-
# and returns it to the pool after the block completes.
-
#
-
# Connections in the pool are actually AbstractAdapter objects (or objects
-
# compatible with AbstractAdapter's interface).
-
#
-
# == Options
-
#
-
# There are two connection-pooling-related options that you can add to
-
# your database connection configuration:
-
#
-
# * +pool+: number indicating size of connection pool (default 5)
-
# * +checkout _timeout+: number of seconds to block and wait for a
-
# connection before giving up and raising a timeout error
-
# (default 5 seconds). ('wait_timeout' supported for backwards
-
# compatibility, but conflicts with key used for different purpose
-
# by mysql2 adapter).
-
2
class ConnectionPool
-
2
include MonitorMixin
-
-
2
attr_accessor :automatic_reconnect
-
2
attr_reader :spec, :connections
-
-
# Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
-
# object which describes database connection information (e.g. adapter,
-
# host name, username, password, etc), as well as the maximum size for
-
# this ConnectionPool.
-
#
-
# The default ConnectionPool maximum size is 5.
-
2
def initialize(spec)
-
2
super()
-
-
2
@spec = spec
-
-
# The cache of reserved connections mapped to threads
-
2
@reserved_connections = {}
-
-
2
@queue = new_cond
-
# 'wait_timeout', the backward-compatible key, conflicts with spec key
-
# used by mysql2 for something entirely different, checkout_timeout
-
# preferred to avoid conflict and allow independent values.
-
2
@timeout = spec.config[:checkout_timeout] || spec.config[:wait_timeout] || 5
-
-
# default max pool size to 5
-
2
@size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
-
-
2
@connections = []
-
2
@automatic_reconnect = true
-
end
-
-
# Retrieve the connection associated with the current thread, or call
-
# #checkout to obtain one if necessary.
-
#
-
# #connection can be called any number of times; the connection is
-
# held in a hash keyed by the thread id.
-
2
def connection
-
5653
synchronize do
-
5653
@reserved_connections[current_connection_id] ||= checkout
-
end
-
end
-
-
# Is there an open connection that is being used for the current thread?
-
2
def active_connection?
-
synchronize do
-
@reserved_connections.fetch(current_connection_id) {
-
return false
-
}.in_use?
-
end
-
end
-
-
# Signal that the thread is finished with the current connection.
-
# #release_connection releases the connection-thread association
-
# and returns the connection to the pool.
-
2
def release_connection(with_id = current_connection_id)
-
290
conn = synchronize { @reserved_connections.delete(with_id) }
-
145
checkin conn if conn
-
end
-
-
# If a connection already exists yield it to the block. If no connection
-
# exists checkout a connection, yield it to the block, and checkin the
-
# connection when finished.
-
2
def with_connection
-
connection_id = current_connection_id
-
fresh_connection = true unless active_connection?
-
yield connection
-
ensure
-
release_connection(connection_id) if fresh_connection
-
end
-
-
# Returns true if a connection has already been opened.
-
2
def connected?
-
18
synchronize { @connections.any? }
-
end
-
-
# Disconnects all connections in the pool, and clears the pool.
-
2
def disconnect!
-
synchronize do
-
@reserved_connections = {}
-
@connections.each do |conn|
-
checkin conn
-
conn.disconnect!
-
end
-
@connections = []
-
end
-
end
-
-
# Clears the cache which maps classes.
-
2
def clear_reloadable_connections!
-
2
synchronize do
-
2
@reserved_connections = {}
-
2
@connections.each do |conn|
-
checkin conn
-
conn.disconnect! if conn.requires_reloading?
-
end
-
2
@connections.delete_if do |conn|
-
conn.requires_reloading?
-
end
-
end
-
end
-
-
# Verify active connections and remove and disconnect connections
-
# associated with stale threads.
-
2
def verify_active_connections! #:nodoc:
-
synchronize do
-
clear_stale_cached_connections!
-
@connections.each do |connection|
-
connection.verify!
-
end
-
end
-
end
-
-
2
def columns
-
with_connection do |c|
-
c.schema_cache.columns
-
end
-
end
-
2
deprecate :columns
-
-
2
def columns_hash
-
with_connection do |c|
-
c.schema_cache.columns_hash
-
end
-
end
-
2
deprecate :columns_hash
-
-
2
def primary_keys
-
with_connection do |c|
-
c.schema_cache.primary_keys
-
end
-
end
-
2
deprecate :primary_keys
-
-
2
def clear_cache!
-
with_connection do |c|
-
c.schema_cache.clear!
-
end
-
end
-
2
deprecate :clear_cache!
-
-
# Return any checked-out connections back to the pool by threads that
-
# are no longer alive.
-
2
def clear_stale_cached_connections!
-
keys = @reserved_connections.keys - Thread.list.find_all { |t|
-
t.alive?
-
}.map { |thread| thread.object_id }
-
keys.each do |key|
-
conn = @reserved_connections[key]
-
ActiveSupport::Deprecation.warn(<<-eowarn) if conn.in_use?
-
Database connections will not be closed automatically, please close your
-
database connection at the end of the thread by calling `close` on your
-
connection. For example: ActiveRecord::Base.connection.close
-
eowarn
-
checkin conn
-
@reserved_connections.delete(key)
-
end
-
end
-
-
# Check-out a database connection from the pool, indicating that you want
-
# to use it. You should call #checkin when you no longer need this.
-
#
-
# This is done by either returning an existing connection, or by creating
-
# a new connection. If the maximum number of connections for this pool has
-
# already been reached, but the pool is empty (i.e. they're all being used),
-
# then this method will wait until a thread has checked in a connection.
-
# The wait time is bounded however: if no connection can be checked out
-
# within the timeout specified for this pool, then a ConnectionTimeoutError
-
# exception will be raised.
-
#
-
# Returns: an AbstractAdapter object.
-
#
-
# Raises:
-
# - ConnectionTimeoutError: no connection can be obtained from the pool
-
# within the timeout period.
-
2
def checkout
-
145
synchronize do
-
145
waited_time = 0
-
-
145
loop do
-
288
conn = @connections.find { |c| c.lease }
-
-
145
unless conn
-
2
if @connections.size < @size
-
2
conn = checkout_new_connection
-
2
conn.lease
-
end
-
end
-
-
145
if conn
-
145
checkout_and_verify conn
-
145
return conn
-
end
-
-
if waited_time >= @timeout
-
raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout} (waited #{waited_time} seconds). The max pool size is currently #{@size}; consider increasing it."
-
end
-
-
# Sometimes our wait can end because a connection is available,
-
# but another thread can snatch it up first. If timeout hasn't
-
# passed but no connection is avail, looks like that happened --
-
# loop and wait again, for the time remaining on our timeout.
-
before_wait = Time.now
-
@queue.wait( [@timeout - waited_time, 0].max )
-
waited_time += (Time.now - before_wait)
-
-
# Will go away in Rails 4, when we don't clean up
-
# after leaked connections automatically anymore. Right now, clean
-
# up after we've returned from a 'wait' if it looks like it's
-
# needed, then loop and try again.
-
if(active_connections.size >= @connections.size)
-
clear_stale_cached_connections!
-
end
-
end
-
end
-
end
-
-
# Check-in a database connection back into the pool, indicating that you
-
# no longer need this connection.
-
#
-
# +conn+: an AbstractAdapter object, which was obtained by earlier by
-
# calling +checkout+ on this pool.
-
2
def checkin(conn)
-
145
synchronize do
-
145
conn.run_callbacks :checkin do
-
145
conn.expire
-
145
@queue.signal
-
end
-
-
145
release conn
-
end
-
end
-
-
2
private
-
-
2
def release(conn)
-
145
synchronize do
-
145
thread_id = nil
-
-
145
if @reserved_connections[current_connection_id] == conn
-
thread_id = current_connection_id
-
else
-
145
thread_id = @reserved_connections.keys.find { |k|
-
@reserved_connections[k] == conn
-
}
-
end
-
-
145
@reserved_connections.delete thread_id if thread_id
-
end
-
end
-
-
2
def new_connection
-
2
ActiveRecord::Base.send(spec.adapter_method, spec.config)
-
end
-
-
2
def current_connection_id #:nodoc:
-
5943
ActiveRecord::Base.connection_id ||= Thread.current.object_id
-
end
-
-
2
def checkout_new_connection
-
2
raise ConnectionNotEstablished unless @automatic_reconnect
-
-
2
c = new_connection
-
2
c.pool = self
-
2
@connections << c
-
2
c
-
end
-
-
2
def checkout_and_verify(c)
-
145
c.run_callbacks :checkout do
-
145
c.verify!
-
end
-
145
c
-
end
-
-
2
def active_connections
-
@connections.find_all { |c| c.in_use? }
-
end
-
end
-
-
# ConnectionHandler is a collection of ConnectionPool objects. It is used
-
# for keeping separate connection pools for Active Record models that connect
-
# to different databases.
-
#
-
# For example, suppose that you have 5 models, with the following hierarchy:
-
#
-
# |
-
# +-- Book
-
# | |
-
# | +-- ScaryBook
-
# | +-- GoodBook
-
# +-- Author
-
# +-- BankAccount
-
#
-
# Suppose that Book is to connect to a separate database (i.e. one other
-
# than the default database). Then Book, ScaryBook and GoodBook will all use
-
# the same connection pool. Likewise, Author and BankAccount will use the
-
# same connection pool. However, the connection pool used by Author/BankAccount
-
# is not the same as the one used by Book/ScaryBook/GoodBook.
-
#
-
# Normally there is only a single ConnectionHandler instance, accessible via
-
# ActiveRecord::Base.connection_handler. Active Record models use this to
-
# determine that connection pool that they should use.
-
2
class ConnectionHandler
-
2
attr_reader :connection_pools
-
-
2
def initialize(pools = {})
-
2
@connection_pools = pools
-
2
@class_to_pool = {}
-
end
-
-
2
def establish_connection(name, spec)
-
2
@connection_pools[spec] ||= ConnectionAdapters::ConnectionPool.new(spec)
-
2
@class_to_pool[name] = @connection_pools[spec]
-
end
-
-
# Returns true if there are any active connections among the connection
-
# pools that the ConnectionHandler is managing.
-
2
def active_connections?
-
connection_pools.values.any? { |pool| pool.active_connection? }
-
end
-
-
# Returns any connections in use by the current thread back to the pool.
-
2
def clear_active_connections!
-
290
@connection_pools.each_value {|pool| pool.release_connection }
-
end
-
-
# Clears the cache which maps classes.
-
2
def clear_reloadable_connections!
-
4
@connection_pools.each_value {|pool| pool.clear_reloadable_connections! }
-
end
-
-
2
def clear_all_connections!
-
@connection_pools.each_value {|pool| pool.disconnect! }
-
end
-
-
# Verify active connections.
-
2
def verify_active_connections! #:nodoc:
-
@connection_pools.each_value {|pool| pool.verify_active_connections! }
-
end
-
-
# Locate the connection of the nearest super class. This can be an
-
# active or defined connection: if it is the latter, it will be
-
# opened and set as the active connection for the class it was defined
-
# for (not necessarily the current class).
-
2
def retrieve_connection(klass) #:nodoc:
-
5508
pool = retrieve_connection_pool(klass)
-
5508
(pool && pool.connection) or raise ConnectionNotEstablished
-
end
-
-
# Returns true if a connection that's accessible to this class has
-
# already been opened.
-
2
def connected?(klass)
-
9
conn = retrieve_connection_pool(klass)
-
9
conn && conn.connected?
-
end
-
-
# Remove the connection for this class. This will close the active
-
# connection and the defined connection (if they exist). The result
-
# can be used as an argument for establish_connection, for easily
-
# re-establishing the connection.
-
2
def remove_connection(klass)
-
2
pool = @class_to_pool.delete(klass.name)
-
2
return nil unless pool
-
-
@connection_pools.delete pool.spec
-
pool.automatic_reconnect = false
-
pool.disconnect!
-
pool.spec.config
-
end
-
-
2
def retrieve_connection_pool(klass)
-
11039
pool = @class_to_pool[klass.name]
-
11039
return pool if pool
-
5502
return nil if ActiveRecord::Base == klass
-
5502
retrieve_connection_pool klass.superclass
-
end
-
end
-
-
2
class ConnectionManagement
-
2
class Proxy # :nodoc:
-
2
attr_reader :body, :testing
-
-
2
def initialize(body, testing = false)
-
@body = body
-
@testing = testing
-
end
-
-
2
def method_missing(method_sym, *arguments, &block)
-
@body.send(method_sym, *arguments, &block)
-
end
-
-
2
def respond_to?(method_sym, include_private = false)
-
super || @body.respond_to?(method_sym)
-
end
-
-
2
def each(&block)
-
body.each(&block)
-
end
-
-
2
def close
-
body.close if body.respond_to?(:close)
-
-
# Don't return connection (and perform implicit rollback) if
-
# this request is a part of integration test
-
ActiveRecord::Base.clear_active_connections! unless testing
-
end
-
end
-
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
testing = env.key?('rack.test')
-
-
status, headers, body = @app.call(env)
-
-
[status, headers, Proxy.new(body, testing)]
-
rescue
-
ActiveRecord::Base.clear_active_connections! unless testing
-
raise
-
end
-
end
-
end
-
end
-
2
require 'uri'
-
-
2
module ActiveRecord
-
2
class Base
-
2
class ConnectionSpecification #:nodoc:
-
2
attr_reader :config, :adapter_method
-
2
def initialize (config, adapter_method)
-
2
@config, @adapter_method = config, adapter_method
-
end
-
-
##
-
# Builds a ConnectionSpecification from user input
-
2
class Resolver # :nodoc:
-
2
attr_reader :config, :klass, :configurations
-
-
2
def initialize(config, configurations)
-
2
@config = config
-
2
@configurations = configurations
-
end
-
-
2
def spec
-
2
case config
-
when nil
-
2
raise AdapterNotSpecified unless defined?(Rails.env)
-
2
resolve_string_connection Rails.env
-
when Symbol, String
-
resolve_string_connection config.to_s
-
when Hash
-
resolve_hash_connection config
-
end
-
end
-
-
2
private
-
2
def resolve_string_connection(spec) # :nodoc:
-
2
hash = configurations.fetch(spec) do |k|
-
connection_url_to_hash(k)
-
end
-
-
2
raise(AdapterNotSpecified, "#{spec} database is not configured") unless hash
-
-
2
resolve_hash_connection hash
-
end
-
-
2
def resolve_hash_connection(spec) # :nodoc:
-
2
spec = spec.symbolize_keys
-
-
2
raise(AdapterNotSpecified, "database configuration does not specify adapter") unless spec.key?(:adapter)
-
-
2
begin
-
2
require "active_record/connection_adapters/#{spec[:adapter]}_adapter"
-
rescue LoadError => e
-
raise LoadError, "Please install the #{spec[:adapter]} adapter: `gem install activerecord-#{spec[:adapter]}-adapter` (#{e.message})", e.backtrace
-
end
-
-
2
adapter_method = "#{spec[:adapter]}_connection"
-
-
2
ConnectionSpecification.new(spec, adapter_method)
-
end
-
-
2
def connection_url_to_hash(url) # :nodoc:
-
config = URI.parse url
-
adapter = config.scheme
-
adapter = "postgresql" if adapter == "postgres"
-
spec = { :adapter => adapter,
-
:username => config.user,
-
:password => config.password,
-
:port => config.port,
-
:database => config.path.sub(%r{^/},""),
-
:host => config.host }
-
spec.reject!{ |_,value| value.blank? }
-
spec.map { |key,value| spec[key] = URI.unescape(value) if value.is_a?(String) }
-
if config.query
-
options = Hash[config.query.split("&").map{ |pair| pair.split("=") }].symbolize_keys
-
spec.merge!(options)
-
end
-
spec
-
end
-
end
-
end
-
-
##
-
# :singleton-method:
-
# The connection handler
-
2
class_attribute :connection_handler, :instance_writer => false
-
2
self.connection_handler = ConnectionAdapters::ConnectionHandler.new
-
-
# Returns the connection currently associated with the class. This can
-
# also be used to "borrow" the connection to do database work that isn't
-
# easily done without going straight to SQL.
-
2
def connection
-
21
self.class.connection
-
end
-
-
# Establishes the connection to the database. Accepts a hash as input where
-
# the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case)
-
# example for regular databases (MySQL, Postgresql, etc):
-
#
-
# ActiveRecord::Base.establish_connection(
-
# :adapter => "mysql",
-
# :host => "localhost",
-
# :username => "myuser",
-
# :password => "mypass",
-
# :database => "somedatabase"
-
# )
-
#
-
# Example for SQLite database:
-
#
-
# ActiveRecord::Base.establish_connection(
-
# :adapter => "sqlite",
-
# :database => "path/to/dbfile"
-
# )
-
#
-
# Also accepts keys as strings (for parsing from YAML for example):
-
#
-
# ActiveRecord::Base.establish_connection(
-
# "adapter" => "sqlite",
-
# "database" => "path/to/dbfile"
-
# )
-
#
-
# Or a URL:
-
#
-
# ActiveRecord::Base.establish_connection(
-
# "postgres://myuser:mypass@localhost/somedatabase"
-
# )
-
#
-
# The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError
-
# may be returned on an error.
-
2
def self.establish_connection(spec = ENV["DATABASE_URL"])
-
2
resolver = ConnectionSpecification::Resolver.new spec, configurations
-
2
spec = resolver.spec
-
-
2
unless respond_to?(spec.adapter_method)
-
raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter"
-
end
-
-
2
remove_connection
-
2
connection_handler.establish_connection name, spec
-
end
-
-
2
class << self
-
# Returns the connection currently associated with the class. This can
-
# also be used to "borrow" the connection to do database work unrelated
-
# to any of the specific Active Records.
-
2
def connection
-
5508
retrieve_connection
-
end
-
-
2
def connection_id
-
5943
Thread.current['ActiveRecord::Base.connection_id']
-
end
-
-
2
def connection_id=(connection_id)
-
2
Thread.current['ActiveRecord::Base.connection_id'] = connection_id
-
end
-
-
# Returns the configuration of the associated connection as a hash:
-
#
-
# ActiveRecord::Base.connection_config
-
# # => {:pool=>5, :timeout=>5000, :database=>"db/development.sqlite3", :adapter=>"sqlite3"}
-
#
-
# Please use only for reading.
-
2
def connection_config
-
connection_pool.spec.config
-
end
-
-
2
def connection_pool
-
connection_handler.retrieve_connection_pool(self) or raise ConnectionNotEstablished
-
end
-
-
2
def retrieve_connection
-
5508
connection_handler.retrieve_connection(self)
-
end
-
-
# Returns true if Active Record is connected.
-
2
def connected?
-
9
connection_handler.connected?(self)
-
end
-
-
2
def remove_connection(klass = self)
-
2
connection_handler.remove_connection(klass)
-
end
-
-
2
def clear_active_connections!
-
145
connection_handler.clear_active_connections!
-
end
-
-
2
delegate :clear_reloadable_connections!,
-
:clear_all_connections!,:verify_active_connections!, :to => :connection_handler
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
2
module DatabaseLimits
-
-
# Returns the maximum length of a table alias.
-
2
def table_alias_length
-
255
-
end
-
-
# Returns the maximum length of a column name.
-
2
def column_name_length
-
64
-
end
-
-
# Returns the maximum length of a table name.
-
2
def table_name_length
-
64
-
end
-
-
# Returns the maximum length of an index name.
-
2
def index_name_length
-
64
-
end
-
-
# Returns the maximum number of columns per table.
-
2
def columns_per_table
-
1024
-
end
-
-
# Returns the maximum number of indexes per table.
-
2
def indexes_per_table
-
16
-
end
-
-
# Returns the maximum number of columns in a multicolumn index.
-
2
def columns_per_multicolumn_index
-
16
-
end
-
-
# Returns the maximum number of elements in an IN (x,y,z) clause.
-
# nil means no limit.
-
2
def in_clause_length
-
nil
-
end
-
-
# Returns the maximum length of an SQL query.
-
2
def sql_query_length
-
1048575
-
end
-
-
# Returns maximum number of joins in a single query.
-
2
def joins_per_query
-
256
-
end
-
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
2
module DatabaseStatements
-
# Converts an arel AST to SQL
-
2
def to_sql(arel, binds = [])
-
1294
if arel.respond_to?(:ast)
-
1274
visitor.accept(arel.ast) do
-
quote(*binds.shift.reverse)
-
end
-
else
-
20
arel
-
end
-
end
-
-
# Returns an array of record hashes with the column names as keys and
-
# column values as values.
-
2
def select_all(arel, name = nil, binds = [])
-
844
select(to_sql(arel, binds), name, binds)
-
end
-
-
# Returns a record hash with the column names as keys and column values
-
# as values.
-
2
def select_one(arel, name = nil)
-
28
result = select_all(arel, name)
-
28
result.first if result
-
end
-
-
# Returns a single value from a record
-
2
def select_value(arel, name = nil)
-
28
if result = select_one(arel, name)
-
28
result.values.first
-
end
-
end
-
-
# Returns an array of the values of the first column in a select:
-
# select_values("SELECT id FROM companies LIMIT 3") => [1,2,3]
-
2
def select_values(arel, name = nil)
-
result = select_rows(to_sql(arel, []), name)
-
result.map { |v| v[0] }
-
end
-
-
# Returns an array of arrays containing the field values.
-
# Order is the same as that returned by +columns+.
-
2
def select_rows(sql, name = nil)
-
end
-
2
undef_method :select_rows
-
-
# Executes the SQL statement in the context of this connection.
-
2
def execute(sql, name = nil)
-
end
-
2
undef_method :execute
-
-
# Executes +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
2
def exec_query(sql, name = 'SQL', binds = [])
-
end
-
-
# Executes insert +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is the logged along with
-
# the executed +sql+ statement.
-
2
def exec_insert(sql, name, binds)
-
308
exec_query(sql, name, binds)
-
end
-
-
# Executes delete +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is the logged along with
-
# the executed +sql+ statement.
-
2
def exec_delete(sql, name, binds)
-
exec_query(sql, name, binds)
-
end
-
-
# Executes update +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is the logged along with
-
# the executed +sql+ statement.
-
2
def exec_update(sql, name, binds)
-
exec_query(sql, name, binds)
-
end
-
-
# Returns the last auto-generated ID from the affected table.
-
#
-
# +id_value+ will be returned unless the value is nil, in
-
# which case the database will attempt to calculate the last inserted
-
# id and return that value.
-
#
-
# If the next id was calculated in advance (as in Oracle), it should be
-
# passed in as +id_value+.
-
2
def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
-
308
sql, binds = sql_for_insert(to_sql(arel, binds), pk, id_value, sequence_name, binds)
-
308
value = exec_insert(sql, name, binds)
-
308
id_value || last_inserted_id(value)
-
end
-
-
# Executes the update statement and returns the number of rows affected.
-
2
def update(arel, name = nil, binds = [])
-
98
exec_update(to_sql(arel, binds), name, binds)
-
end
-
-
# Executes the delete statement and returns the number of rows affected.
-
2
def delete(arel, name = nil, binds = [])
-
44
exec_delete(to_sql(arel, binds), name, binds)
-
end
-
-
# Checks whether there is currently no transaction active. This is done
-
# by querying the database driver, and does not use the transaction
-
# house-keeping information recorded by #increment_open_transactions and
-
# friends.
-
#
-
# Returns true if there is no transaction active, false if there is a
-
# transaction active, and nil if this information is unknown.
-
#
-
# Not all adapters supports transaction state introspection. Currently,
-
# only the PostgreSQL adapter supports this.
-
2
def outside_transaction?
-
nil
-
end
-
-
# Returns +true+ when the connection adapter supports prepared statement
-
# caching, otherwise returns +false+
-
2
def supports_statement_cache?
-
false
-
end
-
-
# Runs the given block in a database transaction, and returns the result
-
# of the block.
-
#
-
# == Nested transactions support
-
#
-
# Most databases don't support true nested transactions. At the time of
-
# writing, the only database that supports true nested transactions that
-
# we're aware of, is MS-SQL.
-
#
-
# In order to get around this problem, #transaction will emulate the effect
-
# of nested transactions, by using savepoints:
-
# http://dev.mysql.com/doc/refman/5.0/en/savepoint.html
-
# Savepoints are supported by MySQL and PostgreSQL, but not SQLite3.
-
#
-
# It is safe to call this method if a database transaction is already open,
-
# i.e. if #transaction is called within another #transaction block. In case
-
# of a nested call, #transaction will behave as follows:
-
#
-
# - The block will be run without doing anything. All database statements
-
# that happen within the block are effectively appended to the already
-
# open database transaction.
-
# - However, if +:requires_new+ is set, the block will be wrapped in a
-
# database savepoint acting as a sub-transaction.
-
#
-
# === Caveats
-
#
-
# MySQL doesn't support DDL transactions. If you perform a DDL operation,
-
# then any created savepoints will be automatically released. For example,
-
# if you've created a savepoint, then you execute a CREATE TABLE statement,
-
# then the savepoint that was created will be automatically released.
-
#
-
# This means that, on MySQL, you shouldn't execute DDL operations inside
-
# a #transaction call that you know might create a savepoint. Otherwise,
-
# #transaction will raise exceptions when it tries to release the
-
# already-automatically-released savepoints:
-
#
-
# Model.connection.transaction do # BEGIN
-
# Model.connection.transaction(:requires_new => true) do # CREATE SAVEPOINT active_record_1
-
# Model.connection.create_table(...)
-
# # active_record_1 now automatically released
-
# end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error!
-
# end
-
2
def transaction(options = {})
-
431
options.assert_valid_keys :requires_new, :joinable
-
-
431
last_transaction_joinable = defined?(@transaction_joinable) ? @transaction_joinable : nil
-
431
if options.has_key?(:joinable)
-
@transaction_joinable = options[:joinable]
-
else
-
431
@transaction_joinable = true
-
end
-
431
requires_new = options[:requires_new] || !last_transaction_joinable
-
-
431
transaction_open = false
-
431
@_current_transaction_records ||= []
-
-
431
begin
-
431
if block_given?
-
431
if requires_new || open_transactions == 0
-
157
if open_transactions == 0
-
2
begin_db_transaction
-
elsif requires_new
-
155
create_savepoint
-
end
-
157
increment_open_transactions
-
157
transaction_open = true
-
157
@_current_transaction_records.push([])
-
end
-
431
yield
-
end
-
26
rescue Exception => database_transaction_rollback
-
26
if transaction_open && !outside_transaction?
-
24
transaction_open = false
-
24
decrement_open_transactions
-
24
if open_transactions == 0
-
rollback_db_transaction
-
rollback_transaction_records(true)
-
else
-
24
rollback_to_savepoint
-
24
rollback_transaction_records(false)
-
end
-
end
-
26
raise unless database_transaction_rollback.is_a?(ActiveRecord::Rollback)
-
end
-
ensure
-
431
@transaction_joinable = last_transaction_joinable
-
-
431
if outside_transaction?
-
@open_transactions = 0
-
elsif transaction_open
-
133
decrement_open_transactions
-
133
begin
-
133
if open_transactions == 0
-
2
commit_db_transaction
-
2
commit_transaction_records
-
else
-
131
release_savepoint
-
131
save_point_records = @_current_transaction_records.pop
-
131
unless save_point_records.blank?
-
127
@_current_transaction_records.push([]) if @_current_transaction_records.empty?
-
127
@_current_transaction_records.last.concat(save_point_records)
-
end
-
end
-
rescue Exception => database_transaction_rollback
-
if open_transactions == 0
-
rollback_db_transaction
-
rollback_transaction_records(true)
-
else
-
rollback_to_savepoint
-
rollback_transaction_records(false)
-
end
-
raise
-
end
-
end
-
end
-
-
# Register a record with the current transaction so that its after_commit and after_rollback callbacks
-
# can be called.
-
2
def add_transaction_record(record)
-
417
last_batch = @_current_transaction_records.last
-
417
last_batch << record if last_batch
-
end
-
-
# Begins the transaction (and turns off auto-committing).
-
2
def begin_db_transaction() end
-
-
# Commits the transaction (and turns on auto-committing).
-
2
def commit_db_transaction() end
-
-
# Rolls back the transaction (and turns on auto-committing). Must be
-
# done if the transaction block raises an exception or returns false.
-
2
def rollback_db_transaction() end
-
-
2
def default_sequence_name(table, column)
-
nil
-
end
-
-
# Set the sequence to the max value of the table's column.
-
2
def reset_sequence!(table, column, sequence = nil)
-
# Do nothing by default. Implement for PostgreSQL, Oracle, ...
-
end
-
-
# Inserts the given fixture into the table. Overridden in adapters that require
-
# something beyond a simple insert (eg. Oracle).
-
2
def insert_fixture(fixture, table_name)
-
26
columns = schema_cache.columns_hash(table_name)
-
-
26
key_list = []
-
26
value_list = fixture.map do |name, value|
-
160
key_list << quote_column_name(name)
-
160
quote(value, columns[name])
-
end
-
-
26
execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert'
-
end
-
-
2
def empty_insert_statement_value
-
"VALUES(DEFAULT)"
-
end
-
-
2
def case_sensitive_equality_operator
-
"="
-
end
-
-
2
def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
-
"WHERE #{quoted_primary_key} IN (SELECT #{quoted_primary_key} FROM #{quoted_table_name} #{where_sql})"
-
end
-
-
# Sanitizes the given LIMIT parameter in order to prevent SQL injection.
-
#
-
# The +limit+ may be anything that can evaluate to a string via #to_s. It
-
# should look like an integer, or a comma-delimited list of integers, or
-
# an Arel SQL literal.
-
#
-
# Returns Integer and Arel::Nodes::SqlLiteral limits as is.
-
# Returns the sanitized limit parameter, either as an integer, or as a
-
# string which contains a comma-delimited list of integers.
-
2
def sanitize_limit(limit)
-
363
if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral)
-
363
limit
-
elsif limit.to_s =~ /,/
-
Arel.sql limit.to_s.split(',').map{ |i| Integer(i) }.join(',')
-
else
-
Integer(limit)
-
end
-
end
-
-
# The default strategy for an UPDATE with joins is to use a subquery. This doesn't work
-
# on mysql (even when aliasing the tables), but mysql allows using JOIN directly in
-
# an UPDATE statement, so in the mysql adapters we redefine this to do that.
-
2
def join_to_update(update, select) #:nodoc:
-
subselect = select.clone
-
subselect.projections = [update.key]
-
-
update.where update.key.in(subselect)
-
end
-
-
2
protected
-
# Returns an array of record hashes with the column names as keys and
-
# column values as values.
-
2
def select(sql, name = nil, binds = [])
-
end
-
2
undef_method :select
-
-
# Returns the last auto-generated ID from the affected table.
-
2
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
-
execute(sql, name)
-
id_value
-
end
-
-
# Executes the update statement and returns the number of rows affected.
-
2
def update_sql(sql, name = nil)
-
execute(sql, name)
-
end
-
-
# Executes the delete statement and returns the number of rows affected.
-
2
def delete_sql(sql, name = nil)
-
update_sql(sql, name)
-
end
-
-
# Send a rollback message to all records after they have been rolled back. If rollback
-
# is false, only rollback records since the last save point.
-
2
def rollback_transaction_records(rollback)
-
24
if rollback
-
records = @_current_transaction_records.flatten
-
@_current_transaction_records.clear
-
else
-
24
records = @_current_transaction_records.pop
-
end
-
-
24
unless records.blank?
-
24
records.uniq.each do |record|
-
24
begin
-
24
record.rolledback!(rollback)
-
rescue Exception => e
-
record.logger.error(e) if record.respond_to?(:logger) && record.logger
-
end
-
end
-
end
-
end
-
-
# Send a commit message to all records after they have been committed.
-
2
def commit_transaction_records
-
2
records = @_current_transaction_records.flatten
-
2
@_current_transaction_records.clear
-
2
unless records.blank?
-
records.uniq.each do |record|
-
begin
-
record.committed!
-
rescue Exception => e
-
record.logger.error(e) if record.respond_to?(:logger) && record.logger
-
end
-
end
-
end
-
end
-
-
2
def sql_for_insert(sql, pk, id_value, sequence_name, binds)
-
308
[sql, binds]
-
end
-
-
2
def last_inserted_id(result)
-
row = result.rows.first
-
row && row.first
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
2
module QueryCache
-
2
class << self
-
2
def included(base)
-
2
dirties_query_cache base, :insert, :update, :delete
-
end
-
-
2
def dirties_query_cache(base, *method_names)
-
2
method_names.each do |method_name|
-
6
base.class_eval <<-end_code, __FILE__, __LINE__ + 1
-
def #{method_name}(*) # def update_with_query_dirty(*args)
-
clear_query_cache if @query_cache_enabled # clear_query_cache if @query_cache_enabled
-
super # update_without_query_dirty(*args)
-
end # end
-
end_code
-
end
-
end
-
end
-
-
2
attr_reader :query_cache, :query_cache_enabled
-
-
# Enable the query cache within the block.
-
2
def cache
-
old, @query_cache_enabled = @query_cache_enabled, true
-
yield
-
ensure
-
clear_query_cache
-
@query_cache_enabled = old
-
end
-
-
2
def enable_query_cache!
-
@query_cache_enabled = true
-
end
-
-
2
def disable_query_cache!
-
@query_cache_enabled = false
-
end
-
-
# Disable the query cache within the block.
-
2
def uncached
-
old, @query_cache_enabled = @query_cache_enabled, false
-
yield
-
ensure
-
@query_cache_enabled = old
-
end
-
-
# Clears the query cache.
-
#
-
# One reason you may wish to call this method explicitly is between queries
-
# that ask the database to randomize results. Otherwise the cache would see
-
# the same SQL query and repeatedly return the same result each time, silently
-
# undermining the randomness you were expecting.
-
2
def clear_query_cache
-
@query_cache.clear
-
end
-
-
2
def select_all(arel, name = nil, binds = [])
-
844
if @query_cache_enabled && !locked?(arel)
-
sql = to_sql(arel, binds)
-
cache_sql(sql, binds) { super(sql, name, binds) }
-
else
-
844
super
-
end
-
end
-
-
2
private
-
2
def cache_sql(sql, binds)
-
result =
-
if @query_cache[sql].key?(binds)
-
ActiveSupport::Notifications.instrument("sql.active_record",
-
:sql => sql, :binds => binds, :name => "CACHE", :connection_id => object_id)
-
@query_cache[sql][binds]
-
else
-
@query_cache[sql][binds] = yield
-
end
-
-
result.collect { |row| row.dup }
-
end
-
-
2
def locked?(arel)
-
if arel.respond_to?(:locked)
-
arel.locked
-
else
-
false
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/big_decimal/conversions'
-
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
2
module Quoting
-
# Quotes the column value to help prevent
-
# {SQL injection attacks}[http://en.wikipedia.org/wiki/SQL_injection].
-
2
def quote(value, column = nil)
-
# records are quoted as their primary key
-
2360
return value.quoted_id if value.respond_to?(:quoted_id)
-
-
2360
case value
-
when String, ActiveSupport::Multibyte::Chars
-
66
value = value.to_s
-
66
return "'#{quote_string(value)}'" unless column
-
-
66
case column.type
-
when :binary then "'#{quote_string(column.string_to_binary(value))}'"
-
when :integer then value.to_i.to_s
-
when :float then value.to_f.to_s
-
else
-
66
"'#{quote_string(value)}'"
-
end
-
-
when true, false
-
833
if column && column.type == :integer
-
value ? '1' : '0'
-
else
-
833
value ? quoted_true : quoted_false
-
end
-
# BigDecimals need to be put in a non-normalized form and quoted.
-
95
when nil then "NULL"
-
when BigDecimal then value.to_s('F')
-
453
when Numeric then value.to_s
-
913
when Date, Time then "'#{quoted_date(value)}'"
-
when Symbol then "'#{quote_string(value.to_s)}'"
-
else
-
"'#{quote_string(YAML.dump(value))}'"
-
end
-
end
-
-
# Cast a +value+ to a type that the database understands. For example,
-
# SQLite does not understand dates, so this method will convert a Date
-
# to a String.
-
2
def type_cast(value, column)
-
3590
return value.id if value.respond_to?(:quoted_id)
-
-
3590
case value
-
when String, ActiveSupport::Multibyte::Chars
-
325
value = value.to_s
-
325
return value unless column
-
-
325
case column.type
-
when :binary then value
-
when :integer then value.to_i
-
when :float then value.to_f
-
else
-
325
value
-
end
-
-
when true, false
-
426
if column && column.type == :integer
-
value ? 1 : 0
-
else
-
426
value ? 't' : 'f'
-
end
-
# BigDecimals need to be put in a non-normalized form and quoted.
-
when nil then nil
-
when BigDecimal then value.to_s('F')
-
754
when Numeric then value
-
1278
when Date, Time then quoted_date(value)
-
when Symbol then value.to_s
-
else
-
YAML.dump(value)
-
end
-
end
-
-
# Quotes a string, escaping any ' (single quote) and \ (backslash)
-
# characters.
-
2
def quote_string(s)
-
s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode)
-
end
-
-
# Quotes the column name. Defaults to no quoting.
-
2
def quote_column_name(column_name)
-
column_name
-
end
-
-
# Quotes the table name. Defaults to column name quoting.
-
2
def quote_table_name(table_name)
-
quote_column_name(table_name)
-
end
-
-
2
def quoted_true
-
115
"'t'"
-
end
-
-
2
def quoted_false
-
718
"'f'"
-
end
-
-
2
def quoted_date(value)
-
2191
if value.acts_like?(:time)
-
2081
zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal
-
-
2081
if value.respond_to?(zone_conversion_method)
-
2081
value = value.send(zone_conversion_method)
-
end
-
end
-
-
2191
value.to_s(:db)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/deprecation/reporting'
-
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
2
module SchemaStatements
-
# Returns a Hash of mappings from the abstract data types to the native
-
# database types. See TableDefinition#column for details on the recognized
-
# abstract data types.
-
2
def native_database_types
-
{}
-
end
-
-
# Truncates a table alias according to the limits of the current adapter.
-
2
def table_alias_for(table_name)
-
table_name[0...table_alias_length].gsub(/\./, '_')
-
end
-
-
# Checks to see if the table +table_name+ exists on the database.
-
#
-
# === Example
-
# table_exists?(:developers)
-
2
def table_exists?(table_name)
-
tables.include?(table_name.to_s)
-
end
-
-
# Returns an array of indexes for the given table.
-
# def indexes(table_name, name = nil) end
-
-
# Checks to see if an index exists on a table for a given index definition.
-
#
-
# === Examples
-
# # Check an index exists
-
# index_exists?(:suppliers, :company_id)
-
#
-
# # Check an index on multiple columns exists
-
# index_exists?(:suppliers, [:company_id, :company_type])
-
#
-
# # Check a unique index exists
-
# index_exists?(:suppliers, :company_id, :unique => true)
-
#
-
# # Check an index with a custom name exists
-
# index_exists?(:suppliers, :company_id, :name => "idx_company_id"
-
2
def index_exists?(table_name, column_name, options = {})
-
column_names = Array.wrap(column_name)
-
index_name = options.key?(:name) ? options[:name].to_s : index_name(table_name, :column => column_names)
-
if options[:unique]
-
indexes(table_name).any?{ |i| i.unique && i.name == index_name }
-
else
-
indexes(table_name).any?{ |i| i.name == index_name }
-
end
-
end
-
-
# Returns an array of Column objects for the table specified by +table_name+.
-
# See the concrete implementation for details on the expected parameter values.
-
2
def columns(table_name, name = nil) end
-
-
# Checks to see if a column exists in a given table.
-
#
-
# === Examples
-
# # Check a column exists
-
# column_exists?(:suppliers, :name)
-
#
-
# # Check a column exists of a particular type
-
# column_exists?(:suppliers, :name, :string)
-
#
-
# # Check a column exists with a specific definition
-
# column_exists?(:suppliers, :name, :string, :limit => 100)
-
2
def column_exists?(table_name, column_name, type = nil, options = {})
-
columns(table_name).any?{ |c| c.name == column_name.to_s &&
-
(!type || c.type == type) &&
-
(!options[:limit] || c.limit == options[:limit]) &&
-
(!options[:precision] || c.precision == options[:precision]) &&
-
(!options[:scale] || c.scale == options[:scale]) }
-
end
-
-
# Creates a new table with the name +table_name+. +table_name+ may either
-
# be a String or a Symbol.
-
#
-
# There are two ways to work with +create_table+. You can use the block
-
# form or the regular form, like this:
-
#
-
# === Block form
-
# # create_table() passes a TableDefinition object to the block.
-
# # This form will not only create the table, but also columns for the
-
# # table.
-
#
-
# create_table(:suppliers) do |t|
-
# t.column :name, :string, :limit => 60
-
# # Other fields here
-
# end
-
#
-
# === Block form, with shorthand
-
# # You can also use the column types as method calls, rather than calling the column method.
-
# create_table(:suppliers) do |t|
-
# t.string :name, :limit => 60
-
# # Other fields here
-
# end
-
#
-
# === Regular form
-
# # Creates a table called 'suppliers' with no columns.
-
# create_table(:suppliers)
-
# # Add a column to 'suppliers'.
-
# add_column(:suppliers, :name, :string, {:limit => 60})
-
#
-
# The +options+ hash can include the following keys:
-
# [<tt>:id</tt>]
-
# Whether to automatically add a primary key column. Defaults to true.
-
# Join tables for +has_and_belongs_to_many+ should set it to false.
-
# [<tt>:primary_key</tt>]
-
# The name of the primary key, if one is to be added automatically.
-
# Defaults to +id+. If <tt>:id</tt> is false this option is ignored.
-
#
-
# Also note that this just sets the primary key in the table. You additionally
-
# need to configure the primary key in the model via +self.primary_key=+.
-
# Models do NOT auto-detect the primary key from their table definition.
-
#
-
# [<tt>:options</tt>]
-
# Any extra options you want appended to the table definition.
-
# [<tt>:temporary</tt>]
-
# Make a temporary table.
-
# [<tt>:force</tt>]
-
# Set to true to drop the table before creating it.
-
# Defaults to false.
-
#
-
# ===== Examples
-
# ====== Add a backend specific option to the generated SQL (MySQL)
-
# create_table(:suppliers, :options => 'ENGINE=InnoDB DEFAULT CHARSET=utf8')
-
# generates:
-
# CREATE TABLE suppliers (
-
# id int(11) DEFAULT NULL auto_increment PRIMARY KEY
-
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8
-
#
-
# ====== Rename the primary key column
-
# create_table(:objects, :primary_key => 'guid') do |t|
-
# t.column :name, :string, :limit => 80
-
# end
-
# generates:
-
# CREATE TABLE objects (
-
# guid int(11) DEFAULT NULL auto_increment PRIMARY KEY,
-
# name varchar(80)
-
# )
-
#
-
# ====== Do not add a primary key column
-
# create_table(:categories_suppliers, :id => false) do |t|
-
# t.column :category_id, :integer
-
# t.column :supplier_id, :integer
-
# end
-
# generates:
-
# CREATE TABLE categories_suppliers (
-
# category_id int,
-
# supplier_id int
-
# )
-
#
-
# See also TableDefinition#column for details on how to create columns.
-
2
def create_table(table_name, options = {})
-
td = table_definition
-
td.primary_key(options[:primary_key] || Base.get_primary_key(table_name.to_s.singularize)) unless options[:id] == false
-
-
yield td if block_given?
-
-
if options[:force] && table_exists?(table_name)
-
drop_table(table_name, options)
-
end
-
-
create_sql = "CREATE#{' TEMPORARY' if options[:temporary]} TABLE "
-
create_sql << "#{quote_table_name(table_name)} ("
-
create_sql << td.to_sql
-
create_sql << ") #{options[:options]}"
-
execute create_sql
-
end
-
-
# A block for changing columns in +table+.
-
#
-
# === Example
-
# # change_table() yields a Table instance
-
# change_table(:suppliers) do |t|
-
# t.column :name, :string, :limit => 60
-
# # Other column alterations here
-
# end
-
#
-
# The +options+ hash can include the following keys:
-
# [<tt>:bulk</tt>]
-
# Set this to true to make this a bulk alter query, such as
-
# ALTER TABLE `users` ADD COLUMN age INT(11), ADD COLUMN birthdate DATETIME ...
-
#
-
# Defaults to false.
-
#
-
# ===== Examples
-
# ====== Add a column
-
# change_table(:suppliers) do |t|
-
# t.column :name, :string, :limit => 60
-
# end
-
#
-
# ====== Add 2 integer columns
-
# change_table(:suppliers) do |t|
-
# t.integer :width, :height, :null => false, :default => 0
-
# end
-
#
-
# ====== Add created_at/updated_at columns
-
# change_table(:suppliers) do |t|
-
# t.timestamps
-
# end
-
#
-
# ====== Add a foreign key column
-
# change_table(:suppliers) do |t|
-
# t.references :company
-
# end
-
#
-
# Creates a <tt>company_id(integer)</tt> column
-
#
-
# ====== Add a polymorphic foreign key column
-
# change_table(:suppliers) do |t|
-
# t.belongs_to :company, :polymorphic => true
-
# end
-
#
-
# Creates <tt>company_type(varchar)</tt> and <tt>company_id(integer)</tt> columns
-
#
-
# ====== Remove a column
-
# change_table(:suppliers) do |t|
-
# t.remove :company
-
# end
-
#
-
# ====== Remove several columns
-
# change_table(:suppliers) do |t|
-
# t.remove :company_id
-
# t.remove :width, :height
-
# end
-
#
-
# ====== Remove an index
-
# change_table(:suppliers) do |t|
-
# t.remove_index :company_id
-
# end
-
#
-
# See also Table for details on
-
# all of the various column transformation
-
2
def change_table(table_name, options = {})
-
if supports_bulk_alter? && options[:bulk]
-
recorder = ActiveRecord::Migration::CommandRecorder.new(self)
-
yield Table.new(table_name, recorder)
-
bulk_change_table(table_name, recorder.commands)
-
else
-
yield Table.new(table_name, self)
-
end
-
end
-
-
# Renames a table.
-
# ===== Example
-
# rename_table('octopuses', 'octopi')
-
2
def rename_table(table_name, new_name)
-
raise NotImplementedError, "rename_table is not implemented"
-
end
-
-
# Drops a table from the database.
-
2
def drop_table(table_name, options = {})
-
execute "DROP TABLE #{quote_table_name(table_name)}"
-
end
-
-
# Adds a new column to the named table.
-
# See TableDefinition#column for details of the options you can use.
-
2
def add_column(table_name, column_name, type, options = {})
-
add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
-
add_column_options!(add_column_sql, options)
-
execute(add_column_sql)
-
end
-
-
# Removes the column(s) from the table definition.
-
# ===== Examples
-
# remove_column(:suppliers, :qualification)
-
# remove_columns(:suppliers, :qualification, :experience)
-
2
def remove_column(table_name, *column_names)
-
if column_names.flatten!
-
message = 'Passing array to remove_columns is deprecated, please use ' +
-
'multiple arguments, like: `remove_columns(:posts, :foo, :bar)`'
-
ActiveSupport::Deprecation.warn message, caller
-
end
-
-
columns_for_remove(table_name, *column_names).each do |column_name|
-
execute "ALTER TABLE #{quote_table_name(table_name)} DROP #{column_name}"
-
end
-
end
-
2
alias :remove_columns :remove_column
-
-
# Changes the column's definition according to the new options.
-
# See TableDefinition#column for details of the options you can use.
-
# ===== Examples
-
# change_column(:suppliers, :name, :string, :limit => 80)
-
# change_column(:accounts, :description, :text)
-
2
def change_column(table_name, column_name, type, options = {})
-
raise NotImplementedError, "change_column is not implemented"
-
end
-
-
# Sets a new default value for a column.
-
# ===== Examples
-
# change_column_default(:suppliers, :qualification, 'new')
-
# change_column_default(:accounts, :authorized, 1)
-
# change_column_default(:users, :email, nil)
-
2
def change_column_default(table_name, column_name, default)
-
raise NotImplementedError, "change_column_default is not implemented"
-
end
-
-
# Renames a column.
-
# ===== Example
-
# rename_column(:suppliers, :description, :name)
-
2
def rename_column(table_name, column_name, new_column_name)
-
raise NotImplementedError, "rename_column is not implemented"
-
end
-
-
# Adds a new index to the table. +column_name+ can be a single Symbol, or
-
# an Array of Symbols.
-
#
-
# The index will be named after the table and the column name(s), unless
-
# you pass <tt>:name</tt> as an option.
-
#
-
# ===== Examples
-
#
-
# ====== Creating a simple index
-
# add_index(:suppliers, :name)
-
# generates
-
# CREATE INDEX suppliers_name_index ON suppliers(name)
-
#
-
# ====== Creating a unique index
-
# add_index(:accounts, [:branch_id, :party_id], :unique => true)
-
# generates
-
# CREATE UNIQUE INDEX accounts_branch_id_party_id_index ON accounts(branch_id, party_id)
-
#
-
# ====== Creating a named index
-
# add_index(:accounts, [:branch_id, :party_id], :unique => true, :name => 'by_branch_party')
-
# generates
-
# CREATE UNIQUE INDEX by_branch_party ON accounts(branch_id, party_id)
-
#
-
# ====== Creating an index with specific key length
-
# add_index(:accounts, :name, :name => 'by_name', :length => 10)
-
# generates
-
# CREATE INDEX by_name ON accounts(name(10))
-
#
-
# add_index(:accounts, [:name, :surname], :name => 'by_name_surname', :length => {:name => 10, :surname => 15})
-
# generates
-
# CREATE INDEX by_name_surname ON accounts(name(10), surname(15))
-
#
-
# Note: SQLite doesn't support index length
-
#
-
# ====== Creating an index with a sort order (desc or asc, asc is the default)
-
# add_index(:accounts, [:branch_id, :party_id, :surname], :order => {:branch_id => :desc, :part_id => :asc})
-
# generates
-
# CREATE INDEX by_branch_desc_party ON accounts(branch_id DESC, party_id ASC, surname)
-
#
-
# Note: mysql doesn't yet support index order (it accepts the syntax but ignores it)
-
#
-
2
def add_index(table_name, column_name, options = {})
-
index_name, index_type, index_columns = add_index_options(table_name, column_name, options)
-
execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{index_columns})"
-
end
-
-
# Remove the given index from the table.
-
#
-
# Remove the index_accounts_on_column in the accounts table.
-
# remove_index :accounts, :column
-
# Remove the index named index_accounts_on_branch_id in the accounts table.
-
# remove_index :accounts, :column => :branch_id
-
# Remove the index named index_accounts_on_branch_id_and_party_id in the accounts table.
-
# remove_index :accounts, :column => [:branch_id, :party_id]
-
# Remove the index named by_branch_party in the accounts table.
-
# remove_index :accounts, :name => :by_branch_party
-
2
def remove_index(table_name, options = {})
-
remove_index!(table_name, index_name_for_remove(table_name, options))
-
end
-
-
2
def remove_index!(table_name, index_name) #:nodoc:
-
execute "DROP INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)}"
-
end
-
-
# Rename an index.
-
#
-
# Rename the index_people_on_last_name index to index_users_on_last_name
-
# rename_index :people, 'index_people_on_last_name', 'index_users_on_last_name'
-
2
def rename_index(table_name, old_name, new_name)
-
# this is a naive implementation; some DBs may support this more efficiently (Postgres, for instance)
-
old_index_def = indexes(table_name).detect { |i| i.name == old_name }
-
return unless old_index_def
-
remove_index(table_name, :name => old_name)
-
add_index(table_name, old_index_def.columns, :name => new_name, :unique => old_index_def.unique)
-
end
-
-
2
def index_name(table_name, options) #:nodoc:
-
if Hash === options # legacy support
-
if options[:column]
-
"index_#{table_name}_on_#{Array.wrap(options[:column]) * '_and_'}"
-
elsif options[:name]
-
options[:name]
-
else
-
raise ArgumentError, "You must specify the index name"
-
end
-
else
-
index_name(table_name, :column => options)
-
end
-
end
-
-
# Verify the existence of an index with a given name.
-
#
-
# The default argument is returned if the underlying implementation does not define the indexes method,
-
# as there's no way to determine the correct answer in that case.
-
2
def index_name_exists?(table_name, index_name, default)
-
return default unless respond_to?(:indexes)
-
index_name = index_name.to_s
-
indexes(table_name).detect { |i| i.name == index_name }
-
end
-
-
# Returns a string of <tt>CREATE TABLE</tt> SQL statement(s) for recreating the
-
# entire structure of the database.
-
2
def structure_dump
-
end
-
-
2
def dump_schema_information #:nodoc:
-
sm_table = ActiveRecord::Migrator.schema_migrations_table_name
-
migrated = select_values("SELECT version FROM #{sm_table} ORDER BY version")
-
migrated.map { |v| "INSERT INTO #{sm_table} (version) VALUES ('#{v}');" }.join("\n\n")
-
end
-
-
# Should not be called normally, but this operation is non-destructive.
-
# The migrations module handles this automatically.
-
2
def initialize_schema_migrations_table
-
sm_table = ActiveRecord::Migrator.schema_migrations_table_name
-
-
unless table_exists?(sm_table)
-
create_table(sm_table, :id => false) do |schema_migrations_table|
-
schema_migrations_table.column :version, :string, :null => false
-
end
-
add_index sm_table, :version, :unique => true,
-
:name => "#{Base.table_name_prefix}unique_schema_migrations#{Base.table_name_suffix}"
-
-
# Backwards-compatibility: if we find schema_info, assume we've
-
# migrated up to that point:
-
si_table = Base.table_name_prefix + 'schema_info' + Base.table_name_suffix
-
-
if table_exists?(si_table)
-
ActiveSupport::Deprecation.warn "Usage of the schema table `#{si_table}` is deprecated. Please switch to using `schema_migrations` table"
-
-
old_version = select_value("SELECT version FROM #{quote_table_name(si_table)}").to_i
-
assume_migrated_upto_version(old_version)
-
drop_table(si_table)
-
end
-
end
-
end
-
-
2
def assume_migrated_upto_version(version, migrations_paths = ActiveRecord::Migrator.migrations_paths)
-
migrations_paths = Array.wrap(migrations_paths)
-
version = version.to_i
-
sm_table = quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name)
-
-
migrated = select_values("SELECT version FROM #{sm_table}").map { |v| v.to_i }
-
paths = migrations_paths.map {|p| "#{p}/[0-9]*_*.rb" }
-
versions = Dir[*paths].map do |filename|
-
filename.split('/').last.split('_').first.to_i
-
end
-
-
unless migrated.include?(version)
-
execute "INSERT INTO #{sm_table} (version) VALUES ('#{version}')"
-
end
-
-
inserted = Set.new
-
(versions - migrated).each do |v|
-
if inserted.include?(v)
-
raise "Duplicate migration #{v}. Please renumber your migrations to resolve the conflict."
-
elsif v < version
-
execute "INSERT INTO #{sm_table} (version) VALUES ('#{v}')"
-
inserted << v
-
end
-
end
-
end
-
-
2
def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
-
if native = native_database_types[type.to_sym]
-
column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup
-
-
if type == :decimal # ignore limit, use precision and scale
-
scale ||= native[:scale]
-
-
if precision ||= native[:precision]
-
if scale
-
column_type_sql << "(#{precision},#{scale})"
-
else
-
column_type_sql << "(#{precision})"
-
end
-
elsif scale
-
raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale if specified"
-
end
-
-
elsif (type != :primary_key) && (limit ||= native.is_a?(Hash) && native[:limit])
-
column_type_sql << "(#{limit})"
-
end
-
-
column_type_sql
-
else
-
type
-
end
-
end
-
-
2
def add_column_options!(sql, options) #:nodoc:
-
sql << " DEFAULT #{quote(options[:default], options[:column])}" if options_include_default?(options)
-
# must explicitly check for :null to allow change_column to work on migrations
-
if options[:null] == false
-
sql << " NOT NULL"
-
end
-
end
-
-
# SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
-
# Both PostgreSQL and Oracle overrides this for custom DISTINCT syntax.
-
#
-
# distinct("posts.id", "posts.created_at desc")
-
2
def distinct(columns, order_by)
-
"DISTINCT #{columns}"
-
end
-
-
# Adds timestamps (created_at and updated_at) columns to the named table.
-
# ===== Examples
-
# add_timestamps(:suppliers)
-
2
def add_timestamps(table_name)
-
add_column table_name, :created_at, :datetime
-
add_column table_name, :updated_at, :datetime
-
end
-
-
# Removes the timestamp columns (created_at and updated_at) from the table definition.
-
# ===== Examples
-
# remove_timestamps(:suppliers)
-
2
def remove_timestamps(table_name)
-
remove_column table_name, :updated_at
-
remove_column table_name, :created_at
-
end
-
-
2
protected
-
2
def add_index_sort_order(option_strings, column_names, options = {})
-
if options.is_a?(Hash) && order = options[:order]
-
case order
-
when Hash
-
column_names.each {|name| option_strings[name] += " #{order[name].to_s.upcase}" if order.has_key?(name)}
-
when String
-
column_names.each {|name| option_strings[name] += " #{order.upcase}"}
-
end
-
end
-
-
return option_strings
-
end
-
-
# Overridden by the mysql adapter for supporting index lengths
-
2
def quoted_columns_for_index(column_names, options = {})
-
option_strings = Hash[column_names.map {|name| [name, '']}]
-
-
# add index sort order if supported
-
if supports_index_sort_order?
-
option_strings = add_index_sort_order(option_strings, column_names, options)
-
end
-
-
column_names.map {|name| quote_column_name(name) + option_strings[name]}
-
end
-
-
2
def options_include_default?(options)
-
options.include?(:default) && !(options[:null] == false && options[:default].nil?)
-
end
-
-
2
def add_index_options(table_name, column_name, options = {})
-
column_names = Array.wrap(column_name)
-
index_name = index_name(table_name, :column => column_names)
-
-
if Hash === options # legacy support, since this param was a string
-
index_type = options[:unique] ? "UNIQUE" : ""
-
index_name = options[:name].to_s if options.key?(:name)
-
else
-
index_type = options
-
end
-
-
if index_name.length > index_name_length
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{index_name_length} characters"
-
end
-
if index_name_exists?(table_name, index_name, false)
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists"
-
end
-
index_columns = quoted_columns_for_index(column_names, options).join(", ")
-
-
[index_name, index_type, index_columns]
-
end
-
-
2
def index_name_for_remove(table_name, options = {})
-
index_name = index_name(table_name, options)
-
-
unless index_name_exists?(table_name, index_name, true)
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
-
end
-
-
index_name
-
end
-
-
2
def columns_for_remove(table_name, *column_names)
-
column_names = column_names.flatten
-
-
raise ArgumentError.new("You must specify at least one column name. Example: remove_column(:people, :first_name)") if column_names.blank?
-
column_names.map {|column_name| quote_column_name(column_name) }
-
end
-
-
2
private
-
2
def table_definition
-
TableDefinition.new(self)
-
end
-
end
-
end
-
end
-
2
require 'date'
-
2
require 'bigdecimal'
-
2
require 'bigdecimal/util'
-
2
require 'active_support/core_ext/benchmark'
-
2
require 'active_support/deprecation'
-
2
require 'active_record/connection_adapters/schema_cache'
-
2
require 'monitor'
-
-
2
module ActiveRecord
-
2
module ConnectionAdapters # :nodoc:
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Column
-
-
2
autoload_under 'abstract' do
-
2
autoload :IndexDefinition, 'active_record/connection_adapters/abstract/schema_definitions'
-
2
autoload :ColumnDefinition, 'active_record/connection_adapters/abstract/schema_definitions'
-
2
autoload :TableDefinition, 'active_record/connection_adapters/abstract/schema_definitions'
-
2
autoload :Table, 'active_record/connection_adapters/abstract/schema_definitions'
-
-
2
autoload :SchemaStatements
-
2
autoload :DatabaseStatements
-
2
autoload :DatabaseLimits
-
2
autoload :Quoting
-
-
2
autoload :ConnectionPool
-
2
autoload :ConnectionHandler, 'active_record/connection_adapters/abstract/connection_pool'
-
2
autoload :ConnectionManagement, 'active_record/connection_adapters/abstract/connection_pool'
-
2
autoload :ConnectionSpecification
-
-
2
autoload :QueryCache
-
end
-
-
# Active Record supports multiple database systems. AbstractAdapter and
-
# related classes form the abstraction layer which makes this possible.
-
# An AbstractAdapter represents a connection to a database, and provides an
-
# abstract interface for database-specific functionality such as establishing
-
# a connection, escaping values, building the right SQL fragments for ':offset'
-
# and ':limit' options, etc.
-
#
-
# All the concrete database adapters follow the interface laid down in this class.
-
# ActiveRecord::Base.connection returns an AbstractAdapter object, which
-
# you can use.
-
#
-
# Most of the methods in the adapter are useful during migrations. Most
-
# notably, the instance methods provided by SchemaStatement are very useful.
-
2
class AbstractAdapter
-
2
include Quoting, DatabaseStatements, SchemaStatements
-
2
include DatabaseLimits
-
2
include QueryCache
-
2
include ActiveSupport::Callbacks
-
2
include MonitorMixin
-
-
2
define_callbacks :checkout, :checkin
-
-
2
attr_accessor :visitor, :pool
-
2
attr_reader :schema_cache, :last_use, :in_use, :logger
-
2
alias :in_use? :in_use
-
-
2
def initialize(connection, logger = nil, pool = nil) #:nodoc:
-
2
super()
-
-
2
@active = nil
-
2
@connection = connection
-
2
@in_use = false
-
2
@instrumenter = ActiveSupport::Notifications.instrumenter
-
2
@last_use = false
-
2
@logger = logger
-
2
@open_transactions = 0
-
2
@pool = pool
-
2
@query_cache = Hash.new { |h,sql| h[sql] = {} }
-
2
@query_cache_enabled = false
-
2
@schema_cache = SchemaCache.new self
-
2
@visitor = nil
-
end
-
-
2
def lease
-
145
synchronize do
-
145
unless in_use
-
145
@in_use = true
-
145
@last_use = Time.now
-
end
-
end
-
end
-
-
2
def expire
-
145
@in_use = false
-
end
-
-
# Returns the human-readable name of the adapter. Use mixed case - one
-
# can always use downcase if needed.
-
2
def adapter_name
-
'Abstract'
-
end
-
-
# Does this adapter support migrations? Backend specific, as the
-
# abstract adapter always returns +false+.
-
2
def supports_migrations?
-
false
-
end
-
-
# Can this adapter determine the primary key for tables not attached
-
# to an Active Record class, such as join tables? Backend specific, as
-
# the abstract adapter always returns +false+.
-
2
def supports_primary_key?
-
false
-
end
-
-
# Does this adapter support using DISTINCT within COUNT? This is +true+
-
# for all adapters except sqlite.
-
2
def supports_count_distinct?
-
true
-
end
-
-
# Does this adapter support DDL rollbacks in transactions? That is, would
-
# CREATE TABLE or ALTER TABLE get rolled back by a transaction? PostgreSQL,
-
# SQL Server, and others support this. MySQL and others do not.
-
2
def supports_ddl_transactions?
-
false
-
end
-
-
2
def supports_bulk_alter?
-
false
-
end
-
-
# Does this adapter support savepoints? PostgreSQL and MySQL do,
-
# SQLite < 3.6.8 does not.
-
2
def supports_savepoints?
-
false
-
end
-
-
# Should primary key values be selected from their corresponding
-
# sequence before the insert statement? If true, next_sequence_value
-
# is called before each insert to set the record's primary key.
-
# This is false for all adapters but Firebird.
-
2
def prefetch_primary_key?(table_name = nil)
-
308
false
-
end
-
-
# Does this adapter support index sort order?
-
2
def supports_index_sort_order?
-
false
-
end
-
-
# Does this adapter support explain? As of this writing sqlite3,
-
# mysql2, and postgresql are the only ones that do.
-
2
def supports_explain?
-
false
-
end
-
-
# QUOTING ==================================================
-
-
# Override to return the quoted table name. Defaults to column quoting.
-
2
def quote_table_name(name)
-
387
quote_column_name(name)
-
end
-
-
# Returns a bind substitution value given a +column+ and list of current
-
# +binds+
-
2
def substitute_at(column, index)
-
3590
Arel::Nodes::BindParam.new '?'
-
end
-
-
# REFERENTIAL INTEGRITY ====================================
-
-
# Override to turn off referential integrity while executing <tt>&block</tt>.
-
2
def disable_referential_integrity
-
2
yield
-
end
-
-
# CONNECTION MANAGEMENT ====================================
-
-
# Checks whether the connection to the database is still active. This includes
-
# checking whether the database is actually capable of responding, i.e. whether
-
# the connection isn't stale.
-
2
def active?
-
145
@active != false
-
end
-
-
# Disconnects from the database if already connected, and establishes a
-
# new connection with the database.
-
2
def reconnect!
-
@active = true
-
end
-
-
# Disconnects from the database if already connected. Otherwise, this
-
# method does nothing.
-
2
def disconnect!
-
@active = false
-
end
-
-
# Reset the state of this connection, directing the DBMS to clear
-
# transactions and other connection-related server-side state. Usually a
-
# database-dependent operation.
-
#
-
# The default implementation does nothing; the implementation should be
-
# overridden by concrete adapters.
-
2
def reset!
-
# this should be overridden by concrete adapters
-
end
-
-
###
-
# Clear any caching the database adapter may be doing, for example
-
# clearing the prepared statement cache. This is database specific.
-
2
def clear_cache!
-
# this should be overridden by concrete adapters
-
end
-
-
# Returns true if its required to reload the connection between requests for development mode.
-
# This is not the case for Ruby/MySQL and it's not necessary for any adapters except SQLite.
-
2
def requires_reloading?
-
false
-
end
-
-
# Checks whether the connection to the database is still active (i.e. not stale).
-
# This is done under the hood by calling <tt>active?</tt>. If the connection
-
# is no longer active, then this method will reconnect to the database.
-
2
def verify!(*ignored)
-
145
reconnect! unless active?
-
end
-
-
# Provides access to the underlying database driver for this adapter. For
-
# example, this method returns a Mysql object in case of MysqlAdapter,
-
# and a PGconn object in case of PostgreSQLAdapter.
-
#
-
# This is useful for when you need to call a proprietary method such as
-
# PostgreSQL's lo_* methods.
-
2
def raw_connection
-
@connection
-
end
-
-
2
attr_reader :open_transactions
-
-
2
def increment_open_transactions
-
302
@open_transactions += 1
-
end
-
-
2
def decrement_open_transactions
-
302
@open_transactions -= 1
-
end
-
-
2
def transaction_joinable=(joinable)
-
145
@transaction_joinable = joinable
-
end
-
-
2
def create_savepoint
-
end
-
-
2
def rollback_to_savepoint
-
end
-
-
2
def release_savepoint
-
end
-
-
2
def case_sensitive_modifier(node)
-
node
-
end
-
-
2
def case_insensitive_comparison(table, attribute, column, value)
-
table[attribute].lower.eq(table.lower(value))
-
end
-
-
2
def current_savepoint_name
-
310
"active_record_#{open_transactions}"
-
end
-
-
# Check the connection back in to the connection pool
-
2
def close
-
pool.checkin self
-
end
-
-
2
protected
-
-
2
def log(sql, name = "SQL", binds = [])
-
1989
@instrumenter.instrument(
-
"sql.active_record",
-
:sql => sql,
-
:name => name,
-
:connection_id => object_id,
-
1989
:binds => binds) { yield }
-
rescue Exception => e
-
message = "#{e.class.name}: #{e.message}: #{sql}"
-
@logger.debug message if @logger
-
exception = translate_exception(e, message)
-
exception.set_backtrace e.backtrace
-
raise exception
-
end
-
-
2
def translate_exception(e, message)
-
# override in derived class
-
ActiveRecord::StatementInvalid.new(message)
-
end
-
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module ActiveRecord
-
# :stopdoc:
-
2
module ConnectionAdapters
-
# An abstract definition of a column in a table.
-
2
class Column
-
2
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE', 'on', 'ON'].to_set
-
2
FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE', 'off', 'OFF'].to_set
-
-
2
module Format
-
2
ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/
-
2
ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
-
end
-
-
2
attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale
-
2
attr_accessor :primary, :coder
-
-
2
alias :encoded? :coder
-
-
# Instantiates a new column in the table.
-
#
-
# +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
-
# +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
-
# +sql_type+ is used to extract the column's length, if necessary. For example +60+ in
-
# <tt>company_name varchar(60)</tt>.
-
# It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
-
# +null+ determines if this column allows +NULL+ values.
-
2
def initialize(name, default, sql_type = nil, null = true)
-
236
@name = name
-
236
@sql_type = sql_type
-
236
@null = null
-
236
@limit = extract_limit(sql_type)
-
236
@precision = extract_precision(sql_type)
-
236
@scale = extract_scale(sql_type)
-
236
@type = simplified_type(sql_type)
-
236
@default = extract_default(default)
-
236
@primary = nil
-
236
@coder = nil
-
end
-
-
# Returns +true+ if the column is either of type string or text.
-
2
def text?
-
type == :string || type == :text
-
end
-
-
# Returns +true+ if the column is either of type integer, float or decimal.
-
2
def number?
-
6916
type == :integer || type == :float || type == :decimal
-
end
-
-
2
def has_default?
-
!default.nil?
-
end
-
-
# Returns the Ruby class that corresponds to the abstract data type.
-
2
def klass
-
case type
-
when :integer then Fixnum
-
when :float then Float
-
when :decimal then BigDecimal
-
when :datetime, :timestamp, :time then Time
-
when :date then Date
-
when :text, :string, :binary then String
-
when :boolean then Object
-
end
-
end
-
-
# Casts value (which is a String) to an appropriate instance.
-
2
def type_cast(value)
-
3417
return nil if value.nil?
-
3176
return coder.load(value) if encoded?
-
-
3176
klass = self.class
-
-
3176
case type
-
339
when :string, :text then value
-
959
when :integer then klass.value_to_integer(value)
-
when :float then value.to_f
-
when :decimal then klass.value_to_decimal(value)
-
1236
when :datetime, :timestamp then klass.string_to_time(value)
-
72
when :time then klass.string_to_dummy_time(value)
-
106
when :date then klass.string_to_date(value)
-
when :binary then klass.binary_to_string(value)
-
464
when :boolean then klass.value_to_boolean(value)
-
else value
-
end
-
end
-
-
2
def type_cast_code(var_name)
-
214
klass = self.class.name
-
-
214
case type
-
24
when :string, :text then var_name
-
68
when :integer then "#{klass}.value_to_integer(#{var_name})"
-
when :float then "#{var_name}.to_f"
-
when :decimal then "#{klass}.value_to_decimal(#{var_name})"
-
60
when :datetime, :timestamp then "#{klass}.string_to_time(#{var_name})"
-
4
when :time then "#{klass}.string_to_dummy_time(#{var_name})"
-
14
when :date then "#{klass}.string_to_date(#{var_name})"
-
when :binary then "#{klass}.binary_to_string(#{var_name})"
-
44
when :boolean then "#{klass}.value_to_boolean(#{var_name})"
-
else var_name
-
end
-
end
-
-
# Returns the human name of the column name.
-
#
-
# ===== Examples
-
# Column.new('sales_stage', ...).human_name # => 'Sales stage'
-
2
def human_name
-
Base.human_attribute_name(@name)
-
end
-
-
2
def extract_default(default)
-
236
type_cast(default)
-
end
-
-
# Used to convert from Strings to BLOBs
-
2
def string_to_binary(value)
-
self.class.string_to_binary(value)
-
end
-
-
2
class << self
-
# Used to convert from Strings to BLOBs
-
2
def string_to_binary(value)
-
value
-
end
-
-
# Used to convert from BLOBs to Strings
-
2
def binary_to_string(value)
-
value
-
end
-
-
2
def string_to_date(string)
-
325
return string unless string.is_a?(String)
-
120
return nil if string.empty?
-
-
120
fast_string_to_date(string) || fallback_string_to_date(string)
-
end
-
-
2
def string_to_time(string)
-
3088
return string unless string.is_a?(String)
-
616
return nil if string.empty?
-
-
616
fast_string_to_time(string) || fallback_string_to_time(string)
-
end
-
-
2
def string_to_dummy_time(string)
-
164
return string unless string.is_a?(String)
-
20
return nil if string.empty?
-
-
20
dummy_time_string = "2000-01-01 #{string}"
-
-
fast_string_to_time(dummy_time_string) || begin
-
20
time_hash = Date._parse(dummy_time_string)
-
20
return nil if time_hash[:hour].nil?
-
20
new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
-
20
end
-
end
-
-
# convert something to a boolean
-
2
def value_to_boolean(value)
-
774
if value.is_a?(String) && value.blank?
-
nil
-
else
-
774
TRUE_VALUES.include?(value)
-
end
-
end
-
-
# Used to convert values to integer.
-
# handle the case when an integer column is used to store boolean values
-
2
def value_to_integer(value)
-
6483
case value
-
when TrueClass, FalseClass
-
value ? 1 : 0
-
else
-
6483
value.to_i rescue nil
-
end
-
end
-
-
# convert something to a BigDecimal
-
2
def value_to_decimal(value)
-
# Using .class is faster than .is_a? and
-
# subclasses of BigDecimal will be handled
-
# in the else clause
-
if value.class == BigDecimal
-
value
-
elsif value.respond_to?(:to_d)
-
value.to_d
-
else
-
value.to_s.to_d
-
end
-
end
-
-
2
protected
-
# '0.123456' -> 123456
-
# '1.123456' -> 123456
-
2
def microseconds(time)
-
time[:sec_fraction] ? (time[:sec_fraction] * 1_000_000).to_i : 0
-
end
-
-
2
def new_date(year, mon, mday)
-
120
if year && year != 0
-
120
Date.new(year, mon, mday) rescue nil
-
end
-
end
-
-
2
def new_time(year, mon, mday, hour, min, sec, microsec)
-
# Treat 0000-00-00 00:00:00 as nil.
-
636
return nil if year.nil? || (year == 0 && mon == 0 && mday == 0)
-
-
636
Time.time_with_datetime_fallback(Base.default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil
-
end
-
-
2
def fast_string_to_date(string)
-
120
if string =~ Format::ISO_DATE
-
120
new_date $1.to_i, $2.to_i, $3.to_i
-
end
-
end
-
-
2
if RUBY_VERSION >= '1.9'
-
# Doesn't handle time zones.
-
2
def fast_string_to_time(string)
-
636
if string =~ Format::ISO_DATETIME
-
616
microsec = ($7.to_r * 1_000_000).to_i
-
616
new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec
-
end
-
end
-
else
-
def fast_string_to_time(string)
-
if string =~ Format::ISO_DATETIME
-
microsec = ($7.to_f * 1_000_000).round.to_i
-
new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec
-
end
-
end
-
end
-
-
2
def fallback_string_to_date(string)
-
new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday))
-
end
-
-
2
def fallback_string_to_time(string)
-
time_hash = Date._parse(string)
-
time_hash[:sec_fraction] = microseconds(time_hash)
-
-
new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
-
end
-
end
-
-
2
private
-
2
def extract_limit(sql_type)
-
236
$1.to_i if sql_type =~ /\((.*)\)/
-
end
-
-
2
def extract_precision(sql_type)
-
236
$2.to_i if sql_type =~ /^(numeric|decimal|number)\((\d+)(,\d+)?\)/i
-
end
-
-
2
def extract_scale(sql_type)
-
236
case sql_type
-
when /^(numeric|decimal|number)\((\d+)\)/i then 0
-
when /^(numeric|decimal|number)\((\d+)(,(\d+))\)/i then $4.to_i
-
end
-
end
-
-
2
def simplified_type(field_type)
-
236
case field_type
-
when /int/i
-
78
:integer
-
when /float|double/i
-
:float
-
when /decimal|numeric|number/i
-
extract_scale(field_type) == 0 ? :integer : :decimal
-
when /datetime/i
-
66
:datetime
-
when /timestamp/i
-
:timestamp
-
when /time/i
-
2
:time
-
when /date/i
-
14
:date
-
when /clob/i, /text/i
-
4
:text
-
when /blob/i, /binary/i
-
:binary
-
when /char/i, /string/i
-
32
:string
-
when /boolean/i
-
40
:boolean
-
end
-
end
-
end
-
end
-
# :startdoc:
-
end
-
2
module ActiveRecord
-
2
module ConnectionAdapters
-
2
class SchemaCache
-
2
attr_reader :primary_keys, :tables
-
2
attr_reader :connection
-
-
2
def initialize(conn)
-
2
@connection = conn
-
2
@tables = {}
-
-
2
@columns = Hash.new do |h, table_name|
-
17
h[table_name] = connection.columns(table_name, "#{table_name} Columns")
-
end
-
-
2
@columns_hash = Hash.new do |h, table_name|
-
17
h[table_name] = Hash[columns[table_name].map { |col|
-
134
[col.name, col]
-
}]
-
end
-
-
2
@primary_keys = Hash.new do |h, table_name|
-
17
h[table_name] = table_exists?(table_name) ? connection.primary_key(table_name) : nil
-
end
-
end
-
-
# A cached lookup for table existence.
-
2
def table_exists?(name)
-
1516
return @tables[name] if @tables.key? name
-
-
17
@tables[name] = connection.table_exists?(name)
-
end
-
-
# Get the columns for a table
-
2
def columns(table = nil)
-
34
if table
-
@columns[table]
-
else
-
34
@columns
-
end
-
end
-
-
# Get the columns for a table as a hash, key is the column name
-
# value is the column object.
-
2
def columns_hash(table = nil)
-
1508
if table
-
26
@columns_hash[table]
-
else
-
1482
@columns_hash
-
end
-
end
-
-
# Clears out internal caches
-
2
def clear!
-
2
@columns.clear
-
2
@columns_hash.clear
-
2
@primary_keys.clear
-
2
@tables.clear
-
end
-
-
# Clear out internal caches for table with +table_name+.
-
2
def clear_table_cache!(table_name)
-
@columns.delete table_name
-
@columns_hash.delete table_name
-
@primary_keys.delete table_name
-
@tables.delete table_name
-
end
-
end
-
end
-
end
-
2
require 'active_record/connection_adapters/sqlite_adapter'
-
-
2
gem 'sqlite3', '~> 1.3.5'
-
2
require 'sqlite3'
-
-
2
module ActiveRecord
-
2
class Base
-
# sqlite3 adapter reuses sqlite_connection.
-
2
def self.sqlite3_connection(config) # :nodoc:
-
# Require database.
-
2
unless config[:database]
-
raise ArgumentError, "No database file specified. Missing argument: database"
-
end
-
-
# Allow database path relative to Rails.root, but only if
-
# the database path is not the special path that tells
-
# Sqlite to build a database only in memory.
-
2
if defined?(Rails.root) && ':memory:' != config[:database]
-
2
config[:database] = File.expand_path(config[:database], Rails.root)
-
end
-
-
2
unless 'sqlite3' == config[:adapter]
-
raise ArgumentError, 'adapter name should be "sqlite3"'
-
end
-
-
2
db = SQLite3::Database.new(
-
config[:database],
-
:results_as_hash => true
-
)
-
-
2
db.busy_timeout(config[:timeout]) if config[:timeout]
-
-
2
ConnectionAdapters::SQLite3Adapter.new(db, logger, config)
-
end
-
end
-
-
2
module ConnectionAdapters #:nodoc:
-
2
class SQLite3Adapter < SQLiteAdapter # :nodoc:
-
2
def quote(value, column = nil)
-
2360
if value.kind_of?(String) && column && column.type == :binary && column.class.respond_to?(:string_to_binary)
-
s = column.class.string_to_binary(value).unpack("H*")[0]
-
"x'#{s}'"
-
else
-
2360
super
-
end
-
end
-
-
# Returns the current database encoding format as a string, eg: 'UTF-8'
-
2
def encoding
-
@connection.encoding.to_s
-
end
-
-
end
-
end
-
end
-
2
require 'active_record/connection_adapters/abstract_adapter'
-
2
require 'active_record/connection_adapters/statement_pool'
-
2
require 'active_support/core_ext/string/encoding'
-
2
require 'arel/visitors/bind_visitor'
-
-
2
module ActiveRecord
-
2
module ConnectionAdapters #:nodoc:
-
2
class SQLiteColumn < Column #:nodoc:
-
2
class << self
-
2
def binary_to_string(value)
-
if value.respond_to?(:force_encoding) && value.encoding != Encoding::ASCII_8BIT
-
value = value.force_encoding(Encoding::ASCII_8BIT)
-
end
-
value
-
end
-
end
-
end
-
-
# The SQLite adapter works with both the 2.x and 3.x series of SQLite with the sqlite-ruby
-
# drivers (available both as gems and from http://rubyforge.org/projects/sqlite-ruby/).
-
#
-
# Options:
-
#
-
# * <tt>:database</tt> - Path to the database file.
-
2
class SQLiteAdapter < AbstractAdapter
-
2
class Version
-
2
include Comparable
-
-
2
def initialize(version_string)
-
@version = version_string.split('.').map { |v| v.to_i }
-
end
-
-
2
def <=>(version_string)
-
@version <=> version_string.split('.').map { |v| v.to_i }
-
end
-
end
-
-
2
class StatementPool < ConnectionAdapters::StatementPool
-
2
def initialize(connection, max)
-
2
super
-
4
@cache = Hash.new { |h,pid| h[pid] = {} }
-
end
-
-
2
def each(&block); cache.each(&block); end
-
2
def key?(key); cache.key?(key); end
-
460
def [](key); cache[key]; end
-
2
def length; cache.length; end
-
-
2
def []=(sql, key)
-
15
while @max <= cache.size
-
dealloc(cache.shift.last[:stmt])
-
end
-
15
cache[sql] = key
-
end
-
-
2
def clear
-
cache.values.each do |hash|
-
dealloc hash[:stmt]
-
end
-
cache.clear
-
end
-
-
2
private
-
2
def cache
-
488
@cache[$$]
-
end
-
-
2
def dealloc(stmt)
-
stmt.close unless stmt.closed?
-
end
-
end
-
-
2
class BindSubstitution < Arel::Visitors::SQLite # :nodoc:
-
2
include Arel::Visitors::BindVisitor
-
end
-
-
2
def initialize(connection, logger, config)
-
2
super(connection, logger)
-
2
@statements = StatementPool.new(@connection,
-
2
config.fetch(:statement_limit) { 1000 })
-
2
@config = config
-
-
4
if config.fetch(:prepared_statements) { true }
-
2
@visitor = Arel::Visitors::SQLite.new self
-
else
-
@visitor = BindSubstitution.new self
-
end
-
end
-
-
2
def adapter_name #:nodoc:
-
'SQLite'
-
end
-
-
# Returns true if SQLite version is '2.0.0' or greater, false otherwise.
-
2
def supports_ddl_transactions?
-
sqlite_version >= '2.0.0'
-
end
-
-
# Returns true if SQLite version is '3.6.8' or greater, false otherwise.
-
2
def supports_savepoints?
-
sqlite_version >= '3.6.8'
-
end
-
-
# Returns true, since this connection adapter supports prepared statement
-
# caching.
-
2
def supports_statement_cache?
-
true
-
end
-
-
# Returns true, since this connection adapter supports migrations.
-
2
def supports_migrations? #:nodoc:
-
true
-
end
-
-
# Returns true.
-
2
def supports_primary_key? #:nodoc:
-
true
-
end
-
-
# Returns true.
-
2
def supports_explain?
-
1690
true
-
end
-
-
2
def requires_reloading?
-
true
-
end
-
-
# Returns true if SQLite version is '3.1.6' or greater, false otherwise.
-
2
def supports_add_column?
-
sqlite_version >= '3.1.6'
-
end
-
-
# Disconnects from the database if already connected. Otherwise, this
-
# method does nothing.
-
2
def disconnect!
-
super
-
clear_cache!
-
@connection.close rescue nil
-
end
-
-
# Clears the prepared statements cache.
-
2
def clear_cache!
-
@statements.clear
-
end
-
-
# Returns true if SQLite version is '3.2.6' or greater, false otherwise.
-
2
def supports_count_distinct? #:nodoc:
-
sqlite_version >= '3.2.6'
-
end
-
-
# Returns true if SQLite version is '3.1.0' or greater, false otherwise.
-
2
def supports_autoincrement? #:nodoc:
-
sqlite_version >= '3.1.0'
-
end
-
-
2
def supports_index_sort_order?
-
sqlite_version >= '3.3.0'
-
end
-
-
2
def native_database_types #:nodoc:
-
{
-
:primary_key => default_primary_key_type,
-
:string => { :name => "varchar", :limit => 255 },
-
:text => { :name => "text" },
-
:integer => { :name => "integer" },
-
:float => { :name => "float" },
-
:decimal => { :name => "decimal" },
-
:datetime => { :name => "datetime" },
-
:timestamp => { :name => "datetime" },
-
:time => { :name => "time" },
-
:date => { :name => "date" },
-
:binary => { :name => "blob" },
-
:boolean => { :name => "boolean" }
-
}
-
end
-
-
-
# QUOTING ==================================================
-
-
2
def quote_string(s) #:nodoc:
-
66
@connection.class.quote(s)
-
end
-
-
2
def quote_column_name(name) #:nodoc:
-
622
%Q("#{name.to_s.gsub('"', '""')}")
-
end
-
-
# Quote date/time values for use in SQL input. Includes microseconds
-
# if the value is a Time responding to usec.
-
2
def quoted_date(value) #:nodoc:
-
2191
if value.respond_to?(:usec)
-
2081
"#{super}.#{sprintf("%06d", value.usec)}"
-
else
-
110
super
-
end
-
end
-
-
2
if "<3".encoding_aware?
-
2
def type_cast(value, column) # :nodoc:
-
3590
return value.to_f if BigDecimal === value
-
3590
return super unless String === value
-
325
return super unless column && value
-
-
325
value = super
-
325
if column.type == :string && value.encoding == Encoding::ASCII_8BIT
-
logger.error "Binary data inserted for `string` type on column `#{column.name}`" if logger
-
value = value.encode Encoding::UTF_8
-
end
-
325
value
-
end
-
else
-
def type_cast(value, column) # :nodoc:
-
return super unless BigDecimal === value
-
-
value.to_f
-
end
-
end
-
-
# DATABASE STATEMENTS ======================================
-
-
2
def explain(arel, binds = [])
-
sql = "EXPLAIN QUERY PLAN #{to_sql(arel, binds)}"
-
ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds))
-
end
-
-
2
class ExplainPrettyPrinter
-
# Pretty prints the result of a EXPLAIN QUERY PLAN in a way that resembles
-
# the output of the SQLite shell:
-
#
-
# 0|0|0|SEARCH TABLE users USING INTEGER PRIMARY KEY (rowid=?) (~1 rows)
-
# 0|1|1|SCAN TABLE posts (~100000 rows)
-
#
-
2
def pp(result) # :nodoc:
-
result.rows.map do |row|
-
row.join('|')
-
end.join("\n") + "\n"
-
end
-
end
-
-
2
def exec_query(sql, name = nil, binds = [])
-
1359
log(sql, name, binds) do
-
-
# Don't cache statements without bind values
-
1359
if binds.empty?
-
901
stmt = @connection.prepare(sql)
-
901
cols = stmt.columns
-
901
records = stmt.to_a
-
901
stmt.close
-
901
stmt = records
-
else
-
458
cache = @statements[sql] ||= {
-
:stmt => @connection.prepare(sql)
-
}
-
458
stmt = cache[:stmt]
-
458
cols = cache[:cols] ||= stmt.columns
-
458
stmt.reset!
-
458
stmt.bind_params binds.map { |col, val|
-
3590
type_cast(val, col)
-
}
-
end
-
-
1359
ActiveRecord::Result.new(cols, stmt.to_a)
-
end
-
end
-
-
2
def exec_delete(sql, name = 'SQL', binds = [])
-
142
exec_query(sql, name, binds)
-
142
@connection.changes
-
end
-
2
alias :exec_update :exec_delete
-
-
2
def last_inserted_id(result)
-
308
@connection.last_insert_row_id
-
end
-
-
2
def execute(sql, name = nil) #:nodoc:
-
672
log(sql, name) { @connection.execute(sql) }
-
end
-
-
2
def update_sql(sql, name = nil) #:nodoc:
-
super
-
@connection.changes
-
end
-
-
2
def delete_sql(sql, name = nil) #:nodoc:
-
sql += " WHERE 1=1" unless sql =~ /WHERE/i
-
super sql, name
-
end
-
-
2
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
-
super
-
id_value || @connection.last_insert_row_id
-
end
-
2
alias :create :insert_sql
-
-
2
def select_rows(sql, name = nil)
-
exec_query(sql, name).rows
-
end
-
-
2
def create_savepoint
-
155
execute("SAVEPOINT #{current_savepoint_name}")
-
end
-
-
2
def rollback_to_savepoint
-
24
execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}")
-
end
-
-
2
def release_savepoint
-
131
execute("RELEASE SAVEPOINT #{current_savepoint_name}")
-
end
-
-
2
def begin_db_transaction #:nodoc:
-
294
log('begin transaction',nil) { @connection.transaction }
-
end
-
-
2
def commit_db_transaction #:nodoc:
-
4
log('commit transaction',nil) { @connection.commit }
-
end
-
-
2
def rollback_db_transaction #:nodoc:
-
290
log('rollback transaction',nil) { @connection.rollback }
-
end
-
-
# SCHEMA STATEMENTS ========================================
-
-
2
def tables(name = 'SCHEMA', table_name = nil) #:nodoc:
-
17
sql = <<-SQL
-
SELECT name
-
FROM sqlite_master
-
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-
SQL
-
17
sql << " AND name = #{quote_table_name(table_name)}" if table_name
-
-
17
exec_query(sql, name).map do |row|
-
17
row['name']
-
end
-
end
-
-
2
def table_exists?(name)
-
17
name && tables('SCHEMA', name).any?
-
end
-
-
# Returns an array of +SQLiteColumn+ objects for the table specified by +table_name+.
-
2
def columns(table_name, name = nil) #:nodoc:
-
31
table_structure(table_name).map do |field|
-
236
case field["dflt_value"]
-
when /^null$/i
-
field["dflt_value"] = nil
-
when /^'(.*)'$/
-
field["dflt_value"] = $1.gsub(/''/, "'")
-
when /^"(.*)"$/
-
field["dflt_value"] = $1.gsub(/""/, '"')
-
end
-
-
236
SQLiteColumn.new(field['name'], field['dflt_value'], field['type'], field['notnull'].to_i == 0)
-
end
-
end
-
-
# Returns an array of indexes for the given table.
-
2
def indexes(table_name, name = nil) #:nodoc:
-
exec_query("PRAGMA index_list(#{quote_table_name(table_name)})", 'SCHEMA').map do |row|
-
IndexDefinition.new(
-
table_name,
-
row['name'],
-
row['unique'] != 0,
-
exec_query("PRAGMA index_info('#{row['name']}')", 'SCHEMA').map { |col|
-
col['name']
-
})
-
end
-
end
-
-
2
def primary_key(table_name) #:nodoc:
-
17
column = table_structure(table_name).find { |field|
-
17
field['pk'] == 1
-
}
-
17
column && column['name']
-
end
-
-
2
def remove_index!(table_name, index_name) #:nodoc:
-
exec_query "DROP INDEX #{quote_column_name(index_name)}"
-
end
-
-
# Renames a table.
-
#
-
# Example:
-
# rename_table('octopuses', 'octopi')
-
2
def rename_table(name, new_name)
-
exec_query "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}"
-
end
-
-
# See: http://www.sqlite.org/lang_altertable.html
-
# SQLite has an additional restriction on the ALTER TABLE statement
-
2
def valid_alter_table_options( type, options)
-
type.to_sym != :primary_key
-
end
-
-
2
def add_column(table_name, column_name, type, options = {}) #:nodoc:
-
if supports_add_column? && valid_alter_table_options( type, options )
-
super(table_name, column_name, type, options)
-
else
-
alter_table(table_name) do |definition|
-
definition.column(column_name, type, options)
-
end
-
end
-
end
-
-
2
def remove_column(table_name, *column_names) #:nodoc:
-
raise ArgumentError.new("You must specify at least one column name. Example: remove_column(:people, :first_name)") if column_names.empty?
-
-
if column_names.flatten!
-
message = 'Passing array to remove_columns is deprecated, please use ' +
-
'multiple arguments, like: `remove_columns(:posts, :foo, :bar)`'
-
ActiveSupport::Deprecation.warn message, caller
-
end
-
-
column_names.each do |column_name|
-
alter_table(table_name) do |definition|
-
definition.columns.delete(definition[column_name])
-
end
-
end
-
end
-
2
alias :remove_columns :remove_column
-
-
2
def change_column_default(table_name, column_name, default) #:nodoc:
-
alter_table(table_name) do |definition|
-
definition[column_name].default = default
-
end
-
end
-
-
2
def change_column_null(table_name, column_name, null, default = nil)
-
unless null || default.nil?
-
exec_query("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
-
end
-
alter_table(table_name) do |definition|
-
definition[column_name].null = null
-
end
-
end
-
-
2
def change_column(table_name, column_name, type, options = {}) #:nodoc:
-
alter_table(table_name) do |definition|
-
include_default = options_include_default?(options)
-
definition[column_name].instance_eval do
-
self.type = type
-
self.limit = options[:limit] if options.include?(:limit)
-
self.default = options[:default] if include_default
-
self.null = options[:null] if options.include?(:null)
-
self.precision = options[:precision] if options.include?(:precision)
-
self.scale = options[:scale] if options.include?(:scale)
-
end
-
end
-
end
-
-
2
def rename_column(table_name, column_name, new_column_name) #:nodoc:
-
unless columns(table_name).detect{|c| c.name == column_name.to_s }
-
raise ActiveRecord::ActiveRecordError, "Missing column #{table_name}.#{column_name}"
-
end
-
alter_table(table_name, :rename => {column_name.to_s => new_column_name.to_s})
-
end
-
-
2
def empty_insert_statement_value
-
"VALUES(NULL)"
-
end
-
-
2
protected
-
2
def select(sql, name = nil, binds = []) #:nodoc:
-
844
exec_query(sql, name, binds).to_a
-
end
-
-
2
def table_structure(table_name)
-
48
structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", 'SCHEMA').to_hash
-
48
raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty?
-
48
structure
-
end
-
-
2
def alter_table(table_name, options = {}) #:nodoc:
-
altered_table_name = "altered_#{table_name}"
-
caller = lambda {|definition| yield definition if block_given?}
-
-
transaction do
-
move_table(table_name, altered_table_name,
-
options.merge(:temporary => true))
-
move_table(altered_table_name, table_name, &caller)
-
end
-
end
-
-
2
def move_table(from, to, options = {}, &block) #:nodoc:
-
copy_table(from, to, options, &block)
-
drop_table(from)
-
end
-
-
2
def copy_table(from, to, options = {}) #:nodoc:
-
from_primary_key = primary_key(from)
-
options[:primary_key] = from_primary_key if from_primary_key != 'id'
-
unless options[:primary_key]
-
options[:id] = !columns(from).detect{|c| c.name == 'id'}.nil? && 'id' == from_primary_key
-
end
-
create_table(to, options) do |definition|
-
@definition = definition
-
columns(from).each do |column|
-
column_name = options[:rename] ?
-
(options[:rename][column.name] ||
-
options[:rename][column.name.to_sym] ||
-
column.name) : column.name
-
-
@definition.column(column_name, column.type,
-
:limit => column.limit, :default => column.default,
-
:precision => column.precision, :scale => column.scale,
-
:null => column.null)
-
end
-
@definition.primary_key(from_primary_key) if from_primary_key
-
yield @definition if block_given?
-
end
-
-
copy_table_indexes(from, to, options[:rename] || {})
-
copy_table_contents(from, to,
-
@definition.columns.map {|column| column.name},
-
options[:rename] || {})
-
end
-
-
2
def copy_table_indexes(from, to, rename = {}) #:nodoc:
-
indexes(from).each do |index|
-
name = index.name
-
if to == "altered_#{from}"
-
name = "temp_#{name}"
-
elsif from == "altered_#{to}"
-
name = name[5..-1]
-
end
-
-
to_column_names = columns(to).map { |c| c.name }
-
columns = index.columns.map {|c| rename[c] || c }.select do |column|
-
to_column_names.include?(column)
-
end
-
-
unless columns.empty?
-
# index name can't be the same
-
opts = { :name => name.gsub(/(^|_)(#{from})_/, "\\1#{to}_") }
-
opts[:unique] = true if index.unique
-
add_index(to, columns, opts)
-
end
-
end
-
end
-
-
2
def copy_table_contents(from, to, columns, rename = {}) #:nodoc:
-
column_mappings = Hash[columns.map {|name| [name, name]}]
-
rename.each { |a| column_mappings[a.last] = a.first }
-
from_columns = columns(from).collect {|col| col.name}
-
columns = columns.find_all{|col| from_columns.include?(column_mappings[col])}
-
quoted_columns = columns.map { |col| quote_column_name(col) } * ','
-
-
quoted_to = quote_table_name(to)
-
exec_query("SELECT * FROM #{quote_table_name(from)}").each do |row|
-
sql = "INSERT INTO #{quoted_to} (#{quoted_columns}) VALUES ("
-
sql << columns.map {|col| quote row[column_mappings[col]]} * ', '
-
sql << ')'
-
exec_query sql
-
end
-
end
-
-
2
def sqlite_version
-
@sqlite_version ||= SQLiteAdapter::Version.new(select_value('select sqlite_version(*)'))
-
end
-
-
2
def default_primary_key_type
-
if supports_autoincrement?
-
'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL'
-
else
-
'INTEGER PRIMARY KEY NOT NULL'
-
end
-
end
-
-
2
def translate_exception(exception, message)
-
case exception.message
-
when /column(s)? .* (is|are) not unique/
-
RecordNotUnique.new(message, exception)
-
else
-
super
-
end
-
end
-
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module ConnectionAdapters
-
2
class StatementPool
-
2
include Enumerable
-
-
2
def initialize(connection, max = 1000)
-
2
@connection = connection
-
2
@max = max
-
end
-
-
2
def each
-
raise NotImplementedError
-
end
-
-
2
def key?(key)
-
raise NotImplementedError
-
end
-
-
2
def [](key)
-
raise NotImplementedError
-
end
-
-
2
def length
-
raise NotImplementedError
-
end
-
-
2
def []=(sql, key)
-
raise NotImplementedError
-
end
-
-
2
def clear
-
raise NotImplementedError
-
end
-
-
2
def delete(key)
-
raise NotImplementedError
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
# = Active Record Counter Cache
-
2
module CounterCache
-
# Resets one or more counter caches to their correct value using an SQL
-
# count query. This is useful when adding new counter caches, or if the
-
# counter has been corrupted or modified directly by SQL.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - The id of the object you wish to reset a counter on.
-
# * +counters+ - One or more counter names to reset
-
#
-
# ==== Examples
-
#
-
# # For Post with id #1 records reset the comments_count
-
# Post.reset_counters(1, :comments)
-
2
def reset_counters(id, *counters)
-
object = find(id)
-
counters.each do |association|
-
has_many_association = reflect_on_association(association.to_sym)
-
-
if has_many_association.options[:as]
-
has_many_association.options[:as].to_s.classify
-
else
-
self.name
-
end
-
-
if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
-
has_many_association = has_many_association.through_reflection
-
end
-
-
foreign_key = has_many_association.foreign_key.to_s
-
child_class = has_many_association.klass
-
belongs_to = child_class.reflect_on_all_associations(:belongs_to)
-
reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? }
-
counter_name = reflection.counter_cache_column
-
-
stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
-
arel_table[counter_name] => object.send(association).count
-
})
-
connection.update stmt
-
end
-
return true
-
end
-
-
# A generic "counter updater" implementation, intended primarily to be
-
# used by increment_counter and decrement_counter, but which may also
-
# be useful on its own. It simply does a direct SQL update for the record
-
# with the given ID, altering the given hash of counters by the amount
-
# given by the corresponding value:
-
#
-
# ==== Parameters
-
#
-
# * +id+ - The id of the object you wish to update a counter on or an Array of ids.
-
# * +counters+ - An Array of Hashes containing the names of the fields
-
# to update as keys and the amount to update the field by as values.
-
#
-
# ==== Examples
-
#
-
# # For the Post with id of 5, decrement the comment_count by 1, and
-
# # increment the action_count by 1
-
# Post.update_counters 5, :comment_count => -1, :action_count => 1
-
# # Executes the following SQL:
-
# # UPDATE posts
-
# # SET comment_count = COALESCE(comment_count, 0) - 1,
-
# # action_count = COALESCE(action_count, 0) + 1
-
# # WHERE id = 5
-
#
-
# # For the Posts with id of 10 and 15, increment the comment_count by 1
-
# Post.update_counters [10, 15], :comment_count => 1
-
# # Executes the following SQL:
-
# # UPDATE posts
-
# # SET comment_count = COALESCE(comment_count, 0) + 1
-
# # WHERE id IN (10, 15)
-
2
def update_counters(id, counters)
-
updates = counters.map do |counter_name, value|
-
operator = value < 0 ? '-' : '+'
-
quoted_column = connection.quote_column_name(counter_name)
-
"#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}"
-
end
-
-
IdentityMap.remove_by_id(symbolized_base_class, id) if IdentityMap.enabled?
-
-
update_all(updates.join(', '), primary_key => id )
-
end
-
-
# Increment a number field by one, usually representing a count.
-
#
-
# This is used for caching aggregate values, so that they don't need to be computed every time.
-
# For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is
-
# shown it would have to run an SQL query to find how many posts and comments there are.
-
#
-
# ==== Parameters
-
#
-
# * +counter_name+ - The name of the field that should be incremented.
-
# * +id+ - The id of the object that should be incremented.
-
#
-
# ==== Examples
-
#
-
# # Increment the post_count column for the record with an id of 5
-
# DiscussionBoard.increment_counter(:post_count, 5)
-
2
def increment_counter(counter_name, id)
-
update_counters(id, counter_name => 1)
-
end
-
-
# Decrement a number field by one, usually representing a count.
-
#
-
# This works the same as increment_counter but reduces the column value by 1 instead of increasing it.
-
#
-
# ==== Parameters
-
#
-
# * +counter_name+ - The name of the field that should be decremented.
-
# * +id+ - The id of the object that should be decremented.
-
#
-
# ==== Examples
-
#
-
# # Decrement the post_count column for the record with an id of 5
-
# DiscussionBoard.decrement_counter(:post_count, 5)
-
2
def decrement_counter(counter_name, id)
-
update_counters(id, counter_name => -1)
-
end
-
end
-
end
-
2
module ActiveRecord
-
-
# = Active Record Dynamic Finder Match
-
#
-
# Refer to ActiveRecord::Base documentation for Dynamic attribute-based finders for detailed info
-
#
-
2
class DynamicFinderMatch
-
2
def self.match(method)
-
1476
finder = :first
-
1476
bang = false
-
1476
instantiator = nil
-
-
1476
case method.to_s
-
when /^find_(all_|last_)?by_([_a-zA-Z]\w*)$/
-
27
finder = :last if $1 == 'last_'
-
27
finder = :all if $1 == 'all_'
-
27
names = $2
-
when /^find_by_([_a-zA-Z]\w*)\!$/
-
bang = true
-
names = $1
-
when /^find_or_create_by_([_a-zA-Z]\w*)\!$/
-
bang = true
-
instantiator = :create
-
names = $1
-
when /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/
-
instantiator = $1 == 'initialize' ? :new : :create
-
names = $2
-
else
-
1449
return nil
-
end
-
-
27
new(finder, instantiator, bang, names.split('_and_'))
-
end
-
-
2
def initialize(finder, instantiator, bang, attribute_names)
-
27
@finder = finder
-
27
@instantiator = instantiator
-
27
@bang = bang
-
27
@attribute_names = attribute_names
-
end
-
-
2
attr_reader :finder, :attribute_names, :instantiator
-
-
2
def finder?
-
27
@finder && !@instantiator
-
end
-
-
2
def instantiator?
-
27
@finder == :first && @instantiator
-
end
-
-
2
def creator?
-
@finder == :first && @instantiator == :create
-
end
-
-
2
def bang?
-
27
@bang
-
end
-
-
2
def save_record?
-
@instantiator == :create
-
end
-
-
2
def save_method
-
bang? ? :save! : :save
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module DynamicMatchers
-
2
def respond_to?(method_id, include_private = false)
-
1167
if match = DynamicFinderMatch.match(method_id)
-
return true if all_attributes_exists?(match.attribute_names)
-
elsif match = DynamicScopeMatch.match(method_id)
-
return true if all_attributes_exists?(match.attribute_names)
-
end
-
-
1167
super
-
end
-
-
2
private
-
-
# Enables dynamic finders like <tt>User.find_by_user_name(user_name)</tt> and
-
# <tt>User.scoped_by_user_name(user_name). Refer to Dynamic attribute-based finders
-
# section at the top of this file for more detailed information.
-
#
-
# It's even possible to use all the additional parameters to +find+. For example, the
-
# full interface for +find_all_by_amount+ is actually <tt>find_all_by_amount(amount, options)</tt>.
-
#
-
# Each dynamic finder using <tt>scoped_by_*</tt> is also defined in the class after it
-
# is first invoked, so that future attempts to use it do not run through method_missing.
-
2
def method_missing(method_id, *arguments, &block)
-
27
if match = (DynamicFinderMatch.match(method_id) || DynamicScopeMatch.match(method_id))
-
27
attribute_names = match.attribute_names
-
27
super unless all_attributes_exists?(attribute_names)
-
27
if !(match.is_a?(DynamicFinderMatch) && match.instantiator? && arguments.first.is_a?(Hash)) && arguments.size < attribute_names.size
-
method_trace = "#{__FILE__}:#{__LINE__}:in `#{method_id}'"
-
backtrace = [method_trace] + caller
-
raise ArgumentError, "wrong number of arguments (#{arguments.size} for #{attribute_names.size})", backtrace
-
end
-
27
if match.respond_to?(:scope?) && match.scope?
-
self.class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def self.#{method_id}(*args) # def self.scoped_by_user_name_and_password(*args)
-
attributes = Hash[[:#{attribute_names.join(',:')}].zip(args)] # attributes = Hash[[:user_name, :password].zip(args)]
-
#
-
scoped(:conditions => attributes) # scoped(:conditions => attributes)
-
end # end
-
METHOD
-
send(method_id, *arguments)
-
27
elsif match.finder?
-
27
options = if arguments.length > attribute_names.size
-
arguments.extract_options!
-
else
-
27
{}
-
end
-
-
27
relation = options.any? ? scoped(options) : scoped
-
27
relation.send :find_by_attributes, match, attribute_names, *arguments, &block
-
elsif match.instantiator?
-
scoped.send :find_or_instantiator_by_attributes, match, attribute_names, *arguments, &block
-
end
-
else
-
super
-
end
-
end
-
-
# Similar in purpose to +expand_hash_conditions_for_aggregates+.
-
2
def expand_attribute_names_for_aggregates(attribute_names)
-
27
attribute_names.map { |attribute_name|
-
27
unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil?
-
aggregate_mapping(aggregation).map do |field_attr, _|
-
field_attr.to_sym
-
end
-
else
-
27
attribute_name.to_sym
-
end
-
}.flatten
-
end
-
-
2
def all_attributes_exists?(attribute_names)
-
(expand_attribute_names_for_aggregates(attribute_names) -
-
27
column_methods_hash.keys).empty?
-
end
-
-
2
def aggregate_mapping(reflection)
-
mapping = reflection.options[:mapping] || [reflection.name, reflection.name]
-
mapping.first.is_a?(Array) ? mapping : [mapping]
-
end
-
-
-
end
-
end
-
2
module ActiveRecord
-
-
# = Active Record Dynamic Scope Match
-
#
-
# Provides dynamic attribute-based scopes such as <tt>scoped_by_price(4.99)</tt>
-
# if, for example, the <tt>Product</tt> has an attribute with that name. You can
-
# chain more <tt>scoped_by_* </tt> methods after the other. It acts like a named
-
# scope except that it's dynamic.
-
2
class DynamicScopeMatch
-
2
def self.match(method)
-
1167
return unless method.to_s =~ /^scoped_by_([_a-zA-Z]\w*)$/
-
new(true, $1 && $1.split('_and_'))
-
end
-
-
2
def initialize(scope, attribute_names)
-
@scope = scope
-
@attribute_names = attribute_names
-
end
-
-
2
attr_reader :scope, :attribute_names
-
2
alias :scope? :scope
-
end
-
end
-
2
module ActiveRecord
-
-
# = Active Record Errors
-
#
-
# Generic Active Record exception class.
-
2
class ActiveRecordError < StandardError
-
end
-
-
# Raised when the single-table inheritance mechanism fails to locate the subclass
-
# (for example due to improper usage of column that +inheritance_column+ points to).
-
2
class SubclassNotFound < ActiveRecordError #:nodoc:
-
end
-
-
# Raised when an object assigned to an association has an incorrect type.
-
#
-
# class Ticket < ActiveRecord::Base
-
# has_many :patches
-
# end
-
#
-
# class Patch < ActiveRecord::Base
-
# belongs_to :ticket
-
# end
-
#
-
# # Comments are not patches, this assignment raises AssociationTypeMismatch.
-
# @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
-
2
class AssociationTypeMismatch < ActiveRecordError
-
end
-
-
# Raised when unserialized object's type mismatches one specified for serializable field.
-
2
class SerializationTypeMismatch < ActiveRecordError
-
end
-
-
# Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt>
-
# misses adapter field).
-
2
class AdapterNotSpecified < ActiveRecordError
-
end
-
-
# Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically.
-
2
class AdapterNotFound < ActiveRecordError
-
end
-
-
# Raised when connection to the database could not been established (for example when <tt>connection=</tt>
-
# is given a nil object).
-
2
class ConnectionNotEstablished < ActiveRecordError
-
end
-
-
# Raised when Active Record cannot find record by given id or set of ids.
-
2
class RecordNotFound < ActiveRecordError
-
end
-
-
# Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
-
# saved because record is invalid.
-
2
class RecordNotSaved < ActiveRecordError
-
end
-
-
# Raised when SQL statement cannot be executed by the database (for example, it's often the case for
-
# MySQL when Ruby driver used is too old).
-
2
class StatementInvalid < ActiveRecordError
-
end
-
-
# Raised when SQL statement is invalid and the application gets a blank result.
-
2
class ThrowResult < ActiveRecordError
-
end
-
-
# Parent class for all specific exceptions which wrap database driver exceptions
-
# provides access to the original exception also.
-
2
class WrappedDatabaseException < StatementInvalid
-
2
attr_reader :original_exception
-
-
2
def initialize(message, original_exception)
-
super(message)
-
@original_exception = original_exception
-
end
-
end
-
-
# Raised when a record cannot be inserted because it would violate a uniqueness constraint.
-
2
class RecordNotUnique < WrappedDatabaseException
-
end
-
-
# Raised when a record cannot be inserted or updated because it references a non-existent record.
-
2
class InvalidForeignKey < WrappedDatabaseException
-
end
-
-
# Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example,
-
# when using +find+ method)
-
# does not match number of expected variables.
-
#
-
# For example, in
-
#
-
# Location.where("lat = ? AND lng = ?", 53.7362)
-
#
-
# two placeholders are given but only one variable to fill them.
-
2
class PreparedStatementInvalid < ActiveRecordError
-
end
-
-
# Raised on attempt to save stale record. Record is stale when it's being saved in another query after
-
# instantiation, for example, when two users edit the same wiki page and one starts editing and saves
-
# the page before the other.
-
#
-
# Read more about optimistic locking in ActiveRecord::Locking module RDoc.
-
2
class StaleObjectError < ActiveRecordError
-
2
attr_reader :record, :attempted_action
-
-
2
def initialize(record, attempted_action)
-
@record = record
-
@attempted_action = attempted_action
-
end
-
-
2
def message
-
"Attempted to #{attempted_action} a stale object: #{record.class.name}"
-
end
-
end
-
-
# Raised when association is being configured improperly or
-
# user tries to use offset and limit together with has_many or has_and_belongs_to_many associations.
-
2
class ConfigurationError < ActiveRecordError
-
end
-
-
# Raised on attempt to update record that is instantiated as read only.
-
2
class ReadOnlyRecord < ActiveRecordError
-
end
-
-
# ActiveRecord::Transactions::ClassMethods.transaction uses this exception
-
# to distinguish a deliberate rollback from other exceptional situations.
-
# Normally, raising an exception will cause the +transaction+ method to rollback
-
# the database transaction *and* pass on the exception. But if you raise an
-
# ActiveRecord::Rollback exception, then the database transaction will be rolled back,
-
# without passing on the exception.
-
#
-
# For example, you could do this in your controller to rollback a transaction:
-
#
-
# class BooksController < ActionController::Base
-
# def create
-
# Book.transaction do
-
# book = Book.new(params[:book])
-
# book.save!
-
# if today_is_friday?
-
# # The system must fail on Friday so that our support department
-
# # won't be out of job. We silently rollback this transaction
-
# # without telling the user.
-
# raise ActiveRecord::Rollback, "Call tech support!"
-
# end
-
# end
-
# # ActiveRecord::Rollback is the only exception that won't be passed on
-
# # by ActiveRecord::Base.transaction, so this line will still be reached
-
# # even on Friday.
-
# redirect_to root_url
-
# end
-
# end
-
2
class Rollback < ActiveRecordError
-
end
-
-
# Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods).
-
2
class DangerousAttributeError < ActiveRecordError
-
end
-
-
# Raised when unknown attributes are supplied via mass assignment.
-
2
class UnknownAttributeError < NoMethodError
-
end
-
-
# Raised when an error occurred while doing a mass assignment to an attribute through the
-
# <tt>attributes=</tt> method. The exception has an +attribute+ property that is the name of the
-
# offending attribute.
-
2
class AttributeAssignmentError < ActiveRecordError
-
2
attr_reader :exception, :attribute
-
2
def initialize(message, exception, attribute)
-
@exception = exception
-
@attribute = attribute
-
@message = message
-
end
-
end
-
-
# Raised when there are multiple errors while doing a mass assignment through the +attributes+
-
# method. The exception has an +errors+ property that contains an array of AttributeAssignmentError
-
# objects, each corresponding to the error while assigning to an attribute.
-
2
class MultiparameterAssignmentErrors < ActiveRecordError
-
2
attr_reader :errors
-
2
def initialize(errors)
-
@errors = errors
-
end
-
end
-
-
# Raised when a primary key is needed, but there is not one specified in the schema or model.
-
2
class UnknownPrimaryKey < ActiveRecordError
-
2
attr_reader :model
-
-
2
def initialize(model)
-
@model = model
-
end
-
-
2
def message
-
"Unknown primary key for table #{model.table_name} in model #{model}."
-
end
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
-
2
module ActiveRecord
-
2
module Explain
-
2
def self.extended(base)
-
2
base.class_eval do
-
# If a query takes longer than these many seconds we log its query plan
-
# automatically. nil disables this feature.
-
2
class_attribute :auto_explain_threshold_in_seconds, :instance_writer => false
-
2
self.auto_explain_threshold_in_seconds = nil
-
end
-
end
-
-
# If the database adapter supports explain and auto explain is enabled,
-
# this method triggers EXPLAIN logging for the queries triggered by the
-
# block if it takes more than the threshold as a whole. That is, the
-
# threshold is not checked against each individual query, but against the
-
# duration of the entire block. This approach is convenient for relations.
-
-
#
-
# The available_queries_for_explain thread variable collects the queries
-
# to be explained. If the value is nil, it means queries are not being
-
# currently collected. A false value indicates collecting is turned
-
# off. Otherwise it is an array of queries.
-
2
def logging_query_plan # :nodoc:
-
1690
return yield unless logger
-
-
1690
threshold = auto_explain_threshold_in_seconds
-
1690
current = Thread.current
-
1690
if connection.supports_explain? && threshold && current[:available_queries_for_explain].nil?
-
begin
-
queries = current[:available_queries_for_explain] = []
-
start = Time.now
-
result = yield
-
logger.warn(exec_explain(queries)) if Time.now - start > threshold
-
result
-
ensure
-
current[:available_queries_for_explain] = nil
-
end
-
else
-
1690
yield
-
end
-
end
-
-
# Relation#explain needs to be able to collect the queries regardless of
-
# whether auto explain is enabled. This method serves that purpose.
-
2
def collecting_queries_for_explain # :nodoc:
-
current = Thread.current
-
original, current[:available_queries_for_explain] = current[:available_queries_for_explain], []
-
return yield, current[:available_queries_for_explain]
-
ensure
-
# Note that the return value above does not depend on this assigment.
-
current[:available_queries_for_explain] = original
-
end
-
-
# Makes the adapter execute EXPLAIN for the tuples of queries and bindings.
-
# Returns a formatted string ready to be logged.
-
2
def exec_explain(queries) # :nodoc:
-
queries && queries.map do |sql, bind|
-
[].tap do |msg|
-
msg << "EXPLAIN for: #{sql}"
-
unless bind.empty?
-
bind_msg = bind.map {|col, val| [col.name, val]}.inspect
-
msg.last << " #{bind_msg}"
-
end
-
msg << connection.explain(sql, bind)
-
end.join("\n")
-
end.join("\n")
-
end
-
-
# Silences automatic EXPLAIN logging for the duration of the block.
-
#
-
# This has high priority, no EXPLAINs will be run even if downwards
-
# the threshold is set to 0.
-
#
-
# As the name of the method suggests this only applies to automatic
-
# EXPLAINs, manual calls to +ActiveRecord::Relation#explain+ run.
-
2
def silence_auto_explain
-
current = Thread.current
-
original, current[:available_queries_for_explain] = current[:available_queries_for_explain], false
-
yield
-
ensure
-
current[:available_queries_for_explain] = original
-
end
-
end
-
end
-
2
require 'active_support/notifications'
-
-
2
module ActiveRecord
-
2
class ExplainSubscriber # :nodoc:
-
2
def call(*args)
-
1989
if queries = Thread.current[:available_queries_for_explain]
-
payload = args.last
-
queries << payload.values_at(:sql, :binds) unless ignore_payload?(payload)
-
end
-
end
-
-
# SCHEMA queries cannot be EXPLAINed, also we do not want to run EXPLAIN on
-
# our own EXPLAINs now matter how loopingly beautiful that would be.
-
#
-
# On the other hand, we want to monitor the performance of our real database
-
# queries, not the performance of the access to the query cache.
-
2
IGNORED_PAYLOADS = %w(SCHEMA EXPLAIN CACHE)
-
2
EXPLAINED_SQLS = /\A\s*(select|update|delete|insert)\b/i
-
2
def ignore_payload?(payload)
-
payload[:exception] || IGNORED_PAYLOADS.include?(payload[:name]) || payload[:sql] !~ EXPLAINED_SQLS
-
end
-
-
2
ActiveSupport::Notifications.subscribe("sql.active_record", new)
-
end
-
end
-
2
require 'erb'
-
-
2
begin
-
2
require 'psych'
-
rescue LoadError
-
end
-
-
2
require 'yaml'
-
2
require 'zlib'
-
2
require 'active_support/dependencies'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/logger'
-
2
require 'active_support/ordered_hash'
-
2
require 'active_record/fixtures/file'
-
-
2
if defined? ActiveRecord
-
2
class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc:
-
end
-
else
-
class FixtureClassNotFound < StandardError #:nodoc:
-
end
-
end
-
-
2
module ActiveRecord
-
# \Fixtures are a way of organizing data that you want to test against; in short, sample data.
-
#
-
# They are stored in YAML files, one file per model, which are placed in the directory
-
# appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically
-
# configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/</tt>).
-
# The fixture file ends with the <tt>.yml</tt> file extension (Rails example:
-
# <tt><your-rails-app>/test/fixtures/web_sites.yml</tt>). The format of a fixture file looks
-
# like this:
-
#
-
# rubyonrails:
-
# id: 1
-
# name: Ruby on Rails
-
# url: http://www.rubyonrails.org
-
#
-
# google:
-
# id: 2
-
# name: Google
-
# url: http://www.google.com
-
#
-
# This fixture file includes two fixtures. Each YAML fixture (ie. record) is given a name and
-
# is followed by an indented list of key/value pairs in the "key: value" format. Records are
-
# separated by a blank line for your viewing pleasure.
-
#
-
# Note that fixtures are unordered. If you want ordered fixtures, use the omap YAML type.
-
# See http://yaml.org/type/omap.html
-
# for the specification. You will need ordered fixtures when you have foreign key constraints
-
# on keys in the same table. This is commonly needed for tree structures. Example:
-
#
-
# --- !omap
-
# - parent:
-
# id: 1
-
# parent_id: NULL
-
# title: Parent
-
# - child:
-
# id: 2
-
# parent_id: 1
-
# title: Child
-
#
-
# = Using Fixtures in Test Cases
-
#
-
# Since fixtures are a testing construct, we use them in our unit and functional tests. There
-
# are two ways to use the fixtures, but first let's take a look at a sample unit test:
-
#
-
# require 'test_helper'
-
#
-
# class WebSiteTest < ActiveSupport::TestCase
-
# test "web_site_count" do
-
# assert_equal 2, WebSite.count
-
# end
-
# end
-
#
-
# By default, <tt>test_helper.rb</tt> will load all of your fixtures into your test database,
-
# so this test will succeed.
-
#
-
# The testing environment will automatically load the all fixtures into the database before each
-
# test. To ensure consistent data, the environment deletes the fixtures before running the load.
-
#
-
# In addition to being available in the database, the fixture's data may also be accessed by
-
# using a special dynamic method, which has the same name as the model, and accepts the
-
# name of the fixture to instantiate:
-
#
-
# test "find" do
-
# assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
-
# end
-
#
-
# Alternatively, you may enable auto-instantiation of the fixture data. For instance, take the
-
# following tests:
-
#
-
# test "find_alt_method_1" do
-
# assert_equal "Ruby on Rails", @web_sites['rubyonrails']['name']
-
# end
-
#
-
# test "find_alt_method_2" do
-
# assert_equal "Ruby on Rails", @rubyonrails.news
-
# end
-
#
-
# In order to use these methods to access fixtured data within your testcases, you must specify one of the
-
# following in your <tt>ActiveSupport::TestCase</tt>-derived class:
-
#
-
# - to fully enable instantiated fixtures (enable alternate methods #1 and #2 above)
-
# self.use_instantiated_fixtures = true
-
#
-
# - create only the hash for the fixtures, do not 'find' each instance (enable alternate method #1 only)
-
# self.use_instantiated_fixtures = :no_instances
-
#
-
# Using either of these alternate methods incurs a performance hit, as the fixtured data must be fully
-
# traversed in the database to create the fixture hash and/or instance variables. This is expensive for
-
# large sets of fixtured data.
-
#
-
# = Dynamic fixtures with ERB
-
#
-
# Some times you don't care about the content of the fixtures as much as you care about the volume.
-
# In these cases, you can mix ERB in with your YAML fixtures to create a bunch of fixtures for load
-
# testing, like:
-
#
-
# <% 1.upto(1000) do |i| %>
-
# fix_<%= i %>:
-
# id: <%= i %>
-
# name: guy_<%= 1 %>
-
# <% end %>
-
#
-
# This will create 1000 very simple fixtures.
-
#
-
# Using ERB, you can also inject dynamic values into your fixtures with inserts like
-
# <tt><%= Date.today.strftime("%Y-%m-%d") %></tt>.
-
# This is however a feature to be used with some caution. The point of fixtures are that they're
-
# stable units of predictable sample data. If you feel that you need to inject dynamic values, then
-
# perhaps you should reexamine whether your application is properly testable. Hence, dynamic values
-
# in fixtures are to be considered a code smell.
-
#
-
# = Transactional Fixtures
-
#
-
# Test cases can use begin+rollback to isolate their changes to the database instead of having to
-
# delete+insert for every test case.
-
#
-
# class FooTest < ActiveSupport::TestCase
-
# self.use_transactional_fixtures = true
-
#
-
# test "godzilla" do
-
# assert !Foo.all.empty?
-
# Foo.destroy_all
-
# assert Foo.all.empty?
-
# end
-
#
-
# test "godzilla aftermath" do
-
# assert !Foo.all.empty?
-
# end
-
# end
-
#
-
# If you preload your test database with all fixture data (probably in the rake task) and use
-
# transactional fixtures, then you may omit all fixtures declarations in your test cases since
-
# all the data's already there and every case rolls back its changes.
-
#
-
# In order to use instantiated fixtures with preloaded data, set +self.pre_loaded_fixtures+ to
-
# true. This will provide access to fixture data for every table that has been loaded through
-
# fixtures (depending on the value of +use_instantiated_fixtures+).
-
#
-
# When *not* to use transactional fixtures:
-
#
-
# 1. You're testing whether a transaction works correctly. Nested transactions don't commit until
-
# all parent transactions commit, particularly, the fixtures transaction which is begun in setup
-
# and rolled back in teardown. Thus, you won't be able to verify
-
# the results of your transaction until Active Record supports nested transactions or savepoints (in progress).
-
# 2. Your database does not support transactions. Every Active Record database supports transactions except MySQL MyISAM.
-
# Use InnoDB, MaxDB, or NDB instead.
-
#
-
# = Advanced Fixtures
-
#
-
# Fixtures that don't specify an ID get some extra features:
-
#
-
# * Stable, autogenerated IDs
-
# * Label references for associations (belongs_to, has_one, has_many)
-
# * HABTM associations as inline lists
-
# * Autofilled timestamp columns
-
# * Fixture label interpolation
-
# * Support for YAML defaults
-
#
-
# == Stable, Autogenerated IDs
-
#
-
# Here, have a monkey fixture:
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
#
-
# reginald:
-
# id: 2
-
# name: Reginald the Pirate
-
#
-
# Each of these fixtures has two unique identifiers: one for the database
-
# and one for the humans. Why don't we generate the primary key instead?
-
# Hashing each fixture's label yields a consistent ID:
-
#
-
# george: # generated id: 503576764
-
# name: George the Monkey
-
#
-
# reginald: # generated id: 324201669
-
# name: Reginald the Pirate
-
#
-
# Active Record looks at the fixture's model class, discovers the correct
-
# primary key, and generates it right before inserting the fixture
-
# into the database.
-
#
-
# The generated ID for a given label is constant, so we can discover
-
# any fixture's ID without loading anything, as long as we know the label.
-
#
-
# == Label references for associations (belongs_to, has_one, has_many)
-
#
-
# Specifying foreign keys in fixtures can be very fragile, not to
-
# mention difficult to read. Since Active Record can figure out the ID of
-
# any fixture from its label, you can specify FK's by label instead of ID.
-
#
-
# === belongs_to
-
#
-
# Let's break out some more monkeys and pirates.
-
#
-
# ### in pirates.yml
-
#
-
# reginald:
-
# id: 1
-
# name: Reginald the Pirate
-
# monkey_id: 1
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
# pirate_id: 1
-
#
-
# Add a few more monkeys and pirates and break this into multiple files,
-
# and it gets pretty hard to keep track of what's going on. Let's
-
# use labels instead of IDs:
-
#
-
# ### in pirates.yml
-
#
-
# reginald:
-
# name: Reginald the Pirate
-
# monkey: george
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# name: George the Monkey
-
# pirate: reginald
-
#
-
# Pow! All is made clear. Active Record reflects on the fixture's model class,
-
# finds all the +belongs_to+ associations, and allows you to specify
-
# a target *label* for the *association* (monkey: george) rather than
-
# a target *id* for the *FK* (<tt>monkey_id: 1</tt>).
-
#
-
# ==== Polymorphic belongs_to
-
#
-
# Supporting polymorphic relationships is a little bit more complicated, since
-
# Active Record needs to know what type your association is pointing at. Something
-
# like this should look familiar:
-
#
-
# ### in fruit.rb
-
#
-
# belongs_to :eater, :polymorphic => true
-
#
-
# ### in fruits.yml
-
#
-
# apple:
-
# id: 1
-
# name: apple
-
# eater_id: 1
-
# eater_type: Monkey
-
#
-
# Can we do better? You bet!
-
#
-
# apple:
-
# eater: george (Monkey)
-
#
-
# Just provide the polymorphic target type and Active Record will take care of the rest.
-
#
-
# === has_and_belongs_to_many
-
#
-
# Time to give our monkey some fruit.
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
#
-
# ### in fruits.yml
-
#
-
# apple:
-
# id: 1
-
# name: apple
-
#
-
# orange:
-
# id: 2
-
# name: orange
-
#
-
# grape:
-
# id: 3
-
# name: grape
-
#
-
# ### in fruits_monkeys.yml
-
#
-
# apple_george:
-
# fruit_id: 1
-
# monkey_id: 1
-
#
-
# orange_george:
-
# fruit_id: 2
-
# monkey_id: 1
-
#
-
# grape_george:
-
# fruit_id: 3
-
# monkey_id: 1
-
#
-
# Let's make the HABTM fixture go away.
-
#
-
# ### in monkeys.yml
-
#
-
# george:
-
# id: 1
-
# name: George the Monkey
-
# fruits: apple, orange, grape
-
#
-
# ### in fruits.yml
-
#
-
# apple:
-
# name: apple
-
#
-
# orange:
-
# name: orange
-
#
-
# grape:
-
# name: grape
-
#
-
# Zap! No more fruits_monkeys.yml file. We've specified the list of fruits
-
# on George's fixture, but we could've just as easily specified a list
-
# of monkeys on each fruit. As with +belongs_to+, Active Record reflects on
-
# the fixture's model class and discovers the +has_and_belongs_to_many+
-
# associations.
-
#
-
# == Autofilled Timestamp Columns
-
#
-
# If your table/model specifies any of Active Record's
-
# standard timestamp columns (+created_at+, +created_on+, +updated_at+, +updated_on+),
-
# they will automatically be set to <tt>Time.now</tt>.
-
#
-
# If you've set specific values, they'll be left alone.
-
#
-
# == Fixture label interpolation
-
#
-
# The label of the current fixture is always available as a column value:
-
#
-
# geeksomnia:
-
# name: Geeksomnia's Account
-
# subdomain: $LABEL
-
#
-
# Also, sometimes (like when porting older join table fixtures) you'll need
-
# to be able to get a hold of the identifier for a given label. ERB
-
# to the rescue:
-
#
-
# george_reginald:
-
# monkey_id: <%= ActiveRecord::Fixtures.identify(:reginald) %>
-
# pirate_id: <%= ActiveRecord::Fixtures.identify(:george) %>
-
#
-
# == Support for YAML defaults
-
#
-
# You probably already know how to use YAML to set and reuse defaults in
-
# your <tt>database.yml</tt> file. You can use the same technique in your fixtures:
-
#
-
# DEFAULTS: &DEFAULTS
-
# created_on: <%= 3.weeks.ago.to_s(:db) %>
-
#
-
# first:
-
# name: Smurf
-
# *DEFAULTS
-
#
-
# second:
-
# name: Fraggle
-
# *DEFAULTS
-
#
-
# Any fixture labeled "DEFAULTS" is safely ignored.
-
2
class Fixtures
-
2
MAX_ID = 2 ** 30 - 1
-
-
4
@@all_cached_fixtures = Hash.new { |h,k| h[k] = {} }
-
-
2
def self.find_table_name(table_name) # :nodoc:
-
20
ActiveRecord::Base.pluralize_table_names ?
-
table_name.to_s.singularize.camelize :
-
table_name.to_s.camelize
-
end
-
-
2
def self.reset_cache
-
@@all_cached_fixtures.clear
-
end
-
-
2
def self.cache_for_connection(connection)
-
266
@@all_cached_fixtures[connection]
-
end
-
-
2
def self.fixture_is_cached?(connection, table_name)
-
240
cache_for_connection(connection)[table_name]
-
end
-
-
2
def self.cached_fixtures(connection, keys_to_fetch = nil)
-
24
if keys_to_fetch
-
24
cache_for_connection(connection).values_at(*keys_to_fetch)
-
else
-
cache_for_connection(connection).values
-
end
-
end
-
-
2
def self.cache_fixtures(connection, fixtures_map)
-
2
cache_for_connection(connection).update(fixtures_map)
-
end
-
-
#--
-
# TODO:NOTE: in the next version, the __with_new_arity suffix and
-
# the method with the old arity will be removed.
-
#++
-
2
def self.instantiate_fixtures__with_new_arity(object, fixture_set, load_instances = true) # :nodoc:
-
if load_instances
-
fixture_set.each do |fixture_name, fixture|
-
begin
-
object.instance_variable_set "@#{fixture_name}", fixture.find
-
rescue FixtureClassNotFound
-
nil
-
end
-
end
-
end
-
end
-
-
# The use with parameters <tt>(object, fixture_set_name, fixture_set, load_instances = true)</tt> is deprecated, +fixture_set_name+ parameter is not used.
-
# Use as:
-
#
-
# instantiate_fixtures(object, fixture_set, load_instances = true)
-
2
def self.instantiate_fixtures(object, fixture_set, load_instances = true, rails_3_2_compatibility_argument = true)
-
unless load_instances == true || load_instances == false
-
ActiveSupport::Deprecation.warn(
-
"ActiveRecord::Fixtures.instantiate_fixtures with parameters (object, fixture_set_name, fixture_set, load_instances = true) is deprecated and shall be removed from future releases. Use it with parameters (object, fixture_set, load_instances = true) instead (skip fixture_set_name).",
-
caller)
-
fixture_set = load_instances
-
load_instances = rails_3_2_compatibility_argument
-
end
-
instantiate_fixtures__with_new_arity(object, fixture_set, load_instances)
-
end
-
-
2
def self.instantiate_all_loaded_fixtures(object, load_instances = true)
-
all_loaded_fixtures.each_value do |fixture_set|
-
ActiveRecord::Fixtures.instantiate_fixtures(object, fixture_set, load_instances)
-
end
-
end
-
-
2
cattr_accessor :all_loaded_fixtures
-
2
self.all_loaded_fixtures = {}
-
-
2
def self.create_fixtures(fixtures_directory, table_names, class_names = {})
-
264
table_names = [table_names].flatten.map { |n| n.to_s }
-
24
table_names.each { |n|
-
240
class_names[n.tr('/', '_').to_sym] = n.classify if n.include?('/')
-
}
-
-
# FIXME: Apparently JK uses this.
-
24
connection = block_given? ? yield : ActiveRecord::Base.connection
-
-
24
files_to_read = table_names.reject { |table_name|
-
240
fixture_is_cached?(connection, table_name)
-
}
-
-
24
unless files_to_read.empty?
-
2
connection.disable_referential_integrity do
-
2
fixtures_map = {}
-
-
2
fixture_files = files_to_read.map do |path|
-
20
table_name = path.tr '/', '_'
-
-
20
fixtures_map[path] = ActiveRecord::Fixtures.new(
-
connection,
-
table_name,
-
class_names[table_name.to_sym] || table_name.classify,
-
::File.join(fixtures_directory, path))
-
end
-
-
2
all_loaded_fixtures.update(fixtures_map)
-
-
2
connection.transaction(:requires_new => true) do
-
2
fixture_files.each do |ff|
-
20
conn = ff.model_class.respond_to?(:connection) ? ff.model_class.connection : connection
-
20
table_rows = ff.table_rows
-
-
20
table_rows.keys.each do |table|
-
20
conn.delete "DELETE FROM #{conn.quote_table_name(table)}", 'Fixture Delete'
-
end
-
-
20
table_rows.each do |table_name,rows|
-
20
rows.each do |row|
-
26
conn.insert_fixture(row, table_name)
-
end
-
end
-
end
-
-
# Cap primary key sequences to max(pk).
-
2
if connection.respond_to?(:reset_pk_sequence!)
-
table_names.each do |table_name|
-
connection.reset_pk_sequence!(table_name.tr('/', '_'))
-
end
-
end
-
end
-
-
2
cache_fixtures(connection, fixtures_map)
-
end
-
end
-
24
cached_fixtures(connection, table_names)
-
end
-
-
# Returns a consistent, platform-independent identifier for +label+.
-
# Identifiers are positive integers less than 2^32.
-
2
def self.identify(label)
-
28
Zlib.crc32(label.to_s) % MAX_ID
-
end
-
-
2
attr_reader :table_name, :name, :fixtures, :model_class
-
-
2
def initialize(connection, table_name, class_name, fixture_path)
-
20
@connection = connection
-
20
@table_name = table_name
-
20
@fixture_path = fixture_path
-
20
@name = table_name # preserve fixture base name
-
20
@class_name = class_name
-
-
20
@fixtures = ActiveSupport::OrderedHash.new
-
20
@table_name = "#{ActiveRecord::Base.table_name_prefix}#{@table_name}#{ActiveRecord::Base.table_name_suffix}"
-
-
# Should be an AR::Base type class
-
20
if class_name.is_a?(Class)
-
@table_name = class_name.table_name
-
@connection = class_name.connection
-
@model_class = class_name
-
else
-
20
@model_class = class_name.constantize rescue nil
-
end
-
-
20
read_fixture_files
-
end
-
-
2
def [](x)
-
257
fixtures[x]
-
end
-
-
2
def []=(k,v)
-
fixtures[k] = v
-
end
-
-
2
def each(&block)
-
fixtures.each(&block)
-
end
-
-
2
def size
-
fixtures.size
-
end
-
-
# Return a hash of rows to be inserted. The key is the table, the value is
-
# a list of rows to insert to that table.
-
2
def table_rows
-
20
now = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now
-
20
now = now.to_s(:db)
-
-
# allow a standard key to be used for doing defaults in YAML
-
20
fixtures.delete('DEFAULTS')
-
-
# track any join tables we need to insert later
-
20
rows = Hash.new { |h,table| h[table] = [] }
-
-
20
rows[table_name] = fixtures.map do |label, fixture|
-
26
row = fixture.to_hash
-
-
26
if model_class && model_class < ActiveRecord::Base
-
# fill in timestamp columns if they aren't specified and the model is set to record_timestamps
-
26
if model_class.record_timestamps
-
26
timestamp_column_names.each do |name|
-
52
row[name] = now unless row.key?(name)
-
end
-
end
-
-
# interpolate the fixture label
-
26
row.each do |key, value|
-
136
row[key] = label if value == "$LABEL"
-
end
-
-
# generate a primary key if necessary
-
26
if has_primary_key_column? && !row.include?(primary_key_name)
-
24
row[primary_key_name] = ActiveRecord::Fixtures.identify(label)
-
end
-
-
# If STI is used, find the correct subclass for association reflection
-
26
reflection_class =
-
if row.include?(inheritance_column_name)
-
row[inheritance_column_name].constantize rescue model_class
-
else
-
26
model_class
-
end
-
-
26
reflection_class.reflect_on_all_associations.each do |association|
-
76
case association.macro
-
when :belongs_to
-
# Do not replace association name with association foreign key if they are named the same
-
32
fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s
-
-
32
if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
-
4
if association.options[:polymorphic] && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
-
# support polymorphic belongs_to as "label (Type)"
-
row[association.foreign_type] = $1
-
end
-
-
4
row[fk_name] = ActiveRecord::Fixtures.identify(value)
-
end
-
when :has_and_belongs_to_many
-
if (targets = row.delete(association.name.to_s))
-
targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
-
table_name = association.options[:join_table]
-
rows[table_name].concat targets.map { |target|
-
{ association.foreign_key => row[primary_key_name],
-
association.association_foreign_key => ActiveRecord::Fixtures.identify(target) }
-
}
-
end
-
end
-
end
-
end
-
-
26
row
-
end
-
20
rows
-
end
-
-
2
private
-
2
def primary_key_name
-
78
@primary_key_name ||= model_class && model_class.primary_key
-
end
-
-
2
def has_primary_key_column?
-
@has_primary_key_column ||= primary_key_name &&
-
40
model_class.columns.any? { |c| c.name == primary_key_name }
-
end
-
-
2
def timestamp_column_names
-
@timestamp_column_names ||=
-
26
%w(created_at created_on updated_at updated_on) & column_names
-
end
-
-
2
def inheritance_column_name
-
26
@inheritance_column_name ||= model_class && model_class.inheritance_column
-
end
-
-
2
def column_names
-
116
@column_names ||= @connection.columns(@table_name).collect { |c| c.name }
-
end
-
-
2
def read_fixture_files
-
20
yaml_files = Dir["#{@fixture_path}/{**,*}/*.yml"].select { |f|
-
::File.file?(f)
-
} + [yaml_file_path]
-
-
20
yaml_files.each do |file|
-
20
Fixtures::File.open(file) do |fh|
-
20
fh.each do |name, row|
-
26
fixtures[name] = ActiveRecord::Fixture.new(row, model_class)
-
end
-
end
-
end
-
end
-
-
2
def yaml_file_path
-
20
"#{@fixture_path}.yml"
-
end
-
-
end
-
-
2
class Fixture #:nodoc:
-
2
include Enumerable
-
-
2
class FixtureError < StandardError #:nodoc:
-
end
-
-
2
class FormatError < FixtureError #:nodoc:
-
end
-
-
2
attr_reader :model_class, :fixture
-
-
2
def initialize(fixture, model_class)
-
26
@fixture = fixture
-
26
@model_class = model_class
-
end
-
-
2
def class_name
-
model_class.name if model_class
-
end
-
-
2
def each
-
fixture.each { |item| yield item }
-
end
-
-
2
def [](key)
-
fixture[key]
-
end
-
-
2
alias :to_hash :fixture
-
-
2
def find
-
102
if model_class
-
102
model_class.find(fixture[model_class.primary_key])
-
else
-
raise FixtureClassNotFound, "No class attached to find."
-
end
-
end
-
end
-
end
-
-
2
module ActiveRecord
-
2
module TestFixtures
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
setup :setup_fixtures
-
2
teardown :teardown_fixtures
-
-
2
class_attribute :fixture_path
-
2
class_attribute :fixture_table_names
-
2
class_attribute :fixture_class_names
-
2
class_attribute :use_transactional_fixtures
-
2
class_attribute :use_instantiated_fixtures # true, false, or :no_instances
-
2
class_attribute :pre_loaded_fixtures
-
-
2
self.fixture_table_names = []
-
2
self.use_transactional_fixtures = true
-
2
self.use_instantiated_fixtures = false
-
2
self.pre_loaded_fixtures = false
-
-
2
self.fixture_class_names = Hash.new do |h, table_name|
-
20
h[table_name] = ActiveRecord::Fixtures.find_table_name(table_name)
-
end
-
end
-
-
2
module ClassMethods
-
2
def set_fixture_class(class_names = {})
-
self.fixture_class_names = self.fixture_class_names.merge(class_names)
-
end
-
-
2
def fixtures(*fixture_names)
-
2
if fixture_names.first == :all
-
2
fixture_names = Dir["#{fixture_path}/{**,*}/*.{yml}"]
-
22
fixture_names.map! { |f| f[(fixture_path.size + 1)..-5] }
-
else
-
fixture_names = fixture_names.flatten.map { |n| n.to_s }
-
end
-
-
2
self.fixture_table_names |= fixture_names
-
2
require_fixture_classes(fixture_names)
-
2
setup_fixture_accessors(fixture_names)
-
end
-
-
2
def try_to_load_dependency(file_name)
-
20
require_dependency file_name
-
rescue LoadError => e
-
# Let's hope the developer has included it himself
-
-
# Let's warn in case this is a subdependency, otherwise
-
# subdependency error messages are totally cryptic
-
if ActiveRecord::Base.logger
-
ActiveRecord::Base.logger.warn("Unable to load #{file_name}, underlying cause #{e.message} \n\n #{e.backtrace.join("\n")}")
-
end
-
end
-
-
2
def require_fixture_classes(fixture_names = nil)
-
2
(fixture_names || fixture_table_names).each do |fixture_name|
-
20
file_name = fixture_name.to_s
-
20
file_name = file_name.singularize if ActiveRecord::Base.pluralize_table_names
-
20
try_to_load_dependency(file_name)
-
end
-
end
-
-
2
def setup_fixture_accessors(fixture_names = nil)
-
2
fixture_names = Array.wrap(fixture_names || fixture_table_names)
-
2
methods = Module.new do
-
2
fixture_names.each do |fixture_name|
-
20
fixture_name = fixture_name.to_s.tr('./', '_')
-
-
20
define_method(fixture_name) do |*fixtures|
-
156
force_reload = fixtures.pop if fixtures.last == true || fixtures.last == :reload
-
-
156
@fixture_cache[fixture_name] ||= {}
-
-
156
instances = fixtures.map do |fixture|
-
155
@fixture_cache[fixture_name].delete(fixture) if force_reload
-
-
155
if @loaded_fixtures[fixture_name][fixture.to_s]
-
106
ActiveRecord::IdentityMap.without do
-
106
@fixture_cache[fixture_name][fixture] ||= @loaded_fixtures[fixture_name][fixture.to_s].find
-
end
-
else
-
49
raise StandardError, "No fixture with name '#{fixture}' found for table '#{fixture_name}'"
-
end
-
end
-
-
107
instances.size == 1 ? instances.first : instances
-
end
-
20
private fixture_name
-
end
-
end
-
2
include methods
-
end
-
-
2
def uses_transaction(*methods)
-
@uses_transaction = [] unless defined?(@uses_transaction)
-
@uses_transaction.concat methods.map { |m| m.to_s }
-
end
-
-
2
def uses_transaction?(method)
-
435
@uses_transaction = [] unless defined?(@uses_transaction)
-
435
@uses_transaction.include?(method.to_s)
-
end
-
end
-
-
2
def run_in_transaction?
-
use_transactional_fixtures &&
-
435
!self.class.uses_transaction?(method_name)
-
end
-
-
2
def setup_fixtures
-
145
return unless !ActiveRecord::Base.configurations.blank?
-
-
145
if pre_loaded_fixtures && !use_transactional_fixtures
-
raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures'
-
end
-
-
145
@fixture_cache = {}
-
145
@fixture_connections = []
-
145
@@already_loaded_fixtures ||= {}
-
-
# Load fixtures once and begin transaction.
-
145
if run_in_transaction?
-
145
if @@already_loaded_fixtures[self.class]
-
121
@loaded_fixtures = @@already_loaded_fixtures[self.class]
-
else
-
24
@loaded_fixtures = load_fixtures
-
24
@@already_loaded_fixtures[self.class] = @loaded_fixtures
-
end
-
145
@fixture_connections = enlist_fixture_connections
-
145
@fixture_connections.each do |connection|
-
145
connection.increment_open_transactions
-
145
connection.transaction_joinable = false
-
145
connection.begin_db_transaction
-
end
-
# Load fixtures for every test.
-
else
-
ActiveRecord::Fixtures.reset_cache
-
@@already_loaded_fixtures[self.class] = nil
-
@loaded_fixtures = load_fixtures
-
end
-
-
# Instantiate fixtures for every test if requested.
-
145
instantiate_fixtures if use_instantiated_fixtures
-
end
-
-
2
def teardown_fixtures
-
145
return unless defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
-
-
145
unless run_in_transaction?
-
ActiveRecord::Fixtures.reset_cache
-
end
-
-
# Rollback changes if a transaction is active.
-
145
if run_in_transaction?
-
145
@fixture_connections.each do |connection|
-
145
if connection.open_transactions != 0
-
145
connection.rollback_db_transaction
-
145
connection.decrement_open_transactions
-
end
-
end
-
145
@fixture_connections.clear
-
end
-
145
ActiveRecord::Base.clear_active_connections!
-
end
-
-
2
def enlist_fixture_connections
-
145
ActiveRecord::Base.connection_handler.connection_pools.values.map(&:connection)
-
end
-
-
2
private
-
2
def load_fixtures
-
24
fixtures = ActiveRecord::Fixtures.create_fixtures(fixture_path, fixture_table_names, fixture_class_names)
-
264
Hash[fixtures.map { |f| [f.name, f] }]
-
end
-
-
# for pre_loaded_fixtures, only require the classes once. huge speed improvement
-
2
@@required_fixture_classes = false
-
-
2
def instantiate_fixtures
-
if pre_loaded_fixtures
-
raise RuntimeError, 'Load fixtures before instantiating them.' if ActiveRecord::Fixtures.all_loaded_fixtures.empty?
-
unless @@required_fixture_classes
-
self.class.require_fixture_classes ActiveRecord::Fixtures.all_loaded_fixtures.keys
-
@@required_fixture_classes = true
-
end
-
ActiveRecord::Fixtures.instantiate_all_loaded_fixtures(self, load_instances?)
-
else
-
raise RuntimeError, 'Load fixtures before instantiating them.' if @loaded_fixtures.nil?
-
@loaded_fixtures.each_value do |fixture_set|
-
ActiveRecord::Fixtures.instantiate_fixtures(self, fixture_set, load_instances?)
-
end
-
end
-
end
-
-
2
def load_instances?
-
use_instantiated_fixtures != :no_instances
-
end
-
end
-
end
-
2
begin
-
2
require 'psych'
-
rescue LoadError
-
end
-
-
2
require 'erb'
-
2
require 'yaml'
-
-
2
module ActiveRecord
-
2
class Fixtures
-
2
class File
-
2
include Enumerable
-
-
##
-
# Open a fixture file named +file+. When called with a block, the block
-
# is called with the filehandle and the filehandle is automatically closed
-
# when the block finishes.
-
2
def self.open(file)
-
20
x = new file
-
20
block_given? ? yield(x) : x
-
end
-
-
2
def initialize(file)
-
20
@file = file
-
20
@rows = nil
-
end
-
-
2
def each(&block)
-
20
rows.each(&block)
-
end
-
-
2
RESCUE_ERRORS = [ ArgumentError ] # :nodoc:
-
-
2
private
-
2
if defined?(Psych) && defined?(Psych::SyntaxError)
-
2
RESCUE_ERRORS << Psych::SyntaxError
-
end
-
-
2
def rows
-
20
return @rows if @rows
-
-
20
begin
-
20
data = YAML.load(render(IO.read(@file)))
-
rescue *RESCUE_ERRORS => error
-
raise Fixture::FormatError, "a YAML error occurred parsing #{@file}. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Please have a look at http://www.yaml.org/faq.html\nThe exact error was:\n #{error.class}: #{error}", error.backtrace
-
end
-
20
@rows = data ? validate(data).to_a : []
-
end
-
-
2
def render(content)
-
20
ERB.new(content).result
-
end
-
-
# Validate our unmarshalled data.
-
2
def validate(data)
-
14
unless Hash === data || YAML::Omap === data
-
raise Fixture::FormatError, 'fixture is not a hash'
-
end
-
-
40
raise Fixture::FormatError unless data.all? { |name, row| Hash === row }
-
14
data
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
# = Active Record Identity Map
-
#
-
# Ensures that each object gets loaded only once by keeping every loaded
-
# object in a map. Looks up objects using the map when referring to them.
-
#
-
# More information on Identity Map pattern:
-
# http://www.martinfowler.com/eaaCatalog/identityMap.html
-
#
-
# == Configuration
-
#
-
# In order to enable IdentityMap, set <tt>config.active_record.identity_map = true</tt>
-
# in your <tt>config/application.rb</tt> file.
-
#
-
# IdentityMap is disabled by default and still in development (i.e. use it with care).
-
#
-
# == Associations
-
#
-
# Active Record Identity Map does not track associations yet. For example:
-
#
-
# comment = @post.comments.first
-
# comment.post = nil
-
# @post.comments.include?(comment) #=> true
-
#
-
# Ideally, the example above would return false, removing the comment object from the
-
# post association when the association is nullified. This may cause side effects, as
-
# in the situation below, if Identity Map is enabled:
-
#
-
# Post.has_many :comments, :dependent => :destroy
-
#
-
# comment = @post.comments.first
-
# comment.post = nil
-
# comment.save
-
# Post.destroy(@post.id)
-
#
-
# Without using Identity Map, the code above will destroy the @post object leaving
-
# the comment object intact. However, once we enable Identity Map, the post loaded
-
# by Post.destroy is exactly the same object as the object @post. As the object @post
-
# still has the comment object in @post.comments, once Identity Map is enabled, the
-
# comment object will be accidently removed.
-
#
-
# This inconsistency is meant to be fixed in future Rails releases.
-
#
-
2
module IdentityMap
-
-
2
class << self
-
2
def enabled=(flag)
-
220
Thread.current[:identity_map_enabled] = flag
-
end
-
-
2
def enabled
-
2098
Thread.current[:identity_map_enabled]
-
end
-
2
alias enabled? enabled
-
-
2
def repository
-
145
Thread.current[:identity_map] ||= Hash.new { |h,k| h[k] = {} }
-
end
-
-
2
def use
-
old, self.enabled = enabled, true
-
-
yield if block_given?
-
ensure
-
self.enabled = old
-
clear
-
end
-
-
2
def without
-
110
old, self.enabled = enabled, false
-
-
110
yield if block_given?
-
ensure
-
110
self.enabled = old
-
end
-
-
2
def get(klass, primary_key)
-
record = repository[klass.symbolized_sti_name][primary_key]
-
-
if record.is_a?(klass)
-
ActiveSupport::Notifications.instrument("identity.active_record",
-
:line => "From Identity Map (id: #{primary_key})",
-
:name => "#{klass} Loaded",
-
:connection_id => object_id)
-
-
record
-
else
-
nil
-
end
-
end
-
-
2
def add(record)
-
repository[record.class.symbolized_sti_name][record.id] = record if contain_all_columns?(record)
-
end
-
-
2
def remove(record)
-
repository[record.class.symbolized_sti_name].delete(record.id)
-
end
-
-
2
def remove_by_id(symbolized_sti_name, id)
-
repository[symbolized_sti_name].delete(id)
-
end
-
-
2
def clear
-
145
repository.clear
-
end
-
-
2
private
-
-
2
def contain_all_columns?(record)
-
(record.class.column_names - record.attribute_names).empty?
-
end
-
end
-
-
# Reinitialize an Identity Map model object from +coder+.
-
# +coder+ must contain the attributes necessary for initializing an empty
-
# model object.
-
2
def reinit_with(coder)
-
@attributes_cache = {}
-
dirty = @changed_attributes.keys
-
attributes = self.class.initialize_attributes(coder['attributes'].except(*dirty))
-
@attributes.update(attributes)
-
@changed_attributes.update(coder['attributes'].slice(*dirty))
-
@changed_attributes.delete_if{|k,v| v.eql? @attributes[k]}
-
-
run_callbacks :find
-
-
self
-
end
-
-
2
class Middleware
-
2
class Body #:nodoc:
-
2
def initialize(target, original)
-
@target = target
-
@original = original
-
end
-
-
2
def each(&block)
-
@target.each(&block)
-
end
-
-
2
def close
-
@target.close if @target.respond_to?(:close)
-
ensure
-
IdentityMap.enabled = @original
-
IdentityMap.clear
-
end
-
end
-
-
2
def initialize(app)
-
@app = app
-
end
-
-
2
def call(env)
-
enabled = IdentityMap.enabled
-
IdentityMap.enabled = true
-
status, headers, body = @app.call(env)
-
[status, headers, Body.new(body, enabled)]
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
-
2
module ActiveRecord
-
2
module Inheritance
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
# Determine whether to store the full constant name including namespace when using STI
-
2
class_attribute :store_full_sti_class
-
2
self.store_full_sti_class = true
-
end
-
-
2
module ClassMethods
-
# True if this isn't a concrete subclass needing a STI type condition.
-
2
def descends_from_active_record?
-
16
if superclass.abstract_class?
-
superclass.descends_from_active_record?
-
else
-
16
superclass == Base || !columns_hash.include?(inheritance_column)
-
end
-
end
-
-
2
def finder_needs_type_condition? #:nodoc:
-
# This is like this because benchmarking justifies the strange :false stuff
-
1923
:true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
-
end
-
-
2
def symbolized_base_class
-
@symbolized_base_class ||= base_class.to_s.to_sym
-
end
-
-
2
def symbolized_sti_name
-
@symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class
-
end
-
-
# Returns the base AR subclass that this class descends from. If A
-
# extends AR::Base, A.base_class will return A. If B descends from A
-
# through some arbitrarily deep hierarchy, B.base_class will return A.
-
#
-
# If B < A and C < B and if A is an abstract_class then both B.base_class
-
# and C.base_class would return B as the answer since A is an abstract_class.
-
2
def base_class
-
67
class_of_active_record_descendant(self)
-
end
-
-
# Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
-
2
attr_accessor :abstract_class
-
-
# Returns whether this class is an abstract class or not.
-
2
def abstract_class?
-
56
defined?(@abstract_class) && @abstract_class == true
-
end
-
-
2
def sti_name
-
store_full_sti_class ? name : name.demodulize
-
end
-
-
# Finder methods must instantiate through this method to work with the
-
# single-table inheritance model that makes it possible to create
-
# objects of different types from the same table.
-
2
def instantiate(record)
-
701
sti_class = find_sti_class(record[inheritance_column])
-
701
record_id = sti_class.primary_key && record[sti_class.primary_key]
-
-
701
if ActiveRecord::IdentityMap.enabled? && record_id
-
instance = use_identity_map(sti_class, record_id, record)
-
else
-
701
instance = sti_class.allocate.init_with('attributes' => record)
-
end
-
-
701
instance
-
end
-
-
2
protected
-
-
# Returns the class descending directly from ActiveRecord::Base or an
-
# abstract class, if any, in the inheritance hierarchy.
-
2
def class_of_active_record_descendant(klass)
-
67
if klass == Base || klass.superclass == Base || klass.superclass.abstract_class?
-
67
klass
-
elsif klass.superclass.nil?
-
raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
-
else
-
class_of_active_record_descendant(klass.superclass)
-
end
-
end
-
-
# Returns the class type of the record using the current module as a prefix. So descendants of
-
# MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
-
2
def compute_type(type_name)
-
20
if type_name.match(/^::/)
-
# If the type is prefixed with a scope operator then we assume that
-
# the type_name is an absolute reference.
-
ActiveSupport::Dependencies.constantize(type_name)
-
else
-
# Build a list of candidates to search for
-
20
candidates = []
-
40
name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" }
-
20
candidates << type_name
-
-
20
candidates.each do |candidate|
-
40
begin
-
40
constant = ActiveSupport::Dependencies.constantize(candidate)
-
20
return constant if candidate == constant.to_s
-
rescue NameError => e
-
# We don't want to swallow NoMethodError < NameError errors
-
20
raise e unless e.instance_of?(NameError)
-
end
-
end
-
-
raise NameError, "uninitialized constant #{candidates.first}"
-
end
-
end
-
-
2
private
-
-
2
def use_identity_map(sti_class, record_id, record)
-
if (column = sti_class.columns_hash[sti_class.primary_key]) && column.number?
-
record_id = record_id.to_i
-
end
-
-
if instance = IdentityMap.get(sti_class, record_id)
-
instance.reinit_with('attributes' => record)
-
else
-
instance = sti_class.allocate.init_with('attributes' => record)
-
IdentityMap.add(instance)
-
end
-
-
instance
-
end
-
-
2
def find_sti_class(type_name)
-
701
if type_name.blank? || !columns_hash.include?(inheritance_column)
-
701
self
-
else
-
begin
-
if store_full_sti_class
-
ActiveSupport::Dependencies.constantize(type_name)
-
else
-
compute_type(type_name)
-
end
-
rescue NameError
-
raise SubclassNotFound,
-
"The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " +
-
"This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
-
"Please rename this column if you didn't intend it to be used for storing the inheritance class " +
-
"or overwrite #{name}.inheritance_column to use another column for that information."
-
end
-
end
-
end
-
-
2
def type_condition(table = arel_table)
-
sti_column = table[inheritance_column.to_sym]
-
sti_names = ([self] + descendants).map { |model| model.sti_name }
-
-
sti_column.in(sti_names)
-
end
-
end
-
-
2
private
-
-
# Sets the attribute used for single table inheritance to this class name if this is not the
-
# ActiveRecord::Base descendant.
-
# Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to
-
# do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself.
-
# No such attribute would be set for objects of the Message class in that example.
-
2
def ensure_proper_type
-
359
klass = self.class
-
359
if klass.finder_needs_type_condition?
-
write_attribute(klass.inheritance_column, klass.sti_name)
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Integration
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
##
-
# :singleton-method:
-
# Indicates the format used to generate the timestamp format in the cache key.
-
# This is +:number+, by default.
-
2
class_attribute :cache_timestamp_format, :instance_writer => false
-
2
self.cache_timestamp_format = :number
-
end
-
-
# Returns a String, which Action Pack uses for constructing an URL to this
-
# object. The default implementation returns this record's id as a String,
-
# or nil if this record's unsaved.
-
#
-
# For example, suppose that you have a User model, and that you have a
-
# <tt>resources :users</tt> route. Normally, +user_path+ will
-
# construct a path with the user object's 'id' in it:
-
#
-
# user = User.find_by_name('Phusion')
-
# user_path(user) # => "/users/1"
-
#
-
# You can override +to_param+ in your model to make +user_path+ construct
-
# a path using the user's name instead of the user's id:
-
#
-
# class User < ActiveRecord::Base
-
# def to_param # overridden
-
# name
-
# end
-
# end
-
#
-
# user = User.find_by_name('Phusion')
-
# user_path(user) # => "/users/Phusion"
-
2
def to_param
-
# We can't use alias_method here, because method 'id' optimizes itself on the fly.
-
12
id && id.to_s # Be sure to stringify the id for routes
-
end
-
-
# Returns a cache key that can be used to identify this record.
-
#
-
# ==== Examples
-
#
-
# Product.new.cache_key # => "products/new"
-
# Product.find(5).cache_key # => "products/5" (updated_at not available)
-
# Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available)
-
2
def cache_key
-
case
-
when new_record?
-
"#{self.class.model_name.cache_key}/new"
-
when timestamp = self[:updated_at]
-
timestamp = timestamp.utc.to_s(cache_timestamp_format)
-
"#{self.class.model_name.cache_key}/#{id}-#{timestamp}"
-
else
-
"#{self.class.model_name.cache_key}/#{id}"
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Locking
-
# == What is Optimistic Locking
-
#
-
# Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of
-
# conflicts with the data. It does this by checking whether another process has made changes to a record since
-
# it was opened, an <tt>ActiveRecord::StaleObjectError</tt> exception is thrown if that has occurred
-
# and the update is ignored.
-
#
-
# Check out <tt>ActiveRecord::Locking::Pessimistic</tt> for an alternative.
-
#
-
# == Usage
-
#
-
# Active Records support optimistic locking if the field +lock_version+ is present. Each update to the
-
# record increments the +lock_version+ column and the locking facilities ensure that records instantiated twice
-
# will let the last one saved raise a +StaleObjectError+ if the first was also updated. Example:
-
#
-
# p1 = Person.find(1)
-
# p2 = Person.find(1)
-
#
-
# p1.first_name = "Michael"
-
# p1.save
-
#
-
# p2.first_name = "should fail"
-
# p2.save # Raises a ActiveRecord::StaleObjectError
-
#
-
# Optimistic locking will also check for stale data when objects are destroyed. Example:
-
#
-
# p1 = Person.find(1)
-
# p2 = Person.find(1)
-
#
-
# p1.first_name = "Michael"
-
# p1.save
-
#
-
# p2.destroy # Raises a ActiveRecord::StaleObjectError
-
#
-
# You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging,
-
# or otherwise apply the business logic needed to resolve the conflict.
-
#
-
# This locking mechanism will function inside a single Ruby process. To make it work across all
-
# web requests, the recommended approach is to add +lock_version+ as a hidden field to your form.
-
#
-
# You must ensure that your database schema defaults the +lock_version+ column to 0.
-
#
-
# This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
-
# To override the name of the +lock_version+ column, invoke the <tt>set_locking_column</tt> method.
-
# This method uses the same syntax as <tt>set_table_name</tt>
-
2
module Optimistic
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
cattr_accessor :lock_optimistically, :instance_writer => false
-
2
self.lock_optimistically = true
-
end
-
-
2
def locking_enabled? #:nodoc:
-
76
self.class.locking_enabled?
-
end
-
-
2
private
-
2
def increment_lock
-
lock_col = self.class.locking_column
-
previous_lock_value = send(lock_col).to_i
-
send(lock_col + '=', previous_lock_value + 1)
-
end
-
-
2
def update(attribute_names = @attributes.keys) #:nodoc:
-
55
return super unless locking_enabled?
-
return 0 if attribute_names.empty?
-
-
lock_col = self.class.locking_column
-
previous_lock_value = send(lock_col).to_i
-
increment_lock
-
-
attribute_names += [lock_col]
-
attribute_names.uniq!
-
-
begin
-
relation = self.class.unscoped
-
-
stmt = relation.where(
-
relation.table[self.class.primary_key].eq(id).and(
-
relation.table[lock_col].eq(quote_value(previous_lock_value, self.class.columns_hash[lock_col]))
-
)
-
).arel.compile_update(arel_attributes_values(false, false, attribute_names))
-
-
affected_rows = connection.update stmt
-
-
unless affected_rows == 1
-
raise ActiveRecord::StaleObjectError.new(self, "update")
-
end
-
-
affected_rows
-
-
# If something went wrong, revert the version.
-
rescue Exception
-
send(lock_col + '=', previous_lock_value)
-
raise
-
end
-
end
-
-
2
def destroy #:nodoc:
-
21
return super unless locking_enabled?
-
-
destroy_associations
-
-
if persisted?
-
table = self.class.arel_table
-
lock_col = self.class.locking_column
-
predicate = table[self.class.primary_key].eq(id).
-
and(table[lock_col].eq(send(lock_col).to_i))
-
-
affected_rows = self.class.unscoped.where(predicate).delete_all
-
-
unless affected_rows == 1
-
raise ActiveRecord::StaleObjectError.new(self, "destroy")
-
end
-
end
-
-
@destroyed = true
-
freeze
-
end
-
-
2
module ClassMethods
-
2
DEFAULT_LOCKING_COLUMN = 'lock_version'
-
-
# Returns true if the +lock_optimistically+ flag is set to true
-
# (which it is, by default) and the table includes the
-
# +locking_column+ column (defaults to +lock_version+).
-
2
def locking_enabled?
-
892
lock_optimistically && columns_hash[locking_column]
-
end
-
-
2
def locking_column=(value)
-
13
@original_locking_column = @locking_column if defined?(@locking_column)
-
13
@locking_column = value.to_s
-
end
-
-
# Set the column to use for optimistic locking. Defaults to +lock_version+.
-
2
def set_locking_column(value = nil, &block)
-
deprecated_property_setter :locking_column, value, block
-
end
-
-
# The version column used for optimistic locking. Defaults to +lock_version+.
-
2
def locking_column
-
1952
reset_locking_column unless defined?(@locking_column)
-
1952
@locking_column
-
end
-
-
2
def original_locking_column #:nodoc:
-
deprecated_original_property_getter :locking_column
-
end
-
-
# Quote the column name used for optimistic locking.
-
2
def quoted_locking_column
-
connection.quote_column_name(locking_column)
-
end
-
-
# Reset the column used for optimistic locking back to the +lock_version+ default.
-
2
def reset_locking_column
-
13
self.locking_column = DEFAULT_LOCKING_COLUMN
-
end
-
-
# Make sure the lock version column gets updated when counters are
-
# updated.
-
2
def update_counters(id, counters)
-
counters = counters.merge(locking_column => 1) if locking_enabled?
-
super
-
end
-
-
# If the locking column has no default value set,
-
# start the lock version at zero. Note we can't use
-
# <tt>locking_enabled?</tt> at this point as
-
# <tt>@attributes</tt> may not have been initialized yet.
-
2
def initialize_attributes(attributes, options = {}) #:nodoc:
-
1060
if attributes.key?(locking_column) && lock_optimistically
-
attributes[locking_column] ||= 0
-
end
-
-
1060
attributes
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Locking
-
# Locking::Pessimistic provides support for row-level locking using
-
# SELECT ... FOR UPDATE and other lock types.
-
#
-
# Pass <tt>:lock => true</tt> to <tt>ActiveRecord::Base.find</tt> to obtain an exclusive
-
# lock on the selected rows:
-
# # select * from accounts where id=1 for update
-
# Account.find(1, :lock => true)
-
#
-
# Pass <tt>:lock => 'some locking clause'</tt> to give a database-specific locking clause
-
# of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'. Example:
-
#
-
# Account.transaction do
-
# # select * from accounts where name = 'shugo' limit 1 for update
-
# shugo = Account.where("name = 'shugo'").lock(true).first
-
# yuko = Account.where("name = 'yuko'").lock(true).first
-
# shugo.balance -= 100
-
# shugo.save!
-
# yuko.balance += 100
-
# yuko.save!
-
# end
-
#
-
# You can also use <tt>ActiveRecord::Base#lock!</tt> method to lock one record by id.
-
# This may be better if you don't need to lock every row. Example:
-
#
-
# Account.transaction do
-
# # select * from accounts where ...
-
# accounts = Account.where(...).all
-
# account1 = accounts.detect { |account| ... }
-
# account2 = accounts.detect { |account| ... }
-
# # select * from accounts where id=? for update
-
# account1.lock!
-
# account2.lock!
-
# account1.balance -= 100
-
# account1.save!
-
# account2.balance += 100
-
# account2.save!
-
# end
-
#
-
# You can start a transaction and acquire the lock in one go by calling
-
# <tt>with_lock</tt> with a block. The block is called from within
-
# a transaction, the object is already locked. Example:
-
#
-
# account = Account.first
-
# account.with_lock do
-
# # This block is called within a transaction,
-
# # account is already locked.
-
# account.balance -= 100
-
# account.save!
-
# end
-
#
-
# Database-specific information on row locking:
-
# MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html
-
# PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
-
2
module Pessimistic
-
# Obtain a row lock on this record. Reloads the record to obtain the requested
-
# lock. Pass an SQL locking clause to append the end of the SELECT statement
-
# or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
-
# the locked record.
-
2
def lock!(lock = true)
-
reload(:lock => lock) if persisted?
-
self
-
end
-
-
# Wraps the passed block in a transaction, locking the object
-
# before yielding. You pass can the SQL locking clause
-
# as argument (see <tt>lock!</tt>).
-
2
def with_lock(lock = true)
-
transaction do
-
lock!(lock)
-
yield
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
class LogSubscriber < ActiveSupport::LogSubscriber
-
2
def self.runtime=(value)
-
2007
Thread.current["active_record_sql_runtime"] = value
-
end
-
-
2
def self.runtime
-
2007
Thread.current["active_record_sql_runtime"] ||= 0
-
end
-
-
2
def self.reset_runtime
-
18
rt, self.runtime = runtime, 0
-
18
rt
-
end
-
-
2
def initialize
-
2
super
-
2
@odd_or_even = false
-
end
-
-
2
def sql(event)
-
1989
self.class.runtime += event.duration
-
1989
return unless logger.debug?
-
-
1989
payload = event.payload
-
-
1989
return if 'SCHEMA' == payload[:name]
-
-
1924
name = '%s (%.1fms)' % [payload[:name], event.duration]
-
1924
sql = payload[:sql].squeeze(' ')
-
1924
binds = nil
-
-
1924
unless (payload[:binds] || []).empty?
-
458
binds = " " + payload[:binds].map { |col,v|
-
3590
if col
-
3590
[col.name, v]
-
else
-
[nil, v]
-
end
-
}.inspect
-
end
-
-
1924
if odd?
-
962
name = color(name, CYAN, true)
-
962
sql = color(sql, nil, true)
-
else
-
962
name = color(name, MAGENTA, true)
-
end
-
-
1924
debug " #{name} #{sql}#{binds}"
-
end
-
-
2
def identity(event)
-
return unless logger.debug?
-
-
name = color(event.payload[:name], odd? ? CYAN : MAGENTA, true)
-
line = odd? ? color(event.payload[:line], nil, true) : event.payload[:line]
-
-
debug " #{name} #{line}"
-
end
-
-
2
def odd?
-
1924
@odd_or_even = !@odd_or_even
-
end
-
-
2
def logger
-
7826
ActiveRecord::Base.logger
-
end
-
end
-
end
-
-
2
ActiveRecord::LogSubscriber.attach_to :active_record
-
2
require 'active_support/concern'
-
-
2
module ActiveRecord
-
2
module ModelSchema
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
##
-
# :singleton-method:
-
# Accessor for the prefix type that will be prepended to every primary key column name.
-
# The options are :table_name and :table_name_with_underscore. If the first is specified,
-
# the Product class will look for "productid" instead of "id" as the primary column. If the
-
# latter is specified, the Product class will look for "product_id" instead of "id". Remember
-
# that this is a global setting for all Active Records.
-
2
cattr_accessor :primary_key_prefix_type, :instance_writer => false
-
2
self.primary_key_prefix_type = nil
-
-
##
-
# :singleton-method:
-
# Accessor for the name of the prefix string to prepend to every table name. So if set
-
# to "basecamp_", all table names will be named like "basecamp_projects", "basecamp_people",
-
# etc. This is a convenient way of creating a namespace for tables in a shared database.
-
# By default, the prefix is the empty string.
-
#
-
# If you are organising your models within modules you can add a prefix to the models within
-
# a namespace by defining a singleton method in the parent module called table_name_prefix which
-
# returns your chosen prefix.
-
2
class_attribute :table_name_prefix, :instance_writer => false
-
2
self.table_name_prefix = ""
-
-
##
-
# :singleton-method:
-
# Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
-
# "people_basecamp"). By default, the suffix is the empty string.
-
2
class_attribute :table_name_suffix, :instance_writer => false
-
2
self.table_name_suffix = ""
-
-
##
-
# :singleton-method:
-
# Indicates whether table names should be the pluralized versions of the corresponding class names.
-
# If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
-
# See table_name for the full rules on table/class naming. This is true, by default.
-
2
class_attribute :pluralize_table_names, :instance_writer => false
-
2
self.pluralize_table_names = true
-
end
-
-
2
module ClassMethods
-
# Guesses the table name (in forced lower-case) based on the name of the class in the
-
# inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy
-
# looks like: Reply < Message < ActiveRecord::Base, then Message is used
-
# to guess the table name even when called on Reply. The rules used to do the guess
-
# are handled by the Inflector class in Active Support, which knows almost all common
-
# English inflections. You can add new inflections in config/initializers/inflections.rb.
-
#
-
# Nested classes are given table names prefixed by the singular form of
-
# the parent's table name. Enclosing modules are not considered.
-
#
-
# ==== Examples
-
#
-
# class Invoice < ActiveRecord::Base
-
# end
-
#
-
# file class table_name
-
# invoice.rb Invoice invoices
-
#
-
# class Invoice < ActiveRecord::Base
-
# class Lineitem < ActiveRecord::Base
-
# end
-
# end
-
#
-
# file class table_name
-
# invoice.rb Invoice::Lineitem invoice_lineitems
-
#
-
# module Invoice
-
# class Lineitem < ActiveRecord::Base
-
# end
-
# end
-
#
-
# file class table_name
-
# invoice/lineitem.rb Invoice::Lineitem lineitems
-
#
-
# Additionally, the class-level +table_name_prefix+ is prepended and the
-
# +table_name_suffix+ is appended. So if you have "myapp_" as a prefix,
-
# the table name guess for an Invoice class becomes "myapp_invoices".
-
# Invoice::Lineitem becomes "myapp_invoice_lineitems".
-
#
-
# You can also set your own table name explicitly:
-
#
-
# class Mouse < ActiveRecord::Base
-
# self.table_name = "mice"
-
# end
-
#
-
# Alternatively, you can override the table_name method to define your
-
# own computation. (Possibly using <tt>super</tt> to manipulate the default
-
# table name.) Example:
-
#
-
# class Post < ActiveRecord::Base
-
# def self.table_name
-
# "special_" + super
-
# end
-
# end
-
# Post.table_name # => "special_posts"
-
2
def table_name
-
1897
reset_table_name unless defined?(@table_name)
-
1897
@table_name
-
end
-
-
2
def original_table_name #:nodoc:
-
deprecated_original_property_getter :table_name
-
end
-
-
# Sets the table name explicitly. Example:
-
#
-
# class Project < ActiveRecord::Base
-
# self.table_name = "project"
-
# end
-
#
-
# You can also just define your own <tt>self.table_name</tt> method; see
-
# the documentation for ActiveRecord::Base#table_name.
-
2
def table_name=(value)
-
20
@original_table_name = @table_name if defined?(@table_name)
-
20
@table_name = value && value.to_s
-
20
@quoted_table_name = nil
-
20
@arel_table = nil
-
20
@relation = Relation.new(self, arel_table)
-
end
-
-
2
def set_table_name(value = nil, &block) #:nodoc:
-
deprecated_property_setter :table_name, value, block
-
@quoted_table_name = nil
-
@arel_table = nil
-
@relation = Relation.new(self, arel_table)
-
end
-
-
# Returns a quoted version of the table name, used to construct SQL statements.
-
2
def quoted_table_name
-
2
@quoted_table_name ||= connection.quote_table_name(table_name)
-
end
-
-
# Computes the table name, (re)sets it internally, and returns it.
-
2
def reset_table_name #:nodoc:
-
20
if abstract_class?
-
self.table_name = if superclass == Base || superclass.abstract_class?
-
nil
-
else
-
superclass.table_name
-
end
-
20
elsif superclass.abstract_class?
-
self.table_name = superclass.table_name || compute_table_name
-
else
-
20
self.table_name = compute_table_name
-
end
-
end
-
-
2
def full_table_name_prefix #:nodoc:
-
40
(parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
-
end
-
-
# The name of the column containing the object's class when Single Table Inheritance is used
-
2
def inheritance_column
-
1430
if self == Base
-
715
(@inheritance_column ||= nil) || 'type'
-
else
-
715
(@inheritance_column ||= nil) || superclass.inheritance_column
-
end
-
end
-
-
2
def original_inheritance_column #:nodoc:
-
deprecated_original_property_getter :inheritance_column
-
end
-
-
# Sets the value of inheritance_column
-
2
def inheritance_column=(value)
-
@original_inheritance_column = inheritance_column
-
@inheritance_column = value.to_s
-
@explicit_inheritance_column = true
-
end
-
-
2
def set_inheritance_column(value = nil, &block) #:nodoc:
-
deprecated_property_setter :inheritance_column, value, block
-
end
-
-
2
def sequence_name
-
if base_class == self
-
@sequence_name ||= reset_sequence_name
-
else
-
(@sequence_name ||= nil) || base_class.sequence_name
-
end
-
end
-
-
2
def original_sequence_name #:nodoc:
-
deprecated_original_property_getter :sequence_name
-
end
-
-
2
def reset_sequence_name #:nodoc:
-
self.sequence_name = connection.default_sequence_name(table_name, primary_key)
-
end
-
-
# Sets the name of the sequence to use when generating ids to the given
-
# value, or (if the value is nil or false) to the value returned by the
-
# given block. This is required for Oracle and is useful for any
-
# database which relies on sequences for primary key generation.
-
#
-
# If a sequence name is not explicitly set when using Oracle or Firebird,
-
# it will default to the commonly used pattern of: #{table_name}_seq
-
#
-
# If a sequence name is not explicitly set when using PostgreSQL, it
-
# will discover the sequence corresponding to your primary key for you.
-
#
-
# class Project < ActiveRecord::Base
-
# self.sequence_name = "projectseq" # default would have been "project_seq"
-
# end
-
2
def sequence_name=(value)
-
@original_sequence_name = @sequence_name if defined?(@sequence_name)
-
@sequence_name = value.to_s
-
end
-
-
2
def set_sequence_name(value = nil, &block) #:nodoc:
-
deprecated_property_setter :sequence_name, value, block
-
end
-
-
# Indicates whether the table associated with this class exists
-
2
def table_exists?
-
17
connection.schema_cache.table_exists?(table_name)
-
end
-
-
# Returns an array of column objects for the table associated with this class.
-
2
def columns
-
@columns ||= connection.schema_cache.columns[table_name].map do |col|
-
134
col = col.dup
-
134
col.primary = (col.name == primary_key)
-
134
col
-
91
end
-
end
-
-
# Returns a hash of column objects for the table associated with this class.
-
2
def columns_hash
-
15902
@columns_hash ||= Hash[columns.map { |c| [c.name, c] }]
-
end
-
-
# Returns a hash where the keys are column names and the values are
-
# default values when instantiating the AR object for this table.
-
2
def column_defaults
-
442
@column_defaults ||= Hash[columns.map { |c| [c.name, c.default] }]
-
end
-
-
# Returns an array of column names as strings.
-
2
def column_names
-
314
@column_names ||= columns.map { |column| column.name }
-
end
-
-
# Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
-
# and columns used for single table inheritance have been removed.
-
2
def content_columns
-
@content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
-
end
-
-
# Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key
-
# and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute
-
# is available.
-
2
def column_methods_hash #:nodoc:
-
@dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr|
-
21
attr_name = attr.to_s
-
21
methods[attr.to_sym] = attr_name
-
21
methods["#{attr}=".to_sym] = attr_name
-
21
methods["#{attr}?".to_sym] = attr_name
-
21
methods["#{attr}_before_type_cast".to_sym] = attr_name
-
21
methods
-
27
end
-
end
-
-
# Resets all the cached information about columns, which will cause them
-
# to be reloaded on the next request.
-
#
-
# The most common usage pattern for this method is probably in a migration,
-
# when just after creating a table you want to populate it with some default
-
# values, eg:
-
#
-
# class CreateJobLevels < ActiveRecord::Migration
-
# def up
-
# create_table :job_levels do |t|
-
# t.integer :id
-
# t.string :name
-
#
-
# t.timestamps
-
# end
-
#
-
# JobLevel.reset_column_information
-
# %w{assistant executive manager director}.each do |type|
-
# JobLevel.create(:name => type)
-
# end
-
# end
-
#
-
# def down
-
# drop_table :job_levels
-
# end
-
# end
-
2
def reset_column_information
-
connection.clear_cache!
-
undefine_attribute_methods
-
connection.schema_cache.clear_table_cache!(table_name) if table_exists?
-
-
@column_names = @content_columns = @column_defaults = @columns = @columns_hash = nil
-
@dynamic_methods_hash = nil
-
@inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column
-
@arel_engine = @relation = nil
-
end
-
-
2
def clear_cache! # :nodoc:
-
2
connection.schema_cache.clear!
-
end
-
-
2
private
-
-
# Guesses the table name, but does not decorate it with prefix and suffix information.
-
2
def undecorated_table_name(class_name = base_class.name)
-
20
table_name = class_name.to_s.demodulize.underscore
-
20
table_name = table_name.pluralize if pluralize_table_names
-
20
table_name
-
end
-
-
# Computes and returns a table name according to default conventions.
-
2
def compute_table_name
-
20
base = base_class
-
20
if self == base
-
# Nested classes are prefixed with singular parent table name.
-
20
if parent < ActiveRecord::Base && !parent.abstract_class?
-
contained = parent.table_name
-
contained = contained.singularize if parent.pluralize_table_names
-
contained += '_'
-
end
-
20
"#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{table_name_suffix}"
-
else
-
# STI subclasses always use their superclass' table.
-
base.table_name
-
end
-
end
-
-
2
def deprecated_property_setter(property, value, block)
-
if block
-
ActiveSupport::Deprecation.warn(
-
"Calling set_#{property} is deprecated. If you need to lazily evaluate " \
-
"the #{property}, define your own `self.#{property}` class method. You can use `super` " \
-
"to get the default #{property} where you would have called `original_#{property}`."
-
)
-
-
define_attr_method property, value, false, &block
-
else
-
ActiveSupport::Deprecation.warn(
-
"Calling set_#{property} is deprecated. Please use `self.#{property} = 'the_name'` instead."
-
)
-
-
define_attr_method property, value, false
-
end
-
end
-
-
2
def deprecated_original_property_getter(property)
-
ActiveSupport::Deprecation.warn("original_#{property} is deprecated. Define self.#{property} and call super instead.")
-
-
if !instance_variable_defined?("@original_#{property}") && respond_to?("reset_#{property}")
-
send("reset_#{property}")
-
else
-
instance_variable_get("@original_#{property}")
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/object/try'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
2
require 'active_support/core_ext/class/attribute'
-
-
2
module ActiveRecord
-
2
module NestedAttributes #:nodoc:
-
2
class TooManyRecords < ActiveRecordError
-
end
-
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :nested_attributes_options, :instance_writer => false
-
2
self.nested_attributes_options = {}
-
end
-
-
# = Active Record Nested Attributes
-
#
-
# Nested attributes allow you to save attributes on associated records
-
# through the parent. By default nested attribute updating is turned off,
-
# you can enable it using the accepts_nested_attributes_for class method.
-
# When you enable nested attributes an attribute writer is defined on
-
# the model.
-
#
-
# The attribute writer is named after the association, which means that
-
# in the following example, two new methods are added to your model:
-
#
-
# <tt>author_attributes=(attributes)</tt> and
-
# <tt>pages_attributes=(attributes)</tt>.
-
#
-
# class Book < ActiveRecord::Base
-
# has_one :author
-
# has_many :pages
-
#
-
# accepts_nested_attributes_for :author, :pages
-
# end
-
#
-
# Note that the <tt>:autosave</tt> option is automatically enabled on every
-
# association that accepts_nested_attributes_for is used for.
-
#
-
# === One-to-one
-
#
-
# Consider a Member model that has one Avatar:
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar
-
# end
-
#
-
# Enabling nested attributes on a one-to-one association allows you to
-
# create the member and avatar in one go:
-
#
-
# params = { :member => { :name => 'Jack', :avatar_attributes => { :icon => 'smiling' } } }
-
# member = Member.create(params[:member])
-
# member.avatar.id # => 2
-
# member.avatar.icon # => 'smiling'
-
#
-
# It also allows you to update the avatar through the member:
-
#
-
# params = { :member => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
-
# member.update_attributes params[:member]
-
# member.avatar.icon # => 'sad'
-
#
-
# By default you will only be able to set and update attributes on the
-
# associated model. If you want to destroy the associated model through the
-
# attributes hash, you have to enable it first using the
-
# <tt>:allow_destroy</tt> option.
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar, :allow_destroy => true
-
# end
-
#
-
# Now, when you add the <tt>_destroy</tt> key to the attributes hash, with a
-
# value that evaluates to +true+, you will destroy the associated model:
-
#
-
# member.avatar_attributes = { :id => '2', :_destroy => '1' }
-
# member.avatar.marked_for_destruction? # => true
-
# member.save
-
# member.reload.avatar # => nil
-
#
-
# Note that the model will _not_ be destroyed until the parent is saved.
-
#
-
# === One-to-many
-
#
-
# Consider a member that has a number of posts:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts
-
# end
-
#
-
# You can now set or update attributes on the associated posts through
-
# an attribute hash for a member: include the key +:posts_attributes+
-
# with an array of hashes of post attributes as a value.
-
#
-
# For each hash that does _not_ have an <tt>id</tt> key a new record will
-
# be instantiated, unless the hash also contains a <tt>_destroy</tt> key
-
# that evaluates to +true+.
-
#
-
# params = { :member => {
-
# :name => 'joe', :posts_attributes => [
-
# { :title => 'Kari, the awesome Ruby documentation browser!' },
-
# { :title => 'The egalitarian assumption of the modern citizen' },
-
# { :title => '', :_destroy => '1' } # this will be ignored
-
# ]
-
# }}
-
#
-
# member = Member.create(params['member'])
-
# member.posts.length # => 2
-
# member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
-
# member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
-
#
-
# You may also set a :reject_if proc to silently ignore any new record
-
# hashes if they fail to pass your criteria. For example, the previous
-
# example could be rewritten as:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes['title'].blank? }
-
# end
-
#
-
# params = { :member => {
-
# :name => 'joe', :posts_attributes => [
-
# { :title => 'Kari, the awesome Ruby documentation browser!' },
-
# { :title => 'The egalitarian assumption of the modern citizen' },
-
# { :title => '' } # this will be ignored because of the :reject_if proc
-
# ]
-
# }}
-
#
-
# member = Member.create(params['member'])
-
# member.posts.length # => 2
-
# member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
-
# member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
-
#
-
# Alternatively, :reject_if also accepts a symbol for using methods:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, :reject_if => :new_record?
-
# end
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, :reject_if => :reject_posts
-
#
-
# def reject_posts(attributed)
-
# attributed['title'].blank?
-
# end
-
# end
-
#
-
# If the hash contains an <tt>id</tt> key that matches an already
-
# associated record, the matching record will be modified:
-
#
-
# member.attributes = {
-
# :name => 'Joe',
-
# :posts_attributes => [
-
# { :id => 1, :title => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
-
# { :id => 2, :title => '[UPDATED] other post' }
-
# ]
-
# }
-
#
-
# member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
-
# member.posts.second.title # => '[UPDATED] other post'
-
#
-
# By default the associated records are protected from being destroyed. If
-
# you want to destroy any of the associated records through the attributes
-
# hash, you have to enable it first using the <tt>:allow_destroy</tt>
-
# option. This will allow you to also use the <tt>_destroy</tt> key to
-
# destroy existing records:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, :allow_destroy => true
-
# end
-
#
-
# params = { :member => {
-
# :posts_attributes => [{ :id => '2', :_destroy => '1' }]
-
# }}
-
#
-
# member.attributes = params['member']
-
# member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
-
# member.posts.length # => 2
-
# member.save
-
# member.reload.posts.length # => 1
-
#
-
# Nested attributes for an associated collection can also be passed in
-
# the form of a hash of hashes instead of an array of hashes:
-
#
-
# Member.create(:name => 'joe',
-
# :posts_attributes => { :first => { :title => 'Foo' },
-
# :second => { :title => 'Bar' } })
-
#
-
# has the same effect as
-
#
-
# Member.create(:name => 'joe',
-
# :posts_attributes => [ { :title => 'Foo' },
-
# { :title => 'Bar' } ])
-
#
-
# The keys of the hash which is the value for +:posts_attributes+ are
-
# ignored in this case.
-
# However, it is not allowed to use +'id'+ or +:id+ for one of
-
# such keys, otherwise the hash will be wrapped in an array and
-
# interpreted as an attribute hash for a single post.
-
#
-
# Passing attributes for an associated collection in the form of a hash
-
# of hashes can be used with hashes generated from HTTP/HTML parameters,
-
# where there maybe no natural way to submit an array of hashes.
-
#
-
# === Saving
-
#
-
# All changes to models, including the destruction of those marked for
-
# destruction, are saved and destroyed automatically and atomically when
-
# the parent model is saved. This happens inside the transaction initiated
-
# by the parents save method. See ActiveRecord::AutosaveAssociation.
-
#
-
# === Using with attr_accessible
-
#
-
# The use of <tt>attr_accessible</tt> can interfere with nested attributes
-
# if you're not careful. For example, if the <tt>Member</tt> model above
-
# was using <tt>attr_accessible</tt> like this:
-
#
-
# attr_accessible :name
-
#
-
# You would need to modify it to look like this:
-
#
-
# attr_accessible :name, :posts_attributes
-
#
-
# === Validating the presence of a parent model
-
#
-
# If you want to validate that a child record is associated with a parent
-
# record, you can use <tt>validates_presence_of</tt> and
-
# <tt>inverse_of</tt> as this example illustrates:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts, :inverse_of => :member
-
# accepts_nested_attributes_for :posts
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :member, :inverse_of => :posts
-
# validates_presence_of :member
-
# end
-
2
module ClassMethods
-
2
REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
-
-
# Defines an attributes writer for the specified association(s). If you
-
# are using <tt>attr_protected</tt> or <tt>attr_accessible</tt>, then you
-
# will need to add the attribute writer to the allowed list.
-
#
-
# Supported options:
-
# [:allow_destroy]
-
# If true, destroys any members from the attributes hash with a
-
# <tt>_destroy</tt> key and a value that evaluates to +true+
-
# (eg. 1, '1', true, or 'true'). This option is off by default.
-
# [:reject_if]
-
# Allows you to specify a Proc or a Symbol pointing to a method
-
# that checks whether a record should be built for a certain attribute
-
# hash. The hash is passed to the supplied Proc or the method
-
# and it should return either +true+ or +false+. When no :reject_if
-
# is specified, a record will be built for all attribute hashes that
-
# do not have a <tt>_destroy</tt> value that evaluates to true.
-
# Passing <tt>:all_blank</tt> instead of a Proc will create a proc
-
# that will reject a record where all the attributes are blank excluding
-
# any value for _destroy.
-
# [:limit]
-
# Allows you to specify the maximum number of the associated records that
-
# can be processed with the nested attributes. If the size of the
-
# nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
-
# exception is raised. If omitted, any number associations can be processed.
-
# Note that the :limit option is only applicable to one-to-many associations.
-
# [:update_only]
-
# Allows you to specify that an existing record may only be updated.
-
# A new record may only be created when there is no existing record.
-
# This option only works for one-to-one associations and is ignored for
-
# collection associations. This option is off by default.
-
#
-
# Examples:
-
# # creates avatar_attributes=
-
# accepts_nested_attributes_for :avatar, :reject_if => proc { |attributes| attributes['name'].blank? }
-
# # creates avatar_attributes=
-
# accepts_nested_attributes_for :avatar, :reject_if => :all_blank
-
# # creates avatar_attributes= and posts_attributes=
-
# accepts_nested_attributes_for :avatar, :posts, :allow_destroy => true
-
2
def accepts_nested_attributes_for(*attr_names)
-
4
options = { :allow_destroy => false, :update_only => false }
-
4
options.update(attr_names.extract_options!)
-
4
options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
-
4
options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank
-
-
4
attr_names.each do |association_name|
-
4
if reflection = reflect_on_association(association_name)
-
4
reflection.options[:autosave] = true
-
4
add_autosave_association_callbacks(reflection)
-
-
4
nested_attributes_options = self.nested_attributes_options.dup
-
4
nested_attributes_options[association_name.to_sym] = options
-
4
self.nested_attributes_options = nested_attributes_options
-
-
4
type = (reflection.collection? ? :collection : :one_to_one)
-
-
# remove_possible_method :pirate_attributes=
-
#
-
# def pirate_attributes=(attributes)
-
# assign_nested_attributes_for_one_to_one_association(:pirate, attributes, mass_assignment_options)
-
# end
-
4
class_eval <<-eoruby, __FILE__, __LINE__ + 1
-
remove_possible_method(:#{association_name}_attributes=)
-
-
def #{association_name}_attributes=(attributes)
-
assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes, mass_assignment_options)
-
end
-
eoruby
-
else
-
raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
-
end
-
end
-
end
-
end
-
-
# Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's
-
# used in conjunction with fields_for to build a form element for the
-
# destruction of this association.
-
#
-
# See ActionView::Helpers::FormHelper::fields_for for more info.
-
2
def _destroy
-
marked_for_destruction?
-
end
-
-
2
private
-
-
# Attribute hash keys that should not be assigned as normal attributes.
-
# These hash keys are nested attributes implementation details.
-
2
UNASSIGNABLE_KEYS = %w( id _destroy )
-
-
# Assigns the given attributes to the association.
-
#
-
# If update_only is false and the given attributes include an <tt>:id</tt>
-
# that matches the existing record's id, then the existing record will be
-
# modified. If update_only is true, a new record is only created when no
-
# object exists. Otherwise a new record will be built.
-
#
-
# If the given attributes include a matching <tt>:id</tt> attribute, or
-
# update_only is true, and a <tt>:_destroy</tt> key set to a truthy value,
-
# then the existing record will be marked for destruction.
-
2
def assign_nested_attributes_for_one_to_one_association(association_name, attributes, assignment_opts = {})
-
options = self.nested_attributes_options[association_name]
-
attributes = attributes.with_indifferent_access
-
-
if (options[:update_only] || !attributes['id'].blank?) && (record = send(association_name)) &&
-
(options[:update_only] || record.id.to_s == attributes['id'].to_s)
-
assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy], assignment_opts) unless call_reject_if(association_name, attributes)
-
-
elsif attributes['id'].present? && !assignment_opts[:without_protection]
-
raise_nested_attributes_record_not_found(association_name, attributes['id'])
-
-
elsif !reject_new_record?(association_name, attributes)
-
method = "build_#{association_name}"
-
if respond_to?(method)
-
send(method, attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
-
else
-
raise ArgumentError, "Cannot build association #{association_name}. Are you trying to build a polymorphic one-to-one association?"
-
end
-
end
-
end
-
-
# Assigns the given attributes to the collection association.
-
#
-
# Hashes with an <tt>:id</tt> value matching an existing associated record
-
# will update that record. Hashes without an <tt>:id</tt> value will build
-
# a new record for the association. Hashes with a matching <tt>:id</tt>
-
# value and a <tt>:_destroy</tt> key set to a truthy value will mark the
-
# matched record for destruction.
-
#
-
# For example:
-
#
-
# assign_nested_attributes_for_collection_association(:people, {
-
# '1' => { :id => '1', :name => 'Peter' },
-
# '2' => { :name => 'John' },
-
# '3' => { :id => '2', :_destroy => true }
-
# })
-
#
-
# Will update the name of the Person with ID 1, build a new associated
-
# person with the name `John', and mark the associated Person with ID 2
-
# for destruction.
-
#
-
# Also accepts an Array of attribute hashes:
-
#
-
# assign_nested_attributes_for_collection_association(:people, [
-
# { :id => '1', :name => 'Peter' },
-
# { :name => 'John' },
-
# { :id => '2', :_destroy => true }
-
# ])
-
2
def assign_nested_attributes_for_collection_association(association_name, attributes_collection, assignment_opts = {})
-
options = self.nested_attributes_options[association_name]
-
-
unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
-
raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
-
end
-
-
if options[:limit] && attributes_collection.size > options[:limit]
-
raise TooManyRecords, "Maximum #{options[:limit]} records are allowed. Got #{attributes_collection.size} records instead."
-
end
-
-
if attributes_collection.is_a? Hash
-
keys = attributes_collection.keys
-
attributes_collection = if keys.include?('id') || keys.include?(:id)
-
Array.wrap(attributes_collection)
-
else
-
attributes_collection.values
-
end
-
end
-
-
association = association(association_name)
-
-
existing_records = if association.loaded?
-
association.target
-
else
-
attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
-
attribute_ids.empty? ? [] : association.scoped.where(association.klass.primary_key => attribute_ids)
-
end
-
-
attributes_collection.each do |attributes|
-
attributes = attributes.with_indifferent_access
-
-
if attributes['id'].blank?
-
unless reject_new_record?(association_name, attributes)
-
association.build(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
-
end
-
elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
-
unless association.loaded? || call_reject_if(association_name, attributes)
-
# Make sure we are operating on the actual object which is in the association's
-
# proxy_target array (either by finding it, or adding it if not found)
-
target_record = association.target.detect { |record| record == existing_record }
-
-
if target_record
-
existing_record = target_record
-
else
-
association.add_to_target(existing_record)
-
end
-
-
end
-
-
if !call_reject_if(association_name, attributes)
-
assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy], assignment_opts)
-
end
-
elsif assignment_opts[:without_protection]
-
association.build(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
-
else
-
raise_nested_attributes_record_not_found(association_name, attributes['id'])
-
end
-
end
-
end
-
-
# Updates a record with the +attributes+ or marks it for destruction if
-
# +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
-
2
def assign_to_or_mark_for_destruction(record, attributes, allow_destroy, assignment_opts)
-
record.assign_attributes(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
-
record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy
-
end
-
-
# Determines if a hash contains a truthy _destroy key.
-
2
def has_destroy_flag?(hash)
-
ConnectionAdapters::Column.value_to_boolean(hash['_destroy'])
-
end
-
-
# Determines if a new record should be build by checking for
-
# has_destroy_flag? or if a <tt>:reject_if</tt> proc exists for this
-
# association and evaluates to +true+.
-
2
def reject_new_record?(association_name, attributes)
-
has_destroy_flag?(attributes) || call_reject_if(association_name, attributes)
-
end
-
-
2
def call_reject_if(association_name, attributes)
-
return false if has_destroy_flag?(attributes)
-
case callback = self.nested_attributes_options[association_name][:reject_if]
-
when Symbol
-
method(callback).arity == 0 ? send(callback) : send(callback, attributes)
-
when Proc
-
callback.call(attributes)
-
end
-
end
-
-
2
def raise_nested_attributes_record_not_found(association_name, record_id)
-
raise RecordNotFound, "Couldn't find #{self.class.reflect_on_association(association_name).klass.name} with ID=#{record_id} for #{self.class.name} with ID=#{id}"
-
end
-
-
2
def unassignable_keys(assignment_opts)
-
assignment_opts[:without_protection] ? UNASSIGNABLE_KEYS - %w[id] : UNASSIGNABLE_KEYS
-
end
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
-
2
module ActiveRecord
-
# = Active Record Observer
-
#
-
# Observer classes respond to life cycle callbacks to implement trigger-like
-
# behavior outside the original class. This is a great way to reduce the
-
# clutter that normally comes when the model class is burdened with
-
# functionality that doesn't pertain to the core responsibility of the
-
# class. Example:
-
#
-
# class CommentObserver < ActiveRecord::Observer
-
# def after_save(comment)
-
# Notifications.comment("admin@do.com", "New comment was posted", comment).deliver
-
# end
-
# end
-
#
-
# This Observer sends an email when a Comment#save is finished.
-
#
-
# class ContactObserver < ActiveRecord::Observer
-
# def after_create(contact)
-
# contact.logger.info('New contact added!')
-
# end
-
#
-
# def after_destroy(contact)
-
# contact.logger.warn("Contact with an id of #{contact.id} was destroyed!")
-
# end
-
# end
-
#
-
# This Observer uses logger to log when specific callbacks are triggered.
-
#
-
# == Observing a class that can't be inferred
-
#
-
# Observers will by default be mapped to the class with which they share a name. So CommentObserver will
-
# be tied to observing Comment, ProductManagerObserver to ProductManager, and so on. If you want to name your observer
-
# differently than the class you're interested in observing, you can use the Observer.observe class method which takes
-
# either the concrete class (Product) or a symbol for that class (:product):
-
#
-
# class AuditObserver < ActiveRecord::Observer
-
# observe :account
-
#
-
# def after_update(account)
-
# AuditTrail.new(account, "UPDATED")
-
# end
-
# end
-
#
-
# If the audit observer needs to watch more than one kind of object, this can be specified with multiple arguments:
-
#
-
# class AuditObserver < ActiveRecord::Observer
-
# observe :account, :balance
-
#
-
# def after_update(record)
-
# AuditTrail.new(record, "UPDATED")
-
# end
-
# end
-
#
-
# The AuditObserver will now act on both updates to Account and Balance by treating them both as records.
-
#
-
# == Available callback methods
-
#
-
# The observer can implement callback methods for each of the methods described in the Callbacks module.
-
#
-
# == Storing Observers in Rails
-
#
-
# If you're using Active Record within Rails, observer classes are usually stored in app/models with the
-
# naming convention of app/models/audit_observer.rb.
-
#
-
# == Configuration
-
#
-
# In order to activate an observer, list it in the <tt>config.active_record.observers</tt> configuration
-
# setting in your <tt>config/application.rb</tt> file.
-
#
-
# config.active_record.observers = :comment_observer, :signup_observer
-
#
-
# Observers will not be invoked unless you define these in your application configuration.
-
#
-
# == Loading
-
#
-
# Observers register themselves in the model class they observe, since it is the class that
-
# notifies them of events when they occur. As a side-effect, when an observer is loaded its
-
# corresponding model class is loaded.
-
#
-
# Up to (and including) Rails 2.0.2 observers were instantiated between plugins and
-
# application initializers. Now observers are loaded after application initializers,
-
# so observed models can make use of extensions.
-
#
-
# If by any chance you are using observed models in the initialization you can still
-
# load their observers by calling <tt>ModelObserver.instance</tt> before. Observers are
-
# singletons and that call instantiates and registers them.
-
#
-
2
class Observer < ActiveModel::Observer
-
-
2
protected
-
-
2
def observed_classes
-
klasses = super
-
klasses + klasses.map { |klass| klass.descendants }.flatten
-
end
-
-
2
def add_observer!(klass)
-
super
-
define_callbacks klass
-
end
-
-
2
def define_callbacks(klass)
-
observer = self
-
observer_name = observer.class.name.underscore.gsub('/', '__')
-
-
ActiveRecord::Callbacks::CALLBACKS.each do |callback|
-
next unless respond_to?(callback)
-
callback_meth = :"_notify_#{observer_name}_for_#{callback}"
-
unless klass.respond_to?(callback_meth)
-
klass.send(:define_method, callback_meth) do |&block|
-
observer.update(callback, self, &block)
-
end
-
klass.send(callback, callback_meth)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
-
2
module ActiveRecord
-
# = Active Record Persistence
-
2
module Persistence
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
# Creates an object (or multiple objects) and saves it to the database, if validations pass.
-
# The resulting object is returned whether the object was saved successfully to the database or not.
-
#
-
# The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the
-
# attributes on the objects that are to be created.
-
#
-
# +create+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options
-
# in the +options+ parameter.
-
#
-
# ==== Examples
-
# # Create a single new object
-
# User.create(:first_name => 'Jamie')
-
#
-
# # Create a single new object using the :admin mass-assignment security role
-
# User.create({ :first_name => 'Jamie', :is_admin => true }, :as => :admin)
-
#
-
# # Create a single new object bypassing mass-assignment security
-
# User.create({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
-
#
-
# # Create an Array of new objects
-
# User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
-
#
-
# # Create a single object and pass it into a block to set other attributes.
-
# User.create(:first_name => 'Jamie') do |u|
-
# u.is_admin = false
-
# end
-
#
-
# # Creating an Array of new objects using a block, where the block is executed for each object:
-
# User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
-
# u.is_admin = false
-
# end
-
2
def create(attributes = nil, options = {}, &block)
-
223
if attributes.is_a?(Array)
-
attributes.collect { |attr| create(attr, options, &block) }
-
else
-
223
object = new(attributes, options, &block)
-
223
object.save
-
223
object
-
end
-
end
-
end
-
-
# Returns true if this object hasn't been saved yet -- that is, a record
-
# for the object doesn't exist in the data store yet; otherwise, returns false.
-
2
def new_record?
-
1146
@new_record
-
end
-
-
# Returns true if this object has been destroyed, otherwise returns false.
-
2
def destroyed?
-
174
@destroyed
-
end
-
-
# Returns if the record is persisted, i.e. it's not a new record and it was
-
# not destroyed.
-
2
def persisted?
-
78
!(new_record? || destroyed?)
-
end
-
-
# Saves the model.
-
#
-
# If the model is new a record gets created in the database, otherwise
-
# the existing record gets updated.
-
#
-
# By default, save always run validations. If any of them fail the action
-
# is cancelled and +save+ returns +false+. However, if you supply
-
# :validate => false, validations are bypassed altogether. See
-
# ActiveRecord::Validations for more information.
-
#
-
# There's a series of callbacks associated with +save+. If any of the
-
# <tt>before_*</tt> callbacks return +false+ the action is cancelled and
-
# +save+ returns +false+. See ActiveRecord::Callbacks for further
-
# details.
-
2
def save(*)
-
332
begin
-
332
create_or_update
-
rescue ActiveRecord::RecordInvalid
-
false
-
end
-
end
-
-
# Saves the model.
-
#
-
# If the model is new a record gets created in the database, otherwise
-
# the existing record gets updated.
-
#
-
# With <tt>save!</tt> validations always run. If any of them fail
-
# ActiveRecord::RecordInvalid gets raised. See ActiveRecord::Validations
-
# for more information.
-
#
-
# There's a series of callbacks associated with <tt>save!</tt>. If any of
-
# the <tt>before_*</tt> callbacks return +false+ the action is cancelled
-
# and <tt>save!</tt> raises ActiveRecord::RecordNotSaved. See
-
# ActiveRecord::Callbacks for further details.
-
2
def save!(*)
-
31
create_or_update || raise(RecordNotSaved)
-
end
-
-
# Deletes the record in the database and freezes this instance to
-
# reflect that no changes should be made (since they can't be
-
# persisted). Returns the frozen instance.
-
#
-
# The row is simply removed with an SQL +DELETE+ statement on the
-
# record's primary key, and no callbacks are executed.
-
#
-
# To enforce the object's +before_destroy+ and +after_destroy+
-
# callbacks, Observer methods, or any <tt>:dependent</tt> association
-
# options, use <tt>#destroy</tt>.
-
2
def delete
-
if persisted?
-
self.class.delete(id)
-
IdentityMap.remove(self) if IdentityMap.enabled?
-
end
-
@destroyed = true
-
freeze
-
end
-
-
# Deletes the record in the database and freezes this instance to reflect
-
# that no changes should be made (since they can't be persisted).
-
2
def destroy
-
21
destroy_associations
-
-
21
if persisted?
-
21
IdentityMap.remove(self) if IdentityMap.enabled?
-
21
pk = self.class.primary_key
-
21
column = self.class.columns_hash[pk]
-
21
substitute = connection.substitute_at(column, 0)
-
-
21
relation = self.class.unscoped.where(
-
self.class.arel_table[pk].eq(substitute))
-
-
21
relation.bind_values = [[column, id]]
-
21
relation.delete_all
-
end
-
-
21
@destroyed = true
-
21
freeze
-
end
-
-
# Returns an instance of the specified +klass+ with the attributes of the
-
# current record. This is mostly useful in relation to single-table
-
# inheritance structures where you want a subclass to appear as the
-
# superclass. This can be used along with record identification in
-
# Action Pack to allow, say, <tt>Client < Company</tt> to do something
-
# like render <tt>:partial => @client.becomes(Company)</tt> to render that
-
# instance using the companies/company partial instead of clients/client.
-
#
-
# Note: The new instance will share a link to the same attributes as the original class.
-
# So any change to the attributes in either instance will affect the other.
-
2
def becomes(klass)
-
became = klass.new
-
became.instance_variable_set("@attributes", @attributes)
-
became.instance_variable_set("@attributes_cache", @attributes_cache)
-
became.instance_variable_set("@new_record", new_record?)
-
became.instance_variable_set("@destroyed", destroyed?)
-
became.instance_variable_set("@errors", errors)
-
became.send("#{klass.inheritance_column}=", klass.name) unless self.class.descends_from_active_record?
-
became
-
end
-
-
# Updates a single attribute and saves the record.
-
# This is especially useful for boolean flags on existing records. Also note that
-
#
-
# * Validation is skipped.
-
# * Callbacks are invoked.
-
# * updated_at/updated_on column is updated if that column is available.
-
# * Updates all the attributes that are dirty in this object.
-
#
-
2
def update_attribute(name, value)
-
37
name = name.to_s
-
37
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
-
37
send("#{name}=", value)
-
37
save(:validate => false)
-
end
-
-
# Updates a single attribute of an object, without calling save.
-
#
-
# * Validation is skipped.
-
# * Callbacks are skipped.
-
# * updated_at/updated_on column is not updated if that column is available.
-
#
-
# Raises an +ActiveRecordError+ when called on new objects, or when the +name+
-
# attribute is marked as readonly.
-
2
def update_column(name, value)
-
44
name = name.to_s
-
44
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
-
44
raise ActiveRecordError, "can not update on a new record object" unless persisted?
-
-
44
updated_count = self.class.unscoped.update_all({ name => value }, self.class.primary_key => id)
-
-
44
raw_write_attribute(name, value)
-
-
44
updated_count == 1
-
end
-
-
# Updates the attributes of the model from the passed-in hash and saves the
-
# record, all wrapped in a transaction. If the object is invalid, the saving
-
# will fail and false will be returned.
-
#
-
# When updating model attributes, mass-assignment security protection is respected.
-
# If no +:as+ option is supplied then the +:default+ role will be used.
-
# If you want to bypass the protection given by +attr_protected+ and
-
# +attr_accessible+ then you can do so using the +:without_protection+ option.
-
2
def update_attributes(attributes, options = {})
-
# The following transaction covers any possible database side-effects of the
-
# attributes assignment. For example, setting the IDs of a child collection.
-
9
with_transaction_returning_status do
-
9
self.assign_attributes(attributes, options)
-
9
save
-
end
-
end
-
-
# Updates its receiver just like +update_attributes+ but calls <tt>save!</tt> instead
-
# of +save+, so an exception is raised if the record is invalid.
-
2
def update_attributes!(attributes, options = {})
-
# The following transaction covers any possible database side-effects of the
-
# attributes assignment. For example, setting the IDs of a child collection.
-
with_transaction_returning_status do
-
self.assign_attributes(attributes, options)
-
save!
-
end
-
end
-
-
# Initializes +attribute+ to zero if +nil+ and adds the value passed as +by+ (default is 1).
-
# The increment is performed directly on the underlying attribute, no setter is invoked.
-
# Only makes sense for number-based attributes. Returns +self+.
-
2
def increment(attribute, by = 1)
-
self[attribute] ||= 0
-
self[attribute] += by
-
self
-
end
-
-
# Wrapper around +increment+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
2
def increment!(attribute, by = 1)
-
increment(attribute, by).update_attribute(attribute, self[attribute])
-
end
-
-
# Initializes +attribute+ to zero if +nil+ and subtracts the value passed as +by+ (default is 1).
-
# The decrement is performed directly on the underlying attribute, no setter is invoked.
-
# Only makes sense for number-based attributes. Returns +self+.
-
2
def decrement(attribute, by = 1)
-
self[attribute] ||= 0
-
self[attribute] -= by
-
self
-
end
-
-
# Wrapper around +decrement+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
2
def decrement!(attribute, by = 1)
-
decrement(attribute, by).update_attribute(attribute, self[attribute])
-
end
-
-
# Assigns to +attribute+ the boolean opposite of <tt>attribute?</tt>. So
-
# if the predicate returns +true+ the attribute will become +false+. This
-
# method toggles directly the underlying value without calling any setter.
-
# Returns +self+.
-
2
def toggle(attribute)
-
self[attribute] = !send("#{attribute}?")
-
self
-
end
-
-
# Wrapper around +toggle+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
2
def toggle!(attribute)
-
toggle(attribute).update_attribute(attribute, self[attribute])
-
end
-
-
# Reloads the attributes of this object from the database.
-
# The optional options argument is passed to find when reloading so you
-
# may do e.g. record.reload(:lock => true) to reload the same record with
-
# an exclusive row lock.
-
2
def reload(options = nil)
-
4
clear_aggregation_cache
-
4
clear_association_cache
-
-
4
IdentityMap.without do
-
8
fresh_object = self.class.unscoped { self.class.find(self.id, options) }
-
4
@attributes.update(fresh_object.instance_variable_get('@attributes'))
-
end
-
-
4
@attributes_cache = {}
-
4
self
-
end
-
-
# Saves the record with the updated_at/on attributes set to the current time.
-
# Please note that no validation is performed and no callbacks are executed.
-
# If an attribute name is passed, that attribute is updated along with
-
# updated_at/on attributes.
-
#
-
# product.touch # updates updated_at/on
-
# product.touch(:designed_at) # updates the designed_at attribute and updated_at/on
-
#
-
# If used along with +belongs_to+ then +touch+ will invoke +touch+ method on associated object.
-
#
-
# class Brake < ActiveRecord::Base
-
# belongs_to :car, :touch => true
-
# end
-
#
-
# class Car < ActiveRecord::Base
-
# belongs_to :corporation, :touch => true
-
# end
-
#
-
# # triggers @brake.car.touch and @brake.car.corporation.touch
-
# @brake.touch
-
2
def touch(name = nil)
-
attributes = timestamp_attributes_for_update_in_model
-
attributes << name if name
-
-
unless attributes.empty?
-
current_time = current_time_from_proper_timezone
-
changes = {}
-
-
attributes.each do |column|
-
changes[column.to_s] = write_attribute(column.to_s, current_time)
-
end
-
-
changes[self.class.locking_column] = increment_lock if locking_enabled?
-
-
@changed_attributes.except!(*changes.keys)
-
primary_key = self.class.primary_key
-
self.class.unscoped.update_all(changes, { primary_key => self[primary_key] }) == 1
-
end
-
end
-
-
2
private
-
-
# A hook to be overridden by association modules.
-
2
def destroy_associations
-
end
-
-
2
def create_or_update
-
363
raise ReadOnlyRecord if readonly?
-
363
result = new_record? ? create : update
-
363
result != false
-
end
-
-
# Updates the associated record with values matching those of the instance attributes.
-
# Returns the number of affected rows.
-
2
def update(attribute_names = @attributes.keys)
-
55
attributes_with_values = arel_attributes_values(false, false, attribute_names)
-
55
return 0 if attributes_with_values.empty?
-
54
klass = self.class
-
54
stmt = klass.unscoped.where(klass.arel_table[klass.primary_key].eq(id)).arel.compile_update(attributes_with_values)
-
54
klass.connection.update stmt
-
end
-
-
# Creates a record with values matching those of the instance attributes
-
# and returns its id.
-
2
def create
-
308
attributes_values = arel_attributes_values(!id.nil?)
-
-
308
new_id = self.class.unscoped.insert attributes_values
-
-
308
self.id ||= new_id if self.class.primary_key
-
-
308
IdentityMap.add(self) if IdentityMap.enabled?
-
308
@new_record = false
-
308
id
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActiveRecord
-
# = Active Record Query Cache
-
2
class QueryCache
-
2
module ClassMethods
-
# Enable the query cache within the block if Active Record is configured.
-
2
def cache(&block)
-
if ActiveRecord::Base.connected?
-
connection.cache(&block)
-
else
-
yield
-
end
-
end
-
-
# Disable the query cache within the block if Active Record is configured.
-
2
def uncached(&block)
-
if ActiveRecord::Base.connected?
-
connection.uncached(&block)
-
else
-
yield
-
end
-
end
-
end
-
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
class BodyProxy # :nodoc:
-
2
def initialize(original_cache_value, target, connection_id)
-
@original_cache_value = original_cache_value
-
@target = target
-
@connection_id = connection_id
-
end
-
-
2
def method_missing(method_sym, *arguments, &block)
-
@target.send(method_sym, *arguments, &block)
-
end
-
-
2
def respond_to?(method_sym, include_private = false)
-
super || @target.respond_to?(method_sym)
-
end
-
-
2
def each(&block)
-
@target.each(&block)
-
end
-
-
2
def close
-
@target.close if @target.respond_to?(:close)
-
ensure
-
ActiveRecord::Base.connection_id = @connection_id
-
ActiveRecord::Base.connection.clear_query_cache
-
unless @original_cache_value
-
ActiveRecord::Base.connection.disable_query_cache!
-
end
-
end
-
end
-
-
2
def call(env)
-
old = ActiveRecord::Base.connection.query_cache_enabled
-
ActiveRecord::Base.connection.enable_query_cache!
-
-
status, headers, body = @app.call(env)
-
[status, headers, BodyProxy.new(old, body, ActiveRecord::Base.connection_id)]
-
rescue Exception => e
-
ActiveRecord::Base.connection.clear_query_cache
-
unless old
-
ActiveRecord::Base.connection.disable_query_cache!
-
end
-
raise e
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/delegation'
-
-
2
module ActiveRecord
-
2
module Querying
-
2
delegate :find, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to => :scoped
-
2
delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :scoped
-
2
delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped
-
2
delegate :find_each, :find_in_batches, :to => :scoped
-
2
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
-
:where, :preload, :eager_load, :includes, :from, :lock, :readonly,
-
:having, :create_with, :uniq, :to => :scoped
-
2
delegate :count, :average, :minimum, :maximum, :sum, :calculate, :pluck, :to => :scoped
-
-
# Executes a custom SQL query against your database and returns all the results. The results will
-
# be returned as an array with columns requested encapsulated as attributes of the model you call
-
# this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
-
# a Product object with the attributes you specified in the SQL query.
-
#
-
# If you call a complicated SQL query which spans multiple tables the columns specified by the
-
# SELECT will be attributes of the model, whether or not they are columns of the corresponding
-
# table.
-
#
-
# The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
-
# no database agnostic conversions performed. This should be a last resort because using, for example,
-
# MySQL specific terms will lock you to using that particular database engine or require you to
-
# change your call if you switch engines.
-
#
-
# ==== Examples
-
# # A simple SQL query spanning multiple tables
-
# Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
-
# > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
-
#
-
# # You can use the same string replacement techniques as you can with ActiveRecord#find
-
# Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
-
# > [#<Post:0x36bff9c @attributes={"title"=>"The Cheap Man Buys Twice"}>, ...]
-
2
def find_by_sql(sql, binds = [])
-
816
logging_query_plan do
-
1517
connection.select_all(sanitize_sql(sql), "#{name} Load", binds).collect! { |record| instantiate(record) }
-
end
-
end
-
-
# Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
-
# The use of this method should be restricted to complicated SQL queries that can't be executed
-
# using the ActiveRecord::Calculations class methods. Look into those before using this.
-
#
-
# ==== Parameters
-
#
-
# * +sql+ - An SQL statement which should return a count query from the database, see the example below.
-
#
-
# ==== Examples
-
#
-
# Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
-
2
def count_by_sql(sql)
-
sql = sanitize_conditions(sql)
-
connection.select_value(sql, "#{name} Count").to_i
-
end
-
end
-
end
-
2
require "active_record"
-
2
require "rails"
-
2
require "active_model/railtie"
-
-
# For now, action_controller must always be present with
-
# rails, so let's make sure that it gets required before
-
# here. This is needed for correctly setting up the middleware.
-
# In the future, this might become an optional require.
-
2
require "action_controller/railtie"
-
-
2
module ActiveRecord
-
# = Active Record Railtie
-
2
class Railtie < Rails::Railtie
-
2
config.active_record = ActiveSupport::OrderedOptions.new
-
-
2
config.app_generators.orm :active_record, :migration => true,
-
:timestamps => true
-
-
2
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
-
"ActiveRecord::QueryCache"
-
-
2
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
-
"ActiveRecord::ConnectionAdapters::ConnectionManagement"
-
-
2
config.action_dispatch.rescue_responses.merge!(
-
'ActiveRecord::RecordNotFound' => :not_found,
-
'ActiveRecord::StaleObjectError' => :conflict,
-
'ActiveRecord::RecordInvalid' => :unprocessable_entity,
-
'ActiveRecord::RecordNotSaved' => :unprocessable_entity
-
)
-
-
2
rake_tasks do
-
require "active_record/base"
-
load "active_record/railties/databases.rake"
-
end
-
-
# When loading console, force ActiveRecord::Base to be loaded
-
# to avoid cross references when loading a constant for the
-
# first time. Also, make it output to STDERR.
-
2
console do |app|
-
require "active_record/railties/console_sandbox" if app.sandbox?
-
require "active_record/base"
-
ActiveRecord::Base.logger = Logger.new(STDERR)
-
end
-
-
2
runner do |app|
-
require "active_record/base"
-
end
-
-
2
initializer "active_record.initialize_timezone" do
-
2
ActiveSupport.on_load(:active_record) do
-
2
self.time_zone_aware_attributes = true
-
2
self.default_timezone = :utc
-
end
-
end
-
-
2
initializer "active_record.logger" do
-
4
ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
-
end
-
-
2
initializer "active_record.identity_map" do |app|
-
config.app_middleware.insert_after "::ActionDispatch::Callbacks",
-
2
"ActiveRecord::IdentityMap::Middleware" if config.active_record.delete(:identity_map)
-
end
-
-
2
initializer "active_record.set_configs" do |app|
-
2
ActiveSupport.on_load(:active_record) do
-
2
if app.config.active_record.delete(:whitelist_attributes)
-
2
attr_accessible(nil)
-
end
-
2
app.config.active_record.each do |k,v|
-
2
send "#{k}=", v
-
end
-
end
-
end
-
-
# This sets the database configuration from Configuration#database_configuration
-
# and then establishes the connection.
-
2
initializer "active_record.initialize_database" do |app|
-
2
ActiveSupport.on_load(:active_record) do
-
2
db_connection_type = "DATABASE_URL"
-
2
unless ENV['DATABASE_URL']
-
2
db_connection_type = "database.yml"
-
2
self.configurations = app.config.database_configuration
-
end
-
2
Rails.logger.info "Connecting to database specified by #{db_connection_type}"
-
-
2
establish_connection
-
end
-
end
-
-
# Expose database runtime to controller for logging.
-
2
initializer "active_record.log_runtime" do |app|
-
2
require "active_record/railties/controller_runtime"
-
2
ActiveSupport.on_load(:action_controller) do
-
2
include ActiveRecord::Railties::ControllerRuntime
-
end
-
end
-
-
2
initializer "active_record.set_reloader_hooks" do |app|
-
2
hook = lambda do
-
2
ActiveRecord::Base.clear_reloadable_connections!
-
2
ActiveRecord::Base.clear_cache!
-
end
-
-
2
if app.config.reload_classes_only_on_change
-
2
ActiveSupport.on_load(:active_record) do
-
2
ActionDispatch::Reloader.to_prepare(&hook)
-
end
-
else
-
ActiveSupport.on_load(:active_record) do
-
ActionDispatch::Reloader.to_cleanup(&hook)
-
end
-
end
-
end
-
-
2
initializer "active_record.add_watchable_files" do |app|
-
2
config.watchable_files.concat ["#{app.root}/db/schema.rb", "#{app.root}/db/structure.sql"]
-
end
-
-
2
config.after_initialize do
-
2
ActiveSupport.on_load(:active_record) do
-
2
instantiate_observers
-
-
2
ActionDispatch::Reloader.to_prepare do
-
ActiveRecord::Base.instantiate_observers
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attr_internal'
-
2
require 'active_record/log_subscriber'
-
-
2
module ActiveRecord
-
2
module Railties
-
2
module ControllerRuntime #:nodoc:
-
2
extend ActiveSupport::Concern
-
-
2
protected
-
-
2
attr_internal :db_runtime
-
-
2
def process_action(action, *args)
-
# We also need to reset the runtime before each action
-
# because of queries in middleware or in cases we are streaming
-
# and it won't be cleaned up by the method below.
-
9
ActiveRecord::LogSubscriber.reset_runtime
-
9
super
-
end
-
-
2
def cleanup_view_runtime
-
if ActiveRecord::Base.connected?
-
db_rt_before_render = ActiveRecord::LogSubscriber.reset_runtime
-
runtime = super
-
db_rt_after_render = ActiveRecord::LogSubscriber.reset_runtime
-
self.db_runtime = db_rt_before_render + db_rt_after_render
-
runtime - db_rt_after_render
-
else
-
super
-
end
-
end
-
-
2
def append_info_to_payload(payload)
-
9
super
-
9
if ActiveRecord::Base.connected?
-
9
payload[:db_runtime] = (db_runtime || 0) + ActiveRecord::LogSubscriber.reset_runtime
-
end
-
end
-
-
2
module ClassMethods
-
2
def log_process_action(payload)
-
9
messages, db_runtime = super, payload[:db_runtime]
-
9
messages << ("ActiveRecord: %.1fms" % db_runtime.to_f) if db_runtime
-
9
messages
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/core_ext/class/attribute'
-
-
2
module ActiveRecord
-
2
module ReadonlyAttributes
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :_attr_readonly, :instance_writer => false
-
2
self._attr_readonly = []
-
end
-
-
2
module ClassMethods
-
# Attributes listed as readonly will be used to create a new record but update operations will
-
# ignore these fields.
-
2
def attr_readonly(*attributes)
-
self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || [])
-
end
-
-
# Returns an array of all the attributes that have been specified as readonly.
-
2
def readonly_attributes
-
195
self._attr_readonly
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/object/inclusion'
-
-
2
module ActiveRecord
-
# = Active Record Reflection
-
2
module Reflection # :nodoc:
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :reflections
-
2
self.reflections = {}
-
end
-
-
# Reflection enables to interrogate Active Record classes and objects
-
# about their associations and aggregations. This information can,
-
# for example, be used in a form builder that takes an Active Record object
-
# and creates input fields for all of the attributes depending on their type
-
# and displays the associations to other objects.
-
#
-
# MacroReflection class has info for AggregateReflection and AssociationReflection
-
# classes.
-
2
module ClassMethods
-
2
def create_reflection(macro, name, options, active_record)
-
64
case macro
-
when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many
-
64
klass = options[:through] ? ThroughReflection : AssociationReflection
-
64
reflection = klass.new(macro, name, options, active_record)
-
when :composed_of
-
reflection = AggregateReflection.new(macro, name, options, active_record)
-
end
-
-
64
self.reflections = self.reflections.merge(name => reflection)
-
64
reflection
-
end
-
-
# Returns an array of AggregateReflection objects for all the aggregations in the class.
-
2
def reflect_on_all_aggregations
-
reflections.values.grep(AggregateReflection)
-
end
-
-
# Returns the AggregateReflection object for the named +aggregation+ (use the symbol).
-
#
-
# Account.reflect_on_aggregation(:balance) # => the balance AggregateReflection
-
#
-
2
def reflect_on_aggregation(aggregation)
-
98
reflections[aggregation].is_a?(AggregateReflection) ? reflections[aggregation] : nil
-
end
-
-
# Returns an array of AssociationReflection objects for all the
-
# associations in the class. If you only want to reflect on a certain
-
# association type, pass in the symbol (<tt>:has_many</tt>, <tt>:has_one</tt>,
-
# <tt>:belongs_to</tt>) as the first parameter.
-
#
-
# Example:
-
#
-
# Account.reflect_on_all_associations # returns an array of all associations
-
# Account.reflect_on_all_associations(:has_many) # returns an array of all has_many associations
-
#
-
2
def reflect_on_all_associations(macro = nil)
-
26
association_reflections = reflections.values.grep(AssociationReflection)
-
26
macro ? association_reflections.select { |reflection| reflection.macro == macro } : association_reflections
-
end
-
-
# Returns the AssociationReflection object for the +association+ (use the symbol).
-
#
-
# Account.reflect_on_association(:owner) # returns the owner AssociationReflection
-
# Invoice.reflect_on_association(:line_items).macro # returns :has_many
-
#
-
2
def reflect_on_association(association)
-
326
reflections[association].is_a?(AssociationReflection) ? reflections[association] : nil
-
end
-
-
# Returns an array of AssociationReflection objects for all associations which have <tt>:autosave</tt> enabled.
-
2
def reflect_on_all_autosave_associations
-
2
reflections.values.select { |reflection| reflection.options[:autosave] }
-
end
-
end
-
-
-
# Abstract base class for AggregateReflection and AssociationReflection. Objects of
-
# AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
-
2
class MacroReflection
-
# Returns the name of the macro.
-
#
-
# <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>:balance</tt>
-
# <tt>has_many :clients</tt> returns <tt>:clients</tt>
-
2
attr_reader :name
-
-
# Returns the macro type.
-
#
-
# <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>:composed_of</tt>
-
# <tt>has_many :clients</tt> returns <tt>:has_many</tt>
-
2
attr_reader :macro
-
-
# Returns the hash of options used for the macro.
-
#
-
# <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>{ :class_name => "Money" }</tt>
-
# <tt>has_many :clients</tt> returns +{}+
-
2
attr_reader :options
-
-
2
attr_reader :active_record
-
-
2
attr_reader :plural_name # :nodoc:
-
-
2
def initialize(macro, name, options, active_record)
-
64
@macro = macro
-
64
@name = name
-
64
@options = options
-
64
@active_record = active_record
-
64
@plural_name = active_record.pluralize_table_names ?
-
name.to_s.pluralize : name.to_s
-
end
-
-
# Returns the class for the macro.
-
#
-
# <tt>composed_of :balance, :class_name => 'Money'</tt> returns the Money class
-
# <tt>has_many :clients</tt> returns the Client class
-
2
def klass
-
@klass ||= class_name.constantize
-
end
-
-
# Returns the class name for the macro.
-
#
-
# <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>'Money'</tt>
-
# <tt>has_many :clients</tt> returns <tt>'Client'</tt>
-
2
def class_name
-
20
@class_name ||= (options[:class_name] || derive_class_name).to_s
-
end
-
-
# Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute,
-
# and +other_aggregation+ has an options hash assigned to it.
-
2
def ==(other_aggregation)
-
super ||
-
other_aggregation.kind_of?(self.class) &&
-
name == other_aggregation.name &&
-
other_aggregation.options &&
-
789
active_record == other_aggregation.active_record
-
end
-
-
2
def sanitized_conditions #:nodoc:
-
@sanitized_conditions ||= klass.send(:sanitize_sql, options[:conditions]) if options[:conditions]
-
end
-
-
2
private
-
2
def derive_class_name
-
name.to_s.camelize
-
end
-
end
-
-
-
# Holds all the meta-data about an aggregation as it was specified in the
-
# Active Record class.
-
2
class AggregateReflection < MacroReflection #:nodoc:
-
end
-
-
# Holds all the meta-data about an association as it was specified in the
-
# Active Record class.
-
2
class AssociationReflection < MacroReflection #:nodoc:
-
# Returns the target association's class.
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :books
-
# end
-
#
-
# Author.reflect_on_association(:books).klass
-
# # => Book
-
#
-
# <b>Note:</b> Do not call +klass.new+ or +klass.create+ to instantiate
-
# a new association object. Use +build_association+ or +create_association+
-
# instead. This allows plugins to hook into association object creation.
-
2
def klass
-
1789
@klass ||= active_record.send(:compute_type, class_name)
-
end
-
-
2
def initialize(macro, name, options, active_record)
-
64
super
-
64
@collection = macro.in?([:has_many, :has_and_belongs_to_many])
-
end
-
-
# Returns a new, unsaved instance of the associated class. +options+ will
-
# be passed to the class's constructor.
-
2
def build_association(*options, &block)
-
5
klass.new(*options, &block)
-
end
-
-
2
def table_name
-
@table_name ||= klass.table_name
-
end
-
-
2
def quoted_table_name
-
@quoted_table_name ||= klass.quoted_table_name
-
end
-
-
2
def foreign_key
-
1792
@foreign_key ||= options[:foreign_key] || derive_foreign_key
-
end
-
-
2
def foreign_type
-
@foreign_type ||= options[:foreign_type] || "#{name}_type"
-
end
-
-
2
def type
-
268
@type ||= options[:as] && "#{options[:as]}_type"
-
end
-
-
2
def primary_key_column
-
@primary_key_column ||= klass.columns.find { |c| c.name == klass.primary_key }
-
end
-
-
2
def association_foreign_key
-
@association_foreign_key ||= options[:association_foreign_key] || class_name.foreign_key
-
end
-
-
# klass option is necessary to support loading polymorphic associations
-
2
def association_primary_key(klass = nil)
-
161
options[:primary_key] || primary_key(klass || self.klass)
-
end
-
-
2
def active_record_primary_key
-
142
@active_record_primary_key ||= options[:primary_key] || primary_key(active_record)
-
end
-
-
2
def counter_cache_column
-
2
if options[:counter_cache] == true
-
"#{active_record.name.demodulize.underscore.pluralize}_count"
-
2
elsif options[:counter_cache]
-
options[:counter_cache].to_s
-
end
-
end
-
-
2
def columns(tbl_name, log_msg)
-
@columns ||= klass.connection.columns(tbl_name, log_msg)
-
end
-
-
2
def reset_column_information
-
@columns = nil
-
end
-
-
2
def check_validity!
-
293
check_validity_of_inverse!
-
end
-
-
2
def check_validity_of_inverse!
-
293
unless options[:polymorphic]
-
293
if has_inverse? && inverse_of.nil?
-
raise InverseOfAssociationNotFoundError.new(self)
-
end
-
end
-
end
-
-
2
def through_reflection
-
nil
-
end
-
-
2
def source_reflection
-
nil
-
end
-
-
# A chain of reflections from this one back to the owner. For more see the explanation in
-
# ThroughReflection.
-
2
def chain
-
789
[self]
-
end
-
-
2
def nested?
-
false
-
end
-
-
# An array of arrays of conditions. Each item in the outside array corresponds to a reflection
-
# in the #chain. The inside arrays are simply conditions (and each condition may itself be
-
# a hash, array, arel predicate, etc...)
-
2
def conditions
-
263
[[options[:conditions]].compact]
-
end
-
-
2
alias :source_macro :macro
-
-
2
def has_inverse?
-
534
@options[:inverse_of]
-
end
-
-
2
def inverse_of
-
241
if has_inverse?
-
@inverse_of ||= klass.reflect_on_association(options[:inverse_of])
-
end
-
end
-
-
2
def polymorphic_inverse_of(associated_class)
-
if has_inverse?
-
if inverse_relationship = associated_class.reflect_on_association(options[:inverse_of])
-
inverse_relationship
-
else
-
raise InverseOfAssociationNotFoundError.new(self, associated_class)
-
end
-
end
-
end
-
-
# Returns whether or not this association reflection is for a collection
-
# association. Returns +true+ if the +macro+ is either +has_many+ or
-
# +has_and_belongs_to_many+, +false+ otherwise.
-
2
def collection?
-
92
@collection
-
end
-
-
# Returns whether or not the association should be validated as part of
-
# the parent's validation.
-
#
-
# Unless you explicitly disable validation with
-
# <tt>:validate => false</tt>, validation will take place when:
-
#
-
# * you explicitly enable validation; <tt>:validate => true</tt>
-
# * you use autosave; <tt>:autosave => true</tt>
-
# * the association is a +has_many+ association
-
2
def validate?
-
68
!options[:validate].nil? ? options[:validate] : (options[:autosave] == true || macro == :has_many)
-
end
-
-
# Returns +true+ if +self+ is a +belongs_to+ reflection.
-
2
def belongs_to?
-
30
macro == :belongs_to
-
end
-
-
2
def association_class
-
293
case macro
-
when :belongs_to
-
130
if options[:polymorphic]
-
Associations::BelongsToPolymorphicAssociation
-
else
-
130
Associations::BelongsToAssociation
-
end
-
when :has_and_belongs_to_many
-
Associations::HasAndBelongsToManyAssociation
-
when :has_many
-
66
if options[:through]
-
Associations::HasManyThroughAssociation
-
else
-
66
Associations::HasManyAssociation
-
end
-
when :has_one
-
97
if options[:through]
-
Associations::HasOneThroughAssociation
-
else
-
97
Associations::HasOneAssociation
-
end
-
end
-
end
-
-
2
private
-
2
def derive_class_name
-
20
class_name = name.to_s.camelize
-
20
class_name = class_name.singularize if collection?
-
20
class_name
-
end
-
-
2
def derive_foreign_key
-
30
if belongs_to?
-
15
"#{name}_id"
-
15
elsif options[:as]
-
"#{options[:as]}_id"
-
else
-
15
active_record.name.foreign_key
-
end
-
end
-
-
2
def primary_key(klass)
-
170
klass.primary_key || raise(UnknownPrimaryKey.new(klass))
-
end
-
end
-
-
# Holds all the meta-data about a :through association as it was specified
-
# in the Active Record class.
-
2
class ThroughReflection < AssociationReflection #:nodoc:
-
2
delegate :foreign_key, :foreign_type, :association_foreign_key,
-
:active_record_primary_key, :type, :to => :source_reflection
-
-
# Gets the source of the through reflection. It checks both a singularized
-
# and pluralized form for <tt>:belongs_to</tt> or <tt>:has_many</tt>.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, :through => :taggings
-
# end
-
#
-
2
def source_reflection
-
@source_reflection ||= source_reflection_names.collect { |name| through_reflection.klass.reflect_on_association(name) }.compact.first
-
end
-
-
# Returns the AssociationReflection object specified in the <tt>:through</tt> option
-
# of a HasManyThrough or HasOneThrough association.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, :through => :taggings
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# taggings_reflection = tags_reflection.through_reflection
-
#
-
2
def through_reflection
-
@through_reflection ||= active_record.reflect_on_association(options[:through])
-
end
-
-
# Returns an array of reflections which are involved in this association. Each item in the
-
# array corresponds to a table which will be part of the query for this association.
-
#
-
# The chain is built by recursively calling #chain on the source reflection and the through
-
# reflection. The base case for the recursion is a normal association, which just returns
-
# [self] as its #chain.
-
2
def chain
-
@chain ||= begin
-
chain = source_reflection.chain + through_reflection.chain
-
chain[0] = self # Use self so we don't lose the information from :source_type
-
chain
-
end
-
end
-
-
# Consider the following example:
-
#
-
# class Person
-
# has_many :articles
-
# has_many :comment_tags, :through => :articles
-
# end
-
#
-
# class Article
-
# has_many :comments
-
# has_many :comment_tags, :through => :comments, :source => :tags
-
# end
-
#
-
# class Comment
-
# has_many :tags
-
# end
-
#
-
# There may be conditions on Person.comment_tags, Article.comment_tags and/or Comment.tags,
-
# but only Comment.tags will be represented in the #chain. So this method creates an array
-
# of conditions corresponding to the chain. Each item in the #conditions array corresponds
-
# to an item in the #chain, and is itself an array of conditions from an arbitrary number
-
# of relevant reflections, plus any :source_type or polymorphic :as constraints.
-
2
def conditions
-
@conditions ||= begin
-
conditions = source_reflection.conditions.map { |c| c.dup }
-
-
# Add to it the conditions from this reflection if necessary.
-
conditions.first << options[:conditions] if options[:conditions]
-
-
through_conditions = through_reflection.conditions
-
-
if options[:source_type]
-
through_conditions.first << { foreign_type => options[:source_type] }
-
end
-
-
# Recursively fill out the rest of the array from the through reflection
-
conditions += through_conditions
-
-
# And return
-
conditions
-
end
-
end
-
-
# The macro used by the source association
-
2
def source_macro
-
source_reflection.source_macro
-
end
-
-
# A through association is nested if there would be more than one join table
-
2
def nested?
-
chain.length > 2 || through_reflection.macro == :has_and_belongs_to_many
-
end
-
-
# We want to use the klass from this reflection, rather than just delegate straight to
-
# the source_reflection, because the source_reflection may be polymorphic. We still
-
# need to respect the source_reflection's :primary_key option, though.
-
2
def association_primary_key(klass = nil)
-
# Get the "actual" source reflection if the immediate source reflection has a
-
# source reflection itself
-
source_reflection = self.source_reflection
-
while source_reflection.source_reflection
-
source_reflection = source_reflection.source_reflection
-
end
-
-
source_reflection.options[:primary_key] || primary_key(klass || self.klass)
-
end
-
-
# Gets an array of possible <tt>:through</tt> source reflection names:
-
#
-
# [:singularized, :pluralized]
-
#
-
2
def source_reflection_names
-
@source_reflection_names ||= (options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }
-
end
-
-
2
def source_options
-
source_reflection.options
-
end
-
-
2
def through_options
-
through_reflection.options
-
end
-
-
2
def check_validity!
-
if through_reflection.nil?
-
raise HasManyThroughAssociationNotFoundError.new(active_record.name, self)
-
end
-
-
if through_reflection.options[:polymorphic]
-
raise HasManyThroughAssociationPolymorphicThroughError.new(active_record.name, self)
-
end
-
-
if source_reflection.nil?
-
raise HasManyThroughSourceAssociationNotFoundError.new(self)
-
end
-
-
if options[:source_type] && source_reflection.options[:polymorphic].nil?
-
raise HasManyThroughAssociationPointlessSourceTypeError.new(active_record.name, self, source_reflection)
-
end
-
-
if source_reflection.options[:polymorphic] && options[:source_type].nil?
-
raise HasManyThroughAssociationPolymorphicSourceError.new(active_record.name, self, source_reflection)
-
end
-
-
if macro == :has_one && through_reflection.collection?
-
raise HasOneThroughCantAssociateThroughCollection.new(active_record.name, self, through_reflection)
-
end
-
-
check_validity_of_inverse!
-
end
-
-
2
private
-
2
def derive_class_name
-
# get the class_name of the belongs_to association of the through reflection
-
options[:source_type] || source_reflection.class_name
-
end
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActiveRecord
-
# = Active Record Relation
-
2
class Relation
-
2
JoinOperation = Struct.new(:relation, :join_class, :on)
-
2
ASSOCIATION_METHODS = [:includes, :eager_load, :preload]
-
2
MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having, :bind]
-
2
SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering, :reverse_order, :uniq]
-
-
2
include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
-
-
2
attr_reader :table, :klass, :loaded
-
2
attr_accessor :extensions, :default_scoped
-
2
alias :loaded? :loaded
-
2
alias :default_scoped? :default_scoped
-
-
2
def initialize(klass, table)
-
1584
@klass, @table = klass, table
-
-
1584
@implicit_readonly = nil
-
1584
@loaded = false
-
1584
@default_scoped = false
-
-
14256
SINGLE_VALUE_METHODS.each {|v| instance_variable_set(:"@#{v}_value", nil)}
-
17424
(ASSOCIATION_METHODS + MULTI_VALUE_METHODS).each {|v| instance_variable_set(:"@#{v}_values", [])}
-
1584
@extensions = []
-
1584
@create_with_value = {}
-
end
-
-
2
def insert(values)
-
308
primary_key_value = nil
-
-
308
if primary_key && Hash === values
-
308
primary_key_value = values[values.keys.find { |k|
-
3440
k.name == primary_key
-
}]
-
-
308
if !primary_key_value && connection.prefetch_primary_key?(klass.table_name)
-
primary_key_value = connection.next_sequence_value(klass.sequence_name)
-
values[klass.arel_table[klass.primary_key]] = primary_key_value
-
end
-
end
-
-
308
im = arel.create_insert
-
308
im.into @table
-
-
308
conn = @klass.connection
-
-
3748
substitutes = values.sort_by { |arel_attr,_| arel_attr.name }
-
308
binds = substitutes.map do |arel_attr, value|
-
3440
[@klass.columns_hash[arel_attr.name], value]
-
end
-
-
308
substitutes.each_with_index do |tuple, i|
-
3440
tuple[1] = conn.substitute_at(binds[i][0], i)
-
end
-
-
308
if values.empty? # empty insert
-
im.values = Arel.sql(connection.empty_insert_statement_value)
-
else
-
308
im.insert substitutes
-
end
-
-
308
conn.insert(
-
im,
-
'SQL',
-
primary_key,
-
primary_key_value,
-
nil,
-
binds)
-
end
-
-
2
def new(*args, &block)
-
scoping { @klass.new(*args, &block) }
-
end
-
-
2
def initialize_copy(other)
-
2089
@bind_values = @bind_values.dup
-
2089
reset
-
end
-
-
2
alias build new
-
-
2
def create(*args, &block)
-
scoping { @klass.create(*args, &block) }
-
end
-
-
2
def create!(*args, &block)
-
scoping { @klass.create!(*args, &block) }
-
end
-
-
# Tries to load the first record; if it fails, then <tt>create</tt> is called with the same arguments as this method.
-
#
-
# Expects arguments in the same format as <tt>Base.create</tt>.
-
#
-
# ==== Examples
-
# # Find the first user named Penélope or create a new one.
-
# User.where(:first_name => 'Penélope').first_or_create
-
# # => <User id: 1, first_name: 'Penélope', last_name: nil>
-
#
-
# # Find the first user named Penélope or create a new one.
-
# # We already have one so the existing record will be returned.
-
# User.where(:first_name => 'Penélope').first_or_create
-
# # => <User id: 1, first_name: 'Penélope', last_name: nil>
-
#
-
# # Find the first user named Scarlett or create a new one with a particular last name.
-
# User.where(:first_name => 'Scarlett').first_or_create(:last_name => 'Johansson')
-
# # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
-
#
-
# # Find the first user named Scarlett or create a new one with a different last name.
-
# # We already have one so the existing record will be returned.
-
# User.where(:first_name => 'Scarlett').first_or_create do |user|
-
# user.last_name = "O'Hara"
-
# end
-
# # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
-
2
def first_or_create(attributes = nil, options = {}, &block)
-
first || create(attributes, options, &block)
-
end
-
-
# Like <tt>first_or_create</tt> but calls <tt>create!</tt> so an exception is raised if the created record is invalid.
-
#
-
# Expects arguments in the same format as <tt>Base.create!</tt>.
-
2
def first_or_create!(attributes = nil, options = {}, &block)
-
first || create!(attributes, options, &block)
-
end
-
-
# Like <tt>first_or_create</tt> but calls <tt>new</tt> instead of <tt>create</tt>.
-
#
-
# Expects arguments in the same format as <tt>Base.new</tt>.
-
2
def first_or_initialize(attributes = nil, options = {}, &block)
-
first || new(attributes, options, &block)
-
end
-
-
# Runs EXPLAIN on the query or queries triggered by this relation and
-
# returns the result as a string. The string is formatted imitating the
-
# ones printed by the database shell.
-
#
-
# Note that this method actually runs the queries, since the results of some
-
# are needed by the next ones when eager loading is going on.
-
#
-
# Please see further details in the
-
# {Active Record Query Interface guide}[http://edgeguides.rubyonrails.org/active_record_querying.html#running-explain].
-
2
def explain
-
_, queries = collecting_queries_for_explain { exec_queries }
-
exec_explain(queries)
-
end
-
-
2
def to_a
-
# We monitor here the entire execution rather than individual SELECTs
-
# because from the point of view of the user fetching the records of a
-
# relation is a single unit of work. You want to know if this call takes
-
# too long, not if the individual queries take too long.
-
#
-
# It could be the case that none of the queries involved surpass the
-
# threshold, and at the same time the sum of them all does. The user
-
# should get a query plan logged in that case.
-
874
logging_query_plan do
-
874
exec_queries
-
end
-
end
-
-
2
def exec_queries
-
874
return @records if loaded?
-
-
816
default_scoped = with_default_scope
-
-
816
if default_scoped.equal?(self)
-
816
@records = if @readonly_value.nil? && !@klass.locking_enabled?
-
816
eager_loading? ? find_with_associations : @klass.find_by_sql(arel, @bind_values)
-
else
-
IdentityMap.without do
-
eager_loading? ? find_with_associations : @klass.find_by_sql(arel, @bind_values)
-
end
-
end
-
-
816
preload = @preload_values
-
816
preload += @includes_values unless eager_loading?
-
816
preload.each do |associations|
-
ActiveRecord::Associations::Preloader.new(@records, associations).run
-
end
-
-
# @readonly_value is true only if set explicitly. @implicit_readonly is true if there
-
# are JOINS and no explicit SELECT.
-
816
readonly = @readonly_value.nil? ? @implicit_readonly : @readonly_value
-
816
@records.each { |record| record.readonly! } if readonly
-
else
-
@records = default_scoped.to_a
-
end
-
-
816
@loaded = true
-
816
@records
-
end
-
2
private :exec_queries
-
-
2
def as_json(options = nil) #:nodoc:
-
to_a.as_json(options)
-
end
-
-
# Returns size of the records.
-
2
def size
-
loaded? ? @records.length : count
-
end
-
-
# Returns true if there are no records.
-
2
def empty?
-
return @records.empty? if loaded?
-
-
c = count
-
c.respond_to?(:zero?) ? c.zero? : c.empty?
-
end
-
-
2
def any?
-
if block_given?
-
to_a.any? { |*block_args| yield(*block_args) }
-
else
-
!empty?
-
end
-
end
-
-
2
def many?
-
if block_given?
-
to_a.many? { |*block_args| yield(*block_args) }
-
else
-
@limit_value ? to_a.many? : size > 1
-
end
-
end
-
-
# Scope all queries to the current scope.
-
#
-
# ==== Example
-
#
-
# Comment.where(:post_id => 1).scoping do
-
# Comment.first # SELECT * FROM comments WHERE post_id = 1
-
# end
-
#
-
# Please check unscoped if you want to remove all previous scopes (including
-
# the default_scope) during the execution of a block.
-
2
def scoping
-
1868
@klass.with_scope(self, :overwrite) { yield }
-
end
-
-
# Updates all records with details given if they match a set of conditions supplied, limits and order can
-
# also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
-
# database. It does not instantiate the involved models and it does not trigger Active Record callbacks
-
# or validations.
-
#
-
# ==== Parameters
-
#
-
# * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
-
# * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement.
-
# See conditions in the intro.
-
# * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
-
#
-
# ==== Examples
-
#
-
# # Update all customers with the given attributes
-
# Customer.update_all :wants_email => true
-
#
-
# # Update all books with 'Rails' in their title
-
# Book.update_all "author = 'David'", "title LIKE '%Rails%'"
-
#
-
# # Update all avatars migrated more than a week ago
-
# Avatar.update_all ['migrated_at = ?', Time.now.utc], ['migrated_at > ?', 1.week.ago]
-
#
-
# # Update all books that match conditions, but limit it to 5 ordered by date
-
# Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5
-
#
-
# # Conditions from the current relation also works
-
# Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David')
-
#
-
# # The same idea applies to limit and order
-
# Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(:author => 'David')
-
2
def update_all(updates, conditions = nil, options = {})
-
88
IdentityMap.repository[symbolized_base_class].clear if IdentityMap.enabled?
-
88
if conditions || options.present?
-
44
where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
-
else
-
44
stmt = Arel::UpdateManager.new(arel.engine)
-
-
44
stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
-
44
stmt.table(table)
-
44
stmt.key = table[primary_key]
-
-
44
if joins_values.any?
-
@klass.connection.join_to_update(stmt, arel)
-
else
-
44
stmt.take(arel.limit)
-
44
stmt.order(*arel.orders)
-
44
stmt.wheres = arel.constraints
-
end
-
-
44
@klass.connection.update stmt, 'SQL', bind_values
-
end
-
end
-
-
# Updates an object (or multiple objects) and saves it to the database, if validations pass.
-
# The resulting object is returned whether the object was saved successfully to the database or not.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - This should be the id or an array of ids to be updated.
-
# * +attributes+ - This should be a hash of attributes or an array of hashes.
-
#
-
# ==== Examples
-
#
-
# # Updates one record
-
# Person.update(15, :user_name => 'Samuel', :group => 'expert')
-
#
-
# # Updates multiple records
-
# people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
-
# Person.update(people.keys, people.values)
-
2
def update(id, attributes)
-
if id.is_a?(Array)
-
id.each.with_index.map {|one_id, idx| update(one_id, attributes[idx])}
-
else
-
object = find(id)
-
object.update_attributes(attributes)
-
object
-
end
-
end
-
-
# Destroys the records matching +conditions+ by instantiating each
-
# record and calling its +destroy+ method. Each object's callbacks are
-
# executed (including <tt>:dependent</tt> association options and
-
# +before_destroy+/+after_destroy+ Observer methods). Returns the
-
# collection of objects that were destroyed; each will be frozen, to
-
# reflect that no changes should be made (since they can't be
-
# persisted).
-
#
-
# Note: Instantiation, callback execution, and deletion of each
-
# record can be time consuming when you're removing many records at
-
# once. It generates at least one SQL +DELETE+ query per record (or
-
# possibly more, to enforce your callbacks). If you want to delete many
-
# rows quickly, without concern for their associations or callbacks, use
-
# +delete_all+ instead.
-
#
-
# ==== Parameters
-
#
-
# * +conditions+ - A string, array, or hash that specifies which records
-
# to destroy. If omitted, all records are destroyed. See the
-
# Conditions section in the introduction to ActiveRecord::Base for
-
# more information.
-
#
-
# ==== Examples
-
#
-
# Person.destroy_all("last_login < '2004-04-04'")
-
# Person.destroy_all(:status => "inactive")
-
# Person.where(:age => 0..18).destroy_all
-
2
def destroy_all(conditions = nil)
-
1
if conditions
-
where(conditions).destroy_all
-
else
-
23
to_a.each {|object| object.destroy }.tap { reset }
-
end
-
end
-
-
# Destroy an object (or multiple objects) that has the given id, the object is instantiated first,
-
# therefore all callbacks and filters are fired off before the object is deleted. This method is
-
# less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
-
#
-
# This essentially finds the object (or multiple objects) with the given id, creates a new object
-
# from the attributes, and then calls destroy on it.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - Can be either an Integer or an Array of Integers.
-
#
-
# ==== Examples
-
#
-
# # Destroy a single object
-
# Todo.destroy(1)
-
#
-
# # Destroy multiple objects
-
# todos = [1,2,3]
-
# Todo.destroy(todos)
-
2
def destroy(id)
-
if id.is_a?(Array)
-
id.map { |one_id| destroy(one_id) }
-
else
-
find(id).destroy
-
end
-
end
-
-
# Deletes the records matching +conditions+ without instantiating the records first, and hence not
-
# calling the +destroy+ method nor invoking callbacks. This is a single SQL DELETE statement that
-
# goes straight to the database, much more efficient than +destroy_all+. Be careful with relations
-
# though, in particular <tt>:dependent</tt> rules defined on associations are not honored. Returns
-
# the number of rows affected.
-
#
-
# ==== Parameters
-
#
-
# * +conditions+ - Conditions are specified the same way as with +find+ method.
-
#
-
# ==== Example
-
#
-
# Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
-
# Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
-
# Post.where(:person_id => 5).where(:category => ['Something', 'Else']).delete_all
-
#
-
# Both calls delete the affected posts all at once with a single DELETE statement.
-
# If you need to destroy dependent associations or call your <tt>before_*</tt> or
-
# +after_destroy+ callbacks, use the +destroy_all+ method instead.
-
2
def delete_all(conditions = nil)
-
24
raise ActiveRecordError.new("delete_all doesn't support limit scope") if self.limit_value
-
-
24
IdentityMap.repository[symbolized_base_class] = {} if IdentityMap.enabled?
-
24
if conditions
-
where(conditions).delete_all
-
else
-
24
statement = arel.compile_delete
-
24
affected = @klass.connection.delete(statement, 'SQL', bind_values)
-
-
24
reset
-
24
affected
-
end
-
end
-
-
# Deletes the row with a primary key matching the +id+ argument, using a
-
# SQL +DELETE+ statement, and returns the number of rows deleted. Active
-
# Record objects are not instantiated, so the object's callbacks are not
-
# executed, including any <tt>:dependent</tt> association options or
-
# Observer methods.
-
#
-
# You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
-
#
-
# Note: Although it is often much faster than the alternative,
-
# <tt>#destroy</tt>, skipping callbacks might bypass business logic in
-
# your application that ensures referential integrity or performs other
-
# essential jobs.
-
#
-
# ==== Examples
-
#
-
# # Delete a single row
-
# Todo.delete(1)
-
#
-
# # Delete multiple rows
-
# Todo.delete([2,3,4])
-
2
def delete(id_or_array)
-
IdentityMap.remove_by_id(self.symbolized_base_class, id_or_array) if IdentityMap.enabled?
-
where(primary_key => id_or_array).delete_all
-
end
-
-
2
def reload
-
reset
-
to_a # force reload
-
self
-
end
-
-
2
def reset
-
2114
@first = @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
-
2114
@should_eager_load = @join_dependency = nil
-
2114
@records = []
-
2114
self
-
end
-
-
2
def to_sql
-
@to_sql ||= klass.connection.to_sql(arel, @bind_values.dup)
-
end
-
-
2
def where_values_hash
-
5
equalities = with_default_scope.where_values.grep(Arel::Nodes::Equality).find_all { |node|
-
5
node.left.relation.name == table_name
-
}
-
-
10
Hash[equalities.map { |where| [where.left.name, where.right] }].with_indifferent_access
-
end
-
-
2
def scope_for_create
-
5
@scope_for_create ||= where_values_hash.merge(create_with_value)
-
end
-
-
2
def eager_loading?
-
@should_eager_load ||=
-
@eager_load_values.any? ||
-
1660
@includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
-
end
-
-
# Joins that are also marked for preloading. In which case we should just eager load them.
-
# Note that this is a naive implementation because we could have strings and symbols which
-
# represent the same association, but that aren't matched by this. Also, we could have
-
# nested hashes which partially match, e.g. { :a => :b } & { :a => [:b, :c] }
-
2
def joined_includes_values
-
@includes_values & @joins_values
-
end
-
-
2
def ==(other)
-
86
case other
-
when Relation
-
other.to_sql == to_sql
-
when Array
-
86
to_a == other
-
end
-
end
-
-
2
def inspect
-
to_a.inspect
-
end
-
-
2
def with_default_scope #:nodoc:
-
2151
if default_scoped? && default_scope = klass.send(:build_default_scope)
-
default_scope = default_scope.merge(self)
-
default_scope.default_scoped = false
-
default_scope
-
else
-
2151
self
-
end
-
end
-
-
2
private
-
-
2
def references_eager_loaded_tables?
-
joined_tables = arel.join_sources.map do |join|
-
if join.is_a?(Arel::Nodes::StringJoin)
-
tables_in_string(join.left)
-
else
-
[join.left.table_name, join.left.table_alias]
-
end
-
end
-
-
joined_tables += [table.name, table.table_alias]
-
-
# always convert table names to downcase as in Oracle quoted table names are in uppercase
-
joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq
-
-
(tables_in_string(to_sql) - joined_tables).any?
-
end
-
-
2
def tables_in_string(string)
-
return [] if string.blank?
-
# always convert table names to downcase as in Oracle quoted table names are in uppercase
-
# ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
-
string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActiveRecord
-
2
module Batches
-
# Yields each record that was found by the find +options+. The find is
-
# performed by find_in_batches with a batch size of 1000 (or as
-
# specified by the <tt>:batch_size</tt> option).
-
#
-
# Example:
-
#
-
# Person.where("age > 21").find_each do |person|
-
# person.party_all_night!
-
# end
-
#
-
# Note: This method is only intended to use for batch processing of
-
# large amounts of records that wouldn't fit in memory all at once. If
-
# you just need to loop over less than 1000 records, it's probably
-
# better just to use the regular find methods.
-
2
def find_each(options = {})
-
find_in_batches(options) do |records|
-
records.each { |record| yield record }
-
end
-
end
-
-
# Yields each batch of records that was found by the find +options+ as
-
# an array. The size of each batch is set by the <tt>:batch_size</tt>
-
# option; the default is 1000.
-
#
-
# You can control the starting point for the batch processing by
-
# supplying the <tt>:start</tt> option. This is especially useful if you
-
# want multiple workers dealing with the same processing queue. You can
-
# make worker 1 handle all the records between id 0 and 10,000 and
-
# worker 2 handle from 10,000 and beyond (by setting the <tt>:start</tt>
-
# option on that worker).
-
#
-
# It's not possible to set the order. That is automatically set to
-
# ascending on the primary key ("id ASC") to make the batch ordering
-
# work. This also mean that this method only works with integer-based
-
# primary keys. You can't set the limit either, that's used to control
-
# the batch sizes.
-
#
-
# Example:
-
#
-
# Person.where("age > 21").find_in_batches do |group|
-
# sleep(50) # Make sure it doesn't get too crowded in there!
-
# group.each { |person| person.party_all_night! }
-
# end
-
2
def find_in_batches(options = {})
-
relation = self
-
-
unless arel.orders.blank? && arel.taken.blank?
-
ActiveRecord::Base.logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
-
end
-
-
if (finder_options = options.except(:start, :batch_size)).present?
-
raise "You can't specify an order, it's forced to be #{batch_order}" if options[:order].present?
-
raise "You can't specify a limit, it's forced to be the batch_size" if options[:limit].present?
-
-
relation = apply_finder_options(finder_options)
-
end
-
-
start = options.delete(:start)
-
batch_size = options.delete(:batch_size) || 1000
-
-
relation = relation.reorder(batch_order).limit(batch_size)
-
records = start ? relation.where(table[primary_key].gteq(start)).to_a : relation.to_a
-
-
while records.any?
-
records_size = records.size
-
primary_key_offset = records.last.id
-
-
yield records
-
-
break if records_size < batch_size
-
-
if primary_key_offset
-
records = relation.where(table[primary_key].gt(primary_key_offset)).to_a
-
else
-
raise "Primary key not included in the custom select clause"
-
end
-
end
-
end
-
-
2
private
-
-
2
def batch_order
-
"#{quoted_table_name}.#{quoted_primary_key} ASC"
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/object/try'
-
-
2
module ActiveRecord
-
2
module Calculations
-
# Count operates using three different approaches.
-
#
-
# * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
-
# * Count using column: By passing a column name to count, it will return a count of all the
-
# rows for the model with supplied column present.
-
# * Count using options will find the row count matched by the options used.
-
#
-
# The third approach, count using options, accepts an option hash as the only parameter. The options are:
-
#
-
# * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
-
# See conditions in the intro to ActiveRecord::Base.
-
# * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id"
-
# (rarely needed) or named associations in the same form used for the <tt>:include</tt> option, which will
-
# perform an INNER JOIN on the associated table(s). If the value is a string, then the records
-
# will be returned read-only since they will have attributes that do not correspond to the table's columns.
-
# Pass <tt>:readonly => false</tt> to override.
-
# * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs.
-
# The symbols named refer to already defined associations. When using named associations, count
-
# returns the number of DISTINCT items for the model you're counting.
-
# See eager loading under Associations.
-
# * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
-
# * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
-
# * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example,
-
# want to do a join but not include the joined columns.
-
# * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as
-
# SELECT COUNT(DISTINCT posts.id) ...
-
# * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an
-
# alternate table name (or even the name of a database view).
-
#
-
# Examples for counting all:
-
# Person.count # returns the total count of all people
-
#
-
# Examples for counting by column:
-
# Person.count(:age) # returns the total count of all people whose age is present in database
-
#
-
# Examples for count with options:
-
# Person.count(:conditions => "age > 26")
-
#
-
# # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
-
# Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job)
-
#
-
# # finds the number of rows matching the conditions and joins.
-
# Person.count(:conditions => "age > 26 AND job.salary > 60000",
-
# :joins => "LEFT JOIN jobs on jobs.person_id = person.id")
-
#
-
# Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
-
# Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
-
#
-
# Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition.
-
# Use Person.count instead.
-
2
def count(column_name = nil, options = {})
-
28
column_name, options = nil, column_name if column_name.is_a?(Hash)
-
28
calculate(:count, column_name, options)
-
end
-
-
# Calculates the average value on a given column. Returns +nil+ if there's
-
# no row. See +calculate+ for examples with options.
-
#
-
# Person.average('age') # => 35.8
-
2
def average(column_name, options = {})
-
calculate(:average, column_name, options)
-
end
-
-
# Calculates the minimum value on a given column. The value is returned
-
# with the same data type of the column, or +nil+ if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.minimum('age') # => 7
-
2
def minimum(column_name, options = {})
-
calculate(:minimum, column_name, options)
-
end
-
-
# Calculates the maximum value on a given column. The value is returned
-
# with the same data type of the column, or +nil+ if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.maximum('age') # => 93
-
2
def maximum(column_name, options = {})
-
calculate(:maximum, column_name, options)
-
end
-
-
# Calculates the sum of values on a given column. The value is returned
-
# with the same data type of the column, 0 if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.sum('age') # => 4562
-
2
def sum(*args)
-
if block_given?
-
self.to_a.sum(*args) {|*block_args| yield(*block_args)}
-
else
-
calculate(:sum, *args)
-
end
-
end
-
-
# This calculates aggregate values in the given column. Methods for count, sum, average,
-
# minimum, and maximum have been added as shortcuts. Options such as <tt>:conditions</tt>,
-
# <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
-
#
-
# There are two basic forms of output:
-
# * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
-
# for AVG, and the given column's type for everything else.
-
# * Grouped values: This returns an ordered hash of the values and groups them by the
-
# <tt>:group</tt> option. It takes either a column name, or the name of a belongs_to association.
-
#
-
# values = Person.maximum(:age, :group => 'last_name')
-
# puts values["Drake"]
-
# => 43
-
#
-
# drake = Family.find_by_last_name('Drake')
-
# values = Person.maximum(:age, :group => :family) # Person belongs_to :family
-
# puts values[drake]
-
# => 43
-
#
-
# values.each do |family, max_age|
-
# ...
-
# end
-
#
-
# Options:
-
# * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
-
# See conditions in the intro to ActiveRecord::Base.
-
# * <tt>:include</tt>: Eager loading, see Associations for details. Since calculations don't load anything,
-
# the purpose of this is to access fields on joined tables in your conditions, order, or group clauses.
-
# * <tt>:joins</tt> - An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id".
-
# (Rarely needed).
-
# The records will be returned read-only since they will have attributes that do not correspond to the
-
# table's columns.
-
# * <tt>:order</tt> - An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
-
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
-
# * <tt>:select</tt> - By default, this is * as in SELECT * FROM, but can be changed if you for example
-
# want to do a join, but not include the joined columns.
-
# * <tt>:distinct</tt> - Set this to true to make this a distinct calculation, such as
-
# SELECT COUNT(DISTINCT posts.id) ...
-
#
-
# Examples:
-
# Person.calculate(:count, :all) # The same as Person.count
-
# Person.average(:age) # SELECT AVG(age) FROM people...
-
# Person.minimum(:age, :conditions => ['last_name != ?', 'Drake']) # Selects the minimum age for
-
# # everyone with a last name other than 'Drake'
-
#
-
# # Selects the minimum age for any family without any minors
-
# Person.minimum(:age, :having => 'min(age) > 17', :group => :last_name)
-
#
-
# Person.sum("2 * age")
-
2
def calculate(operation, column_name, options = {})
-
28
if options.except(:distinct).present?
-
apply_finder_options(options.except(:distinct)).calculate(operation, column_name, :distinct => options[:distinct])
-
else
-
28
relation = with_default_scope
-
-
28
if relation.equal?(self)
-
28
if eager_loading? || (includes_values.present? && references_eager_loaded_tables?)
-
construct_relation_for_association_calculations.calculate(operation, column_name, options)
-
else
-
28
perform_calculation(operation, column_name, options)
-
end
-
else
-
relation.calculate(operation, column_name, options)
-
end
-
end
-
rescue ThrowResult
-
0
-
end
-
-
# This method is designed to perform select by a single column as direct SQL query
-
# Returns <tt>Array</tt> with values of the specified column name
-
# The values has same data type as column.
-
#
-
# Examples:
-
#
-
# Person.pluck(:id) # SELECT people.id FROM people
-
# Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
-
# Person.where(:confirmed => true).limit(5).pluck(:id)
-
#
-
2
def pluck(column_name)
-
if column_name.is_a?(Symbol) && column_names.include?(column_name.to_s)
-
column_name = "#{connection.quote_table_name(table_name)}.#{connection.quote_column_name(column_name)}"
-
end
-
-
result = klass.connection.exec_query(select(column_name).to_sql)
-
last_column = result.columns.last
-
-
result.map do |attributes|
-
klass.type_cast_attribute(last_column, klass.initialize_attributes(attributes))
-
end
-
end
-
-
2
private
-
-
2
def perform_calculation(operation, column_name, options = {})
-
28
operation = operation.to_s.downcase
-
-
# If #count is used in conjuction with #uniq it is considered distinct. (eg. relation.uniq.count)
-
28
distinct = options[:distinct] || self.uniq_value
-
-
28
if operation == "count"
-
28
column_name ||= (select_for_count || :all)
-
-
28
unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
-
distinct = true
-
end
-
-
28
column_name = primary_key if column_name == :all && distinct
-
-
28
distinct = nil if column_name =~ /\s*DISTINCT\s+/i
-
end
-
-
28
if @group_values.any?
-
execute_grouped_calculation(operation, column_name, distinct)
-
else
-
28
execute_simple_calculation(operation, column_name, distinct)
-
end
-
end
-
-
2
def aggregate_column(column_name)
-
28
if @klass.column_names.include?(column_name.to_s)
-
Arel::Attribute.new(@klass.unscoped.table, column_name)
-
else
-
28
Arel.sql(column_name == :all ? "*" : column_name.to_s)
-
end
-
end
-
-
2
def operation_over_aggregate_column(column, operation, distinct)
-
28
operation == 'count' ? column.count(distinct) : column.send(operation)
-
end
-
-
2
def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
-
# Postgresql doesn't like ORDER BY when there are no GROUP BY
-
28
relation = reorder(nil)
-
-
28
if operation == "count" && (relation.limit_value || relation.offset_value)
-
# Shortcut when limit is zero.
-
return 0 if relation.limit_value == 0
-
-
query_builder = build_count_subquery(relation, column_name, distinct)
-
else
-
28
column = aggregate_column(column_name)
-
-
28
select_value = operation_over_aggregate_column(column, operation, distinct)
-
-
28
relation.select_values = [select_value]
-
-
28
query_builder = relation.arel
-
end
-
-
28
type_cast_calculated_value(@klass.connection.select_value(query_builder), column_for(column_name), operation)
-
end
-
-
2
def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
-
group_attrs = @group_values
-
-
if group_attrs.first.respond_to?(:to_sym)
-
association = @klass.reflect_on_association(group_attrs.first.to_sym)
-
associated = group_attrs.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
-
group_fields = Array(associated ? association.foreign_key : group_attrs)
-
else
-
group_fields = group_attrs
-
end
-
-
group_aliases = group_fields.map { |field| column_alias_for(field) }
-
group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
-
[aliaz, column_for(field)]
-
}
-
-
group = @klass.connection.adapter_name == 'FrontBase' ? group_aliases : group_fields
-
-
if operation == 'count' && column_name == :all
-
aggregate_alias = 'count_all'
-
else
-
aggregate_alias = column_alias_for(operation, column_name)
-
end
-
-
select_values = [
-
operation_over_aggregate_column(
-
aggregate_column(column_name),
-
operation,
-
distinct).as(aggregate_alias)
-
]
-
select_values += @select_values unless @having_values.empty?
-
-
select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
-
if field.respond_to?(:as)
-
field.as(aliaz)
-
else
-
"#{field} AS #{aliaz}"
-
end
-
}
-
-
relation = except(:group).group(group)
-
relation.select_values = select_values
-
-
calculated_data = @klass.connection.select_all(relation)
-
-
if association
-
key_ids = calculated_data.collect { |row| row[group_aliases.first] }
-
key_records = association.klass.base_class.find(key_ids)
-
key_records = Hash[key_records.map { |r| [r.id, r] }]
-
end
-
-
ActiveSupport::OrderedHash[calculated_data.map do |row|
-
key = group_columns.map { |aliaz, column|
-
type_cast_calculated_value(row[aliaz], column)
-
}
-
key = key.first if key.size == 1
-
key = key_records[key] if associated
-
[key, type_cast_calculated_value(row[aggregate_alias], column_for(column_name), operation)]
-
end]
-
end
-
-
# Converts the given keys to the value that the database adapter returns as
-
# a usable column name:
-
#
-
# column_alias_for("users.id") # => "users_id"
-
# column_alias_for("sum(id)") # => "sum_id"
-
# column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
-
# column_alias_for("count(*)") # => "count_all"
-
# column_alias_for("count", "id") # => "count_id"
-
2
def column_alias_for(*keys)
-
keys.map! {|k| k.respond_to?(:to_sql) ? k.to_sql : k}
-
table_name = keys.join(' ')
-
table_name.downcase!
-
table_name.gsub!(/\*/, 'all')
-
table_name.gsub!(/\W+/, ' ')
-
table_name.strip!
-
table_name.gsub!(/ +/, '_')
-
-
@klass.connection.table_alias_for(table_name)
-
end
-
-
2
def column_for(field)
-
28
field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
-
350
@klass.columns.detect { |c| c.name.to_s == field_name }
-
end
-
-
2
def type_cast_calculated_value(value, column, operation = nil)
-
28
case operation
-
28
when 'count' then value.to_i
-
when 'sum' then type_cast_using_column(value || '0', column)
-
when 'average' then value.respond_to?(:to_d) ? value.to_d : value
-
else type_cast_using_column(value, column)
-
end
-
end
-
-
2
def type_cast_using_column(value, column)
-
column ? column.type_cast(value) : value
-
end
-
-
2
def select_for_count
-
28
if @select_values.present?
-
select = @select_values.join(", ")
-
select if select !~ /(,|\*)/
-
end
-
end
-
-
2
def build_count_subquery(relation, column_name, distinct)
-
column_alias = Arel.sql('count_column')
-
subquery_alias = Arel.sql('subquery_for_count')
-
-
aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias)
-
relation.select_values = [aliased_column]
-
subquery = relation.arel.as(subquery_alias)
-
-
sm = Arel::SelectManager.new relation.engine
-
select_value = operation_over_aggregate_column(column_alias, 'count', distinct)
-
sm.project(select_value).from(subquery)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/delegation'
-
-
2
module ActiveRecord
-
2
module Delegation
-
# Set up common delegations for performance (avoids method_missing)
-
2
delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :to => :to_a
-
2
delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key,
-
:connection, :columns_hash, :auto_explain_threshold_in_seconds, :to => :klass
-
-
2
def self.delegate_to_scoped_klass(method)
-
5
if method.to_s =~ /\A[a-zA-Z_]\w*[!?]?\z/
-
5
module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{method}(*args, &block)
-
scoping { @klass.#{method}(*args, &block) }
-
end
-
RUBY
-
else
-
module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{method}(*args, &block)
-
scoping { @klass.send(#{method.inspect}, *args, &block) }
-
end
-
RUBY
-
end
-
end
-
-
2
def respond_to?(method, include_private = false)
-
29
super || Array.method_defined?(method) ||
-
@klass.respond_to?(method, include_private) ||
-
arel.respond_to?(method, include_private)
-
end
-
-
2
protected
-
-
2
def method_missing(method, *args, &block)
-
6
if @klass.respond_to?(method)
-
5
::ActiveRecord::Delegation.delegate_to_scoped_klass(method)
-
10
scoping { @klass.send(method, *args, &block) }
-
1
elsif Array.method_defined?(method)
-
1
::ActiveRecord::Delegation.delegate method, :to => :to_a
-
1
to_a.send(method, *args, &block)
-
elsif arel.respond_to?(method)
-
::ActiveRecord::Delegation.delegate method, :to => :arel
-
arel.send(method, *args, &block)
-
else
-
super
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
-
2
module ActiveRecord
-
2
module FinderMethods
-
# Find operates with four different retrieval approaches:
-
#
-
# * Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
-
# If no record can be found for all of the listed ids, then RecordNotFound will be raised.
-
# * Find first - This will return the first record matched by the options used. These options can either be specific
-
# conditions or merely an order. If no record can be matched, +nil+ is returned. Use
-
# <tt>Model.find(:first, *args)</tt> or its shortcut <tt>Model.first(*args)</tt>.
-
# * Find last - This will return the last record matched by the options used. These options can either be specific
-
# conditions or merely an order. If no record can be matched, +nil+ is returned. Use
-
# <tt>Model.find(:last, *args)</tt> or its shortcut <tt>Model.last(*args)</tt>.
-
# * Find all - This will return all the records matched by the options used.
-
# If no records are found, an empty array is returned. Use
-
# <tt>Model.find(:all, *args)</tt> or its shortcut <tt>Model.all(*args)</tt>.
-
#
-
# All approaches accept an options hash as their last parameter.
-
#
-
# ==== Options
-
#
-
# * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>["user_name = ?", username]</tt>,
-
# or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
-
# * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
-
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
-
# * <tt>:having</tt> - Combined with +:group+ this can be used to filter the records that a
-
# <tt>GROUP BY</tt> returns. Uses the <tt>HAVING</tt> SQL-clause.
-
# * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
-
# * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5,
-
# it would skip rows 0 through 4.
-
# * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed),
-
# named associations in the same form used for the <tt>:include</tt> option, which will perform an
-
# <tt>INNER JOIN</tt> on the associated table(s),
-
# or an array containing a mixture of both strings and named associations.
-
# If the value is a string, then the records will be returned read-only since they will
-
# have attributes that do not correspond to the table's columns.
-
# Pass <tt>:readonly => false</tt> to override.
-
# * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer
-
# to already defined associations. See eager loading under Associations.
-
# * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you,
-
# for example, want to do a join but not include the joined columns. Takes a string with the SELECT SQL fragment (e.g. "id, name").
-
# * <tt>:from</tt> - By default, this is the table name of the class, but can be changed
-
# to an alternate table name (or even the name of a database view).
-
# * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated.
-
# * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
-
# <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
-
#
-
# ==== Examples
-
#
-
# # find by id
-
# Person.find(1) # returns the object for ID = 1
-
# Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
-
# Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
-
# Person.find([1]) # returns an array for the object with ID = 1
-
# Person.where("administrator = 1").order("created_on DESC").find(1)
-
#
-
# Note that returned records may not be in the same order as the ids you
-
# provide since database rows are unordered. Give an explicit <tt>:order</tt>
-
# to ensure the results are sorted.
-
#
-
# ==== Examples
-
#
-
# # find first
-
# Person.first # returns the first object fetched by SELECT * FROM people
-
# Person.where(["user_name = ?", user_name]).first
-
# Person.where(["user_name = :u", { :u => user_name }]).first
-
# Person.order("created_on DESC").offset(5).first
-
#
-
# # find last
-
# Person.last # returns the last object fetched by SELECT * FROM people
-
# Person.where(["user_name = ?", user_name]).last
-
# Person.order("created_on DESC").offset(5).last
-
#
-
# # find all
-
# Person.all # returns an array of objects for all the rows fetched by SELECT * FROM people
-
# Person.where(["category IN (?)", categories]).limit(50).all
-
# Person.where({ :friends => ["Bob", "Steve", "Fred"] }).all
-
# Person.offset(10).limit(10).all
-
# Person.includes([:account, :friends]).all
-
# Person.group("category").all
-
#
-
# Example for find with a lock: Imagine two concurrent transactions:
-
# each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
-
# in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
-
# transaction has to wait until the first is finished; we get the
-
# expected <tt>person.visits == 4</tt>.
-
#
-
# Person.transaction do
-
# person = Person.lock(true).find(1)
-
# person.visits += 1
-
# person.save!
-
# end
-
2
def find(*args)
-
129
return to_a.find { |*block_args| yield(*block_args) } if block_given?
-
-
129
options = args.extract_options!
-
-
129
if options.present?
-
apply_finder_options(options).find(*args)
-
else
-
129
case args.first
-
when :first, :last, :all
-
send(args.first)
-
else
-
129
find_with_ids(*args)
-
end
-
end
-
end
-
-
# A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the
-
# same arguments to this method as you can to <tt>find(:first)</tt>.
-
2
def first(*args)
-
361
if args.any?
-
if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
-
limit(*args).to_a
-
else
-
apply_finder_options(args.first).first
-
end
-
else
-
361
find_first
-
end
-
end
-
-
# Same as +first+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>first!</tt> accepts no arguments.
-
2
def first!
-
first or raise RecordNotFound
-
end
-
-
# A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the
-
# same arguments to this method as you can to <tt>find(:last)</tt>.
-
2
def last(*args)
-
2
if args.any?
-
if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
-
if order_values.empty? && primary_key
-
order("#{quoted_table_name}.#{quoted_primary_key} DESC").limit(*args).reverse
-
else
-
to_a.last(*args)
-
end
-
else
-
apply_finder_options(args.first).last
-
end
-
else
-
2
find_last
-
end
-
end
-
-
# Same as +last+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>last!</tt> accepts no arguments.
-
2
def last!
-
last or raise RecordNotFound
-
end
-
-
# A convenience wrapper for <tt>find(:all, *args)</tt>. You can pass in all the
-
# same arguments to this method as you can to <tt>find(:all)</tt>.
-
2
def all(*args)
-
42
args.any? ? apply_finder_options(args.first).to_a : to_a
-
end
-
-
# Returns true if a record exists in the table that matches the +id+ or
-
# conditions given, or false otherwise. The argument can take five forms:
-
#
-
# * Integer - Finds the record with this primary key.
-
# * String - Finds the record with a primary key corresponding to this
-
# string (such as <tt>'5'</tt>).
-
# * Array - Finds the record that matches these +find+-style conditions
-
# (such as <tt>['color = ?', 'red']</tt>).
-
# * Hash - Finds the record that matches these +find+-style conditions
-
# (such as <tt>{:color => 'red'}</tt>).
-
# * No args - Returns false if the table is empty, true otherwise.
-
#
-
# For more information about specifying conditions as a Hash or Array,
-
# see the Conditions section in the introduction to ActiveRecord::Base.
-
#
-
# Note: You can't pass in a condition as a string (like <tt>name =
-
# 'Jamie'</tt>), since it would be sanitized and then queried against
-
# the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
-
#
-
# ==== Examples
-
# Person.exists?(5)
-
# Person.exists?('5')
-
# Person.exists?(:name => "David")
-
# Person.exists?(['name LIKE ?', "%#{query}%"])
-
# Person.exists?
-
2
def exists?(id = false)
-
id = id.id if ActiveRecord::Base === id
-
return false if id.nil?
-
-
join_dependency = construct_join_dependency_for_association_find
-
relation = construct_relation_for_association_find(join_dependency)
-
relation = relation.except(:select, :order).select("1 AS one").limit(1)
-
-
case id
-
when Array, Hash
-
relation = relation.where(id)
-
else
-
relation = relation.where(table[primary_key].eq(id)) if id
-
end
-
-
connection.select_value(relation, "#{name} Exists") ? true : false
-
rescue ThrowResult
-
false
-
end
-
-
2
protected
-
-
2
def find_with_associations
-
join_dependency = construct_join_dependency_for_association_find
-
relation = construct_relation_for_association_find(join_dependency)
-
rows = connection.select_all(relation, 'SQL', relation.bind_values.dup)
-
join_dependency.instantiate(rows)
-
rescue ThrowResult
-
[]
-
end
-
-
2
def construct_join_dependency_for_association_find
-
including = (@eager_load_values + @includes_values).uniq
-
ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
-
end
-
-
2
def construct_relation_for_association_calculations
-
including = (@eager_load_values + @includes_values).uniq
-
join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, arel.froms.first)
-
relation = except(:includes, :eager_load, :preload)
-
apply_join_dependency(relation, join_dependency)
-
end
-
-
2
def construct_relation_for_association_find(join_dependency)
-
relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns)
-
apply_join_dependency(relation, join_dependency)
-
end
-
-
2
def apply_join_dependency(relation, join_dependency)
-
join_dependency.join_associations.each do |association|
-
relation = association.join_relation(relation)
-
end
-
-
limitable_reflections = using_limitable_reflections?(join_dependency.reflections)
-
-
if !limitable_reflections && relation.limit_value
-
limited_id_condition = construct_limited_ids_condition(relation.except(:select))
-
relation = relation.where(limited_id_condition)
-
end
-
-
relation = relation.except(:limit, :offset) unless limitable_reflections
-
-
relation
-
end
-
-
2
def construct_limited_ids_condition(relation)
-
orders = relation.order_values.map { |val| val.presence }.compact
-
values = @klass.connection.distinct("#{@klass.connection.quote_table_name table_name}.#{primary_key}", orders)
-
-
relation = relation.dup.select(values)
-
relation.uniq_value = nil
-
-
id_rows = @klass.connection.select_all(relation.arel, 'SQL', relation.bind_values)
-
ids_array = id_rows.map {|row| row[primary_key]}
-
-
ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
-
end
-
-
2
def find_by_attributes(match, attributes, *args)
-
54
conditions = Hash[attributes.map {|a| [a, args[attributes.index(a)]]}]
-
27
result = where(conditions).send(match.finder)
-
-
27
if match.bang? && result.nil?
-
raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}"
-
else
-
27
yield(result) if block_given?
-
27
result
-
end
-
end
-
-
2
def find_or_instantiator_by_attributes(match, attributes, *args)
-
options = args.size > 1 && args.last(2).all?{ |a| a.is_a?(Hash) } ? args.extract_options! : {}
-
protected_attributes_for_create, unprotected_attributes_for_create = {}, {}
-
args.each_with_index do |arg, i|
-
if arg.is_a?(Hash)
-
protected_attributes_for_create = args[i].with_indifferent_access
-
else
-
unprotected_attributes_for_create[attributes[i]] = args[i]
-
end
-
end
-
-
conditions = (protected_attributes_for_create.merge(unprotected_attributes_for_create)).slice(*attributes).symbolize_keys
-
-
record = where(conditions).first
-
-
unless record
-
record = @klass.new(protected_attributes_for_create, options) do |r|
-
r.assign_attributes(unprotected_attributes_for_create, :without_protection => true)
-
end
-
yield(record) if block_given?
-
record.send(match.save_method) if match.save_record?
-
end
-
-
record
-
end
-
-
2
def find_with_ids(*ids)
-
129
return to_a.find { |*block_args| yield(*block_args) } if block_given?
-
-
129
expects_array = ids.first.kind_of?(Array)
-
129
return ids.first if expects_array && ids.first.empty?
-
-
129
ids = ids.flatten.compact.uniq
-
-
129
case ids.size
-
when 0
-
raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
-
when 1
-
129
result = find_one(ids.first)
-
129
expects_array ? [ result ] : result
-
else
-
find_some(ids)
-
end
-
end
-
-
2
def find_one(id)
-
129
id = id.id if ActiveRecord::Base === id
-
-
129
if IdentityMap.enabled? && where_values.blank? &&
-
limit_value.blank? && order_values.blank? &&
-
includes_values.blank? && preload_values.blank? &&
-
readonly_value.nil? && joins_values.blank? &&
-
!@klass.locking_enabled? &&
-
record = IdentityMap.get(@klass, id)
-
return record
-
end
-
-
129
column = columns_hash[primary_key]
-
-
129
substitute = connection.substitute_at(column, @bind_values.length)
-
129
relation = where(table[primary_key].eq(substitute))
-
129
relation.bind_values = [[column, id]]
-
129
record = relation.first
-
-
129
unless record
-
conditions = arel.where_sql
-
conditions = " [#{conditions}]" if conditions
-
raise RecordNotFound, "Couldn't find #{@klass.name} with #{primary_key}=#{id}#{conditions}"
-
end
-
-
129
record
-
end
-
-
2
def find_some(ids)
-
result = where(table[primary_key].in(ids)).all
-
-
expected_size =
-
if @limit_value && ids.size > @limit_value
-
@limit_value
-
else
-
ids.size
-
end
-
-
# 11 ids with limit 3, offset 9 should give 2 results.
-
if @offset_value && (ids.size - @offset_value < expected_size)
-
expected_size = ids.size - @offset_value
-
end
-
-
if result.size == expected_size
-
result
-
else
-
conditions = arel.where_sql
-
conditions = " [#{conditions}]" if conditions
-
-
error = "Couldn't find all #{@klass.name.pluralize} with IDs "
-
error << "(#{ids.join(", ")})#{conditions} (found #{result.size} results, but was looking for #{expected_size})"
-
raise RecordNotFound, error
-
end
-
end
-
-
2
def find_first
-
361
if loaded?
-
@records.first
-
else
-
361
@first ||= limit(1).to_a[0]
-
end
-
end
-
-
2
def find_last
-
2
if loaded?
-
@records.last
-
else
-
@last ||=
-
if offset_value || limit_value
-
to_a.last
-
else
-
2
reverse_order.limit(1).to_a[0]
-
2
end
-
end
-
end
-
-
2
def using_limitable_reflections?(reflections)
-
reflections.none? { |r| r.collection? }
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class PredicateBuilder # :nodoc:
-
1
def self.build_from_hash(engine, attributes, default_table, allow_table_name = true)
-
71
predicates = attributes.map do |column, value|
-
71
table = default_table
-
-
71
if allow_table_name && value.is_a?(Hash)
-
table = Arel::Table.new(column, engine)
-
-
if value.empty?
-
'1 = 2'
-
else
-
build_from_hash(engine, value, table, false)
-
end
-
else
-
71
column = column.to_s
-
-
71
if allow_table_name && column.include?('.')
-
table_name, column = column.split('.', 2)
-
table = Arel::Table.new(table_name, engine)
-
end
-
-
71
attribute = table[column]
-
-
71
case value
-
when ActiveRecord::Relation
-
value = value.select(value.klass.arel_table[value.klass.primary_key]) if value.select_values.empty?
-
attribute.in(value.arel.ast)
-
when Array, ActiveRecord::Associations::CollectionProxy
-
values = value.to_a.map {|x| x.is_a?(ActiveRecord::Base) ? x.id : x}
-
ranges, values = values.partition {|v| v.is_a?(Range) || v.is_a?(Arel::Relation)}
-
-
array_predicates = ranges.map {|range| attribute.in(range)}
-
-
if values.include?(nil)
-
values = values.compact
-
if values.empty?
-
array_predicates << attribute.eq(nil)
-
else
-
array_predicates << attribute.in(values.compact).or(attribute.eq(nil))
-
end
-
else
-
array_predicates << attribute.in(values)
-
end
-
-
array_predicates.inject {|composite, predicate| composite.or(predicate)}
-
when Range, Arel::Relation
-
attribute.in(value)
-
when ActiveRecord::Base
-
27
attribute.eq(value.id)
-
when Class
-
# FIXME: I think we need to deprecate this behavior
-
attribute.eq(value.name)
-
else
-
44
attribute.eq(value)
-
end
-
end
-
end
-
-
71
predicates.flatten
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActiveRecord
-
2
module QueryMethods
-
2
extend ActiveSupport::Concern
-
-
2
attr_accessor :includes_values, :eager_load_values, :preload_values,
-
:select_values, :group_values, :order_values, :joins_values,
-
:where_values, :having_values, :bind_values,
-
:limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value,
-
:from_value, :reordering_value, :reverse_order_value,
-
:uniq_value
-
-
2
def includes(*args)
-
args.reject! {|a| a.blank? }
-
-
return self if args.empty?
-
-
relation = clone
-
relation.includes_values = (relation.includes_values + args).flatten.uniq
-
relation
-
end
-
-
2
def eager_load(*args)
-
return self if args.blank?
-
-
relation = clone
-
relation.eager_load_values += args
-
relation
-
end
-
-
2
def preload(*args)
-
return self if args.blank?
-
-
relation = clone
-
relation.preload_values += args
-
relation
-
end
-
-
# Works in two unique ways.
-
#
-
# First: takes a block so it can be used just like Array#select.
-
#
-
# Model.scoped.select { |m| m.field == value }
-
#
-
# This will build an array of objects from the database for the scope,
-
# converting them into an array and iterating through them using Array#select.
-
#
-
# Second: Modifies the SELECT statement for the query so that only certain
-
# fields are retrieved:
-
#
-
# >> Model.select(:field)
-
# => [#<Model field:value>]
-
#
-
# Although in the above example it looks as though this method returns an
-
# array, it actually returns a relation object and can have other query
-
# methods appended to it, such as the other methods in ActiveRecord::QueryMethods.
-
#
-
# The argument to the method can also be an array of fields.
-
#
-
# >> Model.select([:field, :other_field, :and_one_more])
-
# => [#<Model field: "value", other_field: "value", and_one_more: "value">]
-
#
-
# Any attributes that do not have fields retrieved by a select
-
# will raise a ActiveModel::MissingAttributeError when the getter method for that attribute is used:
-
#
-
# >> Model.select(:field).first.other_field
-
# => ActiveModel::MissingAttributeError: missing attribute: other_field
-
2
def select(value = Proc.new)
-
if block_given?
-
to_a.select {|*block_args| value.call(*block_args) }
-
else
-
relation = clone
-
relation.select_values += Array.wrap(value)
-
relation
-
end
-
end
-
-
2
def group(*args)
-
return self if args.blank?
-
-
relation = clone
-
relation.group_values += args.flatten
-
relation
-
end
-
-
2
def order(*args)
-
3
return self if args.blank?
-
-
3
relation = clone
-
3
relation.order_values += args.flatten
-
3
relation
-
end
-
-
# Replaces any existing order defined on the relation with the specified order.
-
#
-
# User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC'
-
#
-
# Subsequent calls to order on the same relation will be appended. For example:
-
#
-
# User.order('email DESC').reorder('id ASC').order('name ASC')
-
#
-
# generates a query with 'ORDER BY id ASC, name ASC'.
-
#
-
2
def reorder(*args)
-
28
return self if args.blank?
-
-
28
relation = clone
-
28
relation.reordering_value = true
-
28
relation.order_values = args.flatten
-
28
relation
-
end
-
-
2
def joins(*args)
-
return self if args.compact.blank?
-
-
relation = clone
-
-
args.flatten!
-
relation.joins_values += args
-
-
relation
-
end
-
-
2
def bind(value)
-
relation = clone
-
relation.bind_values += [value]
-
relation
-
end
-
-
2
def where(opts, *rest)
-
965
return self if opts.blank?
-
-
965
relation = clone
-
965
relation.where_values += build_where(opts, rest)
-
965
relation
-
end
-
-
2
def having(opts, *rest)
-
return self if opts.blank?
-
-
relation = clone
-
relation.having_values += build_where(opts, rest)
-
relation
-
end
-
-
2
def limit(value)
-
363
relation = clone
-
363
relation.limit_value = value
-
363
relation
-
end
-
-
2
def offset(value)
-
relation = clone
-
relation.offset_value = value
-
relation
-
end
-
-
2
def lock(locks = true)
-
relation = clone
-
-
case locks
-
when String, TrueClass, NilClass
-
relation.lock_value = locks || true
-
else
-
relation.lock_value = false
-
end
-
-
relation
-
end
-
-
2
def readonly(value = true)
-
14
relation = clone
-
14
relation.readonly_value = value
-
14
relation
-
end
-
-
2
def create_with(value)
-
relation = clone
-
relation.create_with_value = value ? create_with_value.merge(value) : {}
-
relation
-
end
-
-
2
def from(value)
-
relation = clone
-
relation.from_value = value
-
relation
-
end
-
-
# Specifies whether the records should be unique or not. For example:
-
#
-
# User.select(:name)
-
# # => Might return two records with the same name
-
#
-
# User.select(:name).uniq
-
# # => Returns 1 record per unique name
-
#
-
# User.select(:name).uniq.uniq(false)
-
# # => You can also remove the uniqueness
-
2
def uniq(value = true)
-
relation = clone
-
relation.uniq_value = value
-
relation
-
end
-
-
# Used to extend a scope with additional methods, either through
-
# a module or through a block provided.
-
#
-
# The object returned is a relation, which can be further extended.
-
#
-
# === Using a module
-
#
-
# module Pagination
-
# def page(number)
-
# # pagination code goes here
-
# end
-
# end
-
#
-
# scope = Model.scoped.extending(Pagination)
-
# scope.page(params[:page])
-
#
-
# You can also pass a list of modules:
-
#
-
# scope = Model.scoped.extending(Pagination, SomethingElse)
-
#
-
# === Using a block
-
#
-
# scope = Model.scoped.extending do
-
# def page(number)
-
# # pagination code goes here
-
# end
-
# end
-
# scope.page(params[:page])
-
#
-
# You can also use a block and a module list:
-
#
-
# scope = Model.scoped.extending(Pagination) do
-
# def per_page(number)
-
# # pagination code goes here
-
# end
-
# end
-
2
def extending(*modules)
-
283
modules << Module.new(&Proc.new) if block_given?
-
-
283
return self if modules.empty?
-
-
20
relation = clone
-
20
relation.send(:apply_modules, modules.flatten)
-
20
relation
-
end
-
-
2
def reverse_order
-
2
relation = clone
-
2
relation.reverse_order_value = !relation.reverse_order_value
-
2
relation
-
end
-
-
2
def arel
-
1463
@arel ||= with_default_scope.build_arel
-
end
-
-
2
def build_arel
-
1302
arel = table.from table
-
-
1302
build_joins(arel, @joins_values) unless @joins_values.empty?
-
-
1302
collapse_wheres(arel, (@where_values - ['']).uniq)
-
-
1302
arel.having(*@having_values.uniq.reject{|h| h.blank?}) unless @having_values.empty?
-
-
1302
arel.take(connection.sanitize_limit(@limit_value)) if @limit_value
-
1302
arel.skip(@offset_value.to_i) if @offset_value
-
-
1302
arel.group(*@group_values.uniq.reject{|g| g.blank?}) unless @group_values.empty?
-
-
1302
order = @order_values
-
1302
order = reverse_sql_order(order) if @reverse_order_value
-
1335
arel.order(*order.uniq.reject{|o| o.blank?}) unless order.empty?
-
-
1302
build_select(arel, @select_values.uniq)
-
-
1302
arel.distinct(@uniq_value)
-
1302
arel.from(@from_value) if @from_value
-
1302
arel.lock(@lock_value) if @lock_value
-
-
1302
arel
-
end
-
-
2
private
-
-
2
def custom_join_ast(table, joins)
-
joins = joins.reject { |join| join.blank? }
-
-
return [] if joins.empty?
-
-
@implicit_readonly = true
-
-
joins.map do |join|
-
case join
-
when Array
-
join = Arel.sql(join.join(' ')) if array_of_strings?(join)
-
when String
-
join = Arel.sql(join)
-
end
-
table.create_string_join(join)
-
end
-
end
-
-
2
def collapse_wheres(arel, wheres)
-
1302
equalities = wheres.grep(Arel::Nodes::Equality)
-
-
1302
arel.where(Arel::Nodes::And.new(equalities)) unless equalities.empty?
-
-
1302
(wheres - equalities).each do |where|
-
461
where = Arel.sql(where) if String === where
-
461
arel.where(Arel::Nodes::Grouping.new(where))
-
end
-
end
-
-
2
def build_where(opts, other = [])
-
965
case opts
-
when String, Array
-
427
[@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
-
when Hash
-
71
attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
-
71
PredicateBuilder.build_from_hash(table.engine, attributes, table)
-
else
-
467
[opts]
-
end
-
end
-
-
2
def build_joins(manager, joins)
-
buckets = joins.group_by do |join|
-
case join
-
when String
-
'string_join'
-
when Hash, Symbol, Array
-
'association_join'
-
when ActiveRecord::Associations::JoinDependency::JoinAssociation
-
'stashed_join'
-
when Arel::Nodes::Join
-
'join_node'
-
else
-
raise 'unknown class: %s' % join.class.name
-
end
-
end
-
-
association_joins = buckets['association_join'] || []
-
stashed_association_joins = buckets['stashed_join'] || []
-
join_nodes = (buckets['join_node'] || []).uniq
-
string_joins = (buckets['string_join'] || []).map { |x|
-
x.strip
-
}.uniq
-
-
join_list = join_nodes + custom_join_ast(manager, string_joins)
-
-
join_dependency = ActiveRecord::Associations::JoinDependency.new(
-
@klass,
-
association_joins,
-
join_list
-
)
-
-
join_dependency.graft(*stashed_association_joins)
-
-
@implicit_readonly = true unless association_joins.empty? && stashed_association_joins.empty?
-
-
# FIXME: refactor this to build an AST
-
join_dependency.join_associations.each do |association|
-
association.join_to(manager)
-
end
-
-
manager.join_sources.concat join_list
-
-
manager
-
end
-
-
2
def build_select(arel, selects)
-
1302
unless selects.empty?
-
28
@implicit_readonly = false
-
28
arel.project(*selects)
-
else
-
1274
arel.project(@klass.arel_table[Arel.star])
-
end
-
end
-
-
2
def apply_modules(modules)
-
347
unless modules.empty?
-
20
@extensions += modules
-
40
modules.each {|extension| extend(extension) }
-
end
-
end
-
-
2
def reverse_sql_order(order_query)
-
2
order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty?
-
-
2
order_query.map do |o|
-
2
case o
-
when Arel::Nodes::Ordering
-
o.reverse
-
when String, Symbol
-
2
o.to_s.split(',').collect do |s|
-
2
s.strip!
-
2
s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
-
end
-
else
-
o
-
end
-
end.flatten
-
end
-
-
2
def array_of_strings?(o)
-
o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)}
-
end
-
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActiveRecord
-
2
module SpawnMethods
-
2
def merge(r)
-
327
return self unless r
-
327
return to_a & r if r.is_a?(Array)
-
-
327
merged_relation = clone
-
-
327
r = r.with_default_scope if r.default_scoped? && r.klass != klass
-
-
327
Relation::ASSOCIATION_METHODS.each do |method|
-
981
value = r.send(:"#{method}_values")
-
-
981
unless value.empty?
-
if method == :includes
-
merged_relation = merged_relation.includes(value)
-
else
-
merge_relation_method(merged_relation, method, value)
-
end
-
end
-
end
-
-
327
(Relation::MULTI_VALUE_METHODS - [:joins, :where, :order]).each do |method|
-
1308
value = r.send(:"#{method}_values")
-
1308
merge_relation_method(merged_relation, method, value) if value.present?
-
end
-
-
327
merge_joins(merged_relation, r)
-
-
327
merged_wheres = @where_values + r.where_values
-
-
327
unless @where_values.empty?
-
# Remove duplicate ARel attributes. Last one wins.
-
55
seen = Hash.new { |h,table| h[table] = {} }
-
38
merged_wheres = merged_wheres.reverse.reject { |w|
-
88
nuke = false
-
88
if w.respond_to?(:operator) && w.operator == :== &&
-
w.left.respond_to?(:relation)
-
17
name = w.left.name
-
17
table = w.left.relation.name
-
17
nuke = seen[table][name]
-
17
seen[table][name] = true
-
end
-
88
nuke
-
}.reverse
-
end
-
-
327
merged_relation.where_values = merged_wheres
-
-
327
(Relation::SINGLE_VALUE_METHODS - [:lock, :create_with, :reordering]).each do |method|
-
1962
value = r.send(:"#{method}_value")
-
1962
merged_relation.send(:"#{method}_value=", value) unless value.nil?
-
end
-
-
327
merged_relation.lock_value = r.lock_value unless merged_relation.lock_value
-
-
327
merged_relation = merged_relation.create_with(r.create_with_value) unless r.create_with_value.empty?
-
-
327
if (r.reordering_value)
-
# override any order specified in the original relation
-
merged_relation.reordering_value = true
-
merged_relation.order_values = r.order_values
-
else
-
# merge in order_values from r
-
327
merged_relation.order_values += r.order_values
-
end
-
-
# Apply scope extension modules
-
327
merged_relation.send :apply_modules, r.extensions
-
-
327
merged_relation
-
end
-
-
# Removes from the query the condition(s) specified in +skips+.
-
#
-
# Example:
-
#
-
# Post.order('id asc').except(:order) # discards the order condition
-
# Post.where('id > 10').order('id asc').except(:where) # discards the where condition but keeps the order
-
#
-
2
def except(*skips)
-
result = self.class.new(@klass, table)
-
result.default_scoped = default_scoped
-
-
((Relation::ASSOCIATION_METHODS + Relation::MULTI_VALUE_METHODS) - skips).each do |method|
-
result.send(:"#{method}_values=", send(:"#{method}_values"))
-
end
-
-
(Relation::SINGLE_VALUE_METHODS - skips).each do |method|
-
result.send(:"#{method}_value=", send(:"#{method}_value"))
-
end
-
-
# Apply scope extension modules
-
result.send(:apply_modules, extensions)
-
-
result
-
end
-
-
# Removes any condition from the query other than the one(s) specified in +onlies+.
-
#
-
# Example:
-
#
-
# Post.order('id asc').only(:where) # discards the order condition
-
# Post.order('id asc').only(:where, :order) # uses the specified order
-
#
-
2
def only(*onlies)
-
result = self.class.new(@klass, table)
-
result.default_scoped = default_scoped
-
-
((Relation::ASSOCIATION_METHODS + Relation::MULTI_VALUE_METHODS) & onlies).each do |method|
-
result.send(:"#{method}_values=", send(:"#{method}_values"))
-
end
-
-
(Relation::SINGLE_VALUE_METHODS & onlies).each do |method|
-
result.send(:"#{method}_value=", send(:"#{method}_value"))
-
end
-
-
# Apply scope extension modules
-
result.send(:apply_modules, extensions)
-
-
result
-
end
-
-
2
VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset, :extend,
-
:order, :select, :readonly, :group, :having, :from, :lock ]
-
-
2
def apply_finder_options(options)
-
307
relation = clone
-
307
return relation unless options
-
-
307
options.assert_valid_keys(VALID_FIND_OPTIONS)
-
307
finders = options.dup
-
307
finders.delete_if { |key, value| value.nil? && key != :limit }
-
-
307
([:joins, :select, :group, :order, :having, :limit, :offset, :from, :lock, :readonly] & finders.keys).each do |finder|
-
relation = relation.send(finder, finders[finder])
-
end
-
-
307
relation = relation.where(finders[:conditions]) if options.has_key?(:conditions)
-
307
relation = relation.includes(finders[:include]) if options.has_key?(:include)
-
307
relation = relation.extending(finders[:extend]) if options.has_key?(:extend)
-
-
307
relation
-
end
-
-
2
private
-
-
2
def merge_joins(relation, other)
-
327
values = other.joins_values
-
327
return if values.blank?
-
-
if other.klass >= relation.klass
-
relation.joins_values += values
-
else
-
joins_dependency, rest = values.partition do |join|
-
case join
-
when Hash, Symbol, Array
-
true
-
else
-
false
-
end
-
end
-
-
join_dependency = ActiveRecord::Associations::JoinDependency.new(
-
other.klass,
-
joins_dependency,
-
[]
-
)
-
-
relation.joins_values += join_dependency.join_associations + rest
-
end
-
end
-
-
2
def merge_relation_method(relation, method, value)
-
relation.send(:"#{method}_values=", relation.send(:"#{method}_values") + value)
-
end
-
end
-
end
-
2
module ActiveRecord
-
###
-
# This class encapsulates a Result returned from calling +exec_query+ on any
-
# database connection adapter. For example:
-
#
-
# x = ActiveRecord::Base.connection.exec_query('SELECT * FROM foo')
-
# x # => #<ActiveRecord::Result:0xdeadbeef>
-
2
class Result
-
2
include Enumerable
-
-
2
attr_reader :columns, :rows
-
-
2
def initialize(columns, rows)
-
1359
@columns = columns
-
1359
@rows = rows
-
1359
@hash_rows = nil
-
end
-
-
2
def each
-
1607
hash_rows.each { |row| yield row }
-
end
-
-
2
def to_hash
-
48
hash_rows
-
end
-
-
2
private
-
2
def hash_rows
-
@hash_rows ||=
-
begin
-
# We freeze the strings to prevent them getting duped when
-
# used as keys in ActiveRecord::Model's @attributes hash
-
10262
columns = @columns.map { |c| c.dup.freeze }
-
909
@rows.map { |row|
-
1116
Hash[columns.zip(row)]
-
}
-
909
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
-
2
module ActiveRecord
-
2
module Sanitization
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
2
def quote_value(value, column = nil) #:nodoc:
-
connection.quote(value,column)
-
end
-
-
# Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
-
2
def sanitize(object) #:nodoc:
-
connection.quote(object)
-
end
-
-
2
protected
-
-
# Accepts an array, hash, or string of SQL conditions and sanitizes
-
# them into a valid SQL fragment for a WHERE clause.
-
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
-
# { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'"
-
# "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
-
2
def sanitize_sql_for_conditions(condition, table_name = self.table_name)
-
1243
return nil if condition.blank?
-
-
1243
case condition
-
427
when Array; sanitize_sql_array(condition)
-
when Hash; sanitize_sql_hash_for_conditions(condition, table_name)
-
816
else condition
-
end
-
end
-
2
alias_method :sanitize_sql, :sanitize_sql_for_conditions
-
-
# Accepts an array, hash, or string of SQL conditions and sanitizes
-
# them into a valid SQL fragment for a SET clause.
-
# { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'"
-
2
def sanitize_sql_for_assignment(assignments)
-
44
case assignments
-
when Array; sanitize_sql_array(assignments)
-
44
when Hash; sanitize_sql_hash_for_assignment(assignments)
-
else assignments
-
end
-
end
-
-
# Accepts a hash of SQL conditions and replaces those attributes
-
# that correspond to a +composed_of+ relationship with their expanded
-
# aggregate attribute values.
-
# Given:
-
# class Person < ActiveRecord::Base
-
# composed_of :address, :class_name => "Address",
-
# :mapping => [%w(address_street street), %w(address_city city)]
-
# end
-
# Then:
-
# { :address => Address.new("813 abc st.", "chicago") }
-
# # => { :address_street => "813 abc st.", :address_city => "chicago" }
-
2
def expand_hash_conditions_for_aggregates(attrs)
-
71
expanded_attrs = {}
-
71
attrs.each do |attr, value|
-
71
unless (aggregation = reflect_on_aggregation(attr.to_sym)).nil?
-
mapping = aggregate_mapping(aggregation)
-
mapping.each do |field_attr, aggregate_attr|
-
if mapping.size == 1 && !value.respond_to?(aggregate_attr)
-
expanded_attrs[field_attr] = value
-
else
-
expanded_attrs[field_attr] = value.send(aggregate_attr)
-
end
-
end
-
else
-
71
expanded_attrs[attr] = value
-
end
-
end
-
71
expanded_attrs
-
end
-
-
# Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.
-
# { :name => "foo'bar", :group_id => 4 }
-
# # => "name='foo''bar' and group_id= 4"
-
# { :status => nil, :group_id => [1,2,3] }
-
# # => "status IS NULL and group_id IN (1,2,3)"
-
# { :age => 13..18 }
-
# # => "age BETWEEN 13 AND 18"
-
# { 'other_records.id' => 7 }
-
# # => "`other_records`.`id` = 7"
-
# { :other_records => { :id => 7 } }
-
# # => "`other_records`.`id` = 7"
-
# And for value objects on a composed_of relationship:
-
# { :address => Address.new("123 abc st.", "chicago") }
-
# # => "address_street='123 abc st.' and address_city='chicago'"
-
2
def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
-
attrs = expand_hash_conditions_for_aggregates(attrs)
-
-
table = Arel::Table.new(table_name).alias(default_table_name)
-
PredicateBuilder.build_from_hash(arel_engine, attrs, table).map { |b|
-
connection.visitor.accept b
-
}.join(' AND ')
-
end
-
2
alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
-
-
# Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
-
# { :status => nil, :group_id => 1 }
-
# # => "status = NULL , group_id = 1"
-
2
def sanitize_sql_hash_for_assignment(attrs)
-
44
attrs.map do |attr, value|
-
44
"#{connection.quote_column_name(attr)} = #{quote_bound_value(value)}"
-
end.join(', ')
-
end
-
-
# Accepts an array of conditions. The array has each value
-
# sanitized and interpolated into the SQL statement.
-
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
-
2
def sanitize_sql_array(ary)
-
427
statement, *values = ary
-
427
if values.first.is_a?(Hash) && statement =~ /:\w+/
-
replace_named_bind_variables(statement, values.first)
-
427
elsif statement.include?('?')
-
427
replace_bind_variables(statement, values)
-
elsif statement.blank?
-
statement
-
else
-
statement % values.collect { |value| connection.quote_string(value.to_s) }
-
end
-
end
-
-
2
alias_method :sanitize_conditions, :sanitize_sql
-
-
2
def replace_bind_variables(statement, values) #:nodoc:
-
427
raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
-
427
bound = values.dup
-
427
c = connection
-
2469
statement.gsub('?') { quote_bound_value(bound.shift, c) }
-
end
-
-
2
def replace_named_bind_variables(statement, bind_vars) #:nodoc:
-
statement.gsub(/(:?):([a-zA-Z]\w*)/) do
-
if $1 == ':' # skip postgresql casts
-
$& # return the whole match
-
elsif bind_vars.include?(match = $2.to_sym)
-
quote_bound_value(bind_vars[match])
-
else
-
raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
-
end
-
end
-
end
-
-
2
def expand_range_bind_variables(bind_vars) #:nodoc:
-
expanded = []
-
-
bind_vars.each do |var|
-
next if var.is_a?(Hash)
-
-
if var.is_a?(Range)
-
expanded << var.first
-
expanded << var.last
-
else
-
expanded << var
-
end
-
end
-
-
expanded
-
end
-
-
2
def quote_bound_value(value, c = connection) #:nodoc:
-
2086
if value.respond_to?(:map) && !value.acts_like?(:string)
-
if value.respond_to?(:empty?) && value.empty?
-
c.quote(nil)
-
else
-
value.map { |v| c.quote(v) }.join(',')
-
end
-
else
-
2086
c.quote(value)
-
end
-
end
-
-
2
def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc:
-
427
unless expected == provided
-
raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
-
end
-
end
-
end
-
-
# TODO: Deprecate this
-
2
def quoted_id #:nodoc:
-
quote_value(id, column_for_attribute(self.class.primary_key))
-
end
-
-
2
private
-
-
# Quote strings appropriately for SQL statements.
-
2
def quote_value(value, column = nil)
-
self.class.connection.quote(value, column)
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
-
2
module ActiveRecord
-
2
module Scoping
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
include Default
-
2
include Named
-
end
-
-
2
module ClassMethods
-
# with_scope lets you apply options to inner block incrementally. It takes a hash and the keys must be
-
# <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameter is <tt>Relation</tt> while
-
# <tt>:create</tt> parameters are an attributes hash.
-
#
-
# class Article < ActiveRecord::Base
-
# def self.create_with_scope
-
# with_scope(:find => where(:blog_id => 1), :create => { :blog_id => 1 }) do
-
# find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1
-
# a = create(1)
-
# a.blog_id # => 1
-
# end
-
# end
-
# end
-
#
-
# In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of
-
# <tt>where</tt>, <tt>includes</tt>, and <tt>joins</tt> operations in <tt>Relation</tt>, which are merged.
-
#
-
# <tt>joins</tt> operations are uniqued so multiple scopes can join in the same table without table aliasing
-
# problems. If you need to join multiple tables, but still want one of the tables to be uniqued, use the
-
# array of strings format for your joins.
-
#
-
# class Article < ActiveRecord::Base
-
# def self.find_with_scope
-
# with_scope(:find => where(:blog_id => 1).limit(1), :create => { :blog_id => 1 }) do
-
# with_scope(:find => limit(10)) do
-
# all # => SELECT * from articles WHERE blog_id = 1 LIMIT 10
-
# end
-
# with_scope(:find => where(:author_id => 3)) do
-
# all # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1
-
# end
-
# end
-
# end
-
# end
-
#
-
# You can ignore any previous scopings by using the <tt>with_exclusive_scope</tt> method.
-
#
-
# class Article < ActiveRecord::Base
-
# def self.find_with_exclusive_scope
-
# with_scope(:find => where(:blog_id => 1).limit(1)) do
-
# with_exclusive_scope(:find => limit(10)) do
-
# all # => SELECT * from articles LIMIT 10
-
# end
-
# end
-
# end
-
# end
-
#
-
# *Note*: the +:find+ scope also has effect on update and deletion methods, like +update_all+ and +delete_all+.
-
2
def with_scope(scope = {}, action = :merge, &block)
-
# If another Active Record class has been passed in, get its current scope
-
934
scope = scope.current_scope if !scope.is_a?(Relation) && scope.respond_to?(:current_scope)
-
-
934
previous_scope = self.current_scope
-
-
934
if scope.is_a?(Hash)
-
# Dup first and second level of hash (method and params).
-
scope = scope.dup
-
scope.each do |method, params|
-
scope[method] = params.dup unless params == true
-
end
-
-
scope.assert_valid_keys([ :find, :create ])
-
relation = construct_finder_arel(scope[:find] || {})
-
relation.default_scoped = true unless action == :overwrite
-
-
if previous_scope && previous_scope.create_with_value && scope[:create]
-
scope_for_create = if action == :merge
-
previous_scope.create_with_value.merge(scope[:create])
-
else
-
scope[:create]
-
end
-
-
relation = relation.create_with(scope_for_create)
-
else
-
scope_for_create = scope[:create]
-
scope_for_create ||= previous_scope.create_with_value if previous_scope
-
relation = relation.create_with(scope_for_create) if scope_for_create
-
end
-
-
scope = relation
-
end
-
-
934
scope = previous_scope.merge(scope) if previous_scope && action == :merge
-
-
934
self.current_scope = scope
-
934
begin
-
934
yield
-
ensure
-
934
self.current_scope = previous_scope
-
end
-
end
-
-
2
protected
-
-
# Works like with_scope, but discards any nested properties.
-
2
def with_exclusive_scope(method_scoping = {}, &block)
-
if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) }
-
raise ArgumentError, <<-MSG
-
New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope:
-
-
User.unscoped.where(:active => true)
-
-
Or call unscoped with a block:
-
-
User.unscoped do
-
User.where(:active => true).all
-
end
-
-
MSG
-
end
-
with_scope(method_scoping, :overwrite, &block)
-
end
-
-
2
def current_scope #:nodoc:
-
2265
Thread.current["#{self}_current_scope"]
-
end
-
-
2
def current_scope=(scope) #:nodoc:
-
1868
Thread.current["#{self}_current_scope"] = scope
-
end
-
-
2
private
-
-
2
def construct_finder_arel(options = {}, scope = nil)
-
relation = options.is_a?(Hash) ? unscoped.apply_finder_options(options) : options
-
relation = scope.merge(relation) if scope
-
relation
-
end
-
-
end
-
-
2
def populate_with_current_scope_attributes
-
359
return unless self.class.scope_attributes?
-
-
self.class.scope_attributes.each do |att,value|
-
send("#{att}=", value) if respond_to?("#{att}=")
-
end
-
end
-
-
end
-
end
-
2
require 'active_support/concern'
-
-
2
module ActiveRecord
-
2
module Scoping
-
2
module Default
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
# Stores the default scope for the class
-
2
class_attribute :default_scopes, :instance_writer => false
-
2
self.default_scopes = []
-
end
-
-
2
module ClassMethods
-
# Returns a scope for the model without the default_scope.
-
#
-
# class Post < ActiveRecord::Base
-
# def self.default_scope
-
# where :published => true
-
# end
-
# end
-
#
-
# Post.all # Fires "SELECT * FROM posts WHERE published = true"
-
# Post.unscoped.all # Fires "SELECT * FROM posts"
-
#
-
# This method also accepts a block. All queries inside the block will
-
# not use the default_scope:
-
#
-
# Post.unscoped {
-
# Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10"
-
# }
-
#
-
# It is recommended to use the block form of unscoped because chaining
-
# unscoped with <tt>scope</tt> does not work. Assuming that
-
# <tt>published</tt> is a <tt>scope</tt>, the following two statements
-
# are equal: the default_scope is applied on both.
-
#
-
# Post.unscoped.published
-
# Post.published
-
2
def unscoped #:nodoc:
-
734
block_given? ? relation.scoping { yield } : relation
-
end
-
-
2
def before_remove_const #:nodoc:
-
self.current_scope = nil
-
end
-
-
2
protected
-
-
# Use this macro in your model to set a default scope for all operations on
-
# the model.
-
#
-
# class Article < ActiveRecord::Base
-
# default_scope where(:published => true)
-
# end
-
#
-
# Article.all # => SELECT * FROM articles WHERE published = true
-
#
-
# The <tt>default_scope</tt> is also applied while creating/building a record. It is not
-
# applied while updating a record.
-
#
-
# Article.new.published # => true
-
# Article.create.published # => true
-
#
-
# You can also use <tt>default_scope</tt> with a block, in order to have it lazily evaluated:
-
#
-
# class Article < ActiveRecord::Base
-
# default_scope { where(:published_at => Time.now - 1.week) }
-
# end
-
#
-
# (You can also pass any object which responds to <tt>call</tt> to the <tt>default_scope</tt>
-
# macro, and it will be called when building the default scope.)
-
#
-
# If you use multiple <tt>default_scope</tt> declarations in your model then they will
-
# be merged together:
-
#
-
# class Article < ActiveRecord::Base
-
# default_scope where(:published => true)
-
# default_scope where(:rating => 'G')
-
# end
-
#
-
# Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G'
-
#
-
# This is also the case with inheritance and module includes where the parent or module
-
# defines a <tt>default_scope</tt> and the child or including class defines a second one.
-
#
-
# If you need to do more complex things with a default scope, you can alternatively
-
# define it as a class method:
-
#
-
# class Article < ActiveRecord::Base
-
# def self.default_scope
-
# # Should return a scope, you can call 'super' here etc.
-
# end
-
# end
-
2
def default_scope(scope = {})
-
scope = Proc.new if block_given?
-
self.default_scopes = default_scopes + [scope]
-
end
-
-
2
def build_default_scope #:nodoc:
-
1716
if method(:default_scope).owner != ActiveRecord::Scoping::Default::ClassMethods
-
evaluate_default_scope { default_scope }
-
1716
elsif default_scopes.any?
-
evaluate_default_scope do
-
default_scopes.inject(relation) do |default_scope, scope|
-
if scope.is_a?(Hash)
-
default_scope.apply_finder_options(scope)
-
elsif !scope.is_a?(Relation) && scope.respond_to?(:call)
-
default_scope.merge(scope.call)
-
else
-
default_scope.merge(scope)
-
end
-
end
-
end
-
end
-
end
-
-
2
def ignore_default_scope? #:nodoc:
-
Thread.current["#{self}_ignore_default_scope"]
-
end
-
-
2
def ignore_default_scope=(ignore) #:nodoc:
-
Thread.current["#{self}_ignore_default_scope"] = ignore
-
end
-
-
# The ignore_default_scope flag is used to prevent an infinite recursion situation where
-
# a default scope references a scope which has a default scope which references a scope...
-
2
def evaluate_default_scope
-
return if ignore_default_scope?
-
-
begin
-
self.ignore_default_scope = true
-
yield
-
ensure
-
self.ignore_default_scope = false
-
end
-
end
-
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/class/attribute'
-
-
2
module ActiveRecord
-
# = Active Record Named \Scopes
-
2
module Scoping
-
2
module Named
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
# Returns an anonymous \scope.
-
#
-
# posts = Post.scoped
-
# posts.size # Fires "select count(*) from posts" and returns the count
-
# posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
-
#
-
# fruits = Fruit.scoped
-
# fruits = fruits.where(:color => 'red') if options[:red_only]
-
# fruits = fruits.limit(10) if limited?
-
#
-
# Anonymous \scopes tend to be useful when procedurally generating complex
-
# queries, where passing intermediate values (\scopes) around as first-class
-
# objects is convenient.
-
#
-
# You can define a \scope that applies to all finders using
-
# ActiveRecord::Base.default_scope.
-
2
def scoped(options = nil)
-
912
if options
-
scoped.apply_finder_options(options)
-
else
-
912
if current_scope
-
60
current_scope.clone
-
else
-
852
scope = relation
-
852
scope.default_scoped = true
-
852
scope
-
end
-
end
-
end
-
-
##
-
# Collects attributes from scopes that should be applied when creating
-
# an AR instance for the particular class this is called on.
-
2
def scope_attributes # :nodoc:
-
if current_scope
-
current_scope.scope_for_create
-
else
-
scope = relation
-
scope.default_scoped = true
-
scope.scope_for_create
-
end
-
end
-
-
##
-
# Are there default attributes associated with this scope?
-
2
def scope_attributes? # :nodoc:
-
359
current_scope || default_scopes.any?
-
end
-
-
# Adds a class method for retrieving and querying objects. A \scope represents a narrowing of a database query,
-
# such as <tt>where(:color => :red).select('shirts.*').includes(:washing_instructions)</tt>.
-
#
-
# class Shirt < ActiveRecord::Base
-
# scope :red, where(:color => 'red')
-
# scope :dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true)
-
# end
-
#
-
# The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red,
-
# in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>.
-
#
-
# Note that this is simply 'syntactic sugar' for defining an actual class method:
-
#
-
# class Shirt < ActiveRecord::Base
-
# def self.red
-
# where(:color => 'red')
-
# end
-
# end
-
#
-
# Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it
-
# resembles the association object constructed by a <tt>has_many</tt> declaration. For instance,
-
# you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <tt>Shirt.red.where(:size => 'small')</tt>.
-
# Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable;
-
# <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt>
-
# all behave as if Shirt.red really was an Array.
-
#
-
# These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce
-
# all shirts that are both red and dry clean only.
-
# Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt>
-
# returns the number of garments for which these criteria obtain. Similarly with
-
# <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
-
#
-
# All \scopes are available as class methods on the ActiveRecord::Base descendant upon which
-
# the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If,
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :shirts
-
# end
-
#
-
# then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean
-
# only shirts.
-
#
-
# Named \scopes can also be procedural:
-
#
-
# class Shirt < ActiveRecord::Base
-
# scope :colored, lambda { |color| where(:color => color) }
-
# end
-
#
-
# In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
-
#
-
# On Ruby 1.9 you can use the 'stabby lambda' syntax:
-
#
-
# scope :colored, ->(color) { where(:color => color) }
-
#
-
# Note that scopes defined with \scope will be evaluated when they are defined, rather than
-
# when they are used. For example, the following would be incorrect:
-
#
-
# class Post < ActiveRecord::Base
-
# scope :recent, where('published_at >= ?', Time.current - 1.week)
-
# end
-
#
-
# The example above would be 'frozen' to the <tt>Time.current</tt> value when the <tt>Post</tt>
-
# class was defined, and so the resultant SQL query would always be the same. The correct
-
# way to do this would be via a lambda, which will re-evaluate the scope each time
-
# it is called:
-
#
-
# class Post < ActiveRecord::Base
-
# scope :recent, lambda { where('published_at >= ?', Time.current - 1.week) }
-
# end
-
#
-
# Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations:
-
#
-
# class Shirt < ActiveRecord::Base
-
# scope :red, where(:color => 'red') do
-
# def dom_id
-
# 'red_shirts'
-
# end
-
# end
-
# end
-
#
-
# Scopes can also be used while creating/building a record.
-
#
-
# class Article < ActiveRecord::Base
-
# scope :published, where(:published => true)
-
# end
-
#
-
# Article.published.new.published # => true
-
# Article.published.create.published # => true
-
#
-
# Class methods on your model are automatically available
-
# on scopes. Assuming the following setup:
-
#
-
# class Article < ActiveRecord::Base
-
# scope :published, where(:published => true)
-
# scope :featured, where(:featured => true)
-
#
-
# def self.latest_article
-
# order('published_at desc').first
-
# end
-
#
-
# def self.titles
-
# pluck(:title)
-
# end
-
# end
-
#
-
# We are able to call the methods like this:
-
#
-
# Article.published.featured.latest_article
-
# Article.featured.titles
-
2
def scope(name, scope_options = {})
-
10
name = name.to_sym
-
10
valid_scope_name?(name)
-
10
extension = Module.new(&Proc.new) if block_given?
-
-
10
scope_proc = lambda do |*args|
-
65
options = scope_options.respond_to?(:call) ? unscoped { scope_options.call(*args) } : scope_options
-
47
options = scoped.apply_finder_options(options) if options.is_a?(Hash)
-
-
47
relation = scoped.merge(options)
-
-
47
extension ? relation.extending(extension) : relation
-
end
-
-
10
singleton_class.send(:redefine_method, name, &scope_proc)
-
end
-
-
2
protected
-
-
2
def valid_scope_name?(name)
-
10
if logger && respond_to?(name, true)
-
logger.warn "Creating scope :#{name}. " \
-
"Overwriting existing method #{self.name}.#{name}."
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord #:nodoc:
-
# = Active Record Serialization
-
2
module Serialization
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::Serializers::JSON
-
-
2
def serializable_hash(options = nil)
-
options = options.try(:clone) || {}
-
-
options[:except] = Array.wrap(options[:except]).map { |n| n.to_s }
-
options[:except] |= Array.wrap(self.class.inheritance_column)
-
-
super(options)
-
end
-
end
-
end
-
-
2
require 'active_record/serializers/xml_serializer'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/hash/conversions'
-
-
2
module ActiveRecord #:nodoc:
-
2
module Serialization
-
2
include ActiveModel::Serializers::Xml
-
-
# Builds an XML document to represent the model. Some configuration is
-
# available through +options+. However more complicated cases should
-
# override ActiveRecord::Base#to_xml.
-
#
-
# By default the generated XML document will include the processing
-
# instruction and all the object's attributes. For example:
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <topic>
-
# <title>The First Topic</title>
-
# <author-name>David</author-name>
-
# <id type="integer">1</id>
-
# <approved type="boolean">false</approved>
-
# <replies-count type="integer">0</replies-count>
-
# <bonus-time type="datetime">2000-01-01T08:28:00+12:00</bonus-time>
-
# <written-on type="datetime">2003-07-16T09:28:00+1200</written-on>
-
# <content>Have a nice day</content>
-
# <author-email-address>david@loudthinking.com</author-email-address>
-
# <parent-id></parent-id>
-
# <last-read type="date">2004-04-15</last-read>
-
# </topic>
-
#
-
# This behavior can be controlled with <tt>:only</tt>, <tt>:except</tt>,
-
# <tt>:skip_instruct</tt>, <tt>:skip_types</tt>, <tt>:dasherize</tt> and <tt>:camelize</tt> .
-
# The <tt>:only</tt> and <tt>:except</tt> options are the same as for the
-
# +attributes+ method. The default is to dasherize all column names, but you
-
# can disable this setting <tt>:dasherize</tt> to +false+. Setting <tt>:camelize</tt>
-
# to +true+ will camelize all column names - this also overrides <tt>:dasherize</tt>.
-
# To not have the column type included in the XML output set <tt>:skip_types</tt> to +true+.
-
#
-
# For instance:
-
#
-
# topic.to_xml(:skip_instruct => true, :except => [ :id, :bonus_time, :written_on, :replies_count ])
-
#
-
# <topic>
-
# <title>The First Topic</title>
-
# <author-name>David</author-name>
-
# <approved type="boolean">false</approved>
-
# <content>Have a nice day</content>
-
# <author-email-address>david@loudthinking.com</author-email-address>
-
# <parent-id></parent-id>
-
# <last-read type="date">2004-04-15</last-read>
-
# </topic>
-
#
-
# To include first level associations use <tt>:include</tt>:
-
#
-
# firm.to_xml :include => [ :account, :clients ]
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <firm>
-
# <id type="integer">1</id>
-
# <rating type="integer">1</rating>
-
# <name>37signals</name>
-
# <clients type="array">
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Summit</name>
-
# </client>
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Microsoft</name>
-
# </client>
-
# </clients>
-
# <account>
-
# <id type="integer">1</id>
-
# <credit-limit type="integer">50</credit-limit>
-
# </account>
-
# </firm>
-
#
-
# Additionally, the record being serialized will be passed to a Proc's second
-
# parameter. This allows for ad hoc additions to the resultant document that
-
# incorporate the context of the record being serialized. And by leveraging the
-
# closure created by a Proc, to_xml can be used to add elements that normally fall
-
# outside of the scope of the model -- for example, generating and appending URLs
-
# associated with models.
-
#
-
# proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
-
# firm.to_xml :procs => [ proc ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <name-reverse>slangis73</name-reverse>
-
# </firm>
-
#
-
# To include deeper levels of associations pass a hash like this:
-
#
-
# firm.to_xml :include => {:account => {}, :clients => {:include => :address}}
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <firm>
-
# <id type="integer">1</id>
-
# <rating type="integer">1</rating>
-
# <name>37signals</name>
-
# <clients type="array">
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Summit</name>
-
# <address>
-
# ...
-
# </address>
-
# </client>
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Microsoft</name>
-
# <address>
-
# ...
-
# </address>
-
# </client>
-
# </clients>
-
# <account>
-
# <id type="integer">1</id>
-
# <credit-limit type="integer">50</credit-limit>
-
# </account>
-
# </firm>
-
#
-
# To include any methods on the model being called use <tt>:methods</tt>:
-
#
-
# firm.to_xml :methods => [ :calculated_earnings, :real_earnings ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <calculated-earnings>100000000000000000</calculated-earnings>
-
# <real-earnings>5</real-earnings>
-
# </firm>
-
#
-
# To call any additional Procs use <tt>:procs</tt>. The Procs are passed a
-
# modified version of the options hash that was given to +to_xml+:
-
#
-
# proc = Proc.new { |options| options[:builder].tag!('abc', 'def') }
-
# firm.to_xml :procs => [ proc ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <abc>def</abc>
-
# </firm>
-
#
-
# Alternatively, you can yield the builder object as part of the +to_xml+ call:
-
#
-
# firm.to_xml do |xml|
-
# xml.creator do
-
# xml.first_name "David"
-
# xml.last_name "Heinemeier Hansson"
-
# end
-
# end
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <creator>
-
# <first_name>David</first_name>
-
# <last_name>Heinemeier Hansson</last_name>
-
# </creator>
-
# </firm>
-
#
-
# As noted above, you may override +to_xml+ in your ActiveRecord::Base
-
# subclasses to have complete control about what's generated. The general
-
# form of doing this is:
-
#
-
# class IHaveMyOwnXML < ActiveRecord::Base
-
# def to_xml(options = {})
-
# require 'builder'
-
# options[:indent] ||= 2
-
# xml = options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent])
-
# xml.instruct! unless options[:skip_instruct]
-
# xml.level_one do
-
# xml.tag!(:second_level, 'content')
-
# end
-
# end
-
# end
-
2
def to_xml(options = {}, &block)
-
XmlSerializer.new(self, options).serialize(&block)
-
end
-
end
-
-
2
class XmlSerializer < ActiveModel::Serializers::Xml::Serializer #:nodoc:
-
2
def initialize(*args)
-
super
-
options[:except] = Array.wrap(options[:except]) | Array.wrap(@serializable.class.inheritance_column)
-
end
-
-
2
class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
-
2
def compute_type
-
klass = @serializable.class
-
type = if klass.serialized_attributes.key?(name)
-
super
-
elsif klass.columns_hash.key?(name)
-
klass.columns_hash[name].type
-
else
-
NilClass
-
end
-
-
{ :text => :string,
-
:time => :datetime }[type] || type
-
end
-
2
protected :compute_type
-
end
-
end
-
end
-
2
module ActiveRecord
-
# Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column.
-
# It's like a simple key/value store backed into your record when you don't care about being able to
-
# query that store outside the context of a single record.
-
#
-
# You can then declare accessors to this store that are then accessible just like any other attribute
-
# of the model. This is very helpful for easily exposing store keys to a form or elsewhere that's
-
# already built around just accessing attributes on the model.
-
#
-
# Make sure that you declare the database column used for the serialized store as a text, so there's
-
# plenty of room.
-
#
-
# Examples:
-
#
-
# class User < ActiveRecord::Base
-
# store :settings, accessors: [ :color, :homepage ]
-
# end
-
#
-
# u = User.new(color: 'black', homepage: '37signals.com')
-
# u.color # Accessor stored attribute
-
# u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
-
#
-
# # Add additional accessors to an existing store through store_accessor
-
# class SuperUser < User
-
# store_accessor :settings, :privileges, :servants
-
# end
-
2
module Store
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
2
def store(store_attribute, options = {})
-
serialize store_attribute, Hash
-
store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
-
end
-
-
2
def store_accessor(store_attribute, *keys)
-
Array(keys).flatten.each do |key|
-
define_method("#{key}=") do |value|
-
send("#{store_attribute}=", {}) unless send(store_attribute).is_a?(Hash)
-
send("#{store_attribute}_will_change!")
-
send(store_attribute)[key] = value
-
end
-
-
define_method(key) do
-
send("#{store_attribute}=", {}) unless send(store_attribute).is_a?(Hash)
-
send(store_attribute)[key]
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
# = Active Record Test Case
-
#
-
# Defines some test assertions to test against SQL queries.
-
2
class TestCase < ActiveSupport::TestCase #:nodoc:
-
2
setup :cleanup_identity_map
-
-
2
def setup
-
cleanup_identity_map
-
end
-
-
2
def cleanup_identity_map
-
ActiveRecord::IdentityMap.clear
-
end
-
-
# Backport skip to Ruby 1.8. test/unit doesn't support it, so just
-
# make it a noop.
-
2
unless instance_methods.map(&:to_s).include?("skip")
-
def skip(message)
-
end
-
end
-
-
2
def assert_date_from_db(expected, actual, message = nil)
-
# SybaseAdapter doesn't have a separate column type just for dates,
-
# so the time is in the string and incorrectly formatted
-
if current_adapter?(:SybaseAdapter)
-
assert_equal expected.to_s, actual.to_date.to_s, message
-
else
-
assert_equal expected.to_s, actual.to_s, message
-
end
-
end
-
-
2
def assert_sql(*patterns_to_match)
-
ActiveRecord::SQLCounter.log = []
-
yield
-
ActiveRecord::SQLCounter.log
-
ensure
-
failed_patterns = []
-
patterns_to_match.each do |pattern|
-
failed_patterns << pattern unless ActiveRecord::SQLCounter.log.any?{ |sql| pattern === sql }
-
end
-
assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map{ |p| p.inspect }.join(', ')} not found.#{ActiveRecord::SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{ActiveRecord::SQLCounter.log.join("\n")}"}"
-
end
-
-
2
def assert_queries(num = 1)
-
ActiveRecord::SQLCounter.log = []
-
yield
-
ensure
-
assert_equal num, ActiveRecord::SQLCounter.log.size, "#{ActiveRecord::SQLCounter.log.size} instead of #{num} queries were executed.#{ActiveRecord::SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{ActiveRecord::SQLCounter.log.join("\n")}"}"
-
end
-
-
2
def assert_no_queries(&block)
-
prev_ignored_sql = ActiveRecord::SQLCounter.ignored_sql
-
ActiveRecord::SQLCounter.ignored_sql = []
-
assert_queries(0, &block)
-
ensure
-
ActiveRecord::SQLCounter.ignored_sql = prev_ignored_sql
-
end
-
-
2
def with_kcode(kcode)
-
if RUBY_VERSION < '1.9'
-
orig_kcode, $KCODE = $KCODE, kcode
-
begin
-
yield
-
ensure
-
$KCODE = orig_kcode
-
end
-
else
-
yield
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
-
2
module ActiveRecord
-
# = Active Record Timestamp
-
#
-
# Active Record automatically timestamps create and update operations if the
-
# table has fields named <tt>created_at/created_on</tt> or
-
# <tt>updated_at/updated_on</tt>.
-
#
-
# Timestamping can be turned off by setting:
-
#
-
# config.active_record.record_timestamps = false
-
#
-
# Timestamps are in the local timezone by default but you can use UTC by setting:
-
#
-
# config.active_record.default_timezone = :utc
-
#
-
# == Time Zone aware attributes
-
#
-
# By default, ActiveRecord::Base keeps all the datetime columns time zone aware by executing following code.
-
#
-
# config.active_record.time_zone_aware_attributes = true
-
#
-
# This feature can easily be turned off by assigning value <tt>false</tt> .
-
#
-
# If your attributes are time zone aware and you desire to skip time zone conversion to the current Time.zone
-
# when reading certain attributes then you can do following:
-
#
-
# class Topic < ActiveRecord::Base
-
# self.skip_time_zone_conversion_for_attributes = [:written_on]
-
# end
-
2
module Timestamp
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
class_attribute :record_timestamps
-
2
self.record_timestamps = true
-
end
-
-
2
def initialize_dup(other)
-
clear_timestamp_attributes
-
super
-
end
-
-
2
private
-
-
2
def create #:nodoc:
-
308
if self.record_timestamps
-
308
current_time = current_time_from_proper_timezone
-
-
308
all_timestamp_attributes.each do |column|
-
1232
if respond_to?(column) && respond_to?("#{column}=") && self.send(column).nil?
-
616
write_attribute(column.to_s, current_time)
-
end
-
end
-
end
-
-
308
super
-
end
-
-
2
def update(*args) #:nodoc:
-
55
if should_record_timestamps?
-
54
current_time = current_time_from_proper_timezone
-
-
54
timestamp_attributes_for_update_in_model.each do |column|
-
54
column = column.to_s
-
54
next if attribute_changed?(column)
-
54
write_attribute(column, current_time)
-
end
-
end
-
55
super
-
end
-
-
2
def should_record_timestamps?
-
55
self.record_timestamps && (!partial_updates? || changed? || (attributes.keys & self.class.serialized_attributes.keys).present?)
-
end
-
-
2
def timestamp_attributes_for_create_in_model
-
timestamp_attributes_for_create.select { |c| self.class.column_names.include?(c.to_s) }
-
end
-
-
2
def timestamp_attributes_for_update_in_model
-
162
timestamp_attributes_for_update.select { |c| self.class.column_names.include?(c.to_s) }
-
end
-
-
2
def all_timestamp_attributes_in_model
-
timestamp_attributes_for_create_in_model + timestamp_attributes_for_update_in_model
-
end
-
-
2
def timestamp_attributes_for_update #:nodoc:
-
362
[:updated_at, :updated_on]
-
end
-
-
2
def timestamp_attributes_for_create #:nodoc:
-
308
[:created_at, :created_on]
-
end
-
-
2
def all_timestamp_attributes #:nodoc:
-
308
timestamp_attributes_for_create + timestamp_attributes_for_update
-
end
-
-
2
def current_time_from_proper_timezone #:nodoc:
-
362
self.class.default_timezone == :utc ? Time.now.utc : Time.now
-
end
-
-
# Clear attributes and changed_attributes
-
2
def clear_timestamp_attributes
-
all_timestamp_attributes_in_model.each do |attribute_name|
-
self[attribute_name] = nil
-
changed_attributes.delete(attribute_name)
-
end
-
end
-
end
-
end
-
2
require 'thread'
-
-
2
module ActiveRecord
-
# See ActiveRecord::Transactions::ClassMethods for documentation.
-
2
module Transactions
-
2
extend ActiveSupport::Concern
-
-
2
class TransactionError < ActiveRecordError # :nodoc:
-
end
-
-
2
included do
-
2
define_callbacks :commit, :rollback, :terminator => "result == false", :scope => [:kind, :name]
-
end
-
-
# = Active Record Transactions
-
#
-
# Transactions are protective blocks where SQL statements are only permanent
-
# if they can all succeed as one atomic action. The classic example is a
-
# transfer between two accounts where you can only have a deposit if the
-
# withdrawal succeeded and vice versa. Transactions enforce the integrity of
-
# the database and guard the data against program errors or database
-
# break-downs. So basically you should use transaction blocks whenever you
-
# have a number of statements that must be executed together or not at all.
-
#
-
# For example:
-
#
-
# ActiveRecord::Base.transaction do
-
# david.withdrawal(100)
-
# mary.deposit(100)
-
# end
-
#
-
# This example will only take money from David and give it to Mary if neither
-
# +withdrawal+ nor +deposit+ raise an exception. Exceptions will force a
-
# ROLLBACK that returns the database to the state before the transaction
-
# began. Be aware, though, that the objects will _not_ have their instance
-
# data returned to their pre-transactional state.
-
#
-
# == Different Active Record classes in a single transaction
-
#
-
# Though the transaction class method is called on some Active Record class,
-
# the objects within the transaction block need not all be instances of
-
# that class. This is because transactions are per-database connection, not
-
# per-model.
-
#
-
# In this example a +balance+ record is transactionally saved even
-
# though +transaction+ is called on the +Account+ class:
-
#
-
# Account.transaction do
-
# balance.save!
-
# account.save!
-
# end
-
#
-
# The +transaction+ method is also available as a model instance method.
-
# For example, you can also do this:
-
#
-
# balance.transaction do
-
# balance.save!
-
# account.save!
-
# end
-
#
-
# == Transactions are not distributed across database connections
-
#
-
# A transaction acts on a single database connection. If you have
-
# multiple class-specific databases, the transaction will not protect
-
# interaction among them. One workaround is to begin a transaction
-
# on each class whose models you alter:
-
#
-
# Student.transaction do
-
# Course.transaction do
-
# course.enroll(student)
-
# student.units += course.units
-
# end
-
# end
-
#
-
# This is a poor solution, but fully distributed transactions are beyond
-
# the scope of Active Record.
-
#
-
# == +save+ and +destroy+ are automatically wrapped in a transaction
-
#
-
# Both +save+ and +destroy+ come wrapped in a transaction that ensures
-
# that whatever you do in validations or callbacks will happen under its
-
# protected cover. So you can use validations to check for values that
-
# the transaction depends on or you can raise exceptions in the callbacks
-
# to rollback, including <tt>after_*</tt> callbacks.
-
#
-
# As a consequence changes to the database are not seen outside your connection
-
# until the operation is complete. For example, if you try to update the index
-
# of a search engine in +after_save+ the indexer won't see the updated record.
-
# The +after_commit+ callback is the only one that is triggered once the update
-
# is committed. See below.
-
#
-
# == Exception handling and rolling back
-
#
-
# Also have in mind that exceptions thrown within a transaction block will
-
# be propagated (after triggering the ROLLBACK), so you should be ready to
-
# catch those in your application code.
-
#
-
# One exception is the <tt>ActiveRecord::Rollback</tt> exception, which will trigger
-
# a ROLLBACK when raised, but not be re-raised by the transaction block.
-
#
-
# *Warning*: one should not catch <tt>ActiveRecord::StatementInvalid</tt> exceptions
-
# inside a transaction block. <tt>ActiveRecord::StatementInvalid</tt> exceptions indicate that an
-
# error occurred at the database level, for example when a unique constraint
-
# is violated. On some database systems, such as PostgreSQL, database errors
-
# inside a transaction cause the entire transaction to become unusable
-
# until it's restarted from the beginning. Here is an example which
-
# demonstrates the problem:
-
#
-
# # Suppose that we have a Number model with a unique column called 'i'.
-
# Number.transaction do
-
# Number.create(:i => 0)
-
# begin
-
# # This will raise a unique constraint error...
-
# Number.create(:i => 0)
-
# rescue ActiveRecord::StatementInvalid
-
# # ...which we ignore.
-
# end
-
#
-
# # On PostgreSQL, the transaction is now unusable. The following
-
# # statement will cause a PostgreSQL error, even though the unique
-
# # constraint is no longer violated:
-
# Number.create(:i => 1)
-
# # => "PGError: ERROR: current transaction is aborted, commands
-
# # ignored until end of transaction block"
-
# end
-
#
-
# One should restart the entire transaction if an
-
# <tt>ActiveRecord::StatementInvalid</tt> occurred.
-
#
-
# == Nested transactions
-
#
-
# +transaction+ calls can be nested. By default, this makes all database
-
# statements in the nested transaction block become part of the parent
-
# transaction. For example, the following behavior may be surprising:
-
#
-
# User.transaction do
-
# User.create(:username => 'Kotori')
-
# User.transaction do
-
# User.create(:username => 'Nemu')
-
# raise ActiveRecord::Rollback
-
# end
-
# end
-
#
-
# creates both "Kotori" and "Nemu". Reason is the <tt>ActiveRecord::Rollback</tt>
-
# exception in the nested block does not issue a ROLLBACK. Since these exceptions
-
# are captured in transaction blocks, the parent block does not see it and the
-
# real transaction is committed.
-
#
-
# In order to get a ROLLBACK for the nested transaction you may ask for a real
-
# sub-transaction by passing <tt>:requires_new => true</tt>. If anything goes wrong,
-
# the database rolls back to the beginning of the sub-transaction without rolling
-
# back the parent transaction. If we add it to the previous example:
-
#
-
# User.transaction do
-
# User.create(:username => 'Kotori')
-
# User.transaction(:requires_new => true) do
-
# User.create(:username => 'Nemu')
-
# raise ActiveRecord::Rollback
-
# end
-
# end
-
#
-
# only "Kotori" is created. (This works on MySQL and PostgreSQL, but not on SQLite3.)
-
#
-
# Most databases don't support true nested transactions. At the time of
-
# writing, the only database that we're aware of that supports true nested
-
# transactions, is MS-SQL. Because of this, Active Record emulates nested
-
# transactions by using savepoints on MySQL and PostgreSQL. See
-
# http://dev.mysql.com/doc/refman/5.0/en/savepoint.html
-
# for more information about savepoints.
-
#
-
# === Callbacks
-
#
-
# There are two types of callbacks associated with committing and rolling back transactions:
-
# +after_commit+ and +after_rollback+.
-
#
-
# +after_commit+ callbacks are called on every record saved or destroyed within a
-
# transaction immediately after the transaction is committed. +after_rollback+ callbacks
-
# are called on every record saved or destroyed within a transaction immediately after the
-
# transaction or savepoint is rolled back.
-
#
-
# These callbacks are useful for interacting with other systems since you will be guaranteed
-
# that the callback is only executed when the database is in a permanent state. For example,
-
# +after_commit+ is a good spot to put in a hook to clearing a cache since clearing it from
-
# within a transaction could trigger the cache to be regenerated before the database is updated.
-
#
-
# === Caveats
-
#
-
# If you're on MySQL, then do not use DDL operations in nested transactions
-
# blocks that are emulated with savepoints. That is, do not execute statements
-
# like 'CREATE TABLE' inside such blocks. This is because MySQL automatically
-
# releases all savepoints upon executing a DDL operation. When +transaction+
-
# is finished and tries to release the savepoint it created earlier, a
-
# database error will occur because the savepoint has already been
-
# automatically released. The following example demonstrates the problem:
-
#
-
# Model.connection.transaction do # BEGIN
-
# Model.connection.transaction(:requires_new => true) do # CREATE SAVEPOINT active_record_1
-
# Model.connection.create_table(...) # active_record_1 now automatically released
-
# end # RELEASE savepoint active_record_1
-
# # ^^^^ BOOM! database error!
-
# end
-
#
-
# Note that "TRUNCATE" is also a MySQL DDL statement!
-
2
module ClassMethods
-
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
-
2
def transaction(options = {}, &block)
-
# See the ConnectionAdapters::DatabaseStatements#transaction API docs.
-
429
connection.transaction(options, &block)
-
end
-
-
# This callback is called after a record has been created, updated, or destroyed.
-
#
-
# You can specify that the callback should only be fired by a certain action with
-
# the +:on+ option:
-
#
-
# after_commit :do_foo, :on => :create
-
# after_commit :do_bar, :on => :update
-
# after_commit :do_baz, :on => :destroy
-
#
-
# Also, to have the callback fired on create and update, but not on destroy:
-
#
-
# after_commit :do_zoo, :if => :persisted?
-
#
-
# Note that transactional fixtures do not play well with this feature. Please
-
# use the +test_after_commit+ gem to have these hooks fired in tests.
-
2
def after_commit(*args, &block)
-
options = args.last
-
if options.is_a?(Hash) && options[:on]
-
options[:if] = Array.wrap(options[:if])
-
options[:if] << "transaction_include_action?(:#{options[:on]})"
-
end
-
set_callback(:commit, :after, *args, &block)
-
end
-
-
# This callback is called after a create, update, or destroy are rolled back.
-
#
-
# Please check the documentation of +after_commit+ for options.
-
2
def after_rollback(*args, &block)
-
options = args.last
-
if options.is_a?(Hash) && options[:on]
-
options[:if] = Array.wrap(options[:if])
-
options[:if] << "transaction_include_action?(:#{options[:on]})"
-
end
-
set_callback(:rollback, :after, *args, &block)
-
end
-
end
-
-
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
-
2
def transaction(options = {}, &block)
-
8
self.class.transaction(options, &block)
-
end
-
-
2
def destroy #:nodoc:
-
42
with_transaction_returning_status { super }
-
end
-
-
2
def save(*) #:nodoc:
-
356
rollback_active_record_state! do
-
712
with_transaction_returning_status { super }
-
end
-
end
-
-
2
def save!(*) #:nodoc:
-
62
with_transaction_returning_status { super }
-
end
-
-
# Reset id and @new_record if the transaction rolls back.
-
2
def rollback_active_record_state!
-
356
remember_transaction_record_state
-
356
yield
-
rescue Exception
-
IdentityMap.remove(self) if IdentityMap.enabled?
-
restore_transaction_record_state
-
raise
-
ensure
-
356
clear_transaction_record_state
-
end
-
-
# Call the after_commit callbacks
-
2
def committed! #:nodoc:
-
run_callbacks :commit
-
ensure
-
clear_transaction_record_state
-
end
-
-
# Call the after rollback callbacks. The restore_state argument indicates if the record
-
# state should be rolled back to the beginning or just to the last savepoint.
-
2
def rolledback!(force_restore_state = false) #:nodoc:
-
24
run_callbacks :rollback
-
ensure
-
24
IdentityMap.remove(self) if IdentityMap.enabled?
-
24
restore_transaction_record_state(force_restore_state)
-
end
-
-
# Add the record to the current transaction so that the :after_rollback and :after_commit callbacks
-
# can be called.
-
2
def add_to_transaction
-
417
if self.class.connection.add_transaction_record(self)
-
417
remember_transaction_record_state
-
end
-
end
-
-
# Executes +method+ within a transaction and captures its return value as a
-
# status flag. If the status is true the transaction is committed, otherwise
-
# a ROLLBACK is issued. In any case the status flag is returned.
-
#
-
# This method is available within the context of an ActiveRecord::Base
-
# instance.
-
2
def with_transaction_returning_status
-
417
status = nil
-
417
self.class.transaction do
-
417
add_to_transaction
-
417
status = yield
-
417
raise ActiveRecord::Rollback unless status
-
end
-
417
status
-
end
-
-
2
protected
-
-
# Save the new record state and id of a record so it can be restored later if a transaction fails.
-
2
def remember_transaction_record_state #:nodoc:
-
773
@_start_transaction_state ||= {}
-
773
@_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
-
773
unless @_start_transaction_state.include?(:new_record)
-
400
@_start_transaction_state[:new_record] = @new_record
-
end
-
773
unless @_start_transaction_state.include?(:destroyed)
-
400
@_start_transaction_state[:destroyed] = @destroyed
-
end
-
773
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1
-
773
@_start_transaction_state[:frozen?] = @attributes.frozen?
-
end
-
-
# Clear the new record state and id of a record.
-
2
def clear_transaction_record_state #:nodoc:
-
356
if defined?(@_start_transaction_state)
-
356
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
-
356
remove_instance_variable(:@_start_transaction_state) if @_start_transaction_state[:level] < 1
-
end
-
end
-
-
# Restore the new record state and id of a record that was previously saved by a call to save_record_state.
-
2
def restore_transaction_record_state(force = false) #:nodoc:
-
24
if defined?(@_start_transaction_state)
-
24
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
-
24
if @_start_transaction_state[:level] < 1 || force
-
restore_state = remove_instance_variable(:@_start_transaction_state)
-
was_frozen = restore_state[:frozen?]
-
@attributes = @attributes.dup if @attributes.frozen?
-
@new_record = restore_state[:new_record]
-
@destroyed = restore_state[:destroyed]
-
if restore_state.has_key?(:id)
-
self.id = restore_state[:id]
-
else
-
@attributes.delete(self.class.primary_key)
-
@attributes_cache.delete(self.class.primary_key)
-
end
-
@attributes.freeze if was_frozen
-
end
-
end
-
end
-
-
# Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed.
-
2
def transaction_record_state(state) #:nodoc:
-
@_start_transaction_state[state] if defined?(@_start_transaction_state)
-
end
-
-
# Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks.
-
2
def transaction_include_action?(action) #:nodoc:
-
case action
-
when :create
-
transaction_record_state(:new_record)
-
when :destroy
-
destroyed?
-
when :update
-
!(transaction_record_state(:new_record) || destroyed?)
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module Translation
-
2
include ActiveModel::Translation
-
-
# Set the lookup ancestors for ActiveModel.
-
2
def lookup_ancestors #:nodoc:
-
klass = self
-
classes = [klass]
-
return classes if klass == ActiveRecord::Base
-
-
while klass != klass.base_class
-
classes << klass = klass.superclass
-
end
-
classes
-
end
-
-
# Set the i18n scope to overwrite ActiveModel.
-
2
def i18n_scope #:nodoc:
-
:activerecord
-
end
-
end
-
end
-
2
module ActiveRecord
-
# = Active Record RecordInvalid
-
#
-
# Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid. Use the
-
# +record+ method to retrieve the record which did not validate.
-
#
-
# begin
-
# complex_operation_that_calls_save!_internally
-
# rescue ActiveRecord::RecordInvalid => invalid
-
# puts invalid.record.errors
-
# end
-
2
class RecordInvalid < ActiveRecordError
-
2
attr_reader :record
-
2
def initialize(record)
-
@record = record
-
errors = @record.errors.full_messages.join(", ")
-
super(I18n.t("activerecord.errors.messages.record_invalid", :errors => errors))
-
end
-
end
-
-
# = Active Record Validations
-
#
-
# Active Record includes the majority of its validations from <tt>ActiveModel::Validations</tt>
-
# all of which accept the <tt>:on</tt> argument to define the context where the
-
# validations are active. Active Record will always supply either the context of
-
# <tt>:create</tt> or <tt>:update</tt> dependent on whether the model is a
-
# <tt>new_record?</tt>.
-
2
module Validations
-
2
extend ActiveSupport::Concern
-
2
include ActiveModel::Validations
-
-
2
module ClassMethods
-
# Creates an object just like Base.create but calls <tt>save!</tt> instead of +save+
-
# so an exception is raised if the record is invalid.
-
2
def create!(attributes = nil, options = {}, &block)
-
31
if attributes.is_a?(Array)
-
attributes.collect { |attr| create!(attr, options, &block) }
-
else
-
31
object = new(attributes, options)
-
31
yield(object) if block_given?
-
31
object.save!
-
31
object
-
end
-
end
-
end
-
-
# The validation process on save can be skipped by passing <tt>:validate => false</tt>. The regular Base#save method is
-
# replaced with this when the validations module is mixed in, which it is by default.
-
2
def save(options={})
-
356
perform_validations(options) ? super : false
-
end
-
-
# Attempts to save the record just like Base#save but will raise a +RecordInvalid+ exception instead of returning false
-
# if the record is not valid.
-
2
def save!(options={})
-
31
perform_validations(options) ? super : raise(RecordInvalid.new(self))
-
end
-
-
# Runs all the validations within the specified context. Returns true if no errors are found,
-
# false otherwise.
-
#
-
# If the argument is false (default is +nil+), the context is set to <tt>:create</tt> if
-
# <tt>new_record?</tt> is true, and to <tt>:update</tt> if it is not.
-
#
-
# Validations with no <tt>:on</tt> option will run no matter the context. Validations with
-
# some <tt>:on</tt> option will only run in the specified context.
-
2
def valid?(context = nil)
-
359
context ||= (new_record? ? :create : :update)
-
359
output = super(context)
-
359
errors.empty? && output
-
end
-
-
2
protected
-
-
2
def perform_validations(options={})
-
387
perform_validation = options[:validate] != false
-
387
perform_validation ? valid?(options[:context]) : true
-
end
-
end
-
end
-
-
2
require "active_record/validations/associated"
-
2
require "active_record/validations/uniqueness"
-
2
module ActiveRecord
-
2
module Validations
-
2
class AssociatedValidator < ActiveModel::EachValidator
-
2
def validate_each(record, attribute, value)
-
if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?}.any?
-
record.errors.add(attribute, :invalid, options.merge(:value => value))
-
end
-
end
-
end
-
-
2
module ClassMethods
-
# Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
-
#
-
# class Book < ActiveRecord::Base
-
# has_many :pages
-
# belongs_to :library
-
#
-
# validates_associated :pages, :library
-
# end
-
#
-
# WARNING: This validation must not be used on both ends of an association. Doing so will lead to a circular dependency and cause infinite recursion.
-
#
-
# NOTE: This validation will not fail if the association hasn't been assigned. If you want to
-
# ensure that the association is both present and guaranteed to be valid, you also need to
-
# use +validates_presence_of+.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "is invalid")
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
-
# method, proc or string should return or evaluate to a true or false value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a true or false value.
-
2
def validates_associated(*attr_names)
-
validates_with AssociatedValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
-
2
module ActiveRecord
-
2
module Validations
-
2
class UniquenessValidator < ActiveModel::EachValidator
-
2
def initialize(options)
-
2
super(options.reverse_merge(:case_sensitive => true))
-
end
-
-
# Unfortunately, we have to tie Uniqueness validators to a class.
-
2
def setup(klass)
-
2
@klass = klass
-
end
-
-
2
def validate_each(record, attribute, value)
-
finder_class = find_finder_class_for(record)
-
table = finder_class.arel_table
-
-
coder = record.class.serialized_attributes[attribute.to_s]
-
-
if value && coder
-
value = coder.dump value
-
end
-
-
relation = build_relation(finder_class, table, attribute, value)
-
relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.send(:id))) if record.persisted?
-
-
Array.wrap(options[:scope]).each do |scope_item|
-
scope_value = record.read_attribute(scope_item)
-
relation = relation.and(table[scope_item].eq(scope_value))
-
end
-
-
if finder_class.unscoped.where(relation).exists?
-
record.errors.add(attribute, :taken, options.except(:case_sensitive, :scope).merge(:value => value))
-
end
-
end
-
-
2
protected
-
-
# The check for an existing value should be run from a class that
-
# isn't abstract. This means working down from the current class
-
# (self), to the first non-abstract class. Since classes don't know
-
# their subclasses, we have to build the hierarchy between self and
-
# the record's class.
-
2
def find_finder_class_for(record) #:nodoc:
-
class_hierarchy = [record.class]
-
-
while class_hierarchy.first != @klass
-
class_hierarchy.insert(0, class_hierarchy.first.superclass)
-
end
-
-
class_hierarchy.detect { |klass| !klass.abstract_class? }
-
end
-
-
2
def build_relation(klass, table, attribute, value) #:nodoc:
-
column = klass.columns_hash[attribute.to_s]
-
value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s if value && column.text?
-
-
if !options[:case_sensitive] && value && column.text?
-
# will use SQL LOWER function before comparison, unless it detects a case insensitive collation
-
relation = klass.connection.case_insensitive_comparison(table, attribute, column, value)
-
else
-
value = klass.connection.case_sensitive_modifier(value) if value
-
relation = table[attribute].eq(value)
-
end
-
-
relation
-
end
-
end
-
-
2
module ClassMethods
-
# Validates whether the value of the specified attributes are unique across the system.
-
# Useful for making sure that only one user
-
# can be named "davidhh".
-
#
-
# class Person < ActiveRecord::Base
-
# validates_uniqueness_of :user_name
-
# end
-
#
-
# It can also validate whether the value of the specified attributes are unique based on a scope parameter:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_uniqueness_of :user_name, :scope => :account_id
-
# end
-
#
-
# Or even multiple scope parameters. For example, making sure that a teacher can only be on the schedule once
-
# per semester for a particular class.
-
#
-
# class TeacherSchedule < ActiveRecord::Base
-
# validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
-
# end
-
#
-
# When the record is created, a check is performed to make sure that no record exists in the database
-
# with the given value for the specified attribute (that maps to a column). When the record is updated,
-
# the same check is made but disregarding the record itself.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
-
# * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
-
# * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+true+ by default).
-
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
-
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
-
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
-
# The method, proc or string should return or evaluate to a true or false value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
-
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or
-
# <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The method, proc or string should
-
# return or evaluate to a true or false value.
-
#
-
# === Concurrency and integrity
-
#
-
# Using this validation method in conjunction with ActiveRecord::Base#save
-
# does not guarantee the absence of duplicate record insertions, because
-
# uniqueness checks on the application level are inherently prone to race
-
# conditions. For example, suppose that two users try to post a Comment at
-
# the same time, and a Comment's title must be unique. At the database-level,
-
# the actions performed by these users could be interleaved in the following manner:
-
#
-
# User 1 | User 2
-
# ------------------------------------+--------------------------------------
-
# # User 1 checks whether there's |
-
# # already a comment with the title |
-
# # 'My Post'. This is not the case. |
-
# SELECT * FROM comments |
-
# WHERE title = 'My Post' |
-
# |
-
# | # User 2 does the same thing and also
-
# | # infers that his title is unique.
-
# | SELECT * FROM comments
-
# | WHERE title = 'My Post'
-
# |
-
# # User 1 inserts his comment. |
-
# INSERT INTO comments |
-
# (title, content) VALUES |
-
# ('My Post', 'hi!') |
-
# |
-
# | # User 2 does the same thing.
-
# | INSERT INTO comments
-
# | (title, content) VALUES
-
# | ('My Post', 'hello!')
-
# |
-
# | # ^^^^^^
-
# | # Boom! We now have a duplicate
-
# | # title!
-
#
-
# This could even happen if you use transactions with the 'serializable'
-
# isolation level. The best way to work around this problem is to add a unique
-
# index to the database table using
-
# ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
-
# rare case that a race condition occurs, the database will guarantee
-
# the field's uniqueness.
-
#
-
# When the database catches such a duplicate insertion,
-
# ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
-
# exception. You can either choose to let this error propagate (which
-
# will result in the default Rails exception page being shown), or you
-
# can catch it and restart the transaction (e.g. by telling the user
-
# that the title already exists, and asking him to re-enter the title).
-
# This technique is also known as optimistic concurrency control:
-
# http://en.wikipedia.org/wiki/Optimistic_concurrency_control
-
#
-
# The bundled ActiveRecord::ConnectionAdapters distinguish unique index
-
# constraint errors from other types of database errors by throwing an
-
# ActiveRecord::RecordNotUnique exception.
-
# For other adapters you will have to parse the (database-specific) exception
-
# message to detect such a case.
-
# The following bundled adapters throw the ActiveRecord::RecordNotUnique exception:
-
# * ActiveRecord::ConnectionAdapters::MysqlAdapter
-
# * ActiveRecord::ConnectionAdapters::Mysql2Adapter
-
# * ActiveRecord::ConnectionAdapters::SQLiteAdapter
-
# * ActiveRecord::ConnectionAdapters::SQLite3Adapter
-
# * ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
-
#
-
2
def validates_uniqueness_of(*attr_names)
-
validates_with UniquenessValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
2
module ActiveRecord
-
2
module VERSION #:nodoc:
-
2
MAJOR = 3
-
2
MINOR = 2
-
2
TINY = 16
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
-
end
-
end
-
#--
-
# Copyright (c) 2006-2011 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
-
2
$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-
-
2
activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
-
2
$:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
-
-
2
require 'active_support'
-
2
require 'active_model'
-
2
require 'active_resource/exceptions'
-
2
require 'active_resource/version'
-
-
2
module ActiveResource
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :Base
-
2
autoload :Connection
-
2
autoload :CustomMethods
-
2
autoload :Formats
-
2
autoload :HttpMock
-
2
autoload :Observing
-
2
autoload :Schema
-
2
autoload :Validations
-
end
-
2
module ActiveResource
-
2
class ConnectionError < StandardError # :nodoc:
-
2
attr_reader :response
-
-
2
def initialize(response, message = nil)
-
@response = response
-
@message = message
-
end
-
-
2
def to_s
-
message = "Failed."
-
message << " Response code = #{response.code}." if response.respond_to?(:code)
-
message << " Response message = #{response.message}." if response.respond_to?(:message)
-
message
-
end
-
end
-
-
# Raised when a Timeout::Error occurs.
-
2
class TimeoutError < ConnectionError
-
2
def initialize(message)
-
@message = message
-
end
-
2
def to_s; @message ;end
-
end
-
-
# Raised when a OpenSSL::SSL::SSLError occurs.
-
2
class SSLError < ConnectionError
-
2
def initialize(message)
-
@message = message
-
end
-
2
def to_s; @message ;end
-
end
-
-
# 3xx Redirection
-
2
class Redirection < ConnectionError # :nodoc:
-
2
def to_s
-
response['Location'] ? "#{super} => #{response['Location']}" : super
-
end
-
end
-
-
2
class MissingPrefixParam < ArgumentError # :nodoc:
-
end
-
-
# 4xx Client Error
-
2
class ClientError < ConnectionError # :nodoc:
-
end
-
-
# 400 Bad Request
-
2
class BadRequest < ClientError # :nodoc:
-
end
-
-
# 401 Unauthorized
-
2
class UnauthorizedAccess < ClientError # :nodoc:
-
end
-
-
# 403 Forbidden
-
2
class ForbiddenAccess < ClientError # :nodoc:
-
end
-
-
# 404 Not Found
-
2
class ResourceNotFound < ClientError # :nodoc:
-
end
-
-
# 409 Conflict
-
2
class ResourceConflict < ClientError # :nodoc:
-
end
-
-
# 410 Gone
-
2
class ResourceGone < ClientError # :nodoc:
-
end
-
-
# 5xx Server Error
-
2
class ServerError < ConnectionError # :nodoc:
-
end
-
-
# 405 Method Not Allowed
-
2
class MethodNotAllowed < ClientError # :nodoc:
-
2
def allowed_methods
-
@response['Allow'].split(',').map { |verb| verb.strip.downcase.to_sym }
-
end
-
end
-
end
-
2
require "active_resource"
-
2
require "rails"
-
-
2
module ActiveResource
-
2
class Railtie < Rails::Railtie
-
2
config.active_resource = ActiveSupport::OrderedOptions.new
-
-
2
initializer "active_resource.set_configs" do |app|
-
2
app.config.active_resource.each do |k,v|
-
ActiveResource::Base.send "#{k}=", v
-
end
-
end
-
end
-
end
-
2
module ActiveResource
-
2
module VERSION #:nodoc:
-
2
MAJOR = 3
-
2
MINOR = 2
-
2
TINY = 16
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
-
end
-
end
-
#--
-
# Copyright (c) 2005-2011 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
2
require 'securerandom'
-
-
2
module ActiveSupport
-
2
class << self
-
2
attr_accessor :load_all_hooks
-
6
def on_load_all(&hook) load_all_hooks << hook end
-
2
def load_all!; load_all_hooks.each { |hook| hook.call } end
-
end
-
2
self.load_all_hooks = []
-
-
2
on_load_all do
-
[Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte]
-
end
-
end
-
-
2
require "active_support/dependencies/autoload"
-
2
require "active_support/version"
-
-
2
module ActiveSupport
-
2
extend ActiveSupport::Autoload
-
-
2
autoload :DescendantsTracker
-
2
autoload :FileUpdateChecker
-
2
autoload :LogSubscriber
-
2
autoload :Notifications
-
-
# TODO: Narrow this list down
-
2
eager_autoload do
-
2
autoload :BacktraceCleaner
-
2
autoload :Base64
-
2
autoload :BasicObject
-
2
autoload :Benchmarkable
-
2
autoload :BufferedLogger
-
2
autoload :Cache
-
2
autoload :Callbacks
-
2
autoload :Concern
-
2
autoload :Configurable
-
2
autoload :Deprecation
-
2
autoload :Gzip
-
2
autoload :Inflector
-
2
autoload :JSON
-
2
autoload :Memoizable
-
2
autoload :MessageEncryptor
-
2
autoload :MessageVerifier
-
2
autoload :Multibyte
-
2
autoload :OptionMerger
-
2
autoload :OrderedHash
-
2
autoload :OrderedOptions
-
2
autoload :Rescuable
-
2
autoload :StringInquirer
-
2
autoload :TaggedLogging
-
2
autoload :XmlMini
-
end
-
-
2
autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
-
2
autoload :TestCase
-
end
-
-
2
autoload :I18n, "active_support/i18n"
-
2
require 'active_support'
-
2
require 'active_support/time'
-
2
require 'active_support/core_ext'
-
1
module ActiveSupport
-
# Backtraces often include many lines that are not relevant for the context under review. This makes it hard to find the
-
# signal amongst the backtrace noise, and adds debugging time. With a BacktraceCleaner, filters and silencers are used to
-
# remove the noisy lines, so that only the most relevant lines remain.
-
#
-
# Filters are used to modify lines of data, while silencers are used to remove lines entirely. The typical filter use case
-
# is to remove lengthy path information from the start of each line, and view file paths relevant to the app directory
-
# instead of the file system root. The typical silencer use case is to exclude the output of a noisy library from the
-
# backtrace, so that you can focus on the rest.
-
#
-
# ==== Example:
-
#
-
# bc = BacktraceCleaner.new
-
# bc.add_filter { |line| line.gsub(Rails.root, '') }
-
# bc.add_silencer { |line| line =~ /mongrel|rubygems/ }
-
# bc.clean(exception.backtrace) # will strip the Rails.root prefix and skip any lines from mongrel or rubygems
-
#
-
# To reconfigure an existing BacktraceCleaner (like the default one in Rails) and show as much data as possible, you can
-
# always call <tt>BacktraceCleaner#remove_silencers!</tt>, which will restore the backtrace to a pristine state. If you
-
# need to reconfigure an existing BacktraceCleaner so that it does not filter or modify the paths of any lines of the
-
# backtrace, you can call BacktraceCleaner#remove_filters! These two methods will give you a completely untouched backtrace.
-
#
-
# Inspired by the Quiet Backtrace gem by Thoughtbot.
-
1
class BacktraceCleaner
-
1
def initialize
-
1
@filters, @silencers = [], []
-
end
-
-
# Returns the backtrace after all filters and silencers have been run against it. Filters run first, then silencers.
-
1
def clean(backtrace, kind = :silent)
-
filtered = filter(backtrace)
-
-
case kind
-
when :silent
-
silence(filtered)
-
when :noise
-
noise(filtered)
-
else
-
filtered
-
end
-
end
-
-
# Adds a filter from the block provided. Each line in the backtrace will be mapped against this filter.
-
#
-
# Example:
-
#
-
# # Will turn "/my/rails/root/app/models/person.rb" into "/app/models/person.rb"
-
# backtrace_cleaner.add_filter { |line| line.gsub(Rails.root, '') }
-
1
def add_filter(&block)
-
4
@filters << block
-
end
-
-
# Adds a silencer from the block provided. If the silencer returns true for a given line, it will be excluded from
-
# the clean backtrace.
-
#
-
# Example:
-
#
-
# # Will reject all lines that include the word "mongrel", like "/gems/mongrel/server.rb" or "/app/my_mongrel_server/rb"
-
# backtrace_cleaner.add_silencer { |line| line =~ /mongrel/ }
-
1
def add_silencer(&block)
-
1
@silencers << block
-
end
-
-
# Will remove all silencers, but leave in the filters. This is useful if your context of debugging suddenly expands as
-
# you suspect a bug in one of the libraries you use.
-
1
def remove_silencers!
-
@silencers = []
-
end
-
-
1
def remove_filters!
-
@filters = []
-
end
-
-
1
private
-
1
def filter(backtrace)
-
@filters.each do |f|
-
backtrace = backtrace.map { |line| f.call(line) }
-
end
-
-
backtrace
-
end
-
-
1
def silence(backtrace)
-
@silencers.each do |s|
-
backtrace = backtrace.reject { |line| s.call(line) }
-
end
-
-
backtrace
-
end
-
-
1
def noise(backtrace)
-
@silencers.each do |s|
-
backtrace = backtrace.select { |line| s.call(line) }
-
end
-
-
backtrace
-
end
-
end
-
end
-
2
require 'active_support/deprecation'
-
-
2
begin
-
2
require 'base64'
-
rescue LoadError
-
# The Base64 module isn't available in earlier versions of Ruby 1.9.
-
module Base64
-
# Encodes a string to its base 64 representation. Each 60 characters of
-
# output is separated by a newline character.
-
#
-
# ActiveSupport::Base64.encode64("Original unencoded string")
-
# # => "T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==\n"
-
def self.encode64(data)
-
[data].pack("m")
-
end
-
-
# Decodes a base 64 encoded string to its original representation.
-
#
-
# ActiveSupport::Base64.decode64("T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==")
-
# # => "Original unencoded string"
-
def self.decode64(data)
-
data.unpack("m").first
-
end
-
end
-
end
-
-
2
unless Base64.respond_to?(:strict_encode64)
-
# Included in Ruby 1.9
-
def Base64.strict_encode64(value)
-
encode64(value).gsub(/\n/, '')
-
end
-
end
-
-
2
module ActiveSupport
-
2
module Base64
-
2
def self.encode64(value)
-
ActiveSupport::Deprecation.warn "ActiveSupport::Base64.encode64 " \
-
"is deprecated. Use Base64.encode64 instead", caller
-
::Base64.encode64(value)
-
end
-
-
2
def self.decode64(value)
-
ActiveSupport::Deprecation.warn "ActiveSupport::Base64.decode64 " \
-
"is deprecated. Use Base64.decode64 instead", caller
-
::Base64.decode64(value)
-
end
-
-
2
def self.encode64s(value)
-
ActiveSupport::Deprecation.warn "ActiveSupport::Base64.encode64s " \
-
"is deprecated. Use Base64.strict_encode64 instead", caller
-
::Base64.strict_encode64(value)
-
end
-
end
-
end
-
2
module ActiveSupport
-
2
if defined? ::BasicObject
-
# A class with no predefined methods that behaves similarly to Builder's
-
# BlankSlate. Used for proxy classes.
-
2
class BasicObject < ::BasicObject
-
2
undef_method :==
-
2
undef_method :equal?
-
-
# Let ActiveSupport::BasicObject at least raise exceptions.
-
2
def raise(*args)
-
::Object.send(:raise, *args)
-
end
-
end
-
else
-
class BasicObject #:nodoc:
-
instance_methods.each do |m|
-
undef_method(m) if m.to_s !~ /(?:^__|^nil\?$|^send$|^object_id$)/
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/benchmark'
-
2
require 'active_support/core_ext/hash/keys'
-
-
2
module ActiveSupport
-
2
module Benchmarkable
-
# Allows you to measure the execution time of a block in a template and records the result to
-
# the log. Wrap this block around expensive operations or possible bottlenecks to get a time
-
# reading for the operation. For example, let's say you thought your file processing method
-
# was taking too long; you could wrap it in a benchmark block.
-
#
-
# <% benchmark "Process data files" do %>
-
# <%= expensive_files_operation %>
-
# <% end %>
-
#
-
# That would add something like "Process data files (345.2ms)" to the log, which you can then
-
# use to compare timings when optimizing your code.
-
#
-
# You may give an optional logger level (:debug, :info, :warn, :error) as the :level option.
-
# The default logger level value is :info.
-
#
-
# <% benchmark "Low-level files", :level => :debug do %>
-
# <%= lowlevel_files_operation %>
-
# <% end %>
-
#
-
# Finally, you can pass true as the third argument to silence all log activity (other than the
-
# timing information) from inside the block. This is great for boiling down a noisy block to
-
# just a single statement that produces one log line:
-
#
-
# <% benchmark "Process data files", :level => :info, :silence => true do %>
-
# <%= expensive_and_chatty_files_operation %>
-
# <% end %>
-
2
def benchmark(message = "Benchmarking", options = {})
-
if logger
-
options.assert_valid_keys(:level, :silence)
-
options[:level] ||= :info
-
-
result = nil
-
ms = Benchmark.ms { result = options[:silence] ? silence { yield } : yield }
-
logger.send(options[:level], '%s (%.1fms)' % [ message, ms ])
-
result
-
else
-
yield
-
end
-
end
-
-
# Silence the logger during the execution of the block.
-
#
-
2
def silence
-
old_logger_level, logger.level = logger.level, ::Logger::ERROR if logger
-
yield
-
ensure
-
logger.level = old_logger_level if logger
-
end
-
end
-
end
-
2
require 'thread'
-
2
require 'logger'
-
2
require 'active_support/core_ext/logger'
-
2
require 'active_support/core_ext/class/attribute_accessors'
-
2
require 'active_support/deprecation'
-
2
require 'fileutils'
-
-
2
module ActiveSupport
-
# Inspired by the buffered logger idea by Ezra
-
2
class BufferedLogger
-
2
module Severity
-
2
DEBUG = 0
-
2
INFO = 1
-
2
WARN = 2
-
2
ERROR = 3
-
2
FATAL = 4
-
2
UNKNOWN = 5
-
end
-
2
include Severity
-
-
2
MAX_BUFFER_SIZE = 1000
-
-
##
-
# :singleton-method:
-
# Set to false to disable the silencer
-
2
cattr_accessor :silencer
-
2
self.silencer = true
-
-
# Silences the logger for the duration of the block.
-
2
def silence(temporary_level = ERROR)
-
if silencer
-
begin
-
logger = self.class.new @log_dest.dup, temporary_level
-
yield logger
-
ensure
-
logger.close
-
end
-
else
-
yield self
-
end
-
end
-
2
deprecate :silence
-
-
2
attr_reader :auto_flushing
-
2
deprecate :auto_flushing
-
-
2
def initialize(log, level = DEBUG)
-
2
@log_dest = log
-
-
2
unless log.respond_to?(:write)
-
unless File.exist?(File.dirname(log))
-
ActiveSupport::Deprecation.warn(<<-eowarn)
-
Automatic directory creation for '#{log}' is deprecated. Please make sure the directory for your log file exists before creating the logger.
-
eowarn
-
FileUtils.mkdir_p(File.dirname(log))
-
end
-
end
-
-
2
@log = open_logfile log
-
2
self.level = level
-
end
-
-
2
def open_log(log, mode)
-
open(log, mode).tap do |open_log|
-
open_log.set_encoding(Encoding::BINARY) if open_log.respond_to?(:set_encoding)
-
open_log.sync = true
-
end
-
end
-
2
deprecate :open_log
-
-
2
def level
-
1989
@log.level
-
end
-
-
2
def level=(l)
-
4
@log.level = l
-
end
-
-
2
def add(severity, message = nil, progname = nil, &block)
-
1999
@log.add(severity, message, progname, &block)
-
end
-
-
# Dynamically add methods such as:
-
# def info
-
# def warn
-
# def debug
-
2
Severity.constants.each do |severity|
-
12
class_eval <<-EOT, __FILE__, __LINE__ + 1
-
def #{severity.downcase}(message = nil, progname = nil, &block) # def debug(message = nil, progname = nil, &block)
-
add(#{severity}, message, progname, &block) # add(DEBUG, message, progname, &block)
-
end # end
-
-
def #{severity.downcase}? # def debug?
-
#{severity} >= level # DEBUG >= level
-
end # end
-
EOT
-
end
-
-
# Set the auto-flush period. Set to true to flush after every log message,
-
# to an integer to flush every N messages, or to false, nil, or zero to
-
# never auto-flush. If you turn auto-flushing off, be sure to regularly
-
# flush the log yourself -- it will eat up memory until you do.
-
2
def auto_flushing=(period)
-
end
-
2
deprecate :auto_flushing=
-
-
2
def flush
-
end
-
2
deprecate :flush
-
-
2
def respond_to?(method, include_private = false)
-
return false if method.to_s == "flush"
-
super
-
end
-
-
2
def close
-
@log.close
-
end
-
-
2
private
-
2
def open_logfile(log)
-
2
Logger.new log
-
end
-
end
-
end
-
2
require 'benchmark'
-
2
require 'zlib'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/benchmark'
-
2
require 'active_support/core_ext/exception'
-
2
require 'active_support/core_ext/class/attribute_accessors'
-
2
require 'active_support/core_ext/numeric/bytes'
-
2
require 'active_support/core_ext/numeric/time'
-
2
require 'active_support/core_ext/object/to_param'
-
2
require 'active_support/core_ext/string/inflections'
-
-
2
module ActiveSupport
-
# See ActiveSupport::Cache::Store for documentation.
-
2
module Cache
-
2
autoload :FileStore, 'active_support/cache/file_store'
-
2
autoload :MemoryStore, 'active_support/cache/memory_store'
-
2
autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
-
2
autoload :NullStore, 'active_support/cache/null_store'
-
-
# These options mean something to all cache implementations. Individual cache
-
# implementations may support additional options.
-
2
UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl]
-
-
2
module Strategy
-
2
autoload :LocalCache, 'active_support/cache/strategy/local_cache'
-
end
-
-
2
class << self
-
# Creates a new CacheStore object according to the given options.
-
#
-
# If no arguments are passed to this method, then a new
-
# ActiveSupport::Cache::MemoryStore object will be returned.
-
#
-
# If you pass a Symbol as the first argument, then a corresponding cache
-
# store class under the ActiveSupport::Cache namespace will be created.
-
# For example:
-
#
-
# ActiveSupport::Cache.lookup_store(:memory_store)
-
# # => returns a new ActiveSupport::Cache::MemoryStore object
-
#
-
# ActiveSupport::Cache.lookup_store(:mem_cache_store)
-
# # => returns a new ActiveSupport::Cache::MemCacheStore object
-
#
-
# Any additional arguments will be passed to the corresponding cache store
-
# class's constructor:
-
#
-
# ActiveSupport::Cache.lookup_store(:file_store, "/tmp/cache")
-
# # => same as: ActiveSupport::Cache::FileStore.new("/tmp/cache")
-
#
-
# If the first argument is not a Symbol, then it will simply be returned:
-
#
-
# ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new)
-
# # => returns MyOwnCacheStore.new
-
2
def lookup_store(*store_option)
-
6
store, *parameters = *Array.wrap(store_option).flatten
-
-
6
case store
-
when Symbol
-
4
store_class_name = store.to_s.camelize
-
4
store_class =
-
begin
-
4
require "active_support/cache/#{store}"
-
rescue LoadError => e
-
raise "Could not find cache store adapter for #{store} (#{e})"
-
else
-
4
ActiveSupport::Cache.const_get(store_class_name)
-
end
-
4
store_class.new(*parameters)
-
when nil
-
ActiveSupport::Cache::MemoryStore.new
-
else
-
2
store
-
end
-
end
-
-
2
def expand_cache_key(key, namespace = nil)
-
expanded_cache_key = namespace ? "#{namespace}/" : ""
-
-
if prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
-
expanded_cache_key << "#{prefix}/"
-
end
-
-
expanded_cache_key << retrieve_cache_key(key)
-
expanded_cache_key
-
end
-
-
2
private
-
-
2
def retrieve_cache_key(key)
-
case
-
when key.respond_to?(:cache_key) then key.cache_key
-
when key.is_a?(Array) then key.map { |element| retrieve_cache_key(element) }.to_param
-
else key.to_param
-
end.to_s
-
end
-
end
-
-
# An abstract cache store class. There are multiple cache store
-
# implementations, each having its own additional features. See the classes
-
# under the ActiveSupport::Cache module, e.g.
-
# ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most
-
# popular cache store for large production websites.
-
#
-
# Some implementations may not support all methods beyond the basic cache
-
# methods of +fetch+, +write+, +read+, +exist?+, and +delete+.
-
#
-
# ActiveSupport::Cache::Store can store any serializable Ruby object.
-
#
-
# cache = ActiveSupport::Cache::MemoryStore.new
-
#
-
# cache.read("city") # => nil
-
# cache.write("city", "Duckburgh")
-
# cache.read("city") # => "Duckburgh"
-
#
-
# Keys are always translated into Strings and are case sensitive. When an
-
# object is specified as a key and has a +cache_key+ method defined, this
-
# method will be called to define the key. Otherwise, the +to_param+
-
# method will be called. Hashes and Arrays can also be used as keys. The
-
# elements will be delimited by slashes, and the elements within a Hash
-
# will be sorted by key so they are consistent.
-
#
-
# cache.read("city") == cache.read(:city) # => true
-
#
-
# Nil values can be cached.
-
#
-
# If your cache is on a shared infrastructure, you can define a namespace
-
# for your cache entries. If a namespace is defined, it will be prefixed on
-
# to every key. The namespace can be either a static value or a Proc. If it
-
# is a Proc, it will be invoked when each key is evaluated so that you can
-
# use application logic to invalidate keys.
-
#
-
# cache.namespace = lambda { @last_mod_time } # Set the namespace to a variable
-
# @last_mod_time = Time.now # Invalidate the entire cache by changing namespace
-
#
-
#
-
# Caches can also store values in a compressed format to save space and
-
# reduce time spent sending data. Since there is overhead, values must be
-
# large enough to warrant compression. To turn on compression either pass
-
# <tt>:compress => true</tt> in the initializer or as an option to +fetch+
-
# or +write+. To specify the threshold at which to compress values, set the
-
# <tt>:compress_threshold</tt> option. The default threshold is 16K.
-
2
class Store
-
-
2
cattr_accessor :logger, :instance_writer => true
-
-
2
attr_reader :silence, :options
-
2
alias :silence? :silence
-
-
# Create a new cache. The options will be passed to any write method calls except
-
# for :namespace which can be used to set the global namespace for the cache.
-
2
def initialize(options = nil)
-
4
@options = options ? options.dup : {}
-
end
-
-
# Silence the logger.
-
2
def silence!
-
@silence = true
-
self
-
end
-
-
# Silence the logger within a block.
-
2
def mute
-
previous_silence, @silence = defined?(@silence) && @silence, true
-
yield
-
ensure
-
@silence = previous_silence
-
end
-
-
# Set to true if cache stores should be instrumented. Default is false.
-
2
def self.instrument=(boolean)
-
Thread.current[:instrument_cache_store] = boolean
-
end
-
-
2
def self.instrument
-
Thread.current[:instrument_cache_store] || false
-
end
-
-
# Fetches data from the cache, using the given key. If there is data in
-
# the cache with the given key, then that data is returned.
-
#
-
# If there is no such data in the cache (a cache miss), then nil will be
-
# returned. However, if a block has been passed, that block will be run
-
# in the event of a cache miss. The return value of the block will be
-
# written to the cache under the given cache key, and that return value
-
# will be returned.
-
#
-
# cache.write("today", "Monday")
-
# cache.fetch("today") # => "Monday"
-
#
-
# cache.fetch("city") # => nil
-
# cache.fetch("city") do
-
# "Duckburgh"
-
# end
-
# cache.fetch("city") # => "Duckburgh"
-
#
-
# You may also specify additional options via the +options+ argument.
-
# Setting <tt>:force => true</tt> will force a cache miss:
-
#
-
# cache.write("today", "Monday")
-
# cache.fetch("today", :force => true) # => nil
-
#
-
# Setting <tt>:compress</tt> will store a large cache entry set by the call
-
# in a compressed format.
-
#
-
#
-
# Setting <tt>:expires_in</tt> will set an expiration time on the cache.
-
# All caches support auto-expiring content after a specified number of
-
# seconds. This value can be specified as an option to the constructor
-
# (in which case all entries will be affected), or it can be supplied to
-
# the +fetch+ or +write+ method to effect just one entry.
-
#
-
# cache = ActiveSupport::Cache::MemoryStore.new(:expires_in => 5.minutes)
-
# cache.write(key, value, :expires_in => 1.minute) # Set a lower value for one entry
-
#
-
# Setting <tt>:race_condition_ttl</tt> is very useful in situations where a cache entry
-
# is used very frequently and is under heavy load. If a cache expires and due to heavy load
-
# seven different processes will try to read data natively and then they all will try to
-
# write to cache. To avoid that case the first process to find an expired cache entry will
-
# bump the cache expiration time by the value set in <tt>:race_condition_ttl</tt>. Yes
-
# this process is extending the time for a stale value by another few seconds. Because
-
# of extended life of the previous cache, other processes will continue to use slightly
-
# stale data for a just a big longer. In the meantime that first process will go ahead
-
# and will write into cache the new value. After that all the processes will start
-
# getting new value. The key is to keep <tt>:race_condition_ttl</tt> small.
-
#
-
# If the process regenerating the entry errors out, the entry will be regenerated
-
# after the specified number of seconds. Also note that the life of stale cache is
-
# extended only if it expired recently. Otherwise a new value is generated and
-
# <tt>:race_condition_ttl</tt> does not play any role.
-
#
-
# # Set all values to expire after one minute.
-
# cache = ActiveSupport::Cache::MemoryStore.new(:expires_in => 1.minute)
-
#
-
# cache.write("foo", "original value")
-
# val_1 = nil
-
# val_2 = nil
-
# sleep 60
-
#
-
# Thread.new do
-
# val_1 = cache.fetch("foo", :race_condition_ttl => 10) do
-
# sleep 1
-
# "new value 1"
-
# end
-
# end
-
#
-
# Thread.new do
-
# val_2 = cache.fetch("foo", :race_condition_ttl => 10) do
-
# "new value 2"
-
# end
-
# end
-
#
-
# # val_1 => "new value 1"
-
# # val_2 => "original value"
-
# # sleep 10 # First thread extend the life of cache by another 10 seconds
-
# # cache.fetch("foo") => "new value 1"
-
#
-
# Other options will be handled by the specific cache store implementation.
-
# Internally, #fetch calls #read_entry, and calls #write_entry on a cache miss.
-
# +options+ will be passed to the #read and #write calls.
-
#
-
# For example, MemCacheStore's #write method supports the +:raw+
-
# option, which tells the memcached server to store all values as strings.
-
# We can use this option with #fetch too:
-
#
-
# cache = ActiveSupport::Cache::MemCacheStore.new
-
# cache.fetch("foo", :force => true, :raw => true) do
-
# :bar
-
# end
-
# cache.fetch("foo") # => "bar"
-
2
def fetch(name, options = nil)
-
if block_given?
-
options = merged_options(options)
-
key = namespaced_key(name, options)
-
unless options[:force]
-
entry = instrument(:read, name, options) do |payload|
-
payload[:super_operation] = :fetch if payload
-
read_entry(key, options)
-
end
-
end
-
if entry && entry.expired?
-
race_ttl = options[:race_condition_ttl].to_f
-
if race_ttl and Time.now.to_f - entry.expires_at <= race_ttl
-
entry.expires_at = Time.now + race_ttl
-
write_entry(key, entry, :expires_in => race_ttl * 2)
-
else
-
delete_entry(key, options)
-
end
-
entry = nil
-
end
-
-
if entry
-
instrument(:fetch_hit, name, options) { |payload| }
-
entry.value
-
else
-
result = instrument(:generate, name, options) do |payload|
-
yield
-
end
-
write(name, result, options)
-
result
-
end
-
else
-
read(name, options)
-
end
-
end
-
-
# Fetches data from the cache, using the given key. If there is data in
-
# the cache with the given key, then that data is returned. Otherwise,
-
# nil is returned.
-
#
-
# Options are passed to the underlying cache implementation.
-
2
def read(name, options = nil)
-
options = merged_options(options)
-
key = namespaced_key(name, options)
-
instrument(:read, name, options) do |payload|
-
entry = read_entry(key, options)
-
if entry
-
if entry.expired?
-
delete_entry(key, options)
-
payload[:hit] = false if payload
-
nil
-
else
-
payload[:hit] = true if payload
-
entry.value
-
end
-
else
-
payload[:hit] = false if payload
-
nil
-
end
-
end
-
end
-
-
# Read multiple values at once from the cache. Options can be passed
-
# in the last argument.
-
#
-
# Some cache implementation may optimize this method.
-
#
-
# Returns a hash mapping the names provided to the values found.
-
2
def read_multi(*names)
-
options = names.extract_options!
-
options = merged_options(options)
-
results = {}
-
names.each do |name|
-
key = namespaced_key(name, options)
-
entry = read_entry(key, options)
-
if entry
-
if entry.expired?
-
delete_entry(key, options)
-
else
-
results[name] = entry.value
-
end
-
end
-
end
-
results
-
end
-
-
# Writes the value to the cache, with the key.
-
#
-
# Options are passed to the underlying cache implementation.
-
2
def write(name, value, options = nil)
-
options = merged_options(options)
-
instrument(:write, name, options) do |payload|
-
entry = Entry.new(value, options)
-
write_entry(namespaced_key(name, options), entry, options)
-
end
-
end
-
-
# Deletes an entry in the cache. Returns +true+ if an entry is deleted.
-
#
-
# Options are passed to the underlying cache implementation.
-
2
def delete(name, options = nil)
-
options = merged_options(options)
-
instrument(:delete, name) do |payload|
-
delete_entry(namespaced_key(name, options), options)
-
end
-
end
-
-
# Return true if the cache contains an entry for the given key.
-
#
-
# Options are passed to the underlying cache implementation.
-
2
def exist?(name, options = nil)
-
options = merged_options(options)
-
instrument(:exist?, name) do |payload|
-
entry = read_entry(namespaced_key(name, options), options)
-
if entry && !entry.expired?
-
true
-
else
-
false
-
end
-
end
-
end
-
-
# Delete all entries with keys matching the pattern.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
2
def delete_matched(matcher, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support delete_matched")
-
end
-
-
# Increment an integer value in the cache.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
2
def increment(name, amount = 1, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support increment")
-
end
-
-
# Increment an integer value in the cache.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
2
def decrement(name, amount = 1, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support decrement")
-
end
-
-
# Cleanup the cache by removing expired entries.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
2
def cleanup(options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support cleanup")
-
end
-
-
# Clear the entire cache. Be careful with this method since it could
-
# affect other processes if shared cache is being used.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
2
def clear(options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support clear")
-
end
-
-
2
protected
-
# Add the namespace defined in the options to a pattern designed to match keys.
-
# Implementations that support delete_matched should call this method to translate
-
# a pattern that matches names into one that matches namespaced keys.
-
2
def key_matcher(pattern, options)
-
prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace]
-
if prefix
-
source = pattern.source
-
if source.start_with?('^')
-
source = source[1, source.length]
-
else
-
source = ".*#{source[0, source.length]}"
-
end
-
Regexp.new("^#{Regexp.escape(prefix)}:#{source}", pattern.options)
-
else
-
pattern
-
end
-
end
-
-
# Read an entry from the cache implementation. Subclasses must implement this method.
-
2
def read_entry(key, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
# Write an entry to the cache implementation. Subclasses must implement this method.
-
2
def write_entry(key, entry, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
# Delete an entry from the cache implementation. Subclasses must implement this method.
-
2
def delete_entry(key, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
2
private
-
# Merge the default options with ones specific to a method call.
-
2
def merged_options(call_options) # :nodoc:
-
if call_options
-
options.merge(call_options)
-
else
-
options.dup
-
end
-
end
-
-
# Expand key to be a consistent string value. Invoke +cache_key+ if
-
# object responds to +cache_key+. Otherwise, to_param method will be
-
# called. If the key is a Hash, then keys will be sorted alphabetically.
-
2
def expanded_key(key) # :nodoc:
-
return key.cache_key.to_s if key.respond_to?(:cache_key)
-
-
case key
-
when Array
-
if key.size > 1
-
key = key.collect{|element| expanded_key(element)}
-
else
-
key = key.first
-
end
-
when Hash
-
key = key.sort_by { |k,_| k.to_s }.collect{|k,v| "#{k}=#{v}"}
-
end
-
-
key.to_param
-
end
-
-
# Prefix a key with the namespace. Namespace and key will be delimited with a colon.
-
2
def namespaced_key(key, options)
-
key = expanded_key(key)
-
namespace = options[:namespace] if options
-
prefix = namespace.is_a?(Proc) ? namespace.call : namespace
-
key = "#{prefix}:#{key}" if prefix
-
key
-
end
-
-
2
def instrument(operation, key, options = nil)
-
log(operation, key, options)
-
-
if self.class.instrument
-
payload = { :key => key }
-
payload.merge!(options) if options.is_a?(Hash)
-
ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) }
-
else
-
yield(nil)
-
end
-
end
-
-
2
def log(operation, key, options = nil)
-
return unless logger && logger.debug? && !silence?
-
logger.debug("Cache #{operation}: #{key}#{options.blank? ? "" : " (#{options.inspect})"}")
-
end
-
end
-
-
# Entry that is put into caches. It supports expiration time on entries and can compress values
-
# to save space in the cache.
-
2
class Entry
-
2
attr_reader :created_at, :expires_in
-
-
2
DEFAULT_COMPRESS_LIMIT = 16.kilobytes
-
-
2
class << self
-
# Create an entry with internal attributes set. This method is intended to be
-
# used by implementations that store cache entries in a native format instead
-
# of as serialized Ruby objects.
-
2
def create(raw_value, created_at, options = {})
-
entry = new(nil)
-
entry.instance_variable_set(:@value, raw_value)
-
entry.instance_variable_set(:@created_at, created_at.to_f)
-
entry.instance_variable_set(:@compressed, options[:compressed])
-
entry.instance_variable_set(:@expires_in, options[:expires_in])
-
entry
-
end
-
end
-
-
# Create a new cache entry for the specified value. Options supported are
-
# +:compress+, +:compress_threshold+, and +:expires_in+.
-
2
def initialize(value, options = {})
-
@compressed = false
-
@expires_in = options[:expires_in]
-
@expires_in = @expires_in.to_f if @expires_in
-
@created_at = Time.now.to_f
-
if value.nil?
-
@value = nil
-
else
-
@value = Marshal.dump(value)
-
if should_compress?(@value, options)
-
@value = Zlib::Deflate.deflate(@value)
-
@compressed = true
-
end
-
end
-
end
-
-
# Get the raw value. This value may be serialized and compressed.
-
2
def raw_value
-
@value
-
end
-
-
# Get the value stored in the cache.
-
2
def value
-
# If the original value was exactly false @value is still true because
-
# it is marshalled and eventually compressed. Both operations yield
-
# strings.
-
if @value
-
# In rails 3.1 and earlier values in entries did not marshaled without
-
# options[:compress] and if it's Numeric.
-
# But after commit a263f377978fc07515b42808ebc1f7894fafaa3a
-
# all values in entries are marshalled. And after that code below expects
-
# that all values in entries will be marshaled (and will be strings).
-
# So here we need a check for old ones.
-
begin
-
Marshal.load(compressed? ? Zlib::Inflate.inflate(@value) : @value)
-
rescue TypeError
-
compressed? ? Zlib::Inflate.inflate(@value) : @value
-
end
-
end
-
end
-
-
2
def compressed?
-
@compressed
-
end
-
-
# Check if the entry is expired. The +expires_in+ parameter can override the
-
# value set when the entry was created.
-
2
def expired?
-
@expires_in && @created_at + @expires_in <= Time.now.to_f
-
end
-
-
# Set a new time when the entry will expire.
-
2
def expires_at=(time)
-
if time
-
@expires_in = time.to_f - @created_at
-
else
-
@expires_in = nil
-
end
-
end
-
-
# Seconds since the epoch when the entry will expire.
-
2
def expires_at
-
@expires_in ? @created_at + @expires_in : nil
-
end
-
-
# Returns the size of the cached value. This could be less than value.size
-
# if the data is compressed.
-
2
def size
-
if @value.nil?
-
0
-
else
-
@value.bytesize
-
end
-
end
-
-
2
private
-
2
def should_compress?(serialized_value, options)
-
if options[:compress]
-
compress_threshold = options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT
-
return true if serialized_value.size >= compress_threshold
-
end
-
false
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/file/atomic'
-
2
require 'active_support/core_ext/string/conversions'
-
2
require 'active_support/core_ext/object/inclusion'
-
2
require 'rack/utils'
-
-
2
module ActiveSupport
-
2
module Cache
-
# A cache store implementation which stores everything on the filesystem.
-
#
-
# FileStore implements the Strategy::LocalCache strategy which implements
-
# an in-memory cache inside of a block.
-
2
class FileStore < Store
-
2
attr_reader :cache_path
-
-
2
DIR_FORMATTER = "%03X"
-
2
FILENAME_MAX_SIZE = 230 # max filename size on file system is 255, minus room for timestamp and random characters appended by Tempfile (used by atomic write)
-
2
EXCLUDED_DIRS = ['.', '..'].freeze
-
-
2
def initialize(cache_path, options = nil)
-
4
super(options)
-
4
@cache_path = cache_path.to_s
-
4
extend Strategy::LocalCache
-
end
-
-
2
def clear(options = nil)
-
root_dirs = Dir.entries(cache_path).reject{|f| f.in?(EXCLUDED_DIRS)}
-
FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
-
end
-
-
2
def cleanup(options = nil)
-
options = merged_options(options)
-
search_dir(cache_path) do |fname|
-
key = file_path_key(fname)
-
entry = read_entry(key, options)
-
delete_entry(key, options) if entry && entry.expired?
-
end
-
end
-
-
2
def increment(name, amount = 1, options = nil)
-
file_name = key_file_path(namespaced_key(name, options))
-
lock_file(file_name) do
-
options = merged_options(options)
-
if num = read(name, options)
-
num = num.to_i + amount
-
write(name, num, options)
-
num
-
else
-
nil
-
end
-
end
-
end
-
-
2
def decrement(name, amount = 1, options = nil)
-
file_name = key_file_path(namespaced_key(name, options))
-
lock_file(file_name) do
-
options = merged_options(options)
-
if num = read(name, options)
-
num = num.to_i - amount
-
write(name, num, options)
-
num
-
else
-
nil
-
end
-
end
-
end
-
-
2
def delete_matched(matcher, options = nil)
-
options = merged_options(options)
-
instrument(:delete_matched, matcher.inspect) do
-
matcher = key_matcher(matcher, options)
-
search_dir(cache_path) do |path|
-
key = file_path_key(path)
-
delete_entry(key, options) if key.match(matcher)
-
end
-
end
-
end
-
-
2
protected
-
-
2
def read_entry(key, options)
-
file_name = key_file_path(key)
-
if File.exist?(file_name)
-
File.open(file_name) { |f| Marshal.load(f) }
-
end
-
rescue
-
nil
-
end
-
-
2
def write_entry(key, entry, options)
-
file_name = key_file_path(key)
-
ensure_cache_path(File.dirname(file_name))
-
File.atomic_write(file_name, cache_path) {|f| Marshal.dump(entry, f)}
-
true
-
end
-
-
2
def delete_entry(key, options)
-
file_name = key_file_path(key)
-
if File.exist?(file_name)
-
begin
-
File.delete(file_name)
-
delete_empty_directories(File.dirname(file_name))
-
true
-
rescue => e
-
# Just in case the error was caused by another process deleting the file first.
-
raise e if File.exist?(file_name)
-
false
-
end
-
end
-
end
-
-
2
private
-
# Lock a file for a block so only one process can modify it at a time.
-
2
def lock_file(file_name, &block) # :nodoc:
-
if File.exist?(file_name)
-
File.open(file_name, 'r+') do |f|
-
begin
-
f.flock File::LOCK_EX
-
yield
-
ensure
-
f.flock File::LOCK_UN
-
end
-
end
-
else
-
yield
-
end
-
end
-
-
# Translate a key into a file path.
-
2
def key_file_path(key)
-
fname = Rack::Utils.escape(key)
-
hash = Zlib.adler32(fname)
-
hash, dir_1 = hash.divmod(0x1000)
-
dir_2 = hash.modulo(0x1000)
-
fname_paths = []
-
-
# Make sure file name doesn't exceed file system limits.
-
begin
-
fname_paths << fname[0, FILENAME_MAX_SIZE]
-
fname = fname[FILENAME_MAX_SIZE..-1]
-
end until fname.blank?
-
-
File.join(cache_path, DIR_FORMATTER % dir_1, DIR_FORMATTER % dir_2, *fname_paths)
-
end
-
-
# Translate a file path into a key.
-
2
def file_path_key(path)
-
fname = path[cache_path.size, path.size].split(File::SEPARATOR, 4).last
-
Rack::Utils.unescape(fname)
-
end
-
-
# Delete empty directories in the cache.
-
2
def delete_empty_directories(dir)
-
return if dir == cache_path
-
if Dir.entries(dir).reject{|f| f.in?(EXCLUDED_DIRS)}.empty?
-
File.delete(dir) rescue nil
-
delete_empty_directories(File.dirname(dir))
-
end
-
end
-
-
# Make sure a file path's directories exist.
-
2
def ensure_cache_path(path)
-
FileUtils.makedirs(path) unless File.exist?(path)
-
end
-
-
2
def search_dir(dir, &callback)
-
return if !File.exist?(dir)
-
Dir.foreach(dir) do |d|
-
next if d.in?(EXCLUDED_DIRS)
-
name = File.join(dir, d)
-
if File.directory?(name)
-
search_dir(name, &callback)
-
else
-
callback.call name
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/duplicable'
-
2
require 'active_support/core_ext/string/inflections'
-
-
2
module ActiveSupport
-
2
module Cache
-
2
module Strategy
-
# Caches that implement LocalCache will be backed by an in-memory cache for the
-
# duration of a block. Repeated calls to the cache for the same key will hit the
-
# in-memory cache for faster access.
-
2
module LocalCache
-
# Simple memory backed cache. This cache is not thread safe and is intended only
-
# for serving as a temporary memory cache for a single thread.
-
2
class LocalStore < Store
-
2
def initialize
-
super
-
@data = {}
-
end
-
-
# Don't allow synchronizing since it isn't thread safe,
-
2
def synchronize # :nodoc:
-
yield
-
end
-
-
2
def clear(options = nil)
-
@data.clear
-
end
-
-
2
def read_entry(key, options)
-
@data[key]
-
end
-
-
2
def write_entry(key, value, options)
-
@data[key] = value
-
true
-
end
-
-
2
def delete_entry(key, options)
-
!!@data.delete(key)
-
end
-
end
-
-
# Use a local cache for the duration of block.
-
2
def with_local_cache
-
save_val = Thread.current[thread_local_key]
-
begin
-
Thread.current[thread_local_key] = LocalStore.new
-
yield
-
ensure
-
Thread.current[thread_local_key] = save_val
-
end
-
end
-
-
#--
-
# This class wraps up local storage for middlewares. Only the middleware method should
-
# construct them.
-
2
class Middleware # :nodoc:
-
2
attr_reader :name, :thread_local_key
-
-
2
def initialize(name, thread_local_key)
-
2
@name = name
-
2
@thread_local_key = thread_local_key
-
2
@app = nil
-
end
-
-
2
def new(app)
-
2
@app = app
-
2
self
-
end
-
-
2
def call(env)
-
Thread.current[thread_local_key] = LocalStore.new
-
@app.call(env)
-
ensure
-
Thread.current[thread_local_key] = nil
-
end
-
end
-
-
# Middleware class can be inserted as a Rack handler to be local cache for the
-
# duration of request.
-
2
def middleware
-
@middleware ||= Middleware.new(
-
"ActiveSupport::Cache::Strategy::LocalCache",
-
2
thread_local_key)
-
end
-
-
2
def clear(options = nil) # :nodoc:
-
local_cache.clear(options) if local_cache
-
super
-
end
-
-
2
def cleanup(options = nil) # :nodoc:
-
local_cache.clear(options) if local_cache
-
super
-
end
-
-
2
def increment(name, amount = 1, options = nil) # :nodoc:
-
value = bypass_local_cache{super}
-
if local_cache
-
local_cache.mute do
-
if value
-
local_cache.write(name, value, options)
-
else
-
local_cache.delete(name, options)
-
end
-
end
-
end
-
value
-
end
-
-
2
def decrement(name, amount = 1, options = nil) # :nodoc:
-
value = bypass_local_cache{super}
-
if local_cache
-
local_cache.mute do
-
if value
-
local_cache.write(name, value, options)
-
else
-
local_cache.delete(name, options)
-
end
-
end
-
end
-
value
-
end
-
-
2
protected
-
2
def read_entry(key, options) # :nodoc:
-
if local_cache
-
entry = local_cache.read_entry(key, options)
-
unless entry
-
entry = super
-
local_cache.write_entry(key, entry, options)
-
end
-
entry
-
else
-
super
-
end
-
end
-
-
2
def write_entry(key, entry, options) # :nodoc:
-
local_cache.write_entry(key, entry, options) if local_cache
-
super
-
end
-
-
2
def delete_entry(key, options) # :nodoc:
-
local_cache.delete_entry(key, options) if local_cache
-
super
-
end
-
-
2
private
-
2
def thread_local_key
-
2
@thread_local_key ||= "#{self.class.name.underscore}_local_cache_#{object_id}".gsub(/[\/-]/, '_').to_sym
-
end
-
-
2
def local_cache
-
Thread.current[thread_local_key]
-
end
-
-
2
def bypass_local_cache
-
save_cache = Thread.current[thread_local_key]
-
begin
-
Thread.current[thread_local_key] = nil
-
yield
-
ensure
-
Thread.current[thread_local_key] = save_cache
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/descendants_tracker'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'active_support/core_ext/object/inclusion'
-
-
2
module ActiveSupport
-
# \Callbacks are code hooks that are run at key points in an object's lifecycle.
-
# The typical use case is to have a base class define a set of callbacks relevant
-
# to the other functionality it supplies, so that subclasses can install callbacks
-
# that enhance or modify the base functionality without needing to override
-
# or redefine methods of the base class.
-
#
-
# Mixing in this module allows you to define the events in the object's lifecycle
-
# that will support callbacks (via +ClassMethods.define_callbacks+), set the instance
-
# methods, procs, or callback objects to be called (via +ClassMethods.set_callback+),
-
# and run the installed callbacks at the appropriate times (via +run_callbacks+).
-
#
-
# Three kinds of callbacks are supported: before callbacks, run before a certain event;
-
# after callbacks, run after the event; and around callbacks, blocks that surround the
-
# event, triggering it when they yield. Callback code can be contained in instance
-
# methods, procs or lambdas, or callback objects that respond to certain predetermined
-
# methods. See +ClassMethods.set_callback+ for details.
-
#
-
# ==== Example
-
#
-
# class Record
-
# include ActiveSupport::Callbacks
-
# define_callbacks :save
-
#
-
# def save
-
# run_callbacks :save do
-
# puts "- save"
-
# end
-
# end
-
# end
-
#
-
# class PersonRecord < Record
-
# set_callback :save, :before, :saving_message
-
# def saving_message
-
# puts "saving..."
-
# end
-
#
-
# set_callback :save, :after do |object|
-
# puts "saved"
-
# end
-
# end
-
#
-
# person = PersonRecord.new
-
# person.save
-
#
-
# Output:
-
# saving...
-
# - save
-
# saved
-
#
-
2
module Callbacks
-
2
extend Concern
-
-
2
included do
-
12
extend ActiveSupport::DescendantsTracker
-
end
-
-
# Runs the callbacks for the given event.
-
#
-
# Calls the before and around callbacks in the order they were set, yields
-
# the block (if given one), and then runs the after callbacks in reverse order.
-
# Optionally accepts a key, which will be used to compile an optimized callback
-
# method for each key. See +ClassMethods.define_callbacks+ for more information.
-
#
-
# If the callback chain was halted, returns +false+. Otherwise returns the result
-
# of the block, or +true+ if no block is given.
-
#
-
# run_callbacks :save do
-
# save
-
# end
-
#
-
2
def run_callbacks(kind, *args, &block)
-
3841
send("_run_#{kind}_callbacks", *args, &block)
-
end
-
-
2
private
-
-
# A hook invoked everytime a before callback is halted.
-
# This can be overriden in AS::Callback implementors in order
-
# to provide better debugging/logging.
-
2
def halted_callback_hook(filter)
-
end
-
-
2
class Callback #:nodoc:#
-
2
@@_callback_sequence = 0
-
-
2
attr_accessor :chain, :filter, :kind, :options, :per_key, :klass, :raw_filter
-
-
2
def initialize(chain, filter, kind, options, klass)
-
283
@chain, @kind, @klass = chain, kind, klass
-
283
normalize_options!(options)
-
-
283
@per_key = options.delete(:per_key)
-
283
@raw_filter, @options = filter, options
-
283
@filter = _compile_filter(filter)
-
283
@compiled_options = _compile_options(options)
-
283
@callback_id = next_id
-
-
283
_compile_per_key_options
-
end
-
-
2
def clone(chain, klass)
-
4
obj = super()
-
4
obj.chain = chain
-
4
obj.klass = klass
-
4
obj.per_key = @per_key.dup
-
4
obj.options = @options.dup
-
4
obj.per_key[:if] = @per_key[:if].dup
-
4
obj.per_key[:unless] = @per_key[:unless].dup
-
4
obj.options[:if] = @options[:if].dup
-
4
obj.options[:unless] = @options[:unless].dup
-
4
obj
-
end
-
-
2
def normalize_options!(options)
-
283
options[:if] = Array.wrap(options[:if])
-
283
options[:unless] = Array.wrap(options[:unless])
-
-
283
options[:per_key] ||= {}
-
283
options[:per_key][:if] = Array.wrap(options[:per_key][:if])
-
283
options[:per_key][:unless] = Array.wrap(options[:per_key][:unless])
-
end
-
-
2
def name
-
18
chain.name
-
end
-
-
2
def next_id
-
772
@@_callback_sequence += 1
-
end
-
-
2
def matches?(_kind, _filter)
-
523
@kind == _kind && @filter == _filter
-
end
-
-
2
def _update_filter(filter_options, new_options)
-
8
filter_options[:if].push(new_options[:unless]) if new_options.key?(:unless)
-
8
filter_options[:unless].push(new_options[:if]) if new_options.key?(:if)
-
end
-
-
2
def recompile!(_options, _per_key)
-
4
_update_filter(self.options, _options)
-
4
_update_filter(self.per_key, _per_key)
-
-
4
@callback_id = next_id
-
4
@filter = _compile_filter(@raw_filter)
-
4
@compiled_options = _compile_options(@options)
-
4
_compile_per_key_options
-
end
-
-
2
def _compile_per_key_options
-
287
key_options = _compile_options(@per_key)
-
-
287
@klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def _one_time_conditions_valid_#{@callback_id}?
-
true if #{key_options}
-
end
-
RUBY_EVAL
-
end
-
-
# This will supply contents for before and around filters, and no
-
# contents for after filters (for the forward pass).
-
2
def start(key=nil, object=nil)
-
234
return if key && !object.send("_one_time_conditions_valid_#{@callback_id}?")
-
-
# options[0] is the compiled form of supplied conditions
-
# options[1] is the "end" for the conditional
-
#
-
234
case @kind
-
when :before
-
# if condition # before_save :filter_name, :if => :condition
-
# filter_name
-
# end
-
<<-RUBY_EVAL
-
174
if !halted && #{@compiled_options}
-
# This double assignment is to prevent warnings in 1.9.3 as
-
# the `result` variable is not always used except if the
-
# terminator code refers to it.
-
result = result = #{@filter}
-
halted = (#{chain.config[:terminator]})
-
if halted
-
halted_callback_hook(#{@raw_filter.inspect.inspect})
-
end
-
end
-
RUBY_EVAL
-
when :around
-
# Compile around filters with conditions into proxy methods
-
# that contain the conditions.
-
#
-
# For `around_save :filter_name, :if => :condition':
-
#
-
# def _conditional_callback_save_17
-
# if condition
-
# filter_name do
-
# yield self
-
# end
-
# else
-
# yield self
-
# end
-
# end
-
#
-
name = "_conditional_callback_#{@kind}_#{next_id}"
-
@klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{name}(halted)
-
if #{@compiled_options} && !halted
-
#{@filter} do
-
yield self
-
end
-
else
-
yield self
-
end
-
end
-
RUBY_EVAL
-
"#{name}(halted) do"
-
end
-
end
-
-
# This will supply contents for around and after filters, but not
-
# before filters (for the backward pass).
-
2
def end(key=nil, object=nil)
-
234
return if key && !object.send("_one_time_conditions_valid_#{@callback_id}?")
-
-
234
case @kind
-
when :after
-
# after_save :filter_name, :if => :condition
-
<<-RUBY_EVAL
-
60
if #{@compiled_options}
-
#{@filter}
-
end
-
RUBY_EVAL
-
when :around
-
<<-RUBY_EVAL
-
value
-
end
-
RUBY_EVAL
-
end
-
end
-
-
2
private
-
-
# Options support the same options as filters themselves (and support
-
# symbols, string, procs, and objects), so compile a conditional
-
# expression based on the options
-
2
def _compile_options(options)
-
574
conditions = ["true"]
-
-
574
unless options[:if].empty?
-
90
conditions << Array.wrap(_compile_filter(options[:if]))
-
end
-
-
574
unless options[:unless].empty?
-
12
conditions << Array.wrap(_compile_filter(options[:unless])).map {|f| "!#{f}"}
-
end
-
-
574
conditions.flatten.join(" && ")
-
end
-
-
# Filters support:
-
#
-
# Arrays:: Used in conditions. This is used to specify
-
# multiple conditions. Used internally to
-
# merge conditions from skip_* filters
-
# Symbols:: A method to call
-
# Strings:: Some content to evaluate
-
# Procs:: A proc to call with the object
-
# Objects:: An object with a before_foo method on it to call
-
#
-
# All of these objects are compiled into methods and handled
-
# the same after this point:
-
#
-
# Arrays:: Merged together into a single filter
-
# Symbols:: Already methods
-
# Strings:: class_eval'ed into methods
-
# Procs:: define_method'ed into methods
-
# Objects::
-
# a method is created that calls the before_foo method
-
# on the object.
-
#
-
2
def _compile_filter(filter)
-
485
method_name = "_callback_#{@kind}_#{next_id}"
-
485
case filter
-
when Array
-
198
filter.map {|f| _compile_filter(f)}
-
when Symbol
-
219
filter
-
when String
-
92
"(#{filter})"
-
when Proc
-
60
@klass.send(:define_method, method_name, &filter)
-
60
return method_name if filter.arity <= 0
-
-
28
method_name << (filter.arity == 1 ? "(self)" : " self, Proc.new ")
-
else
-
35
@klass.send(:define_method, "#{method_name}_object") { filter }
-
-
18
_normalize_legacy_filter(kind, filter)
-
18
scopes = Array.wrap(chain.config[:scope])
-
36
method_to_call = scopes.map{ |s| s.is_a?(Symbol) ? send(s) : s }.join("_")
-
-
18
@klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{method_name}(&blk)
-
#{method_name}_object.send(:#{method_to_call}, self, &blk)
-
end
-
RUBY_EVAL
-
-
18
method_name
-
end
-
end
-
-
2
def _normalize_legacy_filter(kind, filter)
-
18
if !filter.respond_to?(kind) && filter.respond_to?(:filter)
-
filter.singleton_class.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{kind}(context, &block) filter(context, &block) end
-
RUBY_EVAL
-
18
elsif filter.respond_to?(:before) && filter.respond_to?(:after) && kind == :around
-
def filter.around(context)
-
should_continue = before(context)
-
yield if should_continue
-
after(context)
-
end
-
end
-
end
-
end
-
-
# An Array with a compile method
-
2
class CallbackChain < Array #:nodoc:#
-
2
attr_reader :name, :config
-
-
2
def initialize(name, config)
-
38
@name = name
-
38
@config = {
-
:terminator => "false",
-
:rescuable => false,
-
:scope => [ :kind ]
-
}.merge(config)
-
end
-
-
2
def compile(key=nil, object=nil)
-
125
method = []
-
125
method << "value = nil"
-
125
method << "halted = false"
-
-
125
each do |callback|
-
234
method << callback.start(key, object)
-
end
-
-
125
if config[:rescuable]
-
method << "rescued_error = nil"
-
method << "begin"
-
end
-
-
125
method << "value = yield if block_given? && !halted"
-
-
125
if config[:rescuable]
-
method << "rescue Exception => e"
-
method << "rescued_error = e"
-
method << "end"
-
end
-
-
125
reverse_each do |callback|
-
234
method << callback.end(key, object)
-
end
-
-
125
method << "raise rescued_error if rescued_error" if config[:rescuable]
-
125
method << "halted ? false : (block_given? ? value : true)"
-
125
method.compact.join("\n")
-
end
-
end
-
-
2
module ClassMethods
-
# Generate the internal runner method called by +run_callbacks+.
-
2
def __define_runner(symbol) #:nodoc:
-
38
runner_method = "_run_#{symbol}_callbacks"
-
38
unless private_method_defined?(runner_method)
-
38
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{runner_method}(key = nil, &blk)
-
self.class.__run_callback(key, :#{symbol}, self, &blk)
-
end
-
private :#{runner_method}
-
RUBY_EVAL
-
end
-
end
-
-
# This method calls the callback method for the given key.
-
# If this called first time it creates a new callback method for the key,
-
# calculating which callbacks can be omitted because of per_key conditions.
-
#
-
2
def __run_callback(key, kind, object, &blk) #:nodoc:
-
3841
name = __callback_runner_name(key, kind)
-
3841
unless object.respond_to?(name, true)
-
125
str = object.send("_#{kind}_callbacks").compile(key, object)
-
125
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{name}() #{str} end
-
protected :#{name}
-
RUBY_EVAL
-
end
-
3841
object.send(name, &blk)
-
end
-
-
2
def __reset_runner(symbol)
-
305
name = __callback_runner_name(nil, symbol)
-
305
undef_method(name) if method_defined?(name)
-
end
-
-
2
def __callback_runner_name(key, kind)
-
4146
"_run__#{self.name.hash.abs}__#{kind}__#{key.hash.abs}__callbacks"
-
end
-
-
# This is used internally to append, prepend and skip callbacks to the
-
# CallbackChain.
-
#
-
2
def __update_callbacks(name, filters = [], block = nil) #:nodoc:
-
287
type = filters.first.in?([:before, :after, :around]) ? filters.shift : :before
-
287
options = filters.last.is_a?(Hash) ? filters.pop : {}
-
287
filters.unshift(block) if block
-
-
287
([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse.each do |target|
-
305
chain = target.send("_#{name}_callbacks")
-
305
yield target, chain.dup, type, filters, options
-
305
target.__reset_runner(name)
-
end
-
end
-
-
# Install a callback for the given event.
-
#
-
# set_callback :save, :before, :before_meth
-
# set_callback :save, :after, :after_meth, :if => :condition
-
# set_callback :save, :around, lambda { |r| stuff; result = yield; stuff }
-
#
-
# The second arguments indicates whether the callback is to be run +:before+,
-
# +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
-
# means the first example above can also be written as:
-
#
-
# set_callback :save, :before_meth
-
#
-
# The callback can specified as a symbol naming an instance method; as a proc,
-
# lambda, or block; as a string to be instance evaluated; or as an object that
-
# responds to a certain method determined by the <tt>:scope</tt> argument to
-
# +define_callback+.
-
#
-
# If a proc, lambda, or block is given, its body is evaluated in the context
-
# of the current object. It can also optionally accept the current object as
-
# an argument.
-
#
-
# Before and around callbacks are called in the order that they are set; after
-
# callbacks are called in the reverse order.
-
#
-
# Around callbacks can access the return value from the event, if it
-
# wasn't halted, from the +yield+ call.
-
#
-
# ===== Options
-
#
-
# * <tt>:if</tt> - A symbol naming an instance method or a proc; the callback
-
# will be called only when it returns a true value.
-
# * <tt>:unless</tt> - A symbol naming an instance method or a proc; the callback
-
# will be called only when it returns a false value.
-
# * <tt>:prepend</tt> - If true, the callback will be prepended to the existing
-
# chain rather than appended.
-
# * <tt>:per_key</tt> - A hash with <tt>:if</tt> and <tt>:unless</tt> options;
-
# see "Per-key conditions" below.
-
#
-
# ===== Per-key conditions
-
#
-
# When creating or skipping callbacks, you can specify conditions that
-
# are always the same for a given key. For instance, in Action Pack,
-
# we convert :only and :except conditions into per-key conditions.
-
#
-
# before_filter :authenticate, :except => "index"
-
#
-
# becomes
-
#
-
# set_callback :process_action, :before, :authenticate, :per_key => {:unless => proc {|c| c.action_name == "index"}}
-
#
-
# Per-key conditions are evaluated only once per use of a given key.
-
# In the case of the above example, you would do:
-
#
-
# run_callbacks(:process_action, action_name) { ... dispatch stuff ... }
-
#
-
# In that case, each action_name would get its own compiled callback
-
# method that took into consideration the per_key conditions. This
-
# is a speed improvement for ActionPack.
-
#
-
2
def set_callback(name, *filter_list, &block)
-
283
mapped = nil
-
-
283
__update_callbacks(name, filter_list, block) do |target, chain, type, filters, options|
-
mapped ||= filters.map do |filter|
-
283
Callback.new(chain, filter, type, options.dup, self)
-
301
end
-
-
301
filters.each do |filter|
-
816
chain.delete_if {|c| c.matches?(type, filter) }
-
end
-
-
301
options[:prepend] ? chain.unshift(*(mapped.reverse)) : chain.push(*mapped)
-
-
301
target.send("_#{name}_callbacks=", chain)
-
end
-
end
-
-
# Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or <tt>:unless</tt>
-
# options may be passed in order to control when the callback is skipped.
-
#
-
# class Writer < Person
-
# skip_callback :validate, :before, :check_membership, :if => lambda { self.age > 18 }
-
# end
-
#
-
2
def skip_callback(name, *filter_list, &block)
-
4
__update_callbacks(name, filter_list, block) do |target, chain, type, filters, options|
-
4
filters.each do |filter|
-
12
filter = chain.find {|c| c.matches?(type, filter) }
-
-
4
if filter && options.any?
-
4
new_filter = filter.clone(chain, self)
-
4
chain.insert(chain.index(filter), new_filter)
-
4
new_filter.recompile!(options, options[:per_key] || {})
-
end
-
-
4
chain.delete(filter)
-
end
-
4
target.send("_#{name}_callbacks=", chain)
-
end
-
end
-
-
# Remove all set callbacks for the given event.
-
#
-
2
def reset_callbacks(symbol)
-
callbacks = send("_#{symbol}_callbacks")
-
-
ActiveSupport::DescendantsTracker.descendants(self).each do |target|
-
chain = target.send("_#{symbol}_callbacks").dup
-
callbacks.each { |c| chain.delete(c) }
-
target.send("_#{symbol}_callbacks=", chain)
-
target.__reset_runner(symbol)
-
end
-
-
self.send("_#{symbol}_callbacks=", callbacks.dup.clear)
-
-
__reset_runner(symbol)
-
end
-
-
# Define sets of events in the object lifecycle that support callbacks.
-
#
-
# define_callbacks :validate
-
# define_callbacks :initialize, :save, :destroy
-
#
-
# ===== Options
-
#
-
# * <tt>:terminator</tt> - Determines when a before filter will halt the callback
-
# chain, preventing following callbacks from being called and the event from being
-
# triggered. This is a string to be eval'ed. The result of the callback is available
-
# in the <tt>result</tt> variable.
-
#
-
# define_callbacks :validate, :terminator => "result == false"
-
#
-
# In this example, if any before validate callbacks returns +false+,
-
# other callbacks are not executed. Defaults to "false", meaning no value
-
# halts the chain.
-
#
-
# * <tt>:rescuable</tt> - By default, after filters are not executed if
-
# the given block or a before filter raises an error. By setting this option
-
# to <tt>true</tt> exception raised by given block is stored and after
-
# executing all the after callbacks the stored exception is raised.
-
#
-
# * <tt>:scope</tt> - Indicates which methods should be executed when an object
-
# is used as a callback.
-
#
-
# class Audit
-
# def before(caller)
-
# puts 'Audit: before is called'
-
# end
-
#
-
# def before_save(caller)
-
# puts 'Audit: before_save is called'
-
# end
-
# end
-
#
-
# class Account
-
# include ActiveSupport::Callbacks
-
#
-
# define_callbacks :save
-
# set_callback :save, :before, Audit.new
-
#
-
# def save
-
# run_callbacks :save do
-
# puts 'save in main'
-
# end
-
# end
-
# end
-
#
-
# In the above case whenever you save an account the method <tt>Audit#before</tt> will
-
# be called. On the other hand
-
#
-
# define_callbacks :save, :scope => [:kind, :name]
-
#
-
# would trigger <tt>Audit#before_save</tt> instead. That's constructed by calling
-
# <tt>#{kind}_#{name}</tt> on the given instance. In this case "kind" is "before" and
-
# "name" is "save". In this context +:kind+ and +:name+ have special meanings: +:kind+
-
# refers to the kind of callback (before/after/around) and +:name+ refers to the
-
# method on which callbacks are being defined.
-
#
-
# A declaration like
-
#
-
# define_callbacks :save, :scope => [:name]
-
#
-
# would call <tt>Audit#save</tt>.
-
#
-
2
def define_callbacks(*callbacks)
-
32
config = callbacks.last.is_a?(Hash) ? callbacks.pop : {}
-
32
callbacks.each do |callback|
-
38
class_attribute "_#{callback}_callbacks"
-
38
send("_#{callback}_callbacks=", CallbackChain.new(callback, config))
-
38
__define_runner(callback)
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/deprecation'
-
-
2
module ActiveSupport
-
# A typical module looks like this:
-
#
-
# module M
-
# def self.included(base)
-
# base.extend ClassMethods
-
# base.class_eval do
-
# scope :disabled, where(:disabled => true)
-
# end
-
# end
-
#
-
# module ClassMethods
-
# ...
-
# end
-
# end
-
#
-
# By using <tt>ActiveSupport::Concern</tt> the above module could instead be written as:
-
#
-
# require 'active_support/concern'
-
#
-
# module M
-
# extend ActiveSupport::Concern
-
#
-
# included do
-
# scope :disabled, where(:disabled => true)
-
# end
-
#
-
# module ClassMethods
-
# ...
-
# end
-
# end
-
#
-
# Moreover, it gracefully handles module dependencies. Given a +Foo+ module and a +Bar+
-
# module which depends on the former, we would typically write the following:
-
#
-
# module Foo
-
# def self.included(base)
-
# base.class_eval do
-
# def self.method_injected_by_foo
-
# ...
-
# end
-
# end
-
# end
-
# end
-
#
-
# module Bar
-
# def self.included(base)
-
# base.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Foo # We need to include this dependency for Bar
-
# include Bar # Bar is the module that Host really needs
-
# end
-
#
-
# But why should +Host+ care about +Bar+'s dependencies, namely +Foo+? We could try to hide
-
# these from +Host+ directly including +Foo+ in +Bar+:
-
#
-
# module Bar
-
# include Foo
-
# def self.included(base)
-
# base.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Bar
-
# end
-
#
-
# Unfortunately this won't work, since when +Foo+ is included, its <tt>base</tt> is the +Bar+ module,
-
# not the +Host+ class. With <tt>ActiveSupport::Concern</tt>, module dependencies are properly resolved:
-
#
-
# require 'active_support/concern'
-
#
-
# module Foo
-
# extend ActiveSupport::Concern
-
# included do
-
# class_eval do
-
# def self.method_injected_by_foo
-
# ...
-
# end
-
# end
-
# end
-
# end
-
#
-
# module Bar
-
# extend ActiveSupport::Concern
-
# include Foo
-
#
-
# included do
-
# self.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Bar # works, Bar takes care now of its dependencies
-
# end
-
#
-
2
module Concern
-
2
def self.extended(base)
-
214
base.instance_variable_set("@_dependencies", [])
-
end
-
-
2
def append_features(base)
-
558
if base.instance_variable_defined?("@_dependencies")
-
108
base.instance_variable_get("@_dependencies") << self
-
108
return false
-
else
-
450
return false if base < self
-
503
@_dependencies.each { |dep| base.send(:include, dep) }
-
344
super
-
344
base.extend const_get("ClassMethods") if const_defined?("ClassMethods")
-
344
if const_defined?("InstanceMethods")
-
base.send :include, const_get("InstanceMethods")
-
ActiveSupport::Deprecation.warn "The InstanceMethods module inside ActiveSupport::Concern will be " \
-
"no longer included automatically. Please define instance methods directly in #{self} instead.", caller
-
end
-
344
base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block")
-
end
-
end
-
-
2
def included(base = nil, &block)
-
684
if base.nil?
-
126
@_included_block = block
-
else
-
558
super
-
end
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/ordered_options'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
module ActiveSupport
-
# Configurable provides a <tt>config</tt> method to store and retrieve
-
# configuration options as an <tt>OrderedHash</tt>.
-
2
module Configurable
-
2
extend ActiveSupport::Concern
-
-
2
class Configuration < ActiveSupport::InheritableOptions
-
2
def compile_methods!
-
4
self.class.compile_methods!(keys)
-
end
-
-
# compiles reader methods so we don't have to go through method_missing
-
2
def self.compile_methods!(keys)
-
40
keys.reject { |m| method_defined?(m) }.each do |key|
-
22
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{key}; _get(#{key.inspect}); end
-
RUBY
-
end
-
end
-
end
-
-
2
module ClassMethods
-
2
def config
-
@_config ||= if respond_to?(:superclass) && superclass.respond_to?(:config)
-
12
superclass.config.inheritable_copy
-
else
-
# create a new "anonymous" class that will host the compiled reader methods
-
2
Class.new(Configuration).new
-
239
end
-
end
-
-
2
def configure
-
yield config
-
end
-
-
# Allows you to add shortcut so that you don't have to refer to attribute through config.
-
# Also look at the example for config to contrast.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access
-
# end
-
#
-
# user = User.new
-
# user.allowed_access = true
-
# user.allowed_access # => true
-
#
-
2
def config_accessor(*names)
-
14
options = names.extract_options!
-
-
14
names.each do |name|
-
38
reader, line = "def #{name}; config.#{name}; end", __LINE__
-
38
writer, line = "def #{name}=(value); config.#{name} = value; end", __LINE__
-
-
38
singleton_class.class_eval reader, __FILE__, line
-
38
singleton_class.class_eval writer, __FILE__, line
-
38
class_eval reader, __FILE__, line unless options[:instance_reader] == false
-
38
class_eval writer, __FILE__, line unless options[:instance_writer] == false
-
end
-
end
-
end
-
-
# Reads and writes attributes from a configuration <tt>OrderedHash</tt>.
-
#
-
# require 'active_support/configurable'
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# end
-
#
-
# user = User.new
-
#
-
# user.config.allowed_access = true
-
# user.config.level = 1
-
#
-
# user.config.allowed_access # => true
-
# user.config.level # => 1
-
#
-
2
def config
-
22
@_config ||= self.class.config.inheritable_copy
-
end
-
end
-
end
-
-
2
Dir["#{File.dirname(__FILE__)}/core_ext/*.rb"].sort.each do |path|
-
50
require "active_support/core_ext/#{File.basename(path, '.rb')}"
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/array/access'
-
2
require 'active_support/core_ext/array/uniq_by'
-
2
require 'active_support/core_ext/array/conversions'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/array/grouping'
-
2
require 'active_support/core_ext/array/random_access'
-
2
require 'active_support/core_ext/array/prepend_and_append'
-
2
class Array
-
# Returns the tail of the array from +position+.
-
#
-
# %w( a b c d ).from(0) # => %w( a b c d )
-
# %w( a b c d ).from(2) # => %w( c d )
-
# %w( a b c d ).from(10) # => %w()
-
# %w().from(0) # => %w()
-
2
def from(position)
-
self[position, length] || []
-
end
-
-
# Returns the beginning of the array up to +position+.
-
#
-
# %w( a b c d ).to(0) # => %w( a )
-
# %w( a b c d ).to(2) # => %w( a b c )
-
# %w( a b c d ).to(10) # => %w( a b c d )
-
# %w().to(0) # => %w()
-
2
def to(position)
-
self.first position + 1
-
end
-
-
# Equal to <tt>self[1]</tt>.
-
2
def second
-
self[1]
-
end
-
-
# Equal to <tt>self[2]</tt>.
-
2
def third
-
self[2]
-
end
-
-
# Equal to <tt>self[3]</tt>.
-
2
def fourth
-
self[3]
-
end
-
-
# Equal to <tt>self[4]</tt>.
-
2
def fifth
-
self[4]
-
end
-
-
# Equal to <tt>self[41]</tt>. Also known as accessing "the reddit".
-
2
def forty_two
-
self[41]
-
end
-
end
-
2
require 'active_support/xml_mini'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
2
require 'active_support/core_ext/string/inflections'
-
-
2
class Array
-
# Converts the array to a comma-separated sentence where the last element is joined by the connector word. Options:
-
# * <tt>:words_connector</tt> - The sign or word used to join the elements in arrays with two or more elements (default: ", ")
-
# * <tt>:two_words_connector</tt> - The sign or word used to join the elements in arrays with two elements (default: " and ")
-
# * <tt>:last_word_connector</tt> - The sign or word used to join the last element in arrays with three or more elements (default: ", and ")
-
2
def to_sentence(options = {})
-
if defined?(I18n)
-
default_words_connector = I18n.translate(:'support.array.words_connector', :locale => options[:locale])
-
default_two_words_connector = I18n.translate(:'support.array.two_words_connector', :locale => options[:locale])
-
default_last_word_connector = I18n.translate(:'support.array.last_word_connector', :locale => options[:locale])
-
else
-
default_words_connector = ", "
-
default_two_words_connector = " and "
-
default_last_word_connector = ", and "
-
end
-
-
options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)
-
options.reverse_merge! :words_connector => default_words_connector, :two_words_connector => default_two_words_connector, :last_word_connector => default_last_word_connector
-
-
case length
-
when 0
-
""
-
when 1
-
self[0].to_s.dup
-
when 2
-
"#{self[0]}#{options[:two_words_connector]}#{self[1]}"
-
else
-
"#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
-
end
-
end
-
-
# Converts a collection of elements into a formatted string by calling
-
# <tt>to_s</tt> on all elements and joining them:
-
#
-
# Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
-
#
-
# Adding in the <tt>:db</tt> argument as the format yields a comma separated
-
# id list:
-
#
-
# Blog.all.to_formatted_s(:db) # => "1,2,3"
-
2
def to_formatted_s(format = :default)
-
2
case format
-
when :db
-
if respond_to?(:empty?) && self.empty?
-
"null"
-
else
-
collect { |element| element.id }.join(",")
-
end
-
else
-
2
to_default_s
-
end
-
end
-
2
alias_method :to_default_s, :to_s
-
2
alias_method :to_s, :to_formatted_s
-
-
# Returns a string that represents the array in XML by invoking +to_xml+
-
# on each element. Active Record collections delegate their representation
-
# in XML to this method.
-
#
-
# All elements are expected to respond to +to_xml+, if any of them does
-
# not then an exception is raised.
-
#
-
# The root node reflects the class name of the first element in plural
-
# if all elements belong to the same type and that's not Hash:
-
#
-
# customer.projects.to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <projects type="array">
-
# <project>
-
# <amount type="decimal">20000.0</amount>
-
# <customer-id type="integer">1567</customer-id>
-
# <deal-date type="date">2008-04-09</deal-date>
-
# ...
-
# </project>
-
# <project>
-
# <amount type="decimal">57230.0</amount>
-
# <customer-id type="integer">1567</customer-id>
-
# <deal-date type="date">2008-04-15</deal-date>
-
# ...
-
# </project>
-
# </projects>
-
#
-
# Otherwise the root element is "records":
-
#
-
# [{:foo => 1, :bar => 2}, {:baz => 3}].to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <records type="array">
-
# <record>
-
# <bar type="integer">2</bar>
-
# <foo type="integer">1</foo>
-
# </record>
-
# <record>
-
# <baz type="integer">3</baz>
-
# </record>
-
# </records>
-
#
-
# If the collection is empty the root element is "nil-classes" by default:
-
#
-
# [].to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <nil-classes type="array"/>
-
#
-
# To ensure a meaningful root element use the <tt>:root</tt> option:
-
#
-
# customer_with_no_projects.projects.to_xml(:root => "projects")
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <projects type="array"/>
-
#
-
# By default name of the node for the children of root is <tt>root.singularize</tt>.
-
# You can change it with the <tt>:children</tt> option.
-
#
-
# The +options+ hash is passed downwards:
-
#
-
# Message.all.to_xml(:skip_types => true)
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <messages>
-
# <message>
-
# <created-at>2008-03-07T09:58:18+01:00</created-at>
-
# <id>1</id>
-
# <name>1</name>
-
# <updated-at>2008-03-07T09:58:18+01:00</updated-at>
-
# <user-id>1</user-id>
-
# </message>
-
# </messages>
-
#
-
2
def to_xml(options = {})
-
require 'active_support/builder' unless defined?(Builder)
-
-
options = options.dup
-
options[:indent] ||= 2
-
options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
-
options[:root] ||= if first.class.to_s != "Hash" && all? { |e| e.is_a?(first.class) }
-
underscored = ActiveSupport::Inflector.underscore(first.class.name)
-
ActiveSupport::Inflector.pluralize(underscored).tr('/', '_')
-
else
-
"objects"
-
end
-
-
builder = options[:builder]
-
builder.instruct! unless options.delete(:skip_instruct)
-
-
root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
-
children = options.delete(:children) || root.singularize
-
-
attributes = options[:skip_types] ? {} : {:type => "array"}
-
return builder.tag!(root, attributes) if empty?
-
-
builder.__send__(:method_missing, root, attributes) do
-
each { |value| ActiveSupport::XmlMini.to_tag(children, value, options) }
-
yield builder if block_given?
-
end
-
end
-
-
end
-
2
class Hash
-
# By default, only instances of Hash itself are extractable.
-
# Subclasses of Hash may implement this method and return
-
# true to declare themselves as extractable. If a Hash
-
# is extractable, Array#extract_options! pops it from
-
# the Array when it is the last element of the Array.
-
2
def extractable_options?
-
166
instance_of?(Hash)
-
end
-
end
-
-
2
class Array
-
# Extracts options from a set of arguments. Removes and returns the last
-
# element in the array if it's a hash, otherwise returns a blank hash.
-
#
-
# def options(*args)
-
# args.extract_options!
-
# end
-
#
-
# options(1, 2) # => {}
-
# options(1, 2, :a => :b) # => {:a=>:b}
-
2
def extract_options!
-
1137
if last.is_a?(Hash) && last.extractable_options?
-
166
pop
-
else
-
971
{}
-
end
-
end
-
end
-
2
require 'enumerator'
-
-
2
class Array
-
# Splits or iterates over the array in groups of size +number+,
-
# padding any remaining slots with +fill_with+ unless it is +false+.
-
#
-
# %w(1 2 3 4 5 6 7).in_groups_of(3) {|group| p group}
-
# ["1", "2", "3"]
-
# ["4", "5", "6"]
-
# ["7", nil, nil]
-
#
-
# %w(1 2 3).in_groups_of(2, ' ') {|group| p group}
-
# ["1", "2"]
-
# ["3", " "]
-
#
-
# %w(1 2 3).in_groups_of(2, false) {|group| p group}
-
# ["1", "2"]
-
# ["3"]
-
2
def in_groups_of(number, fill_with = nil)
-
if fill_with == false
-
collection = self
-
else
-
# size % number gives how many extra we have;
-
# subtracting from number gives how many to add;
-
# modulo number ensures we don't add group of just fill.
-
padding = (number - size % number) % number
-
collection = dup.concat([fill_with] * padding)
-
end
-
-
if block_given?
-
collection.each_slice(number) { |slice| yield(slice) }
-
else
-
groups = []
-
collection.each_slice(number) { |group| groups << group }
-
groups
-
end
-
end
-
-
# Splits or iterates over the array in +number+ of groups, padding any
-
# remaining slots with +fill_with+ unless it is +false+.
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
-
# ["1", "2", "3", "4"]
-
# ["5", "6", "7", nil]
-
# ["8", "9", "10", nil]
-
#
-
# %w(1 2 3 4 5 6 7).in_groups(3, ' ') {|group| p group}
-
# ["1", "2", "3"]
-
# ["4", "5", " "]
-
# ["6", "7", " "]
-
#
-
# %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
-
# ["1", "2", "3"]
-
# ["4", "5"]
-
# ["6", "7"]
-
2
def in_groups(number, fill_with = nil)
-
# size / number gives minor group size;
-
# size % number gives how many objects need extra accommodation;
-
# each group hold either division or division + 1 items.
-
division = size / number
-
modulo = size % number
-
-
# create a new array avoiding dup
-
groups = []
-
start = 0
-
-
number.times do |index|
-
length = division + (modulo > 0 && modulo > index ? 1 : 0)
-
padding = fill_with != false &&
-
modulo > 0 && length == division ? 1 : 0
-
groups << slice(start, length).concat([fill_with] * padding)
-
start += length
-
end
-
-
if block_given?
-
groups.each { |g| yield(g) }
-
else
-
groups
-
end
-
end
-
-
# Divides the array into one or more subarrays based on a delimiting +value+
-
# or the result of an optional block.
-
#
-
# [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
-
# (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
-
2
def split(value = nil)
-
using_block = block_given?
-
-
inject([[]]) do |results, element|
-
if (using_block && yield(element)) || (value == element)
-
results << []
-
else
-
results.last << element
-
end
-
-
results
-
end
-
end
-
end
-
2
class Array
-
# The human way of thinking about adding stuff to the end of a list is with append
-
2
alias_method :append, :<<
-
-
# The human way of thinking about adding stuff to the beginning of a list is with prepend
-
2
alias_method :prepend, :unshift
-
end
-
2
class Array
-
# Backport of Array#sample based on Marc-Andre Lafortune's https://github.com/marcandre/backports/
-
# Returns a random element or +n+ random elements from the array.
-
# If the array is empty and +n+ is nil, returns <tt>nil</tt>.
-
# If +n+ is passed and its value is less than 0, it raises an +ArgumentError+ exception.
-
# If the value of +n+ is equal or greater than 0 it returns <tt>[]</tt>.
-
#
-
# [1,2,3,4,5,6].sample # => 4
-
# [1,2,3,4,5,6].sample(3) # => [2, 4, 5]
-
# [1,2,3,4,5,6].sample(-3) # => ArgumentError: negative array size
-
# [].sample # => nil
-
# [].sample(3) # => []
-
def sample(n=nil)
-
return self[Kernel.rand(size)] if n.nil?
-
n = n.to_int
-
rescue Exception => e
-
raise TypeError, "Coercion error: #{n.inspect}.to_int => Integer failed:\n(#{e.message})"
-
else
-
raise TypeError, "Coercion error: obj.to_int did NOT return an Integer (was #{n.class})" unless n.kind_of? Integer
-
raise ArgumentError, "negative array size" if n < 0
-
n = size if n > size
-
result = Array.new(self)
-
n.times do |i|
-
r = i + Kernel.rand(size - i)
-
result[i], result[r] = result[r], result[i]
-
end
-
result[n..size] = []
-
result
-
2
end unless method_defined? :sample
-
end
-
2
class Array
-
# Returns an unique array based on the criteria given as a +Proc+.
-
#
-
# [1, 2, 3, 4].uniq_by { |i| i.odd? } # => [1, 2]
-
#
-
2
def uniq_by
-
4
hash, array = {}, []
-
8
each { |i| hash[yield(i)] ||= (array << i) }
-
4
array
-
end
-
-
# Same as uniq_by, but modifies self.
-
2
def uniq_by!
-
replace(uniq_by{ |i| yield(i) })
-
end
-
end
-
2
class Array
-
# Wraps its argument in an array unless it is already an array (or array-like).
-
#
-
# Specifically:
-
#
-
# * If the argument is +nil+ an empty list is returned.
-
# * Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned.
-
# * Otherwise, returns an array with the argument as its single element.
-
#
-
# Array.wrap(nil) # => []
-
# Array.wrap([1, 2, 3]) # => [1, 2, 3]
-
# Array.wrap(0) # => [0]
-
#
-
# This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:
-
#
-
# * If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt>
-
# moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns
-
# such a +nil+ right away.
-
# * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt>
-
# raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.
-
# * It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array.
-
#
-
# The last point is particularly worth comparing for some enumerables:
-
#
-
# Array(:foo => :bar) # => [[:foo, :bar]]
-
# Array.wrap(:foo => :bar) # => [{:foo => :bar}]
-
#
-
# Array("foo\nbar") # => ["foo\n", "bar"], in Ruby 1.8
-
# Array.wrap("foo\nbar") # => ["foo\nbar"]
-
#
-
# There's also a related idiom that uses the splat operator:
-
#
-
# [*object]
-
#
-
# which returns <tt>[nil]</tt> for +nil+, and calls to <tt>Array(object)</tt> otherwise.
-
#
-
# Thus, in this case the behavior is different for +nil+, and the differences with
-
# <tt>Kernel#Array</tt> explained above apply to the rest of +object+s.
-
2
def self.wrap(object)
-
1938
if object.nil?
-
1454
[]
-
484
elsif object.respond_to?(:to_ary)
-
401
object.to_ary || [object]
-
else
-
83
[object]
-
end
-
end
-
end
-
2
require 'benchmark'
-
-
2
class << Benchmark
-
2
def ms
-
1000 * realtime { yield }
-
end
-
end
-
2
require 'active_support/core_ext/big_decimal/conversions'
-
2
require 'bigdecimal'
-
-
2
begin
-
2
require 'psych'
-
rescue LoadError
-
end
-
-
2
require 'yaml'
-
-
2
class BigDecimal
-
2
YAML_TAG = 'tag:yaml.org,2002:float'
-
2
YAML_MAPPING = { 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' }
-
-
# This emits the number without any scientific notation.
-
# This is better than self.to_f.to_s since it doesn't lose precision.
-
#
-
# Note that reconstituting YAML floats to native floats may lose precision.
-
2
def to_yaml(opts = {})
-
return super if defined?(YAML::ENGINE) && !YAML::ENGINE.syck?
-
-
YAML.quick_emit(nil, opts) do |out|
-
string = to_s
-
out.scalar(YAML_TAG, YAML_MAPPING[string] || string, :plain)
-
end
-
end
-
-
2
def encode_with(coder)
-
string = to_s
-
coder.represent_scalar(nil, YAML_MAPPING[string] || string)
-
end
-
-
# Backport this method if it doesn't exist
-
2
unless method_defined?(:to_d)
-
def to_d
-
self
-
end
-
end
-
-
2
DEFAULT_STRING_FORMAT = 'F'
-
2
def to_formatted_s(format = DEFAULT_STRING_FORMAT)
-
_original_to_s(format)
-
end
-
2
alias_method :_original_to_s, :to_s
-
2
alias_method :to_s, :to_formatted_s
-
end
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/class/attribute_accessors'
-
2
require 'active_support/core_ext/class/delegating_attributes'
-
2
require 'active_support/core_ext/class/subclasses'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'active_support/core_ext/module/remove_method'
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
class Class
-
# Declare a class-level attribute whose value is inheritable by subclasses.
-
# Subclasses can change their own value and it will not impact parent class.
-
#
-
# class Base
-
# class_attribute :setting
-
# end
-
#
-
# class Subclass < Base
-
# end
-
#
-
# Base.setting = true
-
# Subclass.setting # => true
-
# Subclass.setting = false
-
# Subclass.setting # => false
-
# Base.setting # => true
-
#
-
# In the above case as long as Subclass does not assign a value to setting
-
# by performing <tt>Subclass.setting = _something_ </tt>, <tt>Subclass.setting</tt>
-
# would read value assigned to parent class. Once Subclass assigns a value then
-
# the value assigned by Subclass would be returned.
-
#
-
# This matches normal Ruby method inheritance: think of writing an attribute
-
# on a subclass as overriding the reader method. However, you need to be aware
-
# when using +class_attribute+ with mutable structures as +Array+ or +Hash+.
-
# In such cases, you don't want to do changes in places but use setters:
-
#
-
# Base.setting = []
-
# Base.setting # => []
-
# Subclass.setting # => []
-
#
-
# # Appending in child changes both parent and child because it is the same object:
-
# Subclass.setting << :foo
-
# Base.setting # => [:foo]
-
# Subclass.setting # => [:foo]
-
#
-
# # Use setters to not propagate changes:
-
# Base.setting = []
-
# Subclass.setting += [:foo]
-
# Base.setting # => []
-
# Subclass.setting # => [:foo]
-
#
-
# For convenience, a query method is defined as well:
-
#
-
# Subclass.setting? # => false
-
#
-
# Instances may overwrite the class value in the same way:
-
#
-
# Base.setting = true
-
# object = Base.new
-
# object.setting # => true
-
# object.setting = false
-
# object.setting # => false
-
# Base.setting # => true
-
#
-
# To opt out of the instance reader method, pass :instance_reader => false.
-
#
-
# object.setting # => NoMethodError
-
# object.setting? # => NoMethodError
-
#
-
# To opt out of the instance writer method, pass :instance_writer => false.
-
#
-
# object.setting = false # => NoMethodError
-
2
def class_attribute(*attrs)
-
274
options = attrs.extract_options!
-
274
instance_reader = instance_reader = options.fetch(:instance_reader, true)
-
274
instance_writer = options.fetch(:instance_writer, true)
-
-
274
attrs.each do |name|
-
280
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def self.#{name}() nil end
-
def self.#{name}?() !!#{name} end
-
-
def self.#{name}=(val)
-
singleton_class.class_eval do
-
remove_possible_method(:#{name})
-
define_method(:#{name}) { val }
-
end
-
-
if singleton_class?
-
class_eval do
-
remove_possible_method(:#{name})
-
def #{name}
-
defined?(@#{name}) ? @#{name} : singleton_class.#{name}
-
end
-
end
-
end
-
val
-
end
-
-
if instance_reader
-
remove_possible_method :#{name}
-
def #{name}
-
defined?(@#{name}) ? @#{name} : self.class.#{name}
-
end
-
-
def #{name}?
-
!!#{name}
-
end
-
end
-
RUBY
-
-
280
attr_writer name if instance_writer
-
end
-
end
-
-
2
private
-
2
def singleton_class?
-
988
ancestors.first != self
-
end
-
end
-
2
require 'active_support/core_ext/array/extract_options'
-
-
# Extends the class object with class and instance accessors for class attributes,
-
# just like the native attr* accessors for instance attributes.
-
2
class Class
-
# Defines a class attribute if it's not defined and creates a reader method that
-
# returns the attribute value.
-
#
-
# class Person
-
# cattr_reader :hair_colors
-
# end
-
#
-
# Person.class_variable_set("@@hair_colors", [:brown, :black])
-
# Person.hair_colors # => [:brown, :black]
-
# Person.new.hair_colors # => [:brown, :black]
-
#
-
# The attribute name must be a valid method name in Ruby.
-
#
-
# class Person
-
# cattr_reader :"1_Badname "
-
# end
-
# # => NameError: invalid attribute name
-
#
-
# If you want to opt out the instance reader method, you can pass <tt>:instance_reader => false</tt>
-
# or <tt>:instance_accessor => false</tt>.
-
#
-
# class Person
-
# cattr_reader :hair_colors, :instance_reader => false
-
# end
-
#
-
# Person.new.hair_colors # => NoMethodError
-
2
def cattr_reader(*syms)
-
48
options = syms.extract_options!
-
48
syms.each do |sym|
-
48
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
unless defined? @@#{sym}
-
@@#{sym} = nil
-
end
-
-
def self.#{sym}
-
@@#{sym}
-
end
-
EOS
-
-
48
unless options[:instance_reader] == false || options[:instance_accessor] == false
-
48
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}
-
@@#{sym}
-
end
-
EOS
-
end
-
end
-
end
-
-
# Defines a class attribute if it's not defined and creates a writer method to allow
-
# assignment to the attribute.
-
#
-
# class Person
-
# cattr_writer :hair_colors
-
# end
-
#
-
# Person.hair_colors = [:brown, :black]
-
# Person.class_variable_get("@@hair_colors") # => [:brown, :black]
-
# Person.new.hair_colors = [:blonde, :red]
-
# Person.class_variable_get("@@hair_colors") # => [:blonde, :red]
-
#
-
# The attribute name must be a valid method name in Ruby.
-
#
-
# class Person
-
# cattr_writer :"1_Badname "
-
# end
-
# # => NameError: invalid attribute name
-
#
-
# If you want to opt out the instance writer method, pass <tt>:instance_writer => false</tt>
-
# or <tt>:instance_accessor => false</tt>.
-
#
-
# class Person
-
# cattr_writer :hair_colors, :instance_writer => false
-
# end
-
#
-
# Person.new.hair_colors = [:blonde, :red] # => NoMethodError
-
#
-
# Also, you can pass a block to set up the attribute with a default value.
-
#
-
# class Person
-
# cattr_writer :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
-
2
def cattr_writer(*syms)
-
44
options = syms.extract_options!
-
44
syms.each do |sym|
-
44
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
unless defined? @@#{sym}
-
@@#{sym} = nil
-
end
-
-
def self.#{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
-
44
unless options[:instance_writer] == false || options[:instance_accessor] == false
-
26
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
end
-
44
self.send("#{sym}=", yield) if block_given?
-
end
-
end
-
-
# Defines both class and instance accessors for class attributes.
-
#
-
# class Person
-
# cattr_accessor :hair_colors
-
# end
-
#
-
# Person.hair_colors = [:brown, :black, :blonde, :red]
-
# Person.hair_colors # => [:brown, :black, :blonde, :red]
-
# Person.new.hair_colors # => [:brown, :black, :blonde, :red]
-
#
-
# If a subclass changes the value then that would also change the value for
-
# parent class. Similarly if parent class changes the value then that would
-
# change the value of subclasses too.
-
#
-
# class Male < Person
-
# end
-
#
-
# Male.hair_colors << :blue
-
# Person.hair_colors # => [:brown, :black, :blonde, :red, :blue]
-
#
-
# To opt out of the instance writer method, pass <tt>:instance_writer => false</tt>.
-
# To opt out of the instance reader method, pass <tt>:instance_reader => false</tt>.
-
#
-
# class Person
-
# cattr_accessor :hair_colors, :instance_writer => false, :instance_reader => false
-
# end
-
#
-
# Person.new.hair_colors = [:brown] # => NoMethodError
-
# Person.new.hair_colors # => NoMethodError
-
#
-
# Or pass <tt>:instance_accessor => false</tt>, to opt out both instance methods.
-
#
-
# class Person
-
# cattr_accessor :hair_colors, :instance_accessor => false
-
# end
-
#
-
# Person.new.hair_colors = [:brown] # => NoMethodError
-
# Person.new.hair_colors # => NoMethodError
-
#
-
# Also you can pass a block to set up the attribute with a default value.
-
#
-
# class Person
-
# cattr_accessor :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red]
-
2
def cattr_accessor(*syms, &blk)
-
44
cattr_reader(*syms)
-
44
cattr_writer(*syms, &blk)
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
require 'active_support/core_ext/module/remove_method'
-
-
2
class Class
-
2
def superclass_delegating_accessor(name, options = {})
-
# Create private _name and _name= methods that can still be used if the public
-
# methods are overridden. This allows
-
_superclass_delegating_accessor("_#{name}")
-
-
# Generate the public methods name, name=, and name?
-
# These methods dispatch to the private _name, and _name= methods, making them
-
# overridable
-
singleton_class.send(:define_method, name) { send("_#{name}") }
-
singleton_class.send(:define_method, "#{name}?") { !!send("_#{name}") }
-
singleton_class.send(:define_method, "#{name}=") { |value| send("_#{name}=", value) }
-
-
# If an instance_reader is needed, generate methods for name and name= on the
-
# class itself, so instances will be able to see them
-
define_method(name) { send("_#{name}") } if options[:instance_reader] != false
-
define_method("#{name}?") { !!send("#{name}") } if options[:instance_reader] != false
-
end
-
-
2
private
-
-
# Take the object being set and store it in a method. This gives us automatic
-
# inheritance behavior, without having to store the object in an instance
-
# variable and look up the superclass chain manually.
-
2
def _stash_object_in_method(object, method, instance_reader = true)
-
singleton_class.remove_possible_method(method)
-
singleton_class.send(:define_method, method) { object }
-
remove_possible_method(method)
-
define_method(method) { object } if instance_reader
-
end
-
-
2
def _superclass_delegating_accessor(name, options = {})
-
singleton_class.send(:define_method, "#{name}=") do |value|
-
_stash_object_in_method(value, name, options[:instance_reader] != false)
-
end
-
send("#{name}=", nil)
-
end
-
-
end
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'active_support/core_ext/module/reachable'
-
-
2
class Class #:nodoc:
-
2
begin
-
2
ObjectSpace.each_object(Class.new) {}
-
-
2
def descendants
-
descendants = []
-
ObjectSpace.each_object(class << self; self; end) do |k|
-
descendants.unshift k unless k == self
-
end
-
descendants
-
end
-
rescue StandardError # JRuby
-
def descendants
-
descendants = []
-
ObjectSpace.each_object(Class) do |k|
-
descendants.unshift k if k < self
-
end
-
descendants.uniq!
-
descendants
-
end
-
end
-
-
# Returns an array with the direct children of +self+.
-
#
-
# Integer.subclasses # => [Bignum, Fixnum]
-
2
def subclasses
-
subclasses, chain = [], descendants
-
chain.each do |k|
-
subclasses << k unless chain.any? { |c| c > k }
-
end
-
subclasses
-
end
-
end
-
2
require 'active_support/core_ext/object/acts_like'
-
-
2
class Date
-
# Duck-types as a Date-like class. See Object#acts_like?.
-
2
def acts_like_date?
-
true
-
end
-
end
-
2
require 'date'
-
2
require 'active_support/duration'
-
2
require 'active_support/core_ext/object/acts_like'
-
2
require 'active_support/core_ext/date/zones'
-
2
require 'active_support/core_ext/time/zones'
-
-
2
class Date
-
2
DAYS_INTO_WEEK = { :monday => 0, :tuesday => 1, :wednesday => 2, :thursday => 3, :friday => 4, :saturday => 5, :sunday => 6 }
-
-
2
if RUBY_VERSION < '1.9'
-
undef :>>
-
-
# Backported from 1.9. The one in 1.8 leads to incorrect next_month and
-
# friends for dates where the calendar reform is involved. It additionally
-
# prevents an infinite loop fixed in r27013.
-
def >>(n)
-
y, m = (year * 12 + (mon - 1) + n).divmod(12)
-
m, = (m + 1) .divmod(1)
-
d = mday
-
until jd2 = self.class.valid_civil?(y, m, d, start)
-
d -= 1
-
raise ArgumentError, 'invalid date' unless d > 0
-
end
-
self + (jd2 - jd)
-
end
-
end
-
-
2
class << self
-
# Returns a new Date representing the date 1 day ago (i.e. yesterday's date).
-
2
def yesterday
-
::Date.current.yesterday
-
end
-
-
# Returns a new Date representing the date 1 day after today (i.e. tomorrow's date).
-
2
def tomorrow
-
3
::Date.current.tomorrow
-
end
-
-
# Returns Time.zone.today when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns Date.today.
-
2
def current
-
191
::Time.zone ? ::Time.zone.today : ::Date.today
-
end
-
end
-
-
# Returns true if the Date object's date lies in the past. Otherwise returns false.
-
2
def past?
-
self < ::Date.current
-
end
-
-
# Returns true if the Date object's date is today.
-
2
def today?
-
self.to_date == ::Date.current # we need the to_date because of DateTime
-
end
-
-
# Returns true if the Date object's date lies in the future.
-
2
def future?
-
self > ::Date.current
-
end
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
# and then subtracts the specified number of seconds.
-
2
def ago(seconds)
-
to_time_in_current_zone.since(-seconds)
-
end
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
# and then adds the specified number of seconds
-
2
def since(seconds)
-
to_time_in_current_zone.since(seconds)
-
end
-
2
alias :in :since
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
2
def beginning_of_day
-
to_time_in_current_zone
-
end
-
2
alias :midnight :beginning_of_day
-
2
alias :at_midnight :beginning_of_day
-
2
alias :at_beginning_of_day :beginning_of_day
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the end of the day (23:59:59)
-
2
def end_of_day
-
to_time_in_current_zone.end_of_day
-
end
-
-
2
def plus_with_duration(other) #:nodoc:
-
1111
if ActiveSupport::Duration === other
-
321
other.since(self)
-
else
-
790
plus_without_duration(other)
-
end
-
end
-
2
alias_method :plus_without_duration, :+
-
2
alias_method :+, :plus_with_duration
-
-
2
def minus_with_duration(other) #:nodoc:
-
20
if ActiveSupport::Duration === other
-
5
plus_with_duration(-other)
-
else
-
15
minus_without_duration(other)
-
end
-
end
-
2
alias_method :minus_without_duration, :-
-
2
alias_method :-, :minus_with_duration
-
-
# Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with
-
# any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>.
-
2
def advance(options)
-
805
options = options.dup
-
805
d = self
-
805
d = d >> options.delete(:years) * 12 if options[:years]
-
805
d = d >> options.delete(:months) if options[:months]
-
805
d = d + options.delete(:weeks) * 7 if options[:weeks]
-
805
d = d + options.delete(:days) if options[:days]
-
805
d
-
end
-
-
# Returns a new Date where one or more of the elements have been changed according to the +options+ parameter.
-
#
-
# Examples:
-
#
-
# Date.new(2007, 5, 12).change(:day => 1) # => Date.new(2007, 5, 1)
-
# Date.new(2007, 5, 12).change(:year => 2005, :month => 1) # => Date.new(2005, 1, 12)
-
2
def change(options)
-
::Date.new(
-
options[:year] || self.year,
-
options[:month] || self.month,
-
options[:day] || self.day
-
)
-
end
-
-
# Returns a new Date/DateTime representing the time a number of specified weeks ago.
-
2
def weeks_ago(weeks)
-
advance(:weeks => -weeks)
-
end
-
-
# Returns a new Date/DateTime representing the time a number of specified months ago.
-
2
def months_ago(months)
-
advance(:months => -months)
-
end
-
-
# Returns a new Date/DateTime representing the time a number of specified months in the future.
-
2
def months_since(months)
-
advance(:months => months)
-
end
-
-
# Returns a new Date/DateTime representing the time a number of specified years ago.
-
2
def years_ago(years)
-
advance(:years => -years)
-
end
-
-
# Returns a new Date/DateTime representing the time a number of specified years in the future.
-
2
def years_since(years)
-
advance(:years => years)
-
end
-
-
# Shorthand for years_ago(1)
-
def prev_year
-
years_ago(1)
-
2
end unless method_defined?(:prev_year)
-
-
# Shorthand for years_since(1)
-
def next_year
-
years_since(1)
-
2
end unless method_defined?(:next_year)
-
-
# Shorthand for months_ago(1)
-
def prev_month
-
months_ago(1)
-
2
end unless method_defined?(:prev_month)
-
-
# Shorthand for months_since(1)
-
def next_month
-
months_since(1)
-
2
end unless method_defined?(:next_month)
-
-
# Returns number of days to start of this week. Week is assumed to start on
-
# +start_day+, default is +:monday+.
-
2
def days_to_week_start(start_day = :monday)
-
2
start_day_number = DAYS_INTO_WEEK[start_day]
-
2
current_day_number = wday != 0 ? wday - 1 : 6
-
2
(current_day_number - start_day_number) % 7
-
end
-
-
# Returns a new +Date+/+DateTime+ representing the start of this week. Week is
-
# assumed to start on +start_day+, default is +:monday+. +DateTime+ objects
-
# have their time set to 0:00.
-
2
def beginning_of_week(start_day = :monday)
-
1
days_to_start = days_to_week_start(start_day)
-
1
result = self - days_to_start
-
1
acts_like?(:time) ? result.midnight : result
-
end
-
2
alias :at_beginning_of_week :beginning_of_week
-
-
# Returns a new +Date+/+DateTime+ representing the start of this week. Week is
-
# assumed to start on a Monday. +DateTime+ objects have their time set to 0:00.
-
2
def monday
-
beginning_of_week
-
end
-
-
# Returns a new +Date+/+DateTime+ representing the end of this week. Week is
-
# assumed to start on +start_day+, default is +:monday+. +DateTime+ objects
-
# have their time set to 23:59:59.
-
2
def end_of_week(start_day = :monday)
-
1
days_to_end = 6 - days_to_week_start(start_day)
-
1
result = self + days_to_end.days
-
1
self.acts_like?(:time) ? result.end_of_day : result
-
end
-
2
alias :at_end_of_week :end_of_week
-
-
# Returns a new +Date+/+DateTime+ representing the end of this week. Week is
-
# assumed to start on a Monday. +DateTime+ objects have their time set to 23:59:59.
-
2
def sunday
-
end_of_week
-
end
-
-
# Returns a new +Date+/+DateTime+ representing the given +day+ in the previous
-
# week. Default is +:monday+. +DateTime+ objects have their time set to 0:00.
-
2
def prev_week(day = :monday)
-
result = (self - 7).beginning_of_week + DAYS_INTO_WEEK[day]
-
self.acts_like?(:time) ? result.change(:hour => 0) : result
-
end
-
-
# Returns a new Date/DateTime representing the start of the given day in next week (default is :monday).
-
2
def next_week(day = :monday)
-
result = (self + 7).beginning_of_week + DAYS_INTO_WEEK[day]
-
self.acts_like?(:time) ? result.change(:hour => 0) : result
-
end
-
-
# Returns a new ; DateTime objects will have time set to 0:00DateTime representing the start of the month (1st of the month; DateTime objects will have time set to 0:00)
-
2
def beginning_of_month
-
self.acts_like?(:time) ? change(:day => 1, :hour => 0) : change(:day => 1)
-
end
-
2
alias :at_beginning_of_month :beginning_of_month
-
-
# Returns a new Date/DateTime representing the end of the month (last day of the month; DateTime objects will have time set to 0:00)
-
2
def end_of_month
-
last_day = ::Time.days_in_month( self.month, self.year )
-
self.acts_like?(:time) ? change(:day => last_day, :hour => 23, :min => 59, :sec => 59) : change(:day => last_day)
-
end
-
2
alias :at_end_of_month :end_of_month
-
-
# Returns a new Date/DateTime representing the start of the quarter (1st of january, april, july, october; DateTime objects will have time set to 0:00)
-
2
def beginning_of_quarter
-
beginning_of_month.change(:month => [10, 7, 4, 1].detect { |m| m <= self.month })
-
end
-
2
alias :at_beginning_of_quarter :beginning_of_quarter
-
-
# Returns a new Date/DateTime representing the end of the quarter (last day of march, june, september, december; DateTime objects will have time set to 23:59:59)
-
2
def end_of_quarter
-
beginning_of_month.change(:month => [3, 6, 9, 12].detect { |m| m >= self.month }).end_of_month
-
end
-
2
alias :at_end_of_quarter :end_of_quarter
-
-
# Returns a new Date/DateTime representing the start of the year (1st of january; DateTime objects will have time set to 0:00)
-
2
def beginning_of_year
-
self.acts_like?(:time) ? change(:month => 1, :day => 1, :hour => 0) : change(:month => 1, :day => 1)
-
end
-
2
alias :at_beginning_of_year :beginning_of_year
-
-
# Returns a new Time representing the end of the year (31st of december; DateTime objects will have time set to 23:59:59)
-
2
def end_of_year
-
self.acts_like?(:time) ? change(:month => 12, :day => 31, :hour => 23, :min => 59, :sec => 59) : change(:month => 12, :day => 31)
-
end
-
2
alias :at_end_of_year :end_of_year
-
-
# Convenience method which returns a new Date/DateTime representing the time 1 day ago
-
2
def yesterday
-
self - 1
-
end
-
-
# Convenience method which returns a new Date/DateTime representing the time 1 day since the instance time
-
2
def tomorrow
-
3
self + 1
-
end
-
end
-
2
require 'date'
-
2
require 'active_support/inflector/methods'
-
2
require 'active_support/core_ext/date/zones'
-
2
require 'active_support/core_ext/module/remove_method'
-
-
2
class Date
-
2
DATE_FORMATS = {
-
:short => "%e %b",
-
:long => "%B %e, %Y",
-
:db => "%Y-%m-%d",
-
:number => "%Y%m%d",
-
:long_ordinal => lambda { |date| date.strftime("%B #{ActiveSupport::Inflector.ordinalize(date.day)}, %Y") }, # => "April 25th, 2007"
-
:rfc822 => "%e %b %Y"
-
}
-
-
# Ruby 1.9 has Date#to_time which converts to localtime only.
-
2
remove_possible_method :to_time
-
-
# Ruby 1.9 has Date#xmlschema which converts to a string without the time component.
-
2
remove_possible_method :xmlschema
-
-
# Convert to a formatted string. See DATE_FORMATS for predefined formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# ==== Examples
-
# date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
-
#
-
# date.to_formatted_s(:db) # => "2007-11-10"
-
# date.to_s(:db) # => "2007-11-10"
-
#
-
# date.to_formatted_s(:short) # => "10 Nov"
-
# date.to_formatted_s(:long) # => "November 10, 2007"
-
# date.to_formatted_s(:long_ordinal) # => "November 10th, 2007"
-
# date.to_formatted_s(:rfc822) # => "10 Nov 2007"
-
#
-
# == Adding your own time formats to to_formatted_s
-
# You can add your own formats to the Date::DATE_FORMATS hash.
-
# Use the format name as the hash key and either a strftime string
-
# or Proc instance that takes a date argument as the value.
-
#
-
# # config/initializers/time_formats.rb
-
# Date::DATE_FORMATS[:month_and_year] = "%B %Y"
-
# Date::DATE_FORMATS[:short_ordinal] = lambda { |date| date.strftime("%B #{date.day.ordinalize}") }
-
2
def to_formatted_s(format = :default)
-
128
if formatter = DATE_FORMATS[format]
-
110
if formatter.respond_to?(:call)
-
formatter.call(self).to_s
-
else
-
110
strftime(formatter)
-
end
-
else
-
18
to_default_s
-
end
-
end
-
2
alias_method :to_default_s, :to_s
-
2
alias_method :to_s, :to_formatted_s
-
-
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005"
-
2
def readable_inspect
-
60
strftime("%a, %d %b %Y")
-
end
-
2
alias_method :default_inspect, :inspect
-
2
alias_method :inspect, :readable_inspect
-
-
# A method to keep Time, Date and DateTime instances interchangeable on conversions.
-
# In this case, it simply returns +self+.
-
def to_date
-
self
-
2
end if RUBY_VERSION < '1.9'
-
-
# Converts a Date instance to a Time, where the time is set to the beginning of the day.
-
# The timezone can be either :local or :utc (default :local).
-
#
-
# ==== Examples
-
# date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
-
#
-
# date.to_time # => Sat Nov 10 00:00:00 0800 2007
-
# date.to_time(:local) # => Sat Nov 10 00:00:00 0800 2007
-
#
-
# date.to_time(:utc) # => Sat Nov 10 00:00:00 UTC 2007
-
2
def to_time(form = :local)
-
6
::Time.send("#{form}_time", year, month, day)
-
end
-
-
# Converts a Date instance to a DateTime, where the time is set to the beginning of the day
-
# and UTC offset is set to 0.
-
#
-
# ==== Examples
-
# date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
-
#
-
# date.to_datetime # => Sat, 10 Nov 2007 00:00:00 0000
-
def to_datetime
-
::DateTime.civil(year, month, day, 0, 0, 0, 0)
-
2
end if RUBY_VERSION < '1.9'
-
-
def iso8601
-
strftime('%F')
-
2
end if RUBY_VERSION < '1.9'
-
-
2
alias_method :rfc3339, :iso8601 if RUBY_VERSION < '1.9'
-
-
2
def xmlschema
-
to_time_in_current_zone.xmlschema
-
end
-
end
-
# Date memoizes some instance methods using metaprogramming to wrap
-
# the methods with one that caches the result in an instance variable.
-
#
-
# If a Date is frozen but the memoized method hasn't been called, the
-
# first call will result in a frozen object error since the memo
-
# instance variable is uninitialized.
-
#
-
# Work around by eagerly memoizing before the first freeze.
-
#
-
# Ruby 1.9 uses a preinitialized instance variable so it's unaffected.
-
# This hack is as close as we can get to feature detection:
-
2
if RUBY_VERSION < '1.9'
-
require 'date'
-
begin
-
::Date.today.freeze.jd
-
rescue => frozen_object_error
-
if frozen_object_error.message =~ /frozen/
-
class Date #:nodoc:
-
def freeze
-
unless frozen?
-
self.class.private_instance_methods(false).each do |m|
-
if m.to_s =~ /\A__\d+__\Z/
-
instance_variable_set(:"@#{m}", [send(m)])
-
end
-
end
-
end
-
-
super
-
end
-
end
-
end
-
end
-
end
-
2
require 'date'
-
2
require 'active_support/core_ext/time/zones'
-
-
2
class Date
-
# Converts Date to a TimeWithZone in the current zone if Time.zone or Time.zone_default
-
# is set, otherwise converts Date to a Time via Date#to_time
-
2
def to_time_in_current_zone
-
if ::Time.zone
-
::Time.zone.local(year, month, day)
-
else
-
to_time
-
end
-
end
-
end
-
2
require 'date'
-
2
require 'active_support/core_ext/object/acts_like'
-
-
2
class DateTime
-
# Duck-types as a Date-like class. See Object#acts_like?.
-
2
def acts_like_date?
-
true
-
end
-
-
# Duck-types as a Time-like class. See Object#acts_like?.
-
2
def acts_like_time?
-
true
-
end
-
end
-
2
require 'rational' unless RUBY_VERSION >= '1.9.2'
-
-
2
class DateTime
-
2
class << self
-
# DateTimes aren't aware of DST rules, so use a consistent non-DST offset when creating a DateTime with an offset in the local zone
-
2
def local_offset
-
::Time.local(2012).utc_offset.to_r / 86400
-
end
-
-
# Returns <tt>Time.zone.now.to_datetime</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise returns <tt>Time.now.to_datetime</tt>.
-
2
def current
-
::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
-
end
-
end
-
-
# Tells whether the DateTime object's datetime lies in the past
-
2
def past?
-
self < ::DateTime.current
-
end
-
-
# Tells whether the DateTime object's datetime lies in the future
-
2
def future?
-
self > ::DateTime.current
-
end
-
-
# Seconds since midnight: DateTime.now.seconds_since_midnight
-
2
def seconds_since_midnight
-
sec + (min * 60) + (hour * 3600)
-
end
-
-
# Returns a new DateTime where one or more of the elements have been changed according to the +options+ parameter. The time options
-
# (hour, minute, sec) reset cascadingly, so if only the hour is passed, then minute and sec is set to 0. If the hour and
-
# minute is passed, then sec is set to 0.
-
2
def change(options)
-
::DateTime.civil(
-
options[:year] || year,
-
options[:month] || month,
-
options[:day] || day,
-
options[:hour] || hour,
-
options[:min] || (options[:hour] ? 0 : min),
-
options[:sec] || ((options[:hour] || options[:min]) ? 0 : sec),
-
options[:offset] || offset,
-
options[:start] || start
-
)
-
end
-
-
# Uses Date to provide precise Time calculations for years, months, and days.
-
# The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
-
# <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
-
# <tt>:minutes</tt>, <tt>:seconds</tt>.
-
2
def advance(options)
-
d = to_date.advance(options)
-
datetime_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
-
seconds_to_advance = (options[:seconds] || 0) + (options[:minutes] || 0) * 60 + (options[:hours] || 0) * 3600
-
seconds_to_advance == 0 ? datetime_advanced_by_date : datetime_advanced_by_date.since(seconds_to_advance)
-
end
-
-
# Returns a new DateTime representing the time a number of seconds ago
-
# Do not use this method in combination with x.months, use months_ago instead!
-
2
def ago(seconds)
-
since(-seconds)
-
end
-
-
# Returns a new DateTime representing the time a number of seconds since the instance time
-
# Do not use this method in combination with x.months, use months_since instead!
-
2
def since(seconds)
-
self + Rational(seconds.round, 86400)
-
end
-
2
alias :in :since
-
-
# Returns a new DateTime representing the start of the day (0:00)
-
2
def beginning_of_day
-
change(:hour => 0)
-
end
-
2
alias :midnight :beginning_of_day
-
2
alias :at_midnight :beginning_of_day
-
2
alias :at_beginning_of_day :beginning_of_day
-
-
# Returns a new DateTime representing the end of the day (23:59:59)
-
2
def end_of_day
-
change(:hour => 23, :min => 59, :sec => 59)
-
end
-
-
# Returns a new DateTime representing the start of the hour (hh:00:00)
-
2
def beginning_of_hour
-
change(:min => 0)
-
end
-
2
alias :at_beginning_of_hour :beginning_of_hour
-
-
# Returns a new DateTime representing the end of the hour (hh:59:59)
-
2
def end_of_hour
-
change(:min => 59, :sec => 59)
-
end
-
-
# 1.9.3 defines + and - on DateTime, < 1.9.3 do not.
-
2
if DateTime.public_instance_methods(false).include?(:+)
-
def plus_with_duration(other) #:nodoc:
-
if ActiveSupport::Duration === other
-
other.since(self)
-
else
-
plus_without_duration(other)
-
end
-
end
-
alias_method :plus_without_duration, :+
-
alias_method :+, :plus_with_duration
-
-
def minus_with_duration(other) #:nodoc:
-
if ActiveSupport::Duration === other
-
plus_with_duration(-other)
-
else
-
minus_without_duration(other)
-
end
-
end
-
alias_method :minus_without_duration, :-
-
alias_method :-, :minus_with_duration
-
end
-
-
# Adjusts DateTime to UTC by adding its offset value; offset is set to 0
-
#
-
# Example:
-
#
-
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)) # => Mon, 21 Feb 2005 10:11:12 -0600
-
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc # => Mon, 21 Feb 2005 16:11:12 +0000
-
2
def utc
-
new_offset(0)
-
end
-
2
alias_method :getutc, :utc
-
-
# Returns true if offset == 0
-
2
def utc?
-
offset == 0
-
end
-
-
# Returns the offset value in seconds
-
2
def utc_offset
-
(offset * 86400).to_i
-
end
-
-
# Layers additional behavior on DateTime#<=> so that Time and ActiveSupport::TimeWithZone instances can be compared with a DateTime
-
2
def <=>(other)
-
365
super other.kind_of?(Infinity) ? other : other.to_datetime
-
end
-
end
-
2
require 'active_support/inflector/methods'
-
2
require 'active_support/core_ext/time/conversions'
-
2
require 'active_support/core_ext/date_time/calculations'
-
2
require 'active_support/values/time_zone'
-
-
2
class DateTime
-
# Ruby 1.9 has DateTime#to_time which internally relies on Time. We define our own #to_time which allows
-
# DateTimes outside the range of what can be created with Time.
-
2
remove_method :to_time if instance_methods.include?(:to_time)
-
-
# Convert to a formatted string. See Time::DATE_FORMATS for predefined formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# === Examples
-
# datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000
-
#
-
# datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00"
-
# datetime.to_s(:db) # => "2007-12-04 00:00:00"
-
# datetime.to_s(:number) # => "20071204000000"
-
# datetime.to_formatted_s(:short) # => "04 Dec 00:00"
-
# datetime.to_formatted_s(:long) # => "December 04, 2007 00:00"
-
# datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00"
-
# datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
-
#
-
# == Adding your own datetime formats to to_formatted_s
-
# DateTime formats are shared with Time. You can add your own to the
-
# Time::DATE_FORMATS hash. Use the format name as the hash key and
-
# either a strftime string or Proc instance that takes a time or
-
# datetime argument as the value.
-
#
-
# # config/initializers/time_formats.rb
-
# Time::DATE_FORMATS[:month_and_year] = "%B %Y"
-
# Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
-
2
def to_formatted_s(format = :default)
-
if formatter = ::Time::DATE_FORMATS[format]
-
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
to_default_s
-
end
-
end
-
2
alias_method :to_default_s, :to_s unless (instance_methods(false) & [:to_s, 'to_s']).empty?
-
2
alias_method :to_s, :to_formatted_s
-
-
# Returns the +utc_offset+ as an +HH:MM formatted string. Examples:
-
#
-
# datetime = DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-6, 24))
-
# datetime.formatted_offset # => "-06:00"
-
# datetime.formatted_offset(false) # => "-0600"
-
2
def formatted_offset(colon = true, alternate_utc_string = nil)
-
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005 14:30:00 +0000".
-
2
def readable_inspect
-
to_s(:rfc822)
-
end
-
2
alias_method :default_inspect, :inspect
-
2
alias_method :inspect, :readable_inspect
-
-
# Converts self to a Ruby Date object; time portion is discarded.
-
def to_date
-
::Date.new(year, month, day)
-
2
end unless instance_methods(false).include?(:to_date)
-
-
# Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class.
-
# If self has an offset other than 0, self will just be returned unaltered, since there's no clean way to map it to a Time.
-
2
def to_time
-
self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec, sec_fraction * (RUBY_VERSION < '1.9' ? 86400000000 : 1000000)) : self
-
end
-
-
# To be able to keep Times, Dates and DateTimes interchangeable on conversions.
-
def to_datetime
-
self
-
2
end unless instance_methods(false).include?(:to_datetime)
-
-
2
def self.civil_from_format(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0)
-
offset = utc_or_local.to_sym == :local ? local_offset : 0
-
civil(year, month, day, hour, min, sec, offset)
-
end
-
-
# Converts datetime to an appropriate format for use in XML.
-
def xmlschema
-
strftime("%Y-%m-%dT%H:%M:%S%Z")
-
2
end unless instance_methods(false).include?(:xmlschema)
-
-
# Converts self to a floating-point number of seconds since the Unix epoch.
-
2
def to_f
-
seconds_since_unix_epoch.to_f
-
end
-
-
# Converts self to an integer number of seconds since the Unix epoch.
-
2
def to_i
-
seconds_since_unix_epoch.to_i
-
end
-
-
2
private
-
-
2
def seconds_since_unix_epoch
-
seconds_per_day = 86_400
-
(self - ::DateTime.civil(1970)) * seconds_per_day
-
end
-
end
-
2
require 'active_support/core_ext/time/zones'
-
-
2
class DateTime
-
# Returns the simultaneous time in <tt>Time.zone</tt>.
-
#
-
# Time.zone = 'Hawaii' # => 'Hawaii'
-
# DateTime.new(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
#
-
# This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone
-
# instead of the operating system's time zone.
-
#
-
# You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
-
# and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
-
#
-
# DateTime.new(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
-
2
def in_time_zone(zone = ::Time.zone)
-
return self unless zone
-
-
ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.find_zone!(zone))
-
end
-
end
-
2
require 'active_support/ordered_hash'
-
-
2
module Enumerable
-
# Ruby 1.8.7 introduces group_by, but the result isn't ordered. Override it.
-
2
remove_method(:group_by) if [].respond_to?(:group_by) && RUBY_VERSION < '1.9'
-
-
# Collect an enumerable into sets, grouped by the result of a block. Useful,
-
# for example, for grouping records by date.
-
#
-
# Example:
-
#
-
# latest_transcripts.group_by(&:day).each do |day, transcripts|
-
# p "#{day} -> #{transcripts.map(&:class).join(', ')}"
-
# end
-
# "2006-03-01 -> Transcript"
-
# "2006-02-28 -> Transcript"
-
# "2006-02-27 -> Transcript, Transcript"
-
# "2006-02-26 -> Transcript, Transcript"
-
# "2006-02-25 -> Transcript"
-
# "2006-02-24 -> Transcript, Transcript"
-
# "2006-02-23 -> Transcript"
-
def group_by
-
return to_enum :group_by unless block_given?
-
assoc = ActiveSupport::OrderedHash.new
-
-
each do |element|
-
key = yield(element)
-
-
if assoc.has_key?(key)
-
assoc[key] << element
-
else
-
assoc[key] = [element]
-
end
-
end
-
-
assoc
-
2
end unless [].respond_to?(:group_by)
-
-
# Calculates a sum from the elements. Examples:
-
#
-
# payments.sum { |p| p.price * p.tax_rate }
-
# payments.sum(&:price)
-
#
-
# The latter is a shortcut for:
-
#
-
# payments.inject(0) { |sum, p| sum + p.price }
-
#
-
# It can also calculate the sum without the use of a block.
-
#
-
# [5, 15, 10].sum # => 30
-
# ["foo", "bar"].sum # => "foobar"
-
# [[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
-
#
-
# The default sum of an empty list is zero. You can override this default:
-
#
-
# [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
-
#
-
2
def sum(identity = 0, &block)
-
263
if block_given?
-
map(&block).sum(identity)
-
else
-
263
inject(:+) || identity
-
end
-
end
-
-
# Iterates over a collection, passing the current element *and* the
-
# +memo+ to the block. Handy for building up hashes or
-
# reducing collections down to one object. Examples:
-
#
-
# %w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase }
-
# # => {'foo' => 'FOO', 'bar' => 'BAR'}
-
#
-
# *Note* that you can't use immutable objects like numbers, true or false as
-
# the memo. You would think the following returns 120, but since the memo is
-
# never changed, it does not.
-
#
-
# (1..5).each_with_object(1) { |value, memo| memo *= value } # => 1
-
#
-
def each_with_object(memo)
-
return to_enum :each_with_object, memo unless block_given?
-
each do |element|
-
yield element, memo
-
end
-
memo
-
2
end unless [].respond_to?(:each_with_object)
-
-
# Convert an enumerable to a hash. Examples:
-
#
-
# people.index_by(&:login)
-
# => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
-
# people.index_by { |person| "#{person.first_name} #{person.last_name}" }
-
# => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
-
#
-
2
def index_by
-
return to_enum :index_by unless block_given?
-
Hash[map { |elem| [yield(elem), elem] }]
-
end
-
-
# Returns true if the enumerable has more than 1 element. Functionally equivalent to enum.to_a.size > 1.
-
# Can be called with a block too, much like any?, so <tt>people.many? { |p| p.age > 26 }</tt> returns true if more than one person is over 26.
-
2
def many?
-
cnt = 0
-
if block_given?
-
any? do |element|
-
cnt += 1 if yield element
-
cnt > 1
-
end
-
else
-
any?{ (cnt += 1) > 1 }
-
end
-
end
-
-
# The negative of the <tt>Enumerable#include?</tt>. Returns true if the collection does not include the object.
-
2
def exclude?(object)
-
!include?(object)
-
end
-
end
-
-
2
class Range #:nodoc:
-
# Optimize range sum to use arithmetic progression if a block is not given and
-
# we have a range of numeric values.
-
2
def sum(identity = 0)
-
return super if block_given? || !(first.instance_of?(Integer) && last.instance_of?(Integer))
-
actual_last = exclude_end? ? (last - 1) : last
-
(actual_last - first + 1) * (actual_last + first) / 2
-
end
-
end
-
2
module ActiveSupport
-
2
FrozenObjectError = RUBY_VERSION < '1.9' ? TypeError : RuntimeError
-
end
-
2
require 'active_support/core_ext/file/atomic'
-
2
require 'active_support/core_ext/file/path'
-
2
class File
-
# Write to a file atomically. Useful for situations where you don't
-
# want other processes or threads to see half-written files.
-
#
-
# File.atomic_write("important.file") do |file|
-
# file.write("hello")
-
# end
-
#
-
# If your temp directory is not on the same filesystem as the file you're
-
# trying to write, you can provide a different temporary directory.
-
#
-
# File.atomic_write("/data/something.important", "/data/tmp") do |file|
-
# file.write("hello")
-
# end
-
2
def self.atomic_write(file_name, temp_dir = Dir.tmpdir)
-
require 'tempfile' unless defined?(Tempfile)
-
require 'fileutils' unless defined?(FileUtils)
-
-
temp_file = Tempfile.new(basename(file_name), temp_dir)
-
temp_file.binmode
-
yield temp_file
-
temp_file.close
-
-
begin
-
# Get original file permissions
-
old_stat = stat(file_name)
-
rescue Errno::ENOENT
-
# No old permissions, write a temp file to determine the defaults
-
check_name = join(dirname(file_name), ".permissions_check.#{Thread.current.object_id}.#{Process.pid}.#{rand(1000000)}")
-
open(check_name, "w") { }
-
old_stat = stat(check_name)
-
unlink(check_name)
-
end
-
-
# Overwrite original file with temp file
-
FileUtils.mv(temp_file.path, file_name)
-
-
# Set correct permissions on new file
-
begin
-
chown(old_stat.uid, old_stat.gid, file_name)
-
# This operation will affect filesystem ACL's
-
chmod(old_stat.mode, file_name)
-
rescue Errno::EPERM
-
# Changing file ownership failed, moving on.
-
end
-
end
-
end
-
2
class File
-
2
unless File.allocate.respond_to?(:to_path)
-
alias to_path path
-
end
-
end
-
2
require 'active_support/core_ext/float/rounding'
-
class Float
-
alias precisionless_round round
-
private :precisionless_round
-
-
# Rounds the float with the specified precision.
-
#
-
# x = 1.337
-
# x.round # => 1
-
# x.round(1) # => 1.3
-
# x.round(2) # => 1.34
-
def round(precision = nil)
-
if precision
-
magnitude = 10.0 ** precision
-
(self * magnitude).round / magnitude
-
else
-
precisionless_round
-
end
-
end
-
2
end if RUBY_VERSION < '1.9'
-
2
require 'active_support/core_ext/hash/conversions'
-
2
require 'active_support/core_ext/hash/deep_merge'
-
2
require 'active_support/core_ext/hash/deep_dup'
-
2
require 'active_support/core_ext/hash/diff'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/hash/indifferent_access'
-
2
require 'active_support/core_ext/hash/keys'
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/xml_mini'
-
2
require 'active_support/time'
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/string/inflections'
-
-
2
class Hash
-
# Returns a string containing an XML representation of its receiver:
-
#
-
# {"foo" => 1, "bar" => 2}.to_xml
-
# # =>
-
# # <?xml version="1.0" encoding="UTF-8"?>
-
# # <hash>
-
# # <foo type="integer">1</foo>
-
# # <bar type="integer">2</bar>
-
# # </hash>
-
#
-
# To do so, the method loops over the pairs and builds nodes that depend on
-
# the _values_. Given a pair +key+, +value+:
-
#
-
# * If +value+ is a hash there's a recursive call with +key+ as <tt>:root</tt>.
-
#
-
# * If +value+ is an array there's a recursive call with +key+ as <tt>:root</tt>,
-
# and +key+ singularized as <tt>:children</tt>.
-
#
-
# * If +value+ is a callable object it must expect one or two arguments. Depending
-
# on the arity, the callable is invoked with the +options+ hash as first argument
-
# with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. The
-
# callable can add nodes by using <tt>options[:builder]</tt>.
-
#
-
# "foo".to_xml(lambda { |options, key| options[:builder].b(key) })
-
# # => "<b>foo</b>"
-
#
-
# * If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>.
-
#
-
# class Foo
-
# def to_xml(options)
-
# options[:builder].bar "fooing!"
-
# end
-
# end
-
#
-
# {:foo => Foo.new}.to_xml(:skip_instruct => true)
-
# # => "<hash><bar>fooing!</bar></hash>"
-
#
-
# * Otherwise, a node with +key+ as tag is created with a string representation of
-
# +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added.
-
# Unless the option <tt>:skip_types</tt> exists and is true, an attribute "type" is
-
# added as well according to the following mapping:
-
#
-
# XML_TYPE_NAMES = {
-
# "Symbol" => "symbol",
-
# "Fixnum" => "integer",
-
# "Bignum" => "integer",
-
# "BigDecimal" => "decimal",
-
# "Float" => "float",
-
# "TrueClass" => "boolean",
-
# "FalseClass" => "boolean",
-
# "Date" => "date",
-
# "DateTime" => "datetime",
-
# "Time" => "datetime"
-
# }
-
#
-
# By default the root node is "hash", but that's configurable via the <tt>:root</tt> option.
-
#
-
# The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can
-
# configure your own builder with the <tt>:builder</tt> option. The method also accepts
-
# options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.
-
2
def to_xml(options = {})
-
require 'active_support/builder' unless defined?(Builder)
-
-
options = options.dup
-
options[:indent] ||= 2
-
options[:root] ||= "hash"
-
options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
-
-
builder = options[:builder]
-
builder.instruct! unless options.delete(:skip_instruct)
-
-
root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
-
-
builder.__send__(:method_missing, root) do
-
each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) }
-
yield builder if block_given?
-
end
-
end
-
-
2
class DisallowedType < StandardError #:nodoc:
-
2
def initialize(type)
-
super "Disallowed type attribute: #{type.inspect}"
-
end
-
end
-
-
2
DISALLOWED_XML_TYPES = %w(symbol yaml)
-
-
2
class << self
-
2
def from_xml(xml, disallowed_types = nil)
-
typecast_xml_value(unrename_keys(ActiveSupport::XmlMini.parse(xml)), disallowed_types)
-
end
-
-
2
def from_trusted_xml(xml)
-
from_xml xml, []
-
end
-
-
2
private
-
2
def typecast_xml_value(value, disallowed_types = nil)
-
disallowed_types ||= DISALLOWED_XML_TYPES
-
-
case value.class.to_s
-
when 'Hash'
-
if value.include?('type') && !value['type'].is_a?(Hash) && disallowed_types.include?(value['type'])
-
raise DisallowedType, value['type']
-
end
-
-
if value['type'] == 'array'
-
_, entries = Array.wrap(value.detect { |k,v| not v.is_a?(String) })
-
if entries.nil? || (c = value['__content__'] && c.blank?)
-
[]
-
else
-
case entries.class.to_s # something weird with classes not matching here. maybe singleton methods breaking is_a?
-
when "Array"
-
entries.collect { |v| typecast_xml_value(v, disallowed_types) }
-
when "Hash"
-
[typecast_xml_value(entries, disallowed_types)]
-
else
-
raise "can't typecast #{entries.inspect}"
-
end
-
end
-
elsif value['type'] == 'file' ||
-
(value["__content__"] && (value.keys.size == 1 || value["__content__"].present?))
-
content = value["__content__"]
-
if parser = ActiveSupport::XmlMini::PARSING[value["type"]]
-
parser.arity == 1 ? parser.call(content) : parser.call(content, value)
-
else
-
content
-
end
-
elsif value['type'] == 'string' && value['nil'] != 'true'
-
""
-
# blank or nil parsed values are represented by nil
-
elsif value.blank? || value['nil'] == 'true'
-
nil
-
# If the type is the only element which makes it then
-
# this still makes the value nil, except if type is
-
# a XML node(where type['value'] is a Hash)
-
elsif value['type'] && value.size == 1 && !value['type'].is_a?(::Hash)
-
nil
-
else
-
xml_value = Hash[value.map { |k,v| [k, typecast_xml_value(v, disallowed_types)] }]
-
-
# Turn { :files => { :file => #<StringIO> } into { :files => #<StringIO> } so it is compatible with
-
# how multipart uploaded files from HTML appear
-
xml_value["file"].is_a?(StringIO) ? xml_value["file"] : xml_value
-
end
-
when 'Array'
-
value.map! { |i| typecast_xml_value(i, disallowed_types) }
-
value.length > 1 ? value : value.first
-
when 'String'
-
value
-
else
-
raise "can't typecast #{value.class.name} - #{value.inspect}"
-
end
-
end
-
-
2
def unrename_keys(params)
-
case params.class.to_s
-
when "Hash"
-
Hash[params.map { |k,v| [k.to_s.tr("-", "_"), unrename_keys(v)] } ]
-
when "Array"
-
params.map { |v| unrename_keys(v) }
-
else
-
params
-
end
-
end
-
end
-
end
-
2
class Hash
-
# Returns a deep copy of hash.
-
#
-
# hash = { :a => { :b => 'b' } }
-
# dup = hash.deep_dup
-
# dup[:a][:c] = 'c'
-
#
-
# hash[:a][:c] #=> nil
-
# dup[:a][:c] #=> "c"
-
2
def deep_dup
-
60
duplicate = self.dup
-
60
duplicate.each_pair do |k,v|
-
128
tv = duplicate[k]
-
128
duplicate[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_dup : v
-
end
-
60
duplicate
-
end
-
end
-
2
class Hash
-
# Returns a new hash with +self+ and +other_hash+ merged recursively.
-
#
-
# h1 = {:x => {:y => [4,5,6]}, :z => [7,8,9]}
-
# h2 = {:x => {:y => [7,8,9]}, :z => "xyz"}
-
#
-
# h1.deep_merge(h2) #=> { :x => {:y => [7, 8, 9]}, :z => "xyz" }
-
# h2.deep_merge(h1) #=> { :x => {:y => [4, 5, 6]}, :z => [7, 8, 9] }
-
2
def deep_merge(other_hash)
-
dup.deep_merge!(other_hash)
-
end
-
-
# Same as +deep_merge+, but modifies +self+.
-
2
def deep_merge!(other_hash)
-
other_hash.each_pair do |k,v|
-
tv = self[k]
-
self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v
-
end
-
self
-
end
-
end
-
2
class Hash
-
# Returns a hash that represents the difference between two hashes.
-
#
-
# Examples:
-
#
-
# {1 => 2}.diff(1 => 2) # => {}
-
# {1 => 2}.diff(1 => 3) # => {1 => 2}
-
# {}.diff(1 => 2) # => {1 => 2}
-
# {1 => 2, 3 => 4}.diff(1 => 2) # => {3 => 4}
-
2
def diff(h2)
-
dup.delete_if { |k, v| h2[k] == v }.merge!(h2.dup.delete_if { |k, v| has_key?(k) })
-
end
-
end
-
2
class Hash
-
# Return a hash that includes everything but the given keys. This is useful for
-
# limiting a set of parameters to everything but a few known toggles:
-
#
-
# @person.update_attributes(params[:person].except(:admin))
-
#
-
# If the receiver responds to +convert_key+, the method is called on each of the
-
# arguments. This allows +except+ to play nice with hashes with indifferent access
-
# for instance:
-
#
-
# {:a => 1}.with_indifferent_access.except(:a) # => {}
-
# {:a => 1}.with_indifferent_access.except("a") # => {}
-
#
-
2
def except(*keys)
-
242
dup.except!(*keys)
-
end
-
-
# Replaces the hash without the given keys.
-
2
def except!(*keys)
-
549
keys.each { |key| delete(key) }
-
242
self
-
end
-
end
-
2
require 'active_support/hash_with_indifferent_access'
-
-
2
class Hash
-
# Returns an <tt>ActiveSupport::HashWithIndifferentAccess</tt> out of its receiver:
-
#
-
# {:a => 1}.with_indifferent_access["a"] # => 1
-
#
-
2
def with_indifferent_access
-
27
ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default(self)
-
end
-
-
# Called when object is nested under an object that receives
-
# #with_indifferent_access. This method will be called on the current object
-
# by the enclosing object and is aliased to #with_indifferent_access by
-
# default. Subclasses of Hash may overwrite this method to return +self+ if
-
# converting to an <tt>ActiveSupport::HashWithIndifferentAccess</tt> would not be
-
# desirable.
-
#
-
# b = {:b => 1}
-
# {:a => b}.with_indifferent_access["a"] # calls b.nested_under_indifferent_access
-
#
-
2
alias nested_under_indifferent_access with_indifferent_access
-
end
-
2
class Hash
-
# Return a new hash with all keys converted to strings.
-
#
-
# { :name => 'Rob', :years => '28' }.stringify_keys
-
# #=> { "name" => "Rob", "years" => "28" }
-
2
def stringify_keys
-
429
dup.stringify_keys!
-
end
-
-
# Destructively convert all keys to strings. Same as
-
# +stringify_keys+, but modifies +self+.
-
2
def stringify_keys!
-
429
keys.each do |key|
-
2273
self[key.to_s] = delete(key)
-
end
-
429
self
-
end
-
-
# Return a new hash with all keys converted to symbols, as long as
-
# they respond to +to_sym+.
-
#
-
# { 'name' => 'Rob', 'years' => '28' }.symbolize_keys
-
# #=> { :name => "Rob", :years => "28" }
-
2
def symbolize_keys
-
31
dup.symbolize_keys!
-
end
-
-
# Destructively convert all keys to symbols, as long as they respond
-
# to +to_sym+. Same as +symbolize_keys+, but modifies +self+.
-
2
def symbolize_keys!
-
51
keys.each do |key|
-
98
self[(key.to_sym rescue key) || key] = delete(key)
-
end
-
51
self
-
end
-
-
2
alias_method :to_options, :symbolize_keys
-
2
alias_method :to_options!, :symbolize_keys!
-
-
# Validate all keys in a hash match *valid keys, raising ArgumentError on a mismatch.
-
# Note that keys are NOT treated indifferently, meaning if you use strings for keys but assert symbols
-
# as keys, this will fail.
-
#
-
# ==== Examples
-
# { :name => "Rob", :years => "28" }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: years"
-
# { :name => "Rob", :age => "28" }.assert_valid_keys("name", "age") # => raises "ArgumentError: Unknown key: name"
-
# { :name => "Rob", :age => "28" }.assert_valid_keys(:name, :age) # => passes, raises nothing
-
2
def assert_valid_keys(*valid_keys)
-
806
valid_keys.flatten!
-
806
each_key do |k|
-
36
raise(ArgumentError, "Unknown key: #{k}") unless valid_keys.include?(k)
-
end
-
end
-
end
-
2
class Hash
-
# Merges the caller into +other_hash+. For example,
-
#
-
# options = options.reverse_merge(:size => 25, :velocity => 10)
-
#
-
# is equivalent to
-
#
-
# options = {:size => 25, :velocity => 10}.merge(options)
-
#
-
# This is particularly useful for initializing an options hash
-
# with default values.
-
2
def reverse_merge(other_hash)
-
24
other_hash.merge(self)
-
end
-
-
# Destructive +reverse_merge+.
-
2
def reverse_merge!(other_hash)
-
# right wins if there is no left
-
169
merge!( other_hash ){|key,left,right| left }
-
end
-
-
2
alias_method :reverse_update, :reverse_merge!
-
end
-
2
class Hash
-
# Slice a hash to include only the given keys. This is useful for
-
# limiting an options hash to valid keys before passing to a method:
-
#
-
# def search(criteria = {})
-
# assert_valid_keys(:mass, :velocity, :time)
-
# end
-
#
-
# search(options.slice(:mass, :velocity, :time))
-
#
-
# If you have an array of keys you want to limit to, you should splat them:
-
#
-
# valid_keys = [:mass, :velocity, :time]
-
# search(options.slice(*valid_keys))
-
2
def slice(*keys)
-
451
keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
-
451
hash = self.class.new
-
3370
keys.each { |k| hash[k] = self[k] if has_key?(k) }
-
451
hash
-
end
-
-
# Replaces the hash with only the given keys.
-
# Returns a hash contained the removed key/value pairs
-
# {:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b) # => {:c => 3, :d => 4}
-
2
def slice!(*keys)
-
36
keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
-
36
omit = slice(*self.keys - keys)
-
36
hash = slice(*keys)
-
36
replace(hash)
-
36
omit
-
end
-
-
# Removes and returns the key/value pairs matching the given keys.
-
# {:a => 1, :b => 2, :c => 3, :d => 4}.extract!(:a, :b) # => {:a => 1, :b => 2}
-
2
def extract!(*keys)
-
result = {}
-
keys.each {|key| result[key] = delete(key) }
-
result
-
end
-
end
-
2
require 'active_support/core_ext/integer/multiple'
-
2
require 'active_support/core_ext/integer/inflections'
-
2
require 'active_support/core_ext/integer/time'
-
2
require 'active_support/inflector'
-
-
2
class Integer
-
# Ordinalize turns a number into an ordinal string used to denote the
-
# position in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# 1.ordinalize # => "1st"
-
# 2.ordinalize # => "2nd"
-
# 1002.ordinalize # => "1002nd"
-
# 1003.ordinalize # => "1003rd"
-
# -11.ordinalize # => "-11th"
-
# -1001.ordinalize # => "-1001st"
-
#
-
2
def ordinalize
-
ActiveSupport::Inflector.ordinalize(self)
-
end
-
end
-
2
class Integer
-
# Check whether the integer is evenly divisible by the argument.
-
#
-
# 0.multiple_of?(0) #=> true
-
# 6.multiple_of?(5) #=> false
-
# 10.multiple_of?(2) #=> true
-
2
def multiple_of?(number)
-
number != 0 ? self % number == 0 : zero?
-
end
-
end
-
2
class Integer
-
# Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years.
-
#
-
# These methods use Time#advance for precise date calculations when using from_now, ago, etc.
-
# as well as adding or subtracting their results from a Time object. For example:
-
#
-
# # equivalent to Time.now.advance(:months => 1)
-
# 1.month.from_now
-
#
-
# # equivalent to Time.now.advance(:years => 2)
-
# 2.years.from_now
-
#
-
# # equivalent to Time.now.advance(:months => 4, :years => 5)
-
# (4.months + 5.years).from_now
-
#
-
# While these methods provide precise calculation when used as in the examples above, care
-
# should be taken to note that this is not true if the result of `months', `years', etc is
-
# converted before use:
-
#
-
# # equivalent to 30.days.to_i.from_now
-
# 1.month.to_i.from_now
-
#
-
# # equivalent to 365.25.days.to_f.from_now
-
# 1.year.to_f.from_now
-
#
-
# In such cases, Ruby's core
-
# Date[http://stdlib.rubyonrails.org/libdoc/date/rdoc/index.html] and
-
# Time[http://stdlib.rubyonrails.org/libdoc/time/rdoc/index.html] should be used for precision
-
# date and time arithmetic
-
2
def months
-
19
ActiveSupport::Duration.new(self * 30.days, [[:months, self]])
-
end
-
2
alias :month :months
-
-
2
def years
-
ActiveSupport::Duration.new(self * 365.25.days, [[:years, self]])
-
end
-
2
alias :year :years
-
end
-
2
if RUBY_VERSION < '1.9.2'
-
-
# :stopdoc:
-
class IO
-
def self.binread(name, length = nil, offset = nil)
-
return File.read name unless length || offset
-
File.open(name, 'rb') { |f|
-
f.seek offset if offset
-
f.read length
-
}
-
end
-
end
-
# :startdoc:
-
-
end
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'active_support/core_ext/kernel/agnostics'
-
2
require 'active_support/core_ext/kernel/debugger'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
2
class Object
-
# Makes backticks behave (somewhat more) similarly on all platforms.
-
# On win32 `nonexistent_command` raises Errno::ENOENT; on Unix, the
-
# spawned shell prints a message to stderr and sets $?. We emulate
-
# Unix on the former but not the latter.
-
2
def `(command) #:nodoc:
-
super
-
rescue Errno::ENOENT => e
-
STDERR.puts "#$0: #{e}"
-
end
-
end
-
2
module Kernel
-
2
unless respond_to?(:debugger)
-
# Starts a debugging session if ruby-debug has been loaded (call rails server --debugger to do load it).
-
2
def debugger
-
message = "\n***** Debugger requested, but was not available (ensure ruby-debug is listed in Gemfile/installed as gem): Start server with --debugger to enable *****\n"
-
defined?(Rails) ? Rails.logger.info(message) : $stderr.puts(message)
-
end
-
2
alias breakpoint debugger unless respond_to?(:breakpoint)
-
end
-
end
-
2
require 'rbconfig'
-
2
require 'stringio'
-
-
2
module Kernel
-
# Sets $VERBOSE to nil for the duration of the block and back to its original value afterwards.
-
#
-
# silence_warnings do
-
# value = noisy_call # no warning voiced
-
# end
-
#
-
# noisy_call # warning voiced
-
2
def silence_warnings
-
20
with_warnings(nil) { yield }
-
end
-
-
# Sets $VERBOSE to true for the duration of the block and back to its original value afterwards.
-
2
def enable_warnings
-
with_warnings(true) { yield }
-
end
-
-
# Sets $VERBOSE for the duration of the block and back to its original value afterwards.
-
2
def with_warnings(flag)
-
10
old_verbose, $VERBOSE = $VERBOSE, flag
-
10
yield
-
ensure
-
10
$VERBOSE = old_verbose
-
end
-
-
# For compatibility
-
2
def silence_stderr #:nodoc:
-
silence_stream(STDERR) { yield }
-
end
-
-
# Silences any stream for the duration of the block.
-
#
-
# silence_stream(STDOUT) do
-
# puts 'This will never be seen'
-
# end
-
#
-
# puts 'But this will'
-
2
def silence_stream(stream)
-
old_stream = stream.dup
-
stream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null')
-
stream.sync = true
-
yield
-
ensure
-
stream.reopen(old_stream)
-
end
-
-
# Blocks and ignores any exception passed as argument if raised within the block.
-
#
-
# suppress(ZeroDivisionError) do
-
# 1/0
-
# puts "This code is NOT reached"
-
# end
-
#
-
# puts "This code gets executed and nothing related to ZeroDivisionError was seen"
-
2
def suppress(*exception_classes)
-
begin yield
-
rescue Exception => e
-
raise unless exception_classes.any? { |cls| e.kind_of?(cls) }
-
end
-
end
-
-
# Captures the given stream and returns it:
-
#
-
# stream = capture(:stdout) { puts "Cool" }
-
# stream # => "Cool\n"
-
#
-
2
def capture(stream)
-
begin
-
stream = stream.to_s
-
eval "$#{stream} = StringIO.new"
-
yield
-
result = eval("$#{stream}").string
-
ensure
-
eval("$#{stream} = #{stream.upcase}")
-
end
-
-
result
-
end
-
2
alias :silence :capture
-
-
# Silences both STDOUT and STDERR, even for subprocesses.
-
#
-
# quietly { system 'bundle install' }
-
#
-
2
def quietly
-
silence_stream(STDOUT) do
-
silence_stream(STDERR) do
-
yield
-
end
-
end
-
end
-
end
-
2
module Kernel
-
# Returns the object's singleton class.
-
def singleton_class
-
class << self
-
self
-
end
-
2
end unless respond_to?(:singleton_class) # exists in 1.9.2
-
-
# class_eval on an object acts like singleton_class.class_eval.
-
2
def class_eval(*args, &block)
-
singleton_class.class_eval(*args, &block)
-
end
-
end
-
2
class LoadError
-
2
REGEXPS = [
-
/^no such file to load -- (.+)$/i,
-
/^Missing \w+ (?:file\s*)?([^\s]+.rb)$/i,
-
/^Missing API definition file in (.+)$/i,
-
/^cannot load such file -- (.+)$/i,
-
]
-
-
2
def path
-
@path ||= begin
-
28
REGEXPS.find do |regex|
-
56
message =~ regex
-
end
-
28
$1
-
28
end
-
end
-
-
2
def is_missing?(location)
-
28
location.sub(/\.rb$/, '') == path.sub(/\.rb$/, '')
-
end
-
end
-
-
2
MissingSourceFile = LoadError
-
2
require 'active_support/core_ext/class/attribute_accessors'
-
2
require 'active_support/deprecation'
-
-
# Adds the 'around_level' method to Logger.
-
2
class Logger #:nodoc:
-
2
def self.define_around_helper(level)
-
8
module_eval <<-end_eval, __FILE__, __LINE__ + 1
-
def around_#{level}(before_message, after_message) # def around_debug(before_message, after_message, &block)
-
self.#{level}(before_message) # self.debug(before_message)
-
return_value = yield(self) # return_value = yield(self)
-
self.#{level}(after_message) # self.debug(after_message)
-
return_value # return_value
-
end # end
-
end_eval
-
end
-
10
[:debug, :info, :error, :fatal].each {|level| define_around_helper(level) }
-
end
-
-
2
require 'logger'
-
-
# Extensions to the built-in Ruby logger.
-
#
-
# If you want to use the default log formatter as defined in the Ruby core, then you
-
# will need to set the formatter for the logger as in:
-
#
-
# logger.formatter = Formatter.new
-
#
-
# You can then specify the datetime format, for example:
-
#
-
# logger.datetime_format = "%Y-%m-%d"
-
#
-
# Note: This logger is deprecated in favor of ActiveSupport::BufferedLogger
-
2
class Logger
-
##
-
# :singleton-method:
-
# Set to false to disable the silencer
-
2
cattr_accessor :silencer
-
2
self.silencer = true
-
-
# Silences the logger for the duration of the block.
-
2
def silence(temporary_level = Logger::ERROR)
-
if silencer
-
begin
-
old_logger_level, self.level = level, temporary_level
-
yield self
-
ensure
-
self.level = old_logger_level
-
end
-
else
-
yield self
-
end
-
end
-
2
deprecate :silence
-
-
2
alias :old_datetime_format= :datetime_format=
-
# Logging date-time format (string passed to +strftime+). Ignored if the formatter
-
# does not respond to datetime_format=.
-
2
def datetime_format=(datetime_format)
-
formatter.datetime_format = datetime_format if formatter.respond_to?(:datetime_format=)
-
end
-
-
2
alias :old_datetime_format :datetime_format
-
# Get the logging datetime format. Returns nil if the formatter does not support
-
# datetime formatting.
-
2
def datetime_format
-
formatter.datetime_format if formatter.respond_to?(:datetime_format)
-
end
-
-
2
alias :old_initialize :initialize
-
# Overwrite initialize to set a default formatter.
-
2
def initialize(*args)
-
4
old_initialize(*args)
-
4
self.formatter = SimpleFormatter.new
-
end
-
-
# Simple formatter which only displays the message.
-
2
class SimpleFormatter < Logger::Formatter
-
# This method is invoked when a log event occurs
-
2
def call(severity, timestamp, progname, msg)
-
1999
"#{String === msg ? msg : msg.inspect}\n"
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/aliasing'
-
2
require 'active_support/core_ext/module/introspection'
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'active_support/core_ext/module/reachable'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/module/attr_internal'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/module/synchronization'
-
2
require 'active_support/core_ext/module/deprecation'
-
2
require 'active_support/core_ext/module/remove_method'
-
2
require 'active_support/core_ext/module/method_names'
-
2
require 'active_support/core_ext/module/qualified_const'
-
2
class Module
-
# Encapsulates the common pattern of:
-
#
-
# alias_method :foo_without_feature, :foo
-
# alias_method :foo, :foo_with_feature
-
#
-
# With this, you simply do:
-
#
-
# alias_method_chain :foo, :feature
-
#
-
# And both aliases are set up for you.
-
#
-
# Query and bang methods (foo?, foo!) keep the same punctuation:
-
#
-
# alias_method_chain :foo?, :feature
-
#
-
# is equivalent to
-
#
-
# alias_method :foo_without_feature?, :foo?
-
# alias_method :foo?, :foo_with_feature?
-
#
-
# so you can safely chain foo, foo?, and foo! with the same feature.
-
2
def alias_method_chain(target, feature)
-
# Strip out punctuation on predicates or bang methods since
-
# e.g. target?_without_feature is not a valid method name.
-
34
aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
-
34
yield(aliased_target, punctuation) if block_given?
-
-
34
with_method, without_method = "#{aliased_target}_with_#{feature}#{punctuation}", "#{aliased_target}_without_#{feature}#{punctuation}"
-
-
34
alias_method without_method, target
-
34
alias_method target, with_method
-
-
case
-
when public_method_defined?(without_method)
-
34
public target
-
when protected_method_defined?(without_method)
-
protected target
-
when private_method_defined?(without_method)
-
private target
-
34
end
-
end
-
-
# Allows you to make aliases for attributes, which includes
-
# getter, setter, and query methods.
-
#
-
# Example:
-
#
-
# class Content < ActiveRecord::Base
-
# # has a title attribute
-
# end
-
#
-
# class Email < Content
-
# alias_attribute :subject, :title
-
# end
-
#
-
# e = Email.find(1)
-
# e.title # => "Superstars"
-
# e.subject # => "Superstars"
-
# e.subject? # => true
-
# e.subject = "Megastars"
-
# e.title # => "Megastars"
-
2
def alias_attribute(new_name, old_name)
-
module_eval <<-STR, __FILE__, __LINE__ + 1
-
def #{new_name}; self.#{old_name}; end # def subject; self.title; end
-
def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end
-
def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end
-
STR
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
-
2
class Module
-
# A module may or may not have a name.
-
#
-
# module M; end
-
# M.name # => "M"
-
#
-
# m = Module.new
-
# m.name # => ""
-
#
-
# A module gets a name when it is first assigned to a constant. Either
-
# via the +module+ or +class+ keyword or by an explicit assignment:
-
#
-
# m = Module.new # creates an anonymous module
-
# M = m # => m gets a name here as a side-effect
-
# m.name # => "M"
-
#
-
2
def anonymous?
-
# Uses blank? because the name of an anonymous class is an empty
-
# string in 1.8, and nil in 1.9.
-
229
name.blank?
-
end
-
end
-
2
class Module
-
# Declares an attribute reader backed by an internally-named instance variable.
-
2
def attr_internal_reader(*attrs)
-
44
attrs.each {|attr_name| attr_internal_define(attr_name, :reader)}
-
end
-
-
# Declares an attribute writer backed by an internally-named instance variable.
-
2
def attr_internal_writer(*attrs)
-
56
attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}
-
end
-
-
# Declares an attribute reader and writer backed by an internally-named instance
-
# variable.
-
2
def attr_internal_accessor(*attrs)
-
18
attr_internal_reader(*attrs)
-
18
attr_internal_writer(*attrs)
-
end
-
-
2
alias_method :attr_internal, :attr_internal_accessor
-
-
4
class << self; attr_accessor :attr_internal_naming_format end
-
2
self.attr_internal_naming_format = '@_%s'
-
-
2
private
-
2
def attr_internal_ivar_name(attr)
-
58
Module.attr_internal_naming_format % attr
-
end
-
-
2
def attr_internal_define(attr_name, type)
-
58
internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, '')
-
58
class_eval do # class_eval is necessary on 1.9 or else the methods a made private
-
# use native attr_* methods as they are faster on some Ruby implementations
-
58
send("attr_#{type}", internal_name)
-
end
-
58
attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer
-
58
alias_method attr_name, internal_name
-
58
remove_method internal_name
-
end
-
end
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
class Module
-
2
def mattr_reader(*syms)
-
44
options = syms.extract_options!
-
44
syms.each do |sym|
-
44
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
@@#{sym} = nil unless defined? @@#{sym}
-
-
def self.#{sym}
-
@@#{sym}
-
end
-
EOS
-
-
44
unless options[:instance_reader] == false || options[:instance_accessor] == false
-
44
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}
-
@@#{sym}
-
end
-
EOS
-
end
-
end
-
end
-
-
2
def mattr_writer(*syms)
-
44
options = syms.extract_options!
-
44
syms.each do |sym|
-
44
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def self.#{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
-
44
unless options[:instance_writer] == false || options[:instance_accessor] == false
-
44
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
end
-
end
-
end
-
-
# Extends the module object with module and instance accessors for class attributes,
-
# just like the native attr* accessors for instance attributes.
-
#
-
# module AppConfiguration
-
# mattr_accessor :google_api_key
-
# self.google_api_key = "123456789"
-
#
-
# mattr_accessor :paypal_url
-
# self.paypal_url = "www.sandbox.paypal.com"
-
# end
-
#
-
# AppConfiguration.google_api_key = "overriding the api key!"
-
#
-
# To opt out of the instance writer method, pass :instance_writer => false.
-
# To opt out of the instance reader method, pass :instance_reader => false.
-
# To opt out of both instance methods, pass :instance_accessor => false.
-
2
def mattr_accessor(*syms)
-
44
mattr_reader(*syms)
-
44
mattr_writer(*syms)
-
end
-
end
-
2
class Module
-
# Provides a delegate class method to easily expose contained objects' methods
-
# as your own. Pass one or more methods (specified as symbols or strings)
-
# and the name of the target object via the <tt>:to</tt> option (also a symbol
-
# or string). At least one method and the <tt>:to</tt> option are required.
-
#
-
# Delegation is particularly useful with Active Record associations:
-
#
-
# class Greeter < ActiveRecord::Base
-
# def hello
-
# "hello"
-
# end
-
#
-
# def goodbye
-
# "goodbye"
-
# end
-
# end
-
#
-
# class Foo < ActiveRecord::Base
-
# belongs_to :greeter
-
# delegate :hello, :to => :greeter
-
# end
-
#
-
# Foo.new.hello # => "hello"
-
# Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
-
#
-
# Multiple delegates to the same target are allowed:
-
#
-
# class Foo < ActiveRecord::Base
-
# belongs_to :greeter
-
# delegate :hello, :goodbye, :to => :greeter
-
# end
-
#
-
# Foo.new.goodbye # => "goodbye"
-
#
-
# Methods can be delegated to instance variables, class variables, or constants
-
# by providing them as a symbols:
-
#
-
# class Foo
-
# CONSTANT_ARRAY = [0,1,2,3]
-
# @@class_array = [4,5,6,7]
-
#
-
# def initialize
-
# @instance_array = [8,9,10,11]
-
# end
-
# delegate :sum, :to => :CONSTANT_ARRAY
-
# delegate :min, :to => :@@class_array
-
# delegate :max, :to => :@instance_array
-
# end
-
#
-
# Foo.new.sum # => 6
-
# Foo.new.min # => 4
-
# Foo.new.max # => 11
-
#
-
# Delegates can optionally be prefixed using the <tt>:prefix</tt> option. If the value
-
# is <tt>true</tt>, the delegate methods are prefixed with the name of the object being
-
# delegated to.
-
#
-
# Person = Struct.new(:name, :address)
-
#
-
# class Invoice < Struct.new(:client)
-
# delegate :name, :address, :to => :client, :prefix => true
-
# end
-
#
-
# john_doe = Person.new("John Doe", "Vimmersvej 13")
-
# invoice = Invoice.new(john_doe)
-
# invoice.client_name # => "John Doe"
-
# invoice.client_address # => "Vimmersvej 13"
-
#
-
# It is also possible to supply a custom prefix.
-
#
-
# class Invoice < Struct.new(:client)
-
# delegate :name, :address, :to => :client, :prefix => :customer
-
# end
-
#
-
# invoice = Invoice.new(john_doe)
-
# invoice.customer_name # => "John Doe"
-
# invoice.customer_address # => "Vimmersvej 13"
-
#
-
# If the delegate object is +nil+ an exception is raised, and that happens
-
# no matter whether +nil+ responds to the delegated method. You can get a
-
# +nil+ instead with the +:allow_nil+ option.
-
#
-
# class Foo
-
# attr_accessor :bar
-
# def initialize(bar = nil)
-
# @bar = bar
-
# end
-
# delegate :zoo, :to => :bar
-
# end
-
#
-
# Foo.new.zoo # raises NoMethodError exception (you called nil.zoo)
-
#
-
# class Foo
-
# attr_accessor :bar
-
# def initialize(bar = nil)
-
# @bar = bar
-
# end
-
# delegate :zoo, :to => :bar, :allow_nil => true
-
# end
-
#
-
# Foo.new.zoo # returns nil
-
#
-
2
def delegate(*methods)
-
108
options = methods.pop
-
108
unless options.is_a?(Hash) && to = options[:to]
-
raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)."
-
end
-
108
prefix, to, allow_nil = options[:prefix], options[:to], options[:allow_nil]
-
-
108
if prefix == true && to.to_s =~ /^[^a-z_]/
-
raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method."
-
end
-
-
108
method_prefix =
-
if prefix
-
"#{prefix == true ? to : prefix}_"
-
else
-
108
''
-
end
-
-
108
file, line = caller.first.split(':', 2)
-
108
line = line.to_i
-
-
108
methods.each do |method|
-
404
method = method.to_s
-
-
404
if allow_nil
-
14
module_eval(<<-EOS, file, line - 2)
-
def #{method_prefix}#{method}(*args, &block) # def customer_name(*args, &block)
-
if #{to} || #{to}.respond_to?(:#{method}) # if client || client.respond_to?(:name)
-
#{to}.__send__(:#{method}, *args, &block) # client.__send__(:name, *args, &block)
-
end # end
-
end # end
-
EOS
-
else
-
390
exception = %(raise "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
-
-
390
module_eval(<<-EOS, file, line - 1)
-
def #{method_prefix}#{method}(*args, &block) # def customer_name(*args, &block)
-
#{to}.__send__(:#{method}, *args, &block) # client.__send__(:name, *args, &block)
-
rescue NoMethodError # rescue NoMethodError
-
if #{to}.nil? # if client.nil?
-
#{exception} # # add helpful message to the exception
-
else # else
-
raise # raise
-
end # end
-
end # end
-
EOS
-
end
-
end
-
end
-
end
-
2
class Module
-
# Declare that a method has been deprecated.
-
# deprecate :foo
-
# deprecate :bar => 'message'
-
# deprecate :foo, :bar, :baz => 'warning!', :qux => 'gone!'
-
2
def deprecate(*method_names)
-
28
ActiveSupport::Deprecation.deprecate_methods(self, *method_names)
-
end
-
end
-
2
require 'active_support/inflector'
-
-
2
class Module
-
# Returns the name of the module containing this one.
-
#
-
# M::N.parent_name # => "M"
-
2
def parent_name
-
229
unless defined? @parent_name
-
67
@parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil
-
end
-
229
@parent_name
-
end
-
-
# Returns the module which contains this one according to its name.
-
#
-
# module M
-
# module N
-
# end
-
# end
-
# X = M::N
-
#
-
# M::N.parent # => M
-
# X.parent # => M
-
#
-
# The parent of top-level and anonymous modules is Object.
-
#
-
# M.parent # => Object
-
# Module.new.parent # => Object
-
#
-
2
def parent
-
98
parent_name ? ActiveSupport::Inflector.constantize(parent_name) : Object
-
end
-
-
# Returns all the parents of this module according to its name, ordered from
-
# nested outwards. The receiver is not contained within the result.
-
#
-
# module M
-
# module N
-
# end
-
# end
-
# X = M::N
-
#
-
# M.parents # => [Object]
-
# M::N.parents # => [M, Object]
-
# X.parents # => [M, Object]
-
#
-
2
def parents
-
115
parents = []
-
115
if parent_name
-
9
parts = parent_name.split('::')
-
9
until parts.empty?
-
17
parents << ActiveSupport::Inflector.constantize(parts * '::')
-
17
parts.pop
-
end
-
end
-
115
parents << Object unless parents.include? Object
-
115
parents
-
end
-
-
2
if RUBY_VERSION < '1.9'
-
# Returns the constants that have been defined locally by this object and
-
# not in an ancestor. This method is exact if running under Ruby 1.9. In
-
# previous versions it may miss some constants if their definition in some
-
# ancestor is identical to their definition in the receiver.
-
def local_constants
-
inherited = {}
-
-
ancestors.each do |anc|
-
next if anc == self
-
anc.constants.each { |const| inherited[const] = anc.const_get(const) }
-
end
-
-
constants.select do |const|
-
!inherited.key?(const) || inherited[const].object_id != const_get(const).object_id
-
end
-
end
-
else
-
2
def local_constants #:nodoc:
-
constants(false)
-
end
-
end
-
-
# Returns the names of the constants defined locally rather than the
-
# constants themselves. See <tt>local_constants</tt>.
-
2
def local_constant_names
-
local_constants.map { |c| c.to_s }
-
end
-
end
-
2
class Module
-
2
if instance_methods[0].is_a?(Symbol)
-
2
def instance_method_names(*args)
-
2
instance_methods(*args).map(&:to_s)
-
end
-
-
2
def method_names(*args)
-
methods(*args).map(&:to_s)
-
end
-
else
-
alias_method :instance_method_names, :instance_methods
-
alias_method :method_names, :methods
-
end
-
end
-
2
require 'active_support/core_ext/string/inflections'
-
-
#--
-
# Allows code reuse in the methods below without polluting Module.
-
#++
-
2
module QualifiedConstUtils
-
2
def self.raise_if_absolute(path)
-
98
raise NameError, "wrong constant name #$&" if path =~ /\A::[^:]+/
-
end
-
-
2
def self.names(path)
-
98
path.split('::')
-
end
-
end
-
-
##
-
# Extends the API for constants to be able to deal with qualified names. Arguments
-
# are assumed to be relative to the receiver.
-
#
-
#--
-
# Qualified names are required to be relative because we are extending existing
-
# methods that expect constant names, ie, relative paths of length 1. For example,
-
# Object.const_get("::String") raises NameError and so does qualified_const_get.
-
#++
-
2
class Module
-
2
if method(:const_defined?).arity == 1
-
def qualified_const_defined?(path)
-
QualifiedConstUtils.raise_if_absolute(path)
-
-
QualifiedConstUtils.names(path).inject(self) do |mod, name|
-
return unless mod.const_defined?(name)
-
mod.const_get(name)
-
end
-
return true
-
end
-
else
-
2
def qualified_const_defined?(path, search_parents=true)
-
98
QualifiedConstUtils.raise_if_absolute(path)
-
-
98
QualifiedConstUtils.names(path).inject(self) do |mod, name|
-
111
return unless mod.const_defined?(name, search_parents)
-
111
mod.const_get(name)
-
end
-
98
return true
-
end
-
end
-
-
2
def qualified_const_get(path)
-
QualifiedConstUtils.raise_if_absolute(path)
-
-
QualifiedConstUtils.names(path).inject(self) do |mod, name|
-
mod.const_get(name)
-
end
-
end
-
-
2
def qualified_const_set(path, value)
-
QualifiedConstUtils.raise_if_absolute(path)
-
-
const_name = path.demodulize
-
mod_name = path.deconstantize
-
mod = mod_name.empty? ? self : qualified_const_get(mod_name)
-
mod.const_set(const_name, value)
-
end
-
end
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'active_support/core_ext/string/inflections'
-
-
2
class Module
-
2
def reachable? #:nodoc:
-
!anonymous? && name.safe_constantize.equal?(self)
-
end
-
end
-
2
class Module
-
2
def remove_possible_method(method)
-
2067
if method_defined?(method) || private_method_defined?(method)
-
1053
remove_method(method)
-
end
-
rescue NameError
-
# If the requested method is defined on a superclass or included module,
-
# method_defined? returns true but remove_method throws a NameError.
-
# Ignore this.
-
end
-
-
2
def redefine_method(method, &block)
-
318
remove_possible_method(method)
-
318
define_method(method, &block)
-
end
-
end
-
2
require 'thread'
-
2
require 'active_support/core_ext/module/aliasing'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/module/deprecation'
-
-
2
class Module
-
# Synchronize access around a method, delegating synchronization to a
-
# particular mutex. A mutex (either a Mutex, or any object that responds to
-
# #synchronize and yields to a block) must be provided as a final :with option.
-
# The :with option should be a symbol or string, and can represent a method,
-
# constant, or instance or class variable.
-
# Example:
-
# class SharedCache
-
# @@lock = Mutex.new
-
# def expire
-
# ...
-
# end
-
# synchronize :expire, :with => :@@lock
-
# end
-
2
def synchronize(*methods)
-
options = methods.extract_options!
-
unless options.is_a?(Hash) && with = options[:with]
-
raise ArgumentError, "Synchronization needs a mutex. Supply an options hash with a :with key as the last argument (e.g. synchronize :hello, :with => :@mutex)."
-
end
-
-
methods.each do |method|
-
aliased_method, punctuation = method.to_s.sub(/([?!=])$/, ''), $1
-
-
if method_defined?("#{aliased_method}_without_synchronization#{punctuation}")
-
raise ArgumentError, "#{method} is already synchronized. Double synchronization is not currently supported."
-
end
-
-
module_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{aliased_method}_with_synchronization#{punctuation}(*args, &block) # def expire_with_synchronization(*args, &block)
-
#{with}.synchronize do # @@lock.synchronize do
-
#{aliased_method}_without_synchronization#{punctuation}(*args, &block) # expire_without_synchronization(*args, &block)
-
end # end
-
end # end
-
EOS
-
-
alias_method_chain method, :synchronization
-
end
-
end
-
2
deprecate :synchronize
-
end
-
2
class NameError
-
# Extract the name of the missing constant from the exception message.
-
2
def missing_name
-
if /undefined local variable or method/ !~ message
-
$1 if /((::)?([A-Z]\w*)(::[A-Z]\w*)*)$/ =~ message
-
end
-
end
-
-
# Was this exception raised because the given name was missing?
-
2
def missing_name?(name)
-
if name.is_a? Symbol
-
last_name = (missing_name || '').split('::').last
-
last_name == name.to_s
-
else
-
missing_name == name.to_s
-
end
-
end
-
end
-
2
require 'active_support/core_ext/numeric/bytes'
-
2
require 'active_support/core_ext/numeric/time'
-
2
class Numeric
-
2
KILOBYTE = 1024
-
2
MEGABYTE = KILOBYTE * 1024
-
2
GIGABYTE = MEGABYTE * 1024
-
2
TERABYTE = GIGABYTE * 1024
-
2
PETABYTE = TERABYTE * 1024
-
2
EXABYTE = PETABYTE * 1024
-
-
# Enables the use of byte calculations and declarations, like 45.bytes + 2.6.megabytes
-
2
def bytes
-
self
-
end
-
2
alias :byte :bytes
-
-
2
def kilobytes
-
2
self * KILOBYTE
-
end
-
2
alias :kilobyte :kilobytes
-
-
2
def megabytes
-
self * MEGABYTE
-
end
-
2
alias :megabyte :megabytes
-
-
2
def gigabytes
-
self * GIGABYTE
-
end
-
2
alias :gigabyte :gigabytes
-
-
2
def terabytes
-
self * TERABYTE
-
end
-
2
alias :terabyte :terabytes
-
-
2
def petabytes
-
self * PETABYTE
-
end
-
2
alias :petabyte :petabytes
-
-
2
def exabytes
-
self * EXABYTE
-
end
-
2
alias :exabyte :exabytes
-
end
-
2
require 'active_support/duration'
-
2
require 'active_support/core_ext/time/calculations'
-
2
require 'active_support/core_ext/time/acts_like'
-
-
2
class Numeric
-
# Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years.
-
#
-
# These methods use Time#advance for precise date calculations when using from_now, ago, etc.
-
# as well as adding or subtracting their results from a Time object. For example:
-
#
-
# # equivalent to Time.now.advance(:months => 1)
-
# 1.month.from_now
-
#
-
# # equivalent to Time.now.advance(:years => 2)
-
# 2.years.from_now
-
#
-
# # equivalent to Time.now.advance(:months => 4, :years => 5)
-
# (4.months + 5.years).from_now
-
#
-
# While these methods provide precise calculation when used as in the examples above, care
-
# should be taken to note that this is not true if the result of `months', `years', etc is
-
# converted before use:
-
#
-
# # equivalent to 30.days.to_i.from_now
-
# 1.month.to_i.from_now
-
#
-
# # equivalent to 365.25.days.to_f.from_now
-
# 1.year.to_f.from_now
-
#
-
# In such cases, Ruby's core
-
# Date[http://stdlib.rubyonrails.org/libdoc/date/rdoc/index.html] and
-
# Time[http://stdlib.rubyonrails.org/libdoc/time/rdoc/index.html] should be used for precision
-
# date and time arithmetic
-
2
def seconds
-
64
ActiveSupport::Duration.new(self, [[:seconds, self]])
-
end
-
2
alias :second :seconds
-
-
2
def minutes
-
250
ActiveSupport::Duration.new(self * 60, [[:seconds, self * 60]])
-
end
-
2
alias :minute :minutes
-
-
2
def hours
-
475
ActiveSupport::Duration.new(self * 3600, [[:seconds, self * 3600]])
-
end
-
2
alias :hour :hours
-
-
2
def days
-
428
ActiveSupport::Duration.new(self * 24.hours, [[:days, self]])
-
end
-
2
alias :day :days
-
-
2
def weeks
-
66
ActiveSupport::Duration.new(self * 7.days, [[:days, self * 7]])
-
end
-
2
alias :week :weeks
-
-
2
def fortnights
-
ActiveSupport::Duration.new(self * 2.weeks, [[:days, self * 14]])
-
end
-
2
alias :fortnight :fortnights
-
-
# Reads best without arguments: 10.minutes.ago
-
2
def ago(time = ::Time.current)
-
time - self
-
end
-
-
# Reads best with argument: 10.minutes.until(time)
-
2
alias :until :ago
-
-
# Reads best with argument: 10.minutes.since(time)
-
2
def since(time = ::Time.current)
-
time + self
-
end
-
-
# Reads best without arguments: 10.minutes.from_now
-
2
alias :from_now :since
-
end
-
2
require 'active_support/core_ext/object/acts_like'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/object/duplicable'
-
2
require 'active_support/core_ext/object/try'
-
2
require 'active_support/core_ext/object/inclusion'
-
-
2
require 'active_support/core_ext/object/conversions'
-
2
require 'active_support/core_ext/object/instance_variables'
-
-
2
require 'active_support/core_ext/object/to_json'
-
2
require 'active_support/core_ext/object/to_param'
-
2
require 'active_support/core_ext/object/to_query'
-
2
require 'active_support/core_ext/object/with_options'
-
2
class Object
-
# A duck-type assistant method. For example, Active Support extends Date
-
# to define an acts_like_date? method, and extends Time to define
-
# acts_like_time?. As a result, we can do "x.acts_like?(:time)" and
-
# "x.acts_like?(:date)" to do duck-type-safe comparisons, since classes that
-
# we want to act like Time simply need to define an acts_like_time? method.
-
2
def acts_like?(duck)
-
7740
respond_to? :"acts_like_#{duck}?"
-
end
-
end
-
# encoding: utf-8
-
2
require 'active_support/core_ext/string/encoding'
-
-
2
class Object
-
# An object is blank if it's false, empty, or a whitespace string.
-
# For example, "", " ", +nil+, [], and {} are all blank.
-
#
-
# This simplifies:
-
#
-
# if address.nil? || address.empty?
-
#
-
# ...to:
-
#
-
# if address.blank?
-
2
def blank?
-
1899
respond_to?(:empty?) ? empty? : !self
-
end
-
-
# An object is present if it's not <tt>blank?</tt>.
-
2
def present?
-
2903
!blank?
-
end
-
-
# Returns object if it's <tt>present?</tt> otherwise returns +nil+.
-
# <tt>object.presence</tt> is equivalent to <tt>object.present? ? object : nil</tt>.
-
#
-
# This is handy for any representation of objects where blank is the same
-
# as not present at all. For example, this simplifies a common check for
-
# HTTP POST/query parameters:
-
#
-
# state = params[:state] if params[:state].present?
-
# country = params[:country] if params[:country].present?
-
# region = state || country || 'US'
-
#
-
# ...becomes:
-
#
-
# region = params[:state].presence || params[:country].presence || 'US'
-
2
def presence
-
519
self if present?
-
end
-
end
-
-
2
class NilClass
-
# +nil+ is blank:
-
#
-
# nil.blank? # => true
-
#
-
2
def blank?
-
1969
true
-
end
-
end
-
-
2
class FalseClass
-
# +false+ is blank:
-
#
-
# false.blank? # => true
-
#
-
2
def blank?
-
true
-
end
-
end
-
-
2
class TrueClass
-
# +true+ is not blank:
-
#
-
# true.blank? # => false
-
#
-
2
def blank?
-
8
false
-
end
-
end
-
-
2
class Array
-
# An array is blank if it's empty:
-
#
-
# [].blank? # => true
-
# [1,2,3].blank? # => false
-
#
-
2
alias_method :blank?, :empty?
-
end
-
-
2
class Hash
-
# A hash is blank if it's empty:
-
#
-
# {}.blank? # => true
-
# {:key => 'value'}.blank? # => false
-
#
-
2
alias_method :blank?, :empty?
-
end
-
-
2
class String
-
# 0x3000: fullwidth whitespace
-
2
NON_WHITESPACE_REGEXP = %r![^\s#{[0x3000].pack("U")}]!
-
-
# A string is blank if it's empty or contains whitespaces only:
-
#
-
# "".blank? # => true
-
# " ".blank? # => true
-
# " ".blank? # => true
-
# " something here ".blank? # => false
-
#
-
2
def blank?
-
# 1.8 does not takes [:space:] properly
-
2659
if encoding_aware?
-
2659
self !~ /[^[:space:]]/
-
else
-
self !~ NON_WHITESPACE_REGEXP
-
end
-
end
-
end
-
-
2
class Numeric #:nodoc:
-
# No number is blank:
-
#
-
# 1.blank? # => false
-
# 0.blank? # => false
-
#
-
2
def blank?
-
659
false
-
end
-
end
-
2
require 'active_support/core_ext/object/to_param'
-
2
require 'active_support/core_ext/object/to_query'
-
2
require 'active_support/core_ext/array/conversions'
-
2
require 'active_support/core_ext/hash/conversions'
-
#--
-
# Most objects are cloneable, but not all. For example you can't dup +nil+:
-
#
-
# nil.dup # => TypeError: can't dup NilClass
-
#
-
# Classes may signal their instances are not duplicable removing +dup+/+clone+
-
# or raising exceptions from them. So, to dup an arbitrary object you normally
-
# use an optimistic approach and are ready to catch an exception, say:
-
#
-
# arbitrary_object.dup rescue object
-
#
-
# Rails dups objects in a few critical spots where they are not that arbitrary.
-
# That rescue is very expensive (like 40 times slower than a predicate), and it
-
# is often triggered.
-
#
-
# That's why we hardcode the following cases and check duplicable? instead of
-
# using that rescue idiom.
-
#++
-
2
class Object
-
# Can you safely dup this object?
-
#
-
# False for +nil+, +false+, +true+, symbols, numbers, class and module objects;
-
# true otherwise.
-
2
def duplicable?
-
636
true
-
end
-
end
-
-
2
class NilClass
-
# +nil+ is not duplicable:
-
#
-
# nil.duplicable? # => false
-
# nil.dup # => TypeError: can't dup NilClass
-
#
-
2
def duplicable?
-
7525
false
-
end
-
end
-
-
2
class FalseClass
-
# +false+ is not duplicable:
-
#
-
# false.duplicable? # => false
-
# false.dup # => TypeError: can't dup FalseClass
-
#
-
2
def duplicable?
-
22
false
-
end
-
end
-
-
2
class TrueClass
-
# +true+ is not duplicable:
-
#
-
# true.duplicable? # => false
-
# true.dup # => TypeError: can't dup TrueClass
-
#
-
2
def duplicable?
-
false
-
end
-
end
-
-
2
class Symbol
-
# Symbols are not duplicable:
-
#
-
# :my_symbol.duplicable? # => false
-
# :my_symbol.dup # => TypeError: can't dup Symbol
-
#
-
2
def duplicable?
-
false
-
end
-
end
-
-
2
class Numeric
-
# Numbers are not duplicable:
-
#
-
# 3.duplicable? # => false
-
# 3.dup # => TypeError: can't dup Fixnum
-
#
-
2
def duplicable?
-
7
false
-
end
-
end
-
-
2
class Class
-
# Classes are not duplicable:
-
#
-
# c = Class.new # => #<Class:0x10328fd80>
-
# c.dup # => #<Class:0x10328fd80>
-
#
-
# Note +dup+ returned the same class object.
-
2
def duplicable?
-
false
-
end
-
end
-
-
2
class Module
-
# Modules are not duplicable:
-
#
-
# m = Module.new # => #<Module:0x10328b6e0>
-
# m.dup # => #<Module:0x10328b6e0>
-
#
-
# Note +dup+ returned the same module object.
-
2
def duplicable?
-
false
-
end
-
end
-
-
2
require 'bigdecimal'
-
2
class BigDecimal
-
2
begin
-
2
BigDecimal.new('4.56').dup
-
-
def duplicable?
-
true
-
end
-
rescue TypeError
-
# can't dup, so use superclass implementation
-
end
-
end
-
2
class Object
-
# Returns true if this object is included in the argument(s). Argument must be
-
# any object which responds to +#include?+ or optionally, multiple arguments can be passed in. Usage:
-
#
-
# characters = ["Konata", "Kagami", "Tsukasa"]
-
# "Konata".in?(characters) # => true
-
#
-
# character = "Konata"
-
# character.in?("Konata", "Kagami", "Tsukasa") # => true
-
#
-
# This will throw an ArgumentError if a single argument is passed in and it doesn't respond
-
# to +#include?+.
-
2
def in?(*args)
-
1800
if args.length > 1
-
args.include? self
-
else
-
1800
another_object = args.first
-
1800
if another_object.respond_to? :include?
-
1800
another_object.include? self
-
else
-
raise ArgumentError.new("The single parameter passed to #in? must respond to #include?")
-
end
-
end
-
end
-
end
-
2
class Object
-
# Returns a hash that maps instance variable names without "@" to their
-
# corresponding values. Keys are strings both in Ruby 1.8 and 1.9.
-
#
-
# class C
-
# def initialize(x, y)
-
# @x, @y = x, y
-
# end
-
# end
-
#
-
# C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
-
2
def instance_values #:nodoc:
-
Hash[instance_variables.map { |name| [name.to_s[1..-1], instance_variable_get(name)] }]
-
end
-
-
# Returns an array of instance variable names including "@". They are strings
-
# both in Ruby 1.8 and 1.9.
-
#
-
# class C
-
# def initialize(x, y)
-
# @x, @y = x, y
-
# end
-
# end
-
#
-
# C.new(0, 1).instance_variable_names # => ["@y", "@x"]
-
2
if RUBY_VERSION >= '1.9'
-
2
def instance_variable_names
-
1628
instance_variables.map { |var| var.to_s }
-
end
-
else
-
alias_method :instance_variable_names, :instance_variables
-
end
-
end
-
# Hack to load json gem first so we can overwrite its to_json.
-
2
begin
-
2
require 'json'
-
rescue LoadError
-
end
-
-
# The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting
-
# their default behavior. That said, we need to define the basic to_json method in all of them,
-
# otherwise they will always use to_json gem implementation, which is backwards incompatible in
-
# several cases (for instance, the JSON implementation for Hash does not work) with inheritance
-
# and consequently classes as ActiveSupport::OrderedHash cannot be serialized to json.
-
2
[Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].each do |klass|
-
18
klass.class_eval do
-
# Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info.
-
18
def to_json(options = nil)
-
ActiveSupport::JSON.encode(self, options)
-
end
-
end
-
end
-
2
class Object
-
# Alias of <tt>to_s</tt>.
-
2
def to_param
-
38
to_s
-
end
-
end
-
-
2
class NilClass
-
2
def to_param
-
21
self
-
end
-
end
-
-
2
class TrueClass
-
2
def to_param
-
self
-
end
-
end
-
-
2
class FalseClass
-
2
def to_param
-
14
self
-
end
-
end
-
-
2
class Array
-
# Calls <tt>to_param</tt> on all its elements and joins the result with
-
# slashes. This is used by <tt>url_for</tt> in Action Pack.
-
2
def to_param
-
collect { |e| e.to_param }.join '/'
-
end
-
end
-
-
2
class Hash
-
# Returns a string representation of the receiver suitable for use as a URL
-
# query string:
-
#
-
# {:name => 'David', :nationality => 'Danish'}.to_param
-
# # => "name=David&nationality=Danish"
-
#
-
# An optional namespace can be passed to enclose the param names:
-
#
-
# {:name => 'David', :nationality => 'Danish'}.to_param('user')
-
# # => "user[name]=David&user[nationality]=Danish"
-
#
-
# The string pairs "key=value" that conform the query string
-
# are sorted lexicographically in ascending order.
-
#
-
# This method is also aliased as +to_query+.
-
2
def to_param(namespace = nil)
-
collect do |key, value|
-
4
value.to_query(namespace ? "#{namespace}[#{key}]" : key)
-
17
end.sort * '&'
-
end
-
end
-
2
require 'active_support/core_ext/object/to_param'
-
-
2
class Object
-
# Converts an object into a string suitable for use as a URL query string, using the given <tt>key</tt> as the
-
# param name.
-
#
-
# Note: This method is defined as a default implementation for all Objects for Hash#to_query to work.
-
2
def to_query(key)
-
require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
-
"#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
-
end
-
end
-
-
2
class Array
-
# Converts an array into a string suitable for use as a URL query string,
-
# using the given +key+ as the param name.
-
#
-
# ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding"
-
2
def to_query(key)
-
prefix = "#{key}[]"
-
collect { |value| value.to_query(prefix) }.join '&'
-
end
-
end
-
-
2
class Hash
-
2
alias_method :to_query, :to_param
-
end
-
2
class Object
-
# Invokes the method identified by the symbol +method+, passing it any arguments
-
# and/or the block specified, just like the regular Ruby <tt>Object#send</tt> does.
-
#
-
# *Unlike* that method however, a +NoMethodError+ exception will *not* be raised
-
# and +nil+ will be returned instead, if the receiving object is a +nil+ object or NilClass.
-
#
-
# If try is called without a method to call, it will yield any given block with the object.
-
#
-
# Please also note that +try+ is defined on +Object+, therefore it won't work with
-
# subclasses of +BasicObject+. For example, using try with +SimpleDelegator+ will
-
# delegate +try+ to target instead of calling it on delegator itself.
-
#
-
# ==== Examples
-
#
-
# Without +try+
-
# @person && @person.name
-
# or
-
# @person ? @person.name : nil
-
#
-
# With +try+
-
# @person.try(:name)
-
#
-
# +try+ also accepts arguments and/or a block, for the method it is trying
-
# Person.try(:find, 1)
-
# @people.try(:collect) {|p| p.name}
-
#
-
# Without a method argument try will yield to the block unless the receiver is nil.
-
# @person.try { |p| "#{p.first_name} #{p.last_name}" }
-
#--
-
# +try+ behaves like +Object#send+, unless called on +NilClass+.
-
2
def try(*a, &b)
-
13
if a.empty? && block_given?
-
yield self
-
else
-
13
__send__(*a, &b)
-
end
-
end
-
end
-
-
2
class NilClass
-
# Calling +try+ on +nil+ always returns +nil+.
-
# It becomes specially helpful when navigating through associations that may return +nil+.
-
#
-
# === Examples
-
#
-
# nil.try(:name) # => nil
-
#
-
# Without +try+
-
# @person && !@person.children.blank? && @person.children.first.name
-
#
-
# With +try+
-
# @person.try(:children).try(:first).try(:name)
-
2
def try(*args)
-
nil
-
end
-
end
-
2
require 'active_support/option_merger'
-
-
2
class Object
-
# An elegant way to factor duplication out of options passed to a series of
-
# method calls. Each method called in the block, with the block variable as
-
# the receiver, will have its options merged with the default +options+ hash
-
# provided. Each method called on the block variable must take an options
-
# hash as its final argument.
-
#
-
# Without <tt>with_options></tt>, this code contains duplication:
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :customers, :dependent => :destroy
-
# has_many :products, :dependent => :destroy
-
# has_many :invoices, :dependent => :destroy
-
# has_many :expenses, :dependent => :destroy
-
# end
-
#
-
# Using <tt>with_options</tt>, we can remove the duplication:
-
#
-
# class Account < ActiveRecord::Base
-
# with_options :dependent => :destroy do |assoc|
-
# assoc.has_many :customers
-
# assoc.has_many :products
-
# assoc.has_many :invoices
-
# assoc.has_many :expenses
-
# end
-
# end
-
#
-
# It can also be used with an explicit receiver:
-
#
-
# I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
-
# subject i18n.t :subject
-
# body i18n.t :body, :user_name => user.name
-
# end
-
#
-
# <tt>with_options</tt> can also be nested since the call is forwarded to its receiver.
-
# Each nesting level will merge inherited defaults in addition to their own.
-
#
-
2
def with_options(options)
-
yield ActiveSupport::OptionMerger.new(self, options)
-
end
-
end
-
2
require "active_support/core_ext/kernel/singleton_class"
-
-
2
class Proc #:nodoc:
-
2
def bind(object)
-
block, time = self, Time.now
-
object.class_eval do
-
method_name = "__bind_#{time.to_i}_#{time.usec}"
-
define_method(method_name, &block)
-
method = instance_method(method_name)
-
remove_method(method_name)
-
method
-
end.bind(object)
-
end
-
end
-
2
require 'active_support/core_ext/process/daemon'
-
2
module Process
-
def self.daemon(nochdir = nil, noclose = nil)
-
exit if fork # Parent exits, child continues.
-
Process.setsid # Become session leader.
-
exit if fork # Zap session leader. See [1].
-
-
unless nochdir
-
Dir.chdir "/" # Release old working directory.
-
end
-
-
File.umask 0000 # Ensure sensible umask. Adjust as needed.
-
-
unless noclose
-
STDIN.reopen "/dev/null" # Free file descriptors and
-
STDOUT.reopen "/dev/null", "a" # point them somewhere sensible.
-
STDERR.reopen '/dev/null', 'a'
-
end
-
-
trap("TERM") { exit }
-
-
return 0
-
2
end unless respond_to?(:daemon)
-
end
-
2
require 'active_support/core_ext/range/blockless_step'
-
2
require 'active_support/core_ext/range/conversions'
-
2
require 'active_support/core_ext/range/include_range'
-
2
require 'active_support/core_ext/range/overlaps'
-
2
require 'active_support/core_ext/range/cover'
-
2
require 'active_support/core_ext/module/aliasing'
-
-
2
class Range
-
2
begin
-
2
(1..2).step
-
# Range#step doesn't return an Enumerator
-
rescue LocalJumpError
-
# Return an array when step is called without a block.
-
def step_with_blockless(*args, &block)
-
if block_given?
-
step_without_blockless(*args, &block)
-
else
-
array = []
-
step_without_blockless(*args) { |step| array << step }
-
array
-
end
-
end
-
else
-
2
def step_with_blockless(*args, &block) #:nodoc:
-
if block_given?
-
step_without_blockless(*args, &block)
-
else
-
step_without_blockless(*args).to_a
-
end
-
end
-
end
-
-
2
alias_method_chain :step, :blockless
-
end
-
2
class Range
-
2
RANGE_FORMATS = {
-
:db => Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" }
-
}
-
-
# Gives a human readable format of the range.
-
#
-
# ==== Example
-
#
-
# (1..100).to_formatted_s # => "1..100"
-
2
def to_formatted_s(format = :default)
-
if formatter = RANGE_FORMATS[format]
-
formatter.call(first, last)
-
else
-
to_default_s
-
end
-
end
-
-
2
alias_method :to_default_s, :to_s
-
2
alias_method :to_s, :to_formatted_s
-
end
-
2
class Range
-
2
alias_method(:cover?, :include?) unless instance_methods.include?(:cover?)
-
end
-
2
class Range
-
# Extends the default Range#include? to support range comparisons.
-
# (1..5).include?(1..5) # => true
-
# (1..5).include?(2..3) # => true
-
# (1..5).include?(2..6) # => false
-
#
-
# The native Range#include? behavior is untouched.
-
# ("a".."f").include?("c") # => true
-
# (5..9).include?(11) # => false
-
2
def include_with_range?(value)
-
16
if value.is_a?(::Range)
-
# 1...10 includes 1..9 but it does not include 1..10.
-
operator = exclude_end? && !value.exclude_end? ? :< : :<=
-
include_without_range?(value.first) && value.last.send(operator, last)
-
else
-
16
include_without_range?(value)
-
end
-
end
-
-
2
alias_method_chain :include?, :range
-
end
-
2
class Range
-
# Compare two ranges and see if they overlap each other
-
# (1..5).overlaps?(4..6) # => true
-
# (1..5).overlaps?(7..9) # => false
-
2
def overlaps?(other)
-
include?(other.first) || other.include?(first)
-
end
-
end
-
2
class Regexp #:nodoc:
-
2
def multiline?
-
options & MULTILINE == MULTILINE
-
end
-
end
-
2
require 'active_support/core_ext/kernel/reporting'
-
-
# Fixes the rexml vulnerability disclosed at:
-
# http://www.ruby-lang.org/en/news/2008/08/23/dos-vulnerability-in-rexml/
-
# This fix is identical to rexml-expansion-fix version 1.0.1.
-
#
-
# We still need to distribute this fix because albeit the REXML
-
# in recent 1.8.7s is patched, it wasn't in early patchlevels.
-
2
require 'rexml/rexml'
-
-
# Earlier versions of rexml defined REXML::Version, newer ones REXML::VERSION
-
2
unless (defined?(REXML::VERSION) ? REXML::VERSION : REXML::Version) > "3.1.7.2"
-
silence_warnings { require 'rexml/document' }
-
-
# REXML in 1.8.7 has the patch but early patchlevels didn't update Version from 3.1.7.2.
-
unless REXML::Document.respond_to?(:entity_expansion_limit=)
-
silence_warnings { require 'rexml/entity' }
-
-
module REXML #:nodoc:
-
class Entity < Child #:nodoc:
-
undef_method :unnormalized
-
def unnormalized
-
document.record_entity_expansion! if document
-
v = value()
-
return nil if v.nil?
-
@unnormalized = Text::unnormalize(v, parent)
-
@unnormalized
-
end
-
end
-
class Document < Element #:nodoc:
-
@@entity_expansion_limit = 10_000
-
def self.entity_expansion_limit= val
-
@@entity_expansion_limit = val
-
end
-
-
def record_entity_expansion!
-
@number_of_expansions ||= 0
-
@number_of_expansions += 1
-
if @number_of_expansions > @@entity_expansion_limit
-
raise "Number of entity expansions exceeded, processing aborted."
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/string/conversions'
-
2
require 'active_support/core_ext/string/filters'
-
2
require 'active_support/core_ext/string/multibyte'
-
2
require 'active_support/core_ext/string/starts_ends_with'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/core_ext/string/access'
-
2
require 'active_support/core_ext/string/xchar'
-
2
require 'active_support/core_ext/string/behavior'
-
2
require 'active_support/core_ext/string/interpolation'
-
2
require 'active_support/core_ext/string/output_safety'
-
2
require 'active_support/core_ext/string/exclude'
-
2
require 'active_support/core_ext/string/encoding'
-
2
require 'active_support/core_ext/string/strip'
-
2
require 'active_support/core_ext/string/inquiry'
-
2
require "active_support/multibyte"
-
-
2
class String
-
2
unless '1.9'.respond_to?(:force_encoding)
-
# Returns the character at the +position+ treating the string as an array (where 0 is the first character).
-
#
-
# Examples:
-
# "hello".at(0) # => "h"
-
# "hello".at(4) # => "o"
-
# "hello".at(10) # => ERROR if < 1.9, nil in 1.9
-
def at(position)
-
mb_chars[position, 1].to_s
-
end
-
-
# Returns the remaining of the string from the +position+ treating the string as an array (where 0 is the first character).
-
#
-
# Examples:
-
# "hello".from(0) # => "hello"
-
# "hello".from(2) # => "llo"
-
# "hello".from(10) # => "" if < 1.9, nil in 1.9
-
def from(position)
-
mb_chars[position..-1].to_s
-
end
-
-
# Returns the beginning of the string up to the +position+ treating the string as an array (where 0 is the first character).
-
#
-
# Examples:
-
# "hello".to(0) # => "h"
-
# "hello".to(2) # => "hel"
-
# "hello".to(10) # => "hello"
-
def to(position)
-
mb_chars[0..position].to_s
-
end
-
-
# Returns the first character of the string or the first +limit+ characters.
-
#
-
# Examples:
-
# "hello".first # => "h"
-
# "hello".first(2) # => "he"
-
# "hello".first(10) # => "hello"
-
def first(limit = 1)
-
if limit == 0
-
''
-
elsif limit >= size
-
self
-
else
-
mb_chars[0...limit].to_s
-
end
-
end
-
-
# Returns the last character of the string or the last +limit+ characters.
-
#
-
# Examples:
-
# "hello".last # => "o"
-
# "hello".last(2) # => "lo"
-
# "hello".last(10) # => "hello"
-
def last(limit = 1)
-
if limit == 0
-
''
-
elsif limit >= size
-
self
-
else
-
mb_chars[(-limit)..-1].to_s
-
end
-
end
-
else
-
2
def at(position)
-
self[position]
-
end
-
-
2
def from(position)
-
self[position..-1]
-
end
-
-
2
def to(position)
-
self[0..position]
-
end
-
-
2
def first(limit = 1)
-
if limit == 0
-
''
-
elsif limit >= size
-
self
-
else
-
to(limit - 1)
-
end
-
end
-
-
2
def last(limit = 1)
-
if limit == 0
-
''
-
elsif limit >= size
-
self
-
else
-
from(-limit)
-
end
-
end
-
end
-
end
-
2
class String
-
# Enable more predictable duck-typing on String-like classes. See <tt>Object#acts_like?</tt>.
-
2
def acts_like_string?
-
true
-
end
-
end
-
# encoding: utf-8
-
2
require 'date'
-
2
require 'active_support/core_ext/time/publicize_conversion_methods'
-
2
require 'active_support/core_ext/time/calculations'
-
-
2
class String
-
# Returns the codepoint of the first character of the string, assuming a
-
# single-byte character encoding:
-
#
-
# "a".ord # => 97
-
# "à".ord # => 224, in ISO-8859-1
-
#
-
# This method is defined in Ruby 1.8 for Ruby 1.9 forward compatibility on
-
# these character encodings.
-
#
-
# <tt>ActiveSupport::Multibyte::Chars#ord</tt> is forward compatible with
-
# Ruby 1.9 on UTF8 strings:
-
#
-
# "a".mb_chars.ord # => 97
-
# "à".mb_chars.ord # => 224, in UTF8
-
#
-
# Note that the 224 is different in both examples. In ISO-8859-1 "à" is
-
# represented as a single byte, 224. In UTF8 it is represented with two
-
# bytes, namely 195 and 160, but its Unicode codepoint is 224. If we
-
# call +ord+ on the UTF8 string "à" the return value will be 195. That is
-
# not an error, because UTF8 is unsupported, the call itself would be
-
# bogus.
-
def ord
-
self[0]
-
2
end unless method_defined?(:ord)
-
-
# +getbyte+ backport from Ruby 1.9
-
2
alias_method :getbyte, :[] unless method_defined?(:getbyte)
-
-
# Form can be either :utc (default) or :local.
-
2
def to_time(form = :utc)
-
return nil if self.blank?
-
d = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset).map { |arg| arg || 0 }
-
d[6] *= 1000000
-
::Time.send("#{form}_time", *d[0..6]) - d[7]
-
end
-
-
# Converts a string to a Date value.
-
#
-
# "1-1-2012".to_date #=> Sun, 01 Jan 2012
-
# "01/01/2012".to_date #=> Sun, 01 Jan 2012
-
# "2012-12-13".to_date #=> Thu, 13 Dec 2012
-
# "12/13/2012".to_date #=> ArgumentError: invalid date
-
2
def to_date
-
return nil if self.blank?
-
::Date.new(*::Date._parse(self, false).values_at(:year, :mon, :mday))
-
end
-
-
# Converts a string to a DateTime value.
-
#
-
# "1-1-2012".to_datetime #=> Sun, 01 Jan 2012 00:00:00 +0000
-
# "01/01/2012 23:59:59".to_datetime #=> Sun, 01 Jan 2012 23:59:59 +0000
-
# "2012-12-13 12:50".to_datetime #=> Thu, 13 Dec 2012 12:50:00 +0000
-
# "12/13/2012".to_datetime #=> ArgumentError: invalid date
-
2
def to_datetime
-
return nil if self.blank?
-
d = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :sec_fraction).map { |arg| arg || 0 }
-
d[5] += d.pop
-
::DateTime.civil(*d)
-
end
-
end
-
2
class String
-
2
if defined?(Encoding) && "".respond_to?(:encode)
-
2
def encoding_aware?
-
2707
true
-
end
-
else
-
def encoding_aware?
-
false
-
end
-
end
-
end
-
2
class String
-
# The inverse of <tt>String#include?</tt>. Returns true if the string
-
# does not include the other string.
-
#
-
# "hello".exclude? "lo" #=> false
-
# "hello".exclude? "ol" #=> true
-
# "hello".exclude? ?h #=> false
-
2
def exclude?(string)
-
!include?(string)
-
end
-
end
-
2
require 'active_support/core_ext/string/multibyte'
-
-
2
class String
-
# Returns the string, first removing all whitespace on both ends of
-
# the string, and then changing remaining consecutive whitespace
-
# groups into one space each.
-
#
-
# Examples:
-
# %{ Multi-line
-
# string }.squish # => "Multi-line string"
-
# " foo bar \n \t boo".squish # => "foo bar boo"
-
2
def squish
-
dup.squish!
-
end
-
-
# Performs a destructive squish. See String#squish.
-
2
def squish!
-
strip!
-
gsub!(/\s+/, ' ')
-
self
-
end
-
-
# Truncates a given +text+ after a given <tt>length</tt> if +text+ is longer than <tt>length</tt>:
-
#
-
# "Once upon a time in a world far far away".truncate(27)
-
# # => "Once upon a time in a wo..."
-
#
-
# Pass a <tt>:separator</tt> to truncate +text+ at a natural break:
-
#
-
# "Once upon a time in a world far far away".truncate(27, :separator => ' ')
-
# # => "Once upon a time in a..."
-
#
-
# The last characters will be replaced with the <tt>:omission</tt> string (defaults to "...")
-
# for a total length not exceeding <tt>:length</tt>:
-
#
-
# "And they found that many people were sleeping better.".truncate(25, :omission => "... (continued)")
-
# # => "And they f... (continued)"
-
2
def truncate(length, options = {})
-
text = self.dup
-
options[:omission] ||= "..."
-
-
length_with_room_for_omission = length - options[:omission].mb_chars.length
-
chars = text.mb_chars
-
stop = options[:separator] ?
-
(chars.rindex(options[:separator].mb_chars, length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission
-
-
(chars.length > length ? chars[0...stop] + options[:omission] : text).to_s
-
end
-
end
-
2
require 'active_support/inflector/methods'
-
2
require 'active_support/inflector/transliterate'
-
-
# String inflections define new methods on the String class to transform names for different purposes.
-
# For instance, you can figure out the name of a table from the name of a class.
-
#
-
# "ScaleScore".tableize # => "scale_scores"
-
#
-
2
class String
-
# Returns the plural form of the word in the string.
-
#
-
# If the optional parameter +count+ is specified,
-
# the singular form will be returned if <tt>count == 1</tt>.
-
# For any other value of +count+ the plural will be returned.
-
#
-
# ==== Examples
-
# "post".pluralize # => "posts"
-
# "octopus".pluralize # => "octopi"
-
# "sheep".pluralize # => "sheep"
-
# "words".pluralize # => "words"
-
# "the blue mailman".pluralize # => "the blue mailmen"
-
# "CamelOctopus".pluralize # => "CamelOctopi"
-
# "apple".pluralize(1) # => "apple"
-
# "apple".pluralize(2) # => "apples"
-
2
def pluralize(count = nil)
-
84
if count == 1
-
self
-
else
-
84
ActiveSupport::Inflector.pluralize(self)
-
end
-
end
-
-
# The reverse of +pluralize+, returns the singular form of a word in a string.
-
#
-
# "posts".singularize # => "post"
-
# "octopi".singularize # => "octopus"
-
# "sheep".singularize # => "sheep"
-
# "word".singularize # => "word"
-
# "the blue mailmen".singularize # => "the blue mailman"
-
# "CamelOctopi".singularize # => "CamelOctopus"
-
2
def singularize
-
126
ActiveSupport::Inflector.singularize(self)
-
end
-
-
# +constantize+ tries to find a declared constant with the name specified
-
# in the string. It raises a NameError when the name is not in CamelCase
-
# or is not initialized. See ActiveSupport::Inflector.constantize
-
#
-
# Examples
-
# "Module".constantize # => Module
-
# "Class".constantize # => Class
-
# "blargle".constantize # => NameError: wrong constant name blargle
-
2
def constantize
-
108
ActiveSupport::Inflector.constantize(self)
-
end
-
-
# +safe_constantize+ tries to find a declared constant with the name specified
-
# in the string. It returns nil when the name is not in CamelCase
-
# or is not initialized. See ActiveSupport::Inflector.safe_constantize
-
#
-
# Examples
-
# "Module".safe_constantize # => Module
-
# "Class".safe_constantize # => Class
-
# "blargle".safe_constantize # => nil
-
2
def safe_constantize
-
77
ActiveSupport::Inflector.safe_constantize(self)
-
end
-
-
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to camelize
-
# is set to <tt>:lower</tt> then camelize produces lowerCamelCase.
-
#
-
# +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
-
#
-
# "active_record".camelize # => "ActiveRecord"
-
# "active_record".camelize(:lower) # => "activeRecord"
-
# "active_record/errors".camelize # => "ActiveRecord::Errors"
-
# "active_record/errors".camelize(:lower) # => "activeRecord::Errors"
-
2
def camelize(first_letter = :upper)
-
158
case first_letter
-
158
when :upper then ActiveSupport::Inflector.camelize(self, true)
-
when :lower then ActiveSupport::Inflector.camelize(self, false)
-
end
-
end
-
2
alias_method :camelcase, :camelize
-
-
# Capitalizes all the words and replaces some characters in the string to create
-
# a nicer looking title. +titleize+ is meant for creating pretty output. It is not
-
# used in the Rails internals.
-
#
-
# +titleize+ is also aliased as +titlecase+.
-
#
-
# "man from the boondocks".titleize # => "Man From The Boondocks"
-
# "x-men: the last stand".titleize # => "X Men: The Last Stand"
-
2
def titleize
-
ActiveSupport::Inflector.titleize(self)
-
end
-
2
alias_method :titlecase, :titleize
-
-
# The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string.
-
#
-
# +underscore+ will also change '::' to '/' to convert namespaces to paths.
-
#
-
# "ActiveModel".underscore # => "active_model"
-
# "ActiveModel::Errors".underscore # => "active_model/errors"
-
2
def underscore
-
416
ActiveSupport::Inflector.underscore(self)
-
end
-
-
# Replaces underscores with dashes in the string.
-
#
-
# "puni_puni" # => "puni-puni"
-
2
def dasherize
-
152
ActiveSupport::Inflector.dasherize(self)
-
end
-
-
# Removes the module part from the constant expression in the string.
-
#
-
# "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
-
# "Inflections".demodulize # => "Inflections"
-
#
-
# See also +deconstantize+.
-
2
def demodulize
-
51
ActiveSupport::Inflector.demodulize(self)
-
end
-
-
# Removes the rightmost segment from the constant expression in the string.
-
#
-
# "Net::HTTP".deconstantize # => "Net"
-
# "::Net::HTTP".deconstantize # => "::Net"
-
# "String".deconstantize # => ""
-
# "::String".deconstantize # => ""
-
# "".deconstantize # => ""
-
#
-
# See also +demodulize+.
-
2
def deconstantize
-
ActiveSupport::Inflector.deconstantize(self)
-
end
-
-
# Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
-
#
-
# ==== Examples
-
#
-
# class Person
-
# def to_param
-
# "#{id}-#{name.parameterize}"
-
# end
-
# end
-
#
-
# @person = Person.find(1)
-
# # => #<Person id: 1, name: "Donald E. Knuth">
-
#
-
# <%= link_to(@person.name, person_path) %>
-
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
-
2
def parameterize(sep = '-')
-
ActiveSupport::Inflector.parameterize(self, sep)
-
end
-
-
# Creates the name of a table like Rails does for models to table names. This method
-
# uses the +pluralize+ method on the last word in the string.
-
#
-
# "RawScaledScorer".tableize # => "raw_scaled_scorers"
-
# "egg_and_ham".tableize # => "egg_and_hams"
-
# "fancyCategory".tableize # => "fancy_categories"
-
2
def tableize
-
ActiveSupport::Inflector.tableize(self)
-
end
-
-
# Create a class name from a plural table name like Rails does for table names to models.
-
# Note that this returns a string and not a class. (To convert to an actual class
-
# follow +classify+ with +constantize+.)
-
#
-
# "egg_and_hams".classify # => "EggAndHam"
-
# "posts".classify # => "Post"
-
#
-
# Singular names are not handled correctly.
-
#
-
# "business".classify # => "Busines"
-
2
def classify
-
43
ActiveSupport::Inflector.classify(self)
-
end
-
-
# Capitalizes the first word, turns underscores into spaces, and strips '_id'.
-
# Like +titleize+, this is meant for creating pretty output.
-
#
-
# "employee_salary" # => "Employee salary"
-
# "author_id" # => "Author"
-
2
def humanize
-
12
ActiveSupport::Inflector.humanize(self)
-
end
-
-
# Creates a foreign key name from a class name.
-
# +separate_class_name_and_id_with_underscore+ sets whether
-
# the method should put '_' between the name and 'id'.
-
#
-
# Examples
-
# "Message".foreign_key # => "message_id"
-
# "Message".foreign_key(false) # => "messageid"
-
# "Admin::Post".foreign_key # => "post_id"
-
2
def foreign_key(separate_class_name_and_id_with_underscore = true)
-
15
ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)
-
end
-
end
-
2
require 'active_support/string_inquirer'
-
-
2
class String
-
# Wraps the current string in the <tt>ActiveSupport::StringInquirer</tt> class,
-
# which gives you a prettier way to test for equality. Example:
-
#
-
# env = "production".inquiry
-
# env.production? # => true
-
# env.development? # => false
-
2
def inquiry
-
ActiveSupport::StringInquirer.new(self)
-
end
-
end
-
2
require 'active_support/i18n'
-
2
require 'i18n/core_ext/string/interpolate'
-
# encoding: utf-8
-
2
require 'active_support/multibyte'
-
-
2
class String
-
2
if RUBY_VERSION >= "1.9"
-
# == Multibyte proxy
-
#
-
# +mb_chars+ is a multibyte safe proxy for string methods.
-
#
-
# In Ruby 1.8 and older it creates and returns an instance of the ActiveSupport::Multibyte::Chars class which
-
# encapsulates the original string. A Unicode safe version of all the String methods are defined on this proxy
-
# class. If the proxy class doesn't respond to a certain method, it's forwarded to the encapsulated string.
-
#
-
# name = 'Claus Müller'
-
# name.reverse # => "rell??M sualC"
-
# name.length # => 13
-
#
-
# name.mb_chars.reverse.to_s # => "rellüM sualC"
-
# name.mb_chars.length # => 12
-
#
-
# In Ruby 1.9 and newer +mb_chars+ returns +self+ because String is (mostly) encoding aware. This means that
-
# it becomes easy to run one version of your code on multiple Ruby versions.
-
#
-
# == Method chaining
-
#
-
# All the methods on the Chars proxy which normally return a string will return a Chars object. This allows
-
# method chaining on the result of any of these methods.
-
#
-
# name.mb_chars.reverse.length # => 12
-
#
-
# == Interoperability and configuration
-
#
-
# The Chars object tries to be as interchangeable with String objects as possible: sorting and comparing between
-
# String and Char work like expected. The bang! methods change the internal string representation in the Chars
-
# object. Interoperability problems can be resolved easily with a +to_s+ call.
-
#
-
# For more information about the methods defined on the Chars proxy see ActiveSupport::Multibyte::Chars. For
-
# information about how to change the default Multibyte behavior see ActiveSupport::Multibyte.
-
2
def mb_chars
-
if ActiveSupport::Multibyte.proxy_class.consumes?(self)
-
ActiveSupport::Multibyte.proxy_class.new(self)
-
else
-
self
-
end
-
end
-
-
2
def is_utf8?
-
case encoding
-
when Encoding::UTF_8
-
valid_encoding?
-
when Encoding::ASCII_8BIT, Encoding::US_ASCII
-
dup.force_encoding(Encoding::UTF_8).valid_encoding?
-
else
-
false
-
end
-
end
-
else
-
def mb_chars
-
if ActiveSupport::Multibyte.proxy_class.wants?(self)
-
ActiveSupport::Multibyte.proxy_class.new(self)
-
else
-
self
-
end
-
end
-
-
# Returns true if the string has UTF-8 semantics (a String used for purely byte resources is unlikely to have
-
# them), returns false otherwise.
-
def is_utf8?
-
ActiveSupport::Multibyte::Chars.consumes?(self)
-
end
-
end
-
end
-
2
require 'erb'
-
2
require 'active_support/core_ext/kernel/singleton_class'
-
-
2
class ERB
-
2
module Util
-
2
HTML_ESCAPE = { '&' => '&', '>' => '>', '<' => '<', '"' => '"', "'" => ''' }
-
2
JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003E', '<' => '\u003C' }
-
-
2
if RUBY_VERSION >= '1.9'
-
# A utility method for escaping HTML tag characters.
-
# This method is also aliased as <tt>h</tt>.
-
#
-
# In your ERB templates, use this method to escape any unsafe content. For example:
-
# <%=h @person.name %>
-
#
-
# ==== Example:
-
# puts html_escape("is a > 0 & a < 10?")
-
# # => is a > 0 & a < 10?
-
2
def html_escape(s)
-
21
s = s.to_s
-
21
if s.html_safe?
-
s
-
else
-
21
s.gsub(/[&"'><]/, HTML_ESCAPE).html_safe
-
end
-
end
-
else
-
def html_escape(s) #:nodoc:
-
s = s.to_s
-
if s.html_safe?
-
s
-
else
-
s.gsub(/[&"'><]/n) { |special| HTML_ESCAPE[special] }.html_safe
-
end
-
end
-
end
-
-
# Aliasing twice issues a warning "discarding old...". Remove first to avoid it.
-
2
remove_method(:h)
-
2
alias h html_escape
-
-
2
module_function :h
-
-
2
singleton_class.send(:remove_method, :html_escape)
-
2
module_function :html_escape
-
-
# A utility method for escaping HTML entities in JSON strings
-
# using \uXXXX JavaScript escape sequences for string literals:
-
#
-
# json_escape("is a > 0 & a < 10?")
-
# # => is a \u003E 0 \u0026 a \u003C 10?
-
#
-
# Note that after this operation is performed the output is not
-
# valid JSON. In particular double quotes are removed:
-
#
-
# json_escape('{"name":"john","created_at":"2010-04-28T01:39:31Z","id":1}')
-
# # => {name:john,created_at:2010-04-28T01:39:31Z,id:1}
-
#
-
# This method is also aliased as +j+, and available as a helper
-
# in Rails templates:
-
#
-
# <%=j @person.to_json %>
-
#
-
2
def json_escape(s)
-
result = s.to_s.gsub(/[&"><]/) { |special| JSON_ESCAPE[special] }
-
s.html_safe? ? result.html_safe : result
-
end
-
-
2
alias j json_escape
-
2
module_function :j
-
2
module_function :json_escape
-
end
-
end
-
-
2
class Object
-
2
def html_safe?
-
33
false
-
end
-
end
-
-
2
class Numeric
-
2
def html_safe?
-
true
-
end
-
end
-
-
2
module ActiveSupport #:nodoc:
-
2
class SafeBuffer < String
-
2
UNSAFE_STRING_METHODS = ["capitalize", "chomp", "chop", "delete", "downcase", "gsub", "lstrip", "next", "reverse", "rstrip", "slice", "squeeze", "strip", "sub", "succ", "swapcase", "tr", "tr_s", "upcase", "prepend"].freeze
-
-
2
alias_method :original_concat, :concat
-
2
private :original_concat
-
-
2
class SafeConcatError < StandardError
-
2
def initialize
-
super "Could not concatenate to the buffer because it is not html safe."
-
end
-
end
-
-
2
def [](*args)
-
return super if args.size < 2
-
-
if html_safe?
-
new_safe_buffer = super
-
new_safe_buffer.instance_eval { @html_safe = true }
-
new_safe_buffer
-
else
-
to_str[*args]
-
end
-
end
-
-
2
def safe_concat(value)
-
28
raise SafeConcatError unless html_safe?
-
28
original_concat(value)
-
end
-
-
2
def initialize(*)
-
25
@html_safe = true
-
25
super
-
end
-
-
2
def initialize_copy(other)
-
super
-
@html_safe = other.html_safe?
-
end
-
-
2
def clone_empty
-
self[0, 0]
-
end
-
-
2
def concat(value)
-
12
if !html_safe? || value.html_safe?
-
super(value)
-
else
-
12
super(ERB::Util.h(value))
-
end
-
end
-
2
alias << concat
-
-
2
def +(other)
-
dup.concat(other)
-
end
-
-
2
def html_safe?
-
40
defined?(@html_safe) && @html_safe
-
end
-
-
2
def to_s
-
8
self
-
end
-
-
2
def to_param
-
to_str
-
end
-
-
2
def encode_with(coder)
-
coder.represent_scalar nil, to_str
-
end
-
-
2
def to_yaml(*args)
-
return super() if defined?(YAML::ENGINE) && !YAML::ENGINE.syck?
-
to_str.to_yaml(*args)
-
end
-
-
2
UNSAFE_STRING_METHODS.each do |unsafe_method|
-
40
if 'String'.respond_to?(unsafe_method)
-
40
class_eval <<-EOT, __FILE__, __LINE__ + 1
-
def #{unsafe_method}(*args, &block) # def capitalize(*args, &block)
-
to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block)
-
end # end
-
-
def #{unsafe_method}!(*args) # def capitalize!(*args)
-
@html_safe = false # @html_safe = false
-
super # super
-
end # end
-
EOT
-
end
-
end
-
end
-
end
-
-
2
class String
-
2
def html_safe
-
21
ActiveSupport::SafeBuffer.new(self)
-
end
-
end
-
2
class String
-
2
alias_method :starts_with?, :start_with?
-
2
alias_method :ends_with?, :end_with?
-
end
-
2
require 'active_support/core_ext/object/try'
-
-
2
class String
-
# Strips indentation in heredocs.
-
#
-
# For example in
-
#
-
# if options[:usage]
-
# puts <<-USAGE.strip_heredoc
-
# This command does such and such.
-
#
-
# Supported options are:
-
# -h This message
-
# ...
-
# USAGE
-
# end
-
#
-
# the user would see the usage message aligned against the left margin.
-
#
-
# Technically, it looks for the least indented line in the whole string, and removes
-
# that amount of leading whitespace.
-
2
def strip_heredoc
-
indent = scan(/^[ \t]*(?=\S)/).min.try(:size) || 0
-
gsub(/^[ \t]{#{indent}}/, '')
-
end
-
end
-
2
begin
-
# See http://fast-xs.rubyforge.org/ by Eric Wong.
-
# Also included with hpricot.
-
2
require 'fast_xs'
-
rescue LoadError
-
# fast_xs extension unavailable
-
else
-
begin
-
require 'builder'
-
rescue LoadError
-
# builder demands the first shot at defining String#to_xs
-
end
-
-
class String
-
alias_method :original_xs, :to_xs if method_defined?(:to_xs)
-
alias_method :to_xs, :fast_xs
-
end
-
end
-
2
require 'active_support/core_ext/object/acts_like'
-
-
2
class Time
-
# Duck-types as a Time-like class. See Object#acts_like?.
-
2
def acts_like_time?
-
true
-
end
-
end
-
2
require 'active_support/duration'
-
2
require 'active_support/core_ext/time/conversions'
-
2
require 'active_support/time_with_zone'
-
2
require 'active_support/core_ext/time/zones'
-
-
2
class Time
-
2
COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-
2
DAYS_INTO_WEEK = { :monday => 0, :tuesday => 1, :wednesday => 2, :thursday => 3, :friday => 4, :saturday => 5, :sunday => 6 }
-
-
2
class << self
-
# Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances
-
2
def ===(other)
-
2081
super || (self == Time && other.is_a?(ActiveSupport::TimeWithZone))
-
end
-
-
# Return the number of days in the given month.
-
# If no year is specified, it will use the current year.
-
2
def days_in_month(month, year = now.year)
-
return 29 if month == 2 && ::Date.gregorian_leap?(year)
-
COMMON_YEAR_DAYS_IN_MONTH[month]
-
end
-
-
# Returns a new Time if requested year can be accommodated by Ruby's Time class
-
# (i.e., if year is within either 1970..2038 or 1902..2038, depending on system architecture);
-
# otherwise returns a DateTime.
-
2
def time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0, usec=0)
-
1679
time = ::Time.send(utc_or_local, year, month, day, hour, min, sec, usec)
-
# This check is needed because Time.utc(y) returns a time object in the 2000s for 0 <= y <= 138.
-
1679
time.year == year ? time : ::DateTime.civil_from_format(utc_or_local, year, month, day, hour, min, sec)
-
rescue
-
::DateTime.civil_from_format(utc_or_local, year, month, day, hour, min, sec)
-
end
-
-
# Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:utc</tt>.
-
2
def utc_time(*args)
-
1033
time_with_datetime_fallback(:utc, *args)
-
end
-
-
# Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:local</tt>.
-
2
def local_time(*args)
-
10
time_with_datetime_fallback(:local, *args)
-
end
-
-
# Returns <tt>Time.zone.now</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns <tt>Time.now</tt>.
-
2
def current
-
71
::Time.zone ? ::Time.zone.now : ::Time.now
-
end
-
-
# Layers additional behavior on Time.at so that ActiveSupport::TimeWithZone and DateTime
-
# instances can be used when called with a single argument
-
2
def at_with_coercion(*args)
-
1052
return at_without_coercion(*args) if args.size != 1
-
-
# Time.at can be called with a time or numerical value
-
1052
time_or_number = args.first
-
-
1052
if time_or_number.is_a?(ActiveSupport::TimeWithZone) || time_or_number.is_a?(DateTime)
-
at_without_coercion(time_or_number.to_f).getlocal
-
else
-
1052
at_without_coercion(time_or_number)
-
end
-
end
-
2
alias_method :at_without_coercion, :at
-
2
alias_method :at, :at_with_coercion
-
end
-
-
# Tells whether the Time object's time lies in the past
-
2
def past?
-
self < ::Time.current
-
end
-
-
# Tells whether the Time object's time is today
-
2
def today?
-
to_date == ::Date.current
-
end
-
-
# Tells whether the Time object's time lies in the future
-
2
def future?
-
self > ::Time.current
-
end
-
-
# Seconds since midnight: Time.now.seconds_since_midnight
-
2
def seconds_since_midnight
-
to_i - change(:hour => 0).to_i + (usec / 1.0e+6)
-
end
-
-
# Returns a new Time where one or more of the elements have been changed according to the +options+ parameter. The time options
-
# (hour, min, sec, usec) reset cascadingly, so if only the hour is passed, then minute, sec, and usec is set to 0. If the hour and
-
# minute is passed, then sec and usec is set to 0.
-
2
def change(options)
-
490
::Time.send(
-
utc? ? :utc_time : :local_time,
-
options[:year] || year,
-
options[:month] || month,
-
options[:day] || day,
-
options[:hour] || hour,
-
484
options[:min] || (options[:hour] ? 0 : min),
-
490
options[:sec] || ((options[:hour] || options[:min]) ? 0 : sec),
-
490
options[:usec] || ((options[:hour] || options[:min] || options[:sec]) ? 0 : usec)
-
)
-
end
-
-
# Uses Date to provide precise Time calculations for years, months, and days.
-
# The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
-
# <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
-
# <tt>:minutes</tt>, <tt>:seconds</tt>.
-
2
def advance(options)
-
484
unless options[:weeks].nil?
-
options[:weeks], partial_weeks = options[:weeks].divmod(1)
-
options[:days] = (options[:days] || 0) + 7 * partial_weeks
-
end
-
-
484
unless options[:days].nil?
-
468
options[:days], partial_days = options[:days].divmod(1)
-
468
options[:hours] = (options[:hours] || 0) + 24 * partial_days
-
end
-
-
484
d = to_date.advance(options)
-
484
time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
-
484
seconds_to_advance = (options[:seconds] || 0) + (options[:minutes] || 0) * 60 + (options[:hours] || 0) * 3600
-
484
seconds_to_advance == 0 ? time_advanced_by_date : time_advanced_by_date.since(seconds_to_advance)
-
end
-
-
# Returns a new Time representing the time a number of seconds ago, this is basically a wrapper around the Numeric extension
-
2
def ago(seconds)
-
since(-seconds)
-
end
-
-
# Returns a new Time representing the time a number of seconds since the instance time
-
2
def since(seconds)
-
626
self + seconds
-
rescue
-
to_datetime.since(seconds)
-
end
-
2
alias :in :since
-
-
# Returns a new Time representing the time a number of specified weeks ago.
-
2
def weeks_ago(weeks)
-
advance(:weeks => -weeks)
-
end
-
-
# Returns a new Time representing the time a number of specified months ago
-
2
def months_ago(months)
-
advance(:months => -months)
-
end
-
-
# Returns a new Time representing the time a number of specified months in the future
-
2
def months_since(months)
-
advance(:months => months)
-
end
-
-
# Returns a new Time representing the time a number of specified years ago
-
2
def years_ago(years)
-
advance(:years => -years)
-
end
-
-
# Returns a new Time representing the time a number of specified years in the future
-
2
def years_since(years)
-
advance(:years => years)
-
end
-
-
# Short-hand for years_ago(1)
-
2
def prev_year
-
years_ago(1)
-
end
-
-
# Short-hand for years_since(1)
-
2
def next_year
-
years_since(1)
-
end
-
-
# Short-hand for months_ago(1)
-
2
def prev_month
-
months_ago(1)
-
end
-
-
# Short-hand for months_since(1)
-
2
def next_month
-
months_since(1)
-
end
-
-
# Returns number of days to start of this week, week starts on start_day (default is :monday).
-
2
def days_to_week_start(start_day = :monday)
-
start_day_number = DAYS_INTO_WEEK[start_day]
-
current_day_number = wday != 0 ? wday - 1 : 6
-
days_span = current_day_number - start_day_number
-
days_span >= 0 ? days_span : 7 + days_span
-
end
-
-
# Returns a new Time representing the "start" of this week, week starts on start_day (default is :monday, i.e. Monday, 0:00).
-
2
def beginning_of_week(start_day = :monday)
-
days_to_start = days_to_week_start(start_day)
-
(self - days_to_start.days).midnight
-
end
-
2
alias :at_beginning_of_week :beginning_of_week
-
-
# Returns a new +Date+/+DateTime+ representing the start of this week. Week is
-
# assumed to start on a Monday. +DateTime+ objects have their time set to 0:00.
-
2
def monday
-
beginning_of_week
-
end
-
-
# Returns a new Time representing the end of this week, week starts on start_day (default is :monday, i.e. end of Sunday).
-
2
def end_of_week(start_day = :monday)
-
days_to_end = 6 - days_to_week_start(start_day)
-
(self + days_to_end.days).end_of_day
-
end
-
2
alias :at_end_of_week :end_of_week
-
-
# Returns a new +Date+/+DateTime+ representing the end of this week. Week is
-
# assumed to start on a Monday. +DateTime+ objects have their time set to 23:59:59.
-
2
def sunday
-
end_of_week
-
end
-
-
# Returns a new Time representing the start of the given day in the previous week (default is :monday).
-
2
def prev_week(day = :monday)
-
ago(1.week).beginning_of_week.since(DAYS_INTO_WEEK[day].day).change(:hour => 0)
-
end
-
-
# Returns a new Time representing the start of the given day in next week (default is :monday).
-
2
def next_week(day = :monday)
-
since(1.week).beginning_of_week.since(DAYS_INTO_WEEK[day].day).change(:hour => 0)
-
end
-
-
# Returns a new Time representing the start of the day (0:00)
-
2
def beginning_of_day
-
#(self - seconds_since_midnight).change(:usec => 0)
-
change(:hour => 0)
-
end
-
2
alias :midnight :beginning_of_day
-
2
alias :at_midnight :beginning_of_day
-
2
alias :at_beginning_of_day :beginning_of_day
-
-
# Returns a new Time representing the end of the day, 23:59:59.999999 (.999999999 in ruby1.9)
-
2
def end_of_day
-
change(:hour => 23, :min => 59, :sec => 59, :usec => Rational(999999999, 1000))
-
end
-
-
# Returns a new Time representing the start of the hour (x:00)
-
2
def beginning_of_hour
-
change(:min => 0)
-
end
-
2
alias :at_beginning_of_hour :beginning_of_hour
-
-
# Returns a new Time representing the end of the hour, x:59:59.999999 (.999999999 in ruby1.9)
-
2
def end_of_hour
-
change(:min => 59, :sec => 59, :usec => Rational(999999999, 1000))
-
end
-
-
# Returns a new Time representing the start of the month (1st of the month, 0:00)
-
2
def beginning_of_month
-
#self - ((self.mday-1).days + self.seconds_since_midnight)
-
change(:day => 1, :hour => 0)
-
end
-
2
alias :at_beginning_of_month :beginning_of_month
-
-
# Returns a new Time representing the end of the month (end of the last day of the month)
-
2
def end_of_month
-
#self - ((self.mday-1).days + self.seconds_since_midnight)
-
last_day = ::Time.days_in_month(month, year)
-
change(:day => last_day, :hour => 23, :min => 59, :sec => 59, :usec => Rational(999999999, 1000))
-
end
-
2
alias :at_end_of_month :end_of_month
-
-
# Returns a new Time representing the start of the quarter (1st of january, april, july, october, 0:00)
-
2
def beginning_of_quarter
-
beginning_of_month.change(:month => [10, 7, 4, 1].detect { |m| m <= month })
-
end
-
2
alias :at_beginning_of_quarter :beginning_of_quarter
-
-
# Returns a new Time representing the end of the quarter (end of the last day of march, june, september, december)
-
2
def end_of_quarter
-
beginning_of_month.change(:month => [3, 6, 9, 12].detect { |m| m >= month }).end_of_month
-
end
-
2
alias :at_end_of_quarter :end_of_quarter
-
-
# Returns a new Time representing the start of the year (1st of january, 0:00)
-
2
def beginning_of_year
-
change(:month => 1, :day => 1, :hour => 0)
-
end
-
2
alias :at_beginning_of_year :beginning_of_year
-
-
# Returns a new Time representing the end of the year (end of the 31st of december)
-
2
def end_of_year
-
change(:month => 12, :day => 31, :hour => 23, :min => 59, :sec => 59, :usec => Rational(999999999, 1000))
-
end
-
2
alias :at_end_of_year :end_of_year
-
-
# Convenience method which returns a new Time representing the time 1 day ago
-
2
def yesterday
-
advance(:days => -1)
-
end
-
-
# Convenience method which returns a new Time representing the time 1 day since the instance time
-
2
def tomorrow
-
advance(:days => 1)
-
end
-
-
# Returns a Range representing the whole day of the current time.
-
2
def all_day
-
beginning_of_day..end_of_day
-
end
-
-
# Returns a Range representing the whole week of the current time. Week starts on start_day (default is :monday, i.e. end of Sunday).
-
2
def all_week(start_day = :monday)
-
beginning_of_week(start_day)..end_of_week(start_day)
-
end
-
-
# Returns a Range representing the whole month of the current time.
-
2
def all_month
-
beginning_of_month..end_of_month
-
end
-
-
# Returns a Range representing the whole quarter of the current time.
-
2
def all_quarter
-
beginning_of_quarter..end_of_quarter
-
end
-
-
# Returns a Range representing the whole year of the current time.
-
2
def all_year
-
beginning_of_year..end_of_year
-
end
-
-
2
def plus_with_duration(other) #:nodoc:
-
5091
if ActiveSupport::Duration === other
-
1042
other.since(self)
-
else
-
4049
plus_without_duration(other)
-
end
-
end
-
2
alias_method :plus_without_duration, :+
-
2
alias_method :+, :plus_with_duration
-
-
2
def minus_with_duration(other) #:nodoc:
-
4245
if ActiveSupport::Duration === other
-
68
other.until(self)
-
else
-
4177
minus_without_duration(other)
-
end
-
end
-
2
alias_method :minus_without_duration, :-
-
2
alias_method :-, :minus_with_duration
-
-
# Time#- can also be used to determine the number of seconds between two Time instances.
-
# We're layering on additional behavior so that ActiveSupport::TimeWithZone instances
-
# are coerced into values that Time#- will recognize
-
2
def minus_with_coercion(other)
-
4245
other = other.comparable_time if other.respond_to?(:comparable_time)
-
4245
other.is_a?(DateTime) ? to_f - other.to_f : minus_without_coercion(other)
-
end
-
2
alias_method :minus_without_coercion, :-
-
2
alias_method :-, :minus_with_coercion
-
-
# Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances
-
# can be chronologically compared with a Time
-
2
def compare_with_coercion(other)
-
# we're avoiding Time#to_datetime cause it's expensive
-
11259
other.is_a?(Time) ? compare_without_coercion(other.to_time) : to_datetime <=> other
-
end
-
2
alias_method :compare_without_coercion, :<=>
-
2
alias_method :<=>, :compare_with_coercion
-
-
# Layers additional behavior on Time#eql? so that ActiveSupport::TimeWithZone instances
-
# can be eql? to an equivalent Time
-
2
def eql_with_coercion(other)
-
# if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do eql? comparison
-
other = other.comparable_time if other.respond_to?(:comparable_time)
-
eql_without_coercion(other)
-
end
-
2
alias_method :eql_without_coercion, :eql?
-
2
alias_method :eql?, :eql_with_coercion
-
end
-
2
require 'active_support/inflector/methods'
-
2
require 'active_support/core_ext/time/publicize_conversion_methods'
-
2
require 'active_support/values/time_zone'
-
-
2
class Time
-
2
DATE_FORMATS = {
-
:db => "%Y-%m-%d %H:%M:%S",
-
:number => "%Y%m%d%H%M%S",
-
:time => "%H:%M",
-
:short => "%d %b %H:%M",
-
:long => "%B %d, %Y %H:%M",
-
:long_ordinal => lambda { |time| time.strftime("%B #{ActiveSupport::Inflector.ordinalize(time.day)}, %Y %H:%M") },
-
:rfc822 => lambda { |time| time.strftime("%a, %d %b %Y %H:%M:%S #{time.formatted_offset(false)}") }
-
}
-
-
2
DATE_FORMATS[:nsec] = '%Y%m%d%H%M%S%9N' if RUBY_VERSION >= '1.9'
-
-
# Converts to a formatted string. See DATE_FORMATS for builtin formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# time = Time.now # => Thu Jan 18 06:10:17 CST 2007
-
#
-
# time.to_formatted_s(:time) # => "06:10"
-
# time.to_s(:time) # => "06:10"
-
#
-
# time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
-
# time.to_formatted_s(:number) # => "20070118061017"
-
# time.to_formatted_s(:short) # => "18 Jan 06:10"
-
# time.to_formatted_s(:long) # => "January 18, 2007 06:10"
-
# time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
-
# time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
-
#
-
# == Adding your own time formats to +to_formatted_s+
-
# You can add your own formats to the Time::DATE_FORMATS hash.
-
# Use the format name as the hash key and either a strftime string
-
# or Proc instance that takes a time argument as the value.
-
#
-
# # config/initializers/time_formats.rb
-
# Time::DATE_FORMATS[:month_and_year] = "%B %Y"
-
# Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
-
2
def to_formatted_s(format = :default)
-
2157
if formatter = DATE_FORMATS[format]
-
2157
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
to_default_s
-
end
-
end
-
2
alias_method :to_default_s, :to_s
-
2
alias_method :to_s, :to_formatted_s
-
-
# Returns the UTC offset as an +HH:MM formatted string.
-
#
-
# Time.local(2000).formatted_offset # => "-06:00"
-
# Time.local(2000).formatted_offset(false) # => "-0600"
-
2
def formatted_offset(colon = true, alternate_utc_string = nil)
-
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Converts a Time object to a Date, dropping hour, minute, and second precision.
-
#
-
# my_time = Time.now # => Mon Nov 12 22:59:51 -0500 2007
-
# my_time.to_date # => Mon, 12 Nov 2007
-
#
-
# your_time = Time.parse("1/13/2009 1:13:03 P.M.") # => Tue Jan 13 13:13:03 -0500 2009
-
# your_time.to_date # => Tue, 13 Jan 2009
-
def to_date
-
::Date.new(year, month, day)
-
2
end unless method_defined?(:to_date)
-
-
# A method to keep Time, Date and DateTime instances interchangeable on conversions.
-
# In this case, it simply returns +self+.
-
def to_time
-
self
-
2
end unless method_defined?(:to_time)
-
-
# Converts a Time instance to a Ruby DateTime instance, preserving UTC offset.
-
#
-
# my_time = Time.now # => Mon Nov 12 23:04:21 -0500 2007
-
# my_time.to_datetime # => Mon, 12 Nov 2007 23:04:21 -0500
-
#
-
# your_time = Time.parse("1/13/2009 1:13:03 P.M.") # => Tue Jan 13 13:13:03 -0500 2009
-
# your_time.to_datetime # => Tue, 13 Jan 2009 13:13:03 -0500
-
def to_datetime
-
::DateTime.civil(year, month, day, hour, min, sec, Rational(utc_offset, 86400))
-
2
end unless method_defined?(:to_datetime)
-
end
-
# Pre-1.9 versions of Ruby have a bug with marshaling Time instances, where utc instances are
-
# unmarshalled in the local zone, instead of utc. We're layering behavior on the _dump and _load
-
# methods so that utc instances can be flagged on dump, and coerced back to utc on load.
-
2
if !Marshal.load(Marshal.dump(Time.now.utc)).utc?
-
class Time
-
class << self
-
alias_method :_load_without_utc_flag, :_load
-
def _load(marshaled_time)
-
time = _load_without_utc_flag(marshaled_time)
-
time.instance_eval do
-
if defined?(@marshal_with_utc_coercion)
-
val = remove_instance_variable("@marshal_with_utc_coercion")
-
end
-
val ? utc : self
-
end
-
end
-
end
-
-
alias_method :_dump_without_utc_flag, :_dump
-
def _dump(*args)
-
obj = dup
-
obj.instance_variable_set('@marshal_with_utc_coercion', utc?)
-
obj.send :_dump_without_utc_flag, *args
-
end
-
end
-
end
-
-
# Ruby 1.9.2 adds utc_offset and zone to Time, but marshaling only
-
# preserves utc_offset. Preserve zone also, even though it may not
-
# work in some edge cases.
-
2
if Time.local(2010).zone != Marshal.load(Marshal.dump(Time.local(2010))).zone
-
2
class Time
-
2
class << self
-
2
alias_method :_load_without_zone, :_load
-
2
def _load(marshaled_time)
-
time = _load_without_zone(marshaled_time)
-
time.instance_eval do
-
if zone = defined?(@_zone) && remove_instance_variable('@_zone')
-
ary = to_a
-
ary[0] += subsec if ary[0] == sec
-
ary[-1] = zone
-
utc? ? Time.utc(*ary) : Time.local(*ary)
-
else
-
self
-
end
-
end
-
end
-
end
-
-
2
alias_method :_dump_without_zone, :_dump
-
2
def _dump(*args)
-
obj = dup
-
obj.instance_variable_set('@_zone', zone)
-
obj.send :_dump_without_zone, *args
-
end
-
end
-
end
-
2
require 'date'
-
-
2
class Time
-
# Ruby 1.8-cvs and early 1.9 series define private Time#to_date
-
2
%w(to_date to_datetime).each do |method|
-
4
if private_instance_methods.include?(method) || private_instance_methods.include?(method.to_sym)
-
public method
-
end
-
end
-
end
-
2
require 'active_support/time_with_zone'
-
-
2
class Time
-
2
class << self
-
2
attr_accessor :zone_default
-
-
# Returns the TimeZone for the current request, if this has been set (via Time.zone=).
-
# If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>.
-
2
def zone
-
3763
Thread.current[:time_zone] || zone_default
-
end
-
-
# Sets <tt>Time.zone</tt> to a TimeZone object for the current request/thread.
-
#
-
# This method accepts any of the following:
-
#
-
# * A Rails TimeZone object.
-
# * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", <tt>-5.hours</tt>).
-
# * A TZInfo::Timezone object.
-
# * An identifier for a TZInfo::Timezone object (e.g., "America/New_York").
-
#
-
# Here's an example of how you might set <tt>Time.zone</tt> on a per request basis and reset it when the request is done.
-
# <tt>current_user.time_zone</tt> just needs to return a string identifying the user's preferred time zone:
-
#
-
# class ApplicationController < ActionController::Base
-
# around_filter :set_time_zone
-
#
-
# def set_time_zone
-
# old_time_zone = Time.zone
-
# Time.zone = current_user.time_zone if logged_in?
-
# yield
-
# ensure
-
# Time.zone = old_time_zone
-
# end
-
# end
-
2
def zone=(time_zone)
-
Thread.current[:time_zone] = find_zone!(time_zone)
-
end
-
-
# Allows override of <tt>Time.zone</tt> locally inside supplied block; resets <tt>Time.zone</tt> to existing value when done.
-
2
def use_zone(time_zone)
-
new_zone = find_zone!(time_zone)
-
begin
-
old_zone, ::Time.zone = ::Time.zone, new_zone
-
yield
-
ensure
-
::Time.zone = old_zone
-
end
-
end
-
-
# Returns a TimeZone instance or nil, or raises an ArgumentError for invalid timezones.
-
2
def find_zone!(time_zone)
-
2197
return time_zone if time_zone.nil? || time_zone.is_a?(ActiveSupport::TimeZone)
-
# lookup timezone based on identifier (unless we've been passed a TZInfo::Timezone)
-
2
unless time_zone.respond_to?(:period_for_local)
-
2
time_zone = ActiveSupport::TimeZone[time_zone] || TZInfo::Timezone.get(time_zone)
-
end
-
# Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone
-
2
time_zone.is_a?(ActiveSupport::TimeZone) ? time_zone : ActiveSupport::TimeZone.create(time_zone.name, nil, time_zone)
-
rescue TZInfo::InvalidTimezoneIdentifier
-
raise ArgumentError, "Invalid Timezone: #{time_zone}"
-
end
-
-
2
def find_zone(time_zone)
-
find_zone!(time_zone) rescue nil
-
end
-
end
-
-
# Returns the simultaneous time in <tt>Time.zone</tt>.
-
#
-
# Time.zone = 'Hawaii' # => 'Hawaii'
-
# Time.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
#
-
# This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone
-
# instead of the operating system's time zone.
-
#
-
# You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
-
# and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
-
#
-
# Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
-
2
def in_time_zone(zone = ::Time.zone)
-
2195
return self unless zone
-
-
2195
ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.find_zone!(zone))
-
end
-
end
-
# encoding: utf-8
-
-
2
if RUBY_VERSION >= '1.9'
-
2
require 'uri'
-
-
2
str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese.
-
-
2
parser = URI::Parser.new
-
-
2
unless str == parser.unescape(parser.escape(str))
-
2
URI::Parser.class_eval do
-
2
remove_method :unescape
-
2
def unescape(str, escaped = /%[a-fA-F\d]{2}/)
-
# TODO: Are we actually sure that ASCII == UTF-8?
-
# YK: My initial experiments say yes, but let's be sure please
-
enc = str.encoding
-
enc = Encoding::UTF_8 if enc == Encoding::US_ASCII
-
str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(enc)
-
end
-
end
-
end
-
end
-
-
2
module URI
-
2
class << self
-
2
def parser
-
@parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI
-
end
-
end
-
end
-
2
require 'set'
-
2
require 'thread'
-
2
require 'pathname'
-
2
require 'active_support/core_ext/module/aliasing'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/module/introspection'
-
2
require 'active_support/core_ext/module/anonymous'
-
2
require 'active_support/core_ext/module/qualified_const'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/load_error'
-
2
require 'active_support/core_ext/name_error'
-
2
require 'active_support/core_ext/string/starts_ends_with'
-
2
require 'active_support/inflector'
-
-
2
module ActiveSupport #:nodoc:
-
2
module Dependencies #:nodoc:
-
2
extend self
-
-
# Should we turn on Ruby warnings on the first load of dependent files?
-
2
mattr_accessor :warnings_on_first_load
-
2
self.warnings_on_first_load = false
-
-
# All files ever loaded.
-
2
mattr_accessor :history
-
2
self.history = Set.new
-
-
# All files currently loaded.
-
2
mattr_accessor :loaded
-
2
self.loaded = Set.new
-
-
# Should we load files or require them?
-
2
mattr_accessor :mechanism
-
2
self.mechanism = ENV['NO_RELOAD'] ? :require : :load
-
-
# The set of directories from which we may automatically load files. Files
-
# under these directories will be reloaded on each request in development mode,
-
# unless the directory also appears in autoload_once_paths.
-
2
mattr_accessor :autoload_paths
-
2
self.autoload_paths = []
-
-
# The set of directories from which automatically loaded constants are loaded
-
# only once. All directories in this set must also be present in +autoload_paths+.
-
2
mattr_accessor :autoload_once_paths
-
2
self.autoload_once_paths = []
-
-
# An array of qualified constant names that have been loaded. Adding a name to
-
# this array will cause it to be unloaded the next time Dependencies are cleared.
-
2
mattr_accessor :autoloaded_constants
-
2
self.autoloaded_constants = []
-
-
# An array of constant names that need to be unloaded on every request. Used
-
# to allow arbitrary constants to be marked for unloading.
-
2
mattr_accessor :explicitly_unloadable_constants
-
2
self.explicitly_unloadable_constants = []
-
-
# The logger is used for generating information on the action run-time (including benchmarking) if available.
-
# Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
-
2
mattr_accessor :logger
-
-
# Set to true to enable logging of const_missing and file loads
-
2
mattr_accessor :log_activity
-
2
self.log_activity = false
-
-
# The WatchStack keeps a stack of the modules being watched as files are loaded.
-
# If a file in the process of being loaded (parent.rb) triggers the load of
-
# another file (child.rb) the stack will ensure that child.rb handles the new
-
# constants.
-
#
-
# If child.rb is being autoloaded, its constants will be added to
-
# autoloaded_constants. If it was being `require`d, they will be discarded.
-
#
-
# This is handled by walking back up the watch stack and adding the constants
-
# found by child.rb to the list of original constants in parent.rb
-
2
class WatchStack
-
2
include Enumerable
-
-
# @watching is a stack of lists of constants being watched. For instance,
-
# if parent.rb is autoloaded, the stack will look like [[Object]]. If parent.rb
-
# then requires namespace/child.rb, the stack will look like [[Object], [Namespace]].
-
-
2
def initialize
-
2
@watching = []
-
2
@stack = Hash.new { |h,k| h[k] = [] }
-
end
-
-
2
def each(&block)
-
@stack.each(&block)
-
end
-
-
2
def watching?
-
1570
!@watching.empty?
-
end
-
-
# return a list of new constants found since the last call to watch_namespaces
-
2
def new_constants
-
constants = []
-
-
# Grab the list of namespaces that we're looking for new constants under
-
@watching.last.each do |namespace|
-
# Retrieve the constants that were present under the namespace when watch_namespaces
-
# was originally called
-
original_constants = @stack[namespace].last
-
-
mod = Inflector.constantize(namespace) if Dependencies.qualified_const_defined?(namespace)
-
next unless mod.is_a?(Module)
-
-
# Get a list of the constants that were added
-
new_constants = mod.local_constant_names - original_constants
-
-
# self[namespace] returns an Array of the constants that are being evaluated
-
# for that namespace. For instance, if parent.rb requires child.rb, the first
-
# element of self[Object] will be an Array of the constants that were present
-
# before parent.rb was required. The second element will be an Array of the
-
# constants that were present before child.rb was required.
-
@stack[namespace].each do |namespace_constants|
-
namespace_constants.concat(new_constants)
-
end
-
-
# Normalize the list of new constants, and add them to the list we will return
-
new_constants.each do |suffix|
-
constants << ([namespace, suffix] - ["Object"]).join("::")
-
end
-
end
-
constants
-
ensure
-
# A call to new_constants is always called after a call to watch_namespaces
-
pop_modules(@watching.pop)
-
end
-
-
# Add a set of modules to the watch stack, remembering the initial constants
-
2
def watch_namespaces(namespaces)
-
watching = []
-
namespaces.map do |namespace|
-
module_name = Dependencies.to_constant_name(namespace)
-
original_constants = Dependencies.qualified_const_defined?(module_name) ?
-
Inflector.constantize(module_name).local_constant_names : []
-
-
watching << module_name
-
@stack[module_name] << original_constants
-
end
-
@watching << watching
-
end
-
-
2
private
-
2
def pop_modules(modules)
-
modules.each { |mod| @stack[mod].pop }
-
end
-
end
-
-
# An internal stack used to record which constants are loaded by any block.
-
2
mattr_accessor :constant_watch_stack
-
2
self.constant_watch_stack = WatchStack.new
-
-
# Module includes this module
-
2
module ModuleConstMissing #:nodoc:
-
2
def self.append_features(base)
-
2
base.class_eval do
-
# Emulate #exclude via an ivar
-
2
return if defined?(@_const_missing) && @_const_missing
-
2
@_const_missing = instance_method(:const_missing)
-
2
remove_method(:const_missing)
-
end
-
2
super
-
end
-
-
2
def self.exclude_from(base)
-
base.class_eval do
-
define_method :const_missing, @_const_missing
-
@_const_missing = nil
-
end
-
end
-
-
# Use const_missing to autoload associations so we don't have to
-
# require_association when using single-table inheritance.
-
2
def const_missing(const_name, nesting = nil)
-
97
klass_name = name.presence || "Object"
-
-
97
unless nesting
-
# We'll assume that the nesting of Foo::Bar is ["Foo::Bar", "Foo"]
-
# even though it might not be, such as in the case of
-
# class Foo::Bar; Baz; end
-
97
nesting = []
-
207
klass_name.to_s.scan(/::|$/) { nesting.unshift $` }
-
end
-
-
# If there are multiple levels of nesting to search under, the top
-
# level is the one we want to report as the lookup fail.
-
97
error = nil
-
-
97
nesting.each do |namespace|
-
98
begin
-
98
return Dependencies.load_missing_constant Inflector.constantize(namespace), const_name
-
rescue NoMethodError then raise
-
rescue NameError => e
-
70
error ||= e
-
end
-
end
-
-
# Raise the first error for this set. If this const_missing came from an
-
# earlier const_missing, this will result in the real error bubbling
-
# all the way up
-
69
raise error
-
end
-
-
2
def unloadable(const_desc = self)
-
super(const_desc)
-
end
-
end
-
-
# Object includes this module
-
2
module Loadable #:nodoc:
-
2
def self.exclude_from(base)
-
base.class_eval { define_method(:load, Kernel.instance_method(:load)) }
-
end
-
-
2
def require_or_load(file_name)
-
Dependencies.require_or_load(file_name)
-
end
-
-
2
def require_dependency(file_name, message = "No such file to load -- %s")
-
238
unless file_name.is_a?(String)
-
raise ArgumentError, "the file name must be a String -- you passed #{file_name.inspect}"
-
end
-
-
238
Dependencies.depend_on(file_name, false, message)
-
end
-
-
2
def require_association(file_name)
-
Dependencies.associate_with(file_name)
-
end
-
-
2
def load_dependency(file)
-
2824
if Dependencies.load? && ActiveSupport::Dependencies.constant_watch_stack.watching?
-
Dependencies.new_constants_in(Object) { yield }
-
else
-
2824
yield
-
end
-
rescue Exception => exception # errors from loading file
-
42
exception.blame_file! file
-
42
raise
-
end
-
-
2
def load(file, wrap = false)
-
18
result = false
-
36
load_dependency(file) { result = super }
-
18
result
-
end
-
-
2
def require(file)
-
2806
result = false
-
5612
load_dependency(file) { result = super }
-
2764
result
-
end
-
-
# Mark the given constant as unloadable. Unloadable constants are removed each
-
# time dependencies are cleared.
-
#
-
# Note that marking a constant for unloading need only be done once. Setup
-
# or init scripts may list each unloadable constant that may need unloading;
-
# each constant will be removed for every subsequent clear, as opposed to for
-
# the first clear.
-
#
-
# The provided constant descriptor may be a (non-anonymous) module or class,
-
# or a qualified constant name as a string or symbol.
-
#
-
# Returns true if the constant was not previously marked for unloading, false
-
# otherwise.
-
2
def unloadable(const_desc)
-
Dependencies.mark_for_unload const_desc
-
end
-
end
-
-
# Exception file-blaming
-
2
module Blamable #:nodoc:
-
2
def blame_file!(file)
-
42
(@blamed_files ||= []).unshift file
-
end
-
-
2
def blamed_files
-
28
@blamed_files ||= []
-
end
-
-
2
def describe_blame
-
return nil if blamed_files.empty?
-
"This error occurred while loading the following files:\n #{blamed_files.join "\n "}"
-
end
-
-
2
def copy_blame!(exc)
-
28
@blamed_files = exc.blamed_files.clone
-
28
self
-
end
-
end
-
-
2
def hook!
-
4
Object.class_eval { include Loadable }
-
4
Module.class_eval { include ModuleConstMissing }
-
4
Exception.class_eval { include Blamable }
-
2
true
-
end
-
-
2
def unhook!
-
ModuleConstMissing.exclude_from(Module)
-
Loadable.exclude_from(Object)
-
true
-
end
-
-
2
def load?
-
2954
mechanism == :load
-
end
-
-
2
def depend_on(file_name, swallow_load_errors = false, message = "No such file to load -- %s.rb")
-
238
path = search_for_file(file_name)
-
238
require_or_load(path || file_name)
-
rescue LoadError => load_error
-
28
unless swallow_load_errors
-
28
if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
-
28
raise LoadError.new(message % file_name).copy_blame!(load_error)
-
end
-
raise
-
end
-
end
-
-
2
def associate_with(file_name)
-
depend_on(file_name, true)
-
end
-
-
2
def clear
-
log_call
-
loaded.clear
-
remove_unloadable_constants!
-
end
-
-
2
def require_or_load(file_name, const_path = nil)
-
258
log_call file_name, const_path
-
258
file_name = $1 if file_name =~ /^(.*)\.rb$/
-
258
expanded = File.expand_path(file_name)
-
258
return if loaded.include?(expanded)
-
-
# Record that we've seen this file *before* loading it to avoid an
-
# infinite loop with mutual dependencies.
-
130
loaded << expanded
-
-
130
begin
-
130
if load?
-
log "loading #{file_name}"
-
-
# Enable warnings if this file has not been loaded before and
-
# warnings_on_first_load is set.
-
load_args = ["#{file_name}.rb"]
-
load_args << const_path unless const_path.nil?
-
-
if !warnings_on_first_load or history.include?(expanded)
-
result = load_file(*load_args)
-
else
-
enable_warnings { result = load_file(*load_args) }
-
end
-
else
-
130
log "requiring #{file_name}"
-
130
result = require file_name
-
end
-
rescue Exception
-
28
loaded.delete expanded
-
28
raise
-
end
-
-
# Record history *after* loading so first load gets warnings.
-
102
history << expanded
-
102
return result
-
end
-
-
# Is the provided constant path defined?
-
2
if Module.method(:const_defined?).arity == 1
-
def qualified_const_defined?(path)
-
Object.qualified_const_defined?(path.sub(/^::/, ''))
-
end
-
else
-
2
def qualified_const_defined?(path)
-
98
Object.qualified_const_defined?(path.sub(/^::/, ''), false)
-
end
-
end
-
-
2
if Module.method(:const_defined?).arity == 1
-
# Does this module define this constant?
-
# Wrapper to accommodate changing Module#const_defined? in Ruby 1.9
-
def local_const_defined?(mod, const)
-
mod.const_defined?(const)
-
end
-
else
-
2
def local_const_defined?(mod, const) #:nodoc:
-
162
mod.const_defined?(const, false)
-
end
-
end
-
-
# Given +path+, a filesystem path to a ruby file, return an array of constant
-
# paths which would cause Dependencies to attempt to load this file.
-
2
def loadable_constants_for_path(path, bases = autoload_paths)
-
path = $1 if path =~ /\A(.*)\.rb\Z/
-
expanded_path = File.expand_path(path)
-
paths = []
-
-
bases.each do |root|
-
expanded_root = File.expand_path(root)
-
next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
-
-
nesting = expanded_path[(expanded_root.size)..-1]
-
nesting = nesting[1..-1] if nesting && nesting[0] == ?/
-
next if nesting.blank?
-
-
paths << nesting.camelize
-
end
-
-
paths.uniq!
-
paths
-
end
-
-
# Search for a file in autoload_paths matching the provided suffix.
-
2
def search_for_file(path_suffix)
-
336
path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb")
-
-
336
autoload_paths.each do |root|
-
1676
path = File.join(root, path_suffix)
-
1676
return path if File.file? path
-
end
-
nil # Gee, I sure wish we had first_match ;-)
-
end
-
-
# Does the provided path_suffix correspond to an autoloadable module?
-
# Instead of returning a boolean, the autoload base for this module is returned.
-
2
def autoloadable_module?(path_suffix)
-
78
autoload_paths.each do |load_path|
-
546
return load_path if File.directory? File.join(load_path, path_suffix)
-
end
-
nil
-
end
-
-
2
def load_once_path?(path)
-
# to_s works around a ruby1.9 issue where #starts_with?(Pathname) will always return false
-
autoload_once_paths.any? { |base| path.starts_with? base.to_s }
-
end
-
-
# Attempt to autoload the provided module name by searching for a directory
-
# matching the expected path suffix. If found, the module is created and assigned
-
# to +into+'s constants with the name +const_name+. Provided that the directory
-
# was loaded from a reloadable base path, it is added to the set of constants
-
# that are to be unloaded.
-
2
def autoload_module!(into, const_name, qualified_name, path_suffix)
-
78
return nil unless base_path = autoloadable_module?(path_suffix)
-
mod = Module.new
-
into.const_set const_name, mod
-
autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path)
-
return mod
-
end
-
-
# Load the file at the provided path. +const_paths+ is a set of qualified
-
# constant names. When loading the file, Dependencies will watch for the
-
# addition of these constants. Each that is defined will be marked as
-
# autoloaded, and will be removed when Dependencies.clear is next called.
-
#
-
# If the second parameter is left off, then Dependencies will construct a set
-
# of names that the file at +path+ may define. See
-
# +loadable_constants_for_path+ for more details.
-
2
def load_file(path, const_paths = loadable_constants_for_path(path))
-
log_call path, const_paths
-
const_paths = [const_paths].compact unless const_paths.is_a? Array
-
parent_paths = const_paths.collect { |const_path| /(.*)::[^:]+\Z/ =~ const_path ? $1 : :Object }
-
-
result = nil
-
newly_defined_paths = new_constants_in(*parent_paths) do
-
result = Kernel.load path
-
end
-
-
autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
-
autoloaded_constants.uniq!
-
log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
-
return result
-
end
-
-
# Return the constant path for the provided parent and constant name.
-
2
def qualified_name_for(mod, name)
-
98
mod_name = to_constant_name mod
-
98
mod_name == "Object" ? name.to_s : "#{mod_name}::#{name}"
-
end
-
-
# Load the constant named +const_name+ which is missing from +from_mod+. If
-
# it is not possible to load the constant into from_mod, try its parent module
-
# using const_missing.
-
2
def load_missing_constant(from_mod, const_name)
-
98
log_call from_mod, const_name
-
-
98
unless qualified_const_defined?(from_mod.name) && Inflector.constantize(from_mod.name).equal?(from_mod)
-
raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
-
end
-
-
98
raise NameError, "#{from_mod} is not missing constant #{const_name}!" if local_const_defined?(from_mod, const_name)
-
-
98
qualified_name = qualified_name_for from_mod, const_name
-
98
path_suffix = qualified_name.underscore
-
-
98
file_path = search_for_file(path_suffix)
-
-
98
if file_path && ! loaded.include?(File.expand_path(file_path).sub(/\.rb\z/, '')) # We found a matching file to load
-
20
require_or_load file_path
-
20
raise LoadError, "Expected #{file_path} to define #{qualified_name}" unless local_const_defined?(from_mod, const_name)
-
20
return from_mod.const_get(const_name)
-
elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
-
return mod
-
78
elsif (parent = from_mod.parent) && parent != from_mod &&
-
44
! from_mod.parents.any? { |p| local_const_defined?(p, const_name) }
-
# If our parents do not have a constant named +const_name+ then we are free
-
# to attempt to load upwards. If they do have such a constant, then this
-
# const_missing must be due to from_mod::const_name, which should not
-
# return constants from from_mod's parents.
-
8
begin
-
8
return parent.const_missing(const_name)
-
rescue NameError => e
-
raise unless e.missing_name? qualified_name_for(parent, const_name)
-
end
-
end
-
-
70
raise NameError,
-
"uninitialized constant #{qualified_name}",
-
3098
caller.reject {|l| l.starts_with? __FILE__ }
-
end
-
-
# Remove the constants that have been autoloaded, and those that have been
-
# marked for unloading. Before each constant is removed a callback is sent
-
# to its class/module if it implements +before_remove_const+.
-
#
-
# The callback implementation should be restricted to cleaning up caches, etc.
-
# as the environment will be in an inconsistent state, e.g. other constants
-
# may have already been unloaded and not accessible.
-
2
def remove_unloadable_constants!
-
autoloaded_constants.each { |const| remove_constant const }
-
autoloaded_constants.clear
-
Reference.clear!
-
explicitly_unloadable_constants.each { |const| remove_constant const }
-
end
-
-
2
class ClassCache
-
2
def initialize
-
2
@store = Hash.new
-
end
-
-
2
def empty?
-
@store.empty?
-
end
-
-
2
def key?(key)
-
@store.key?(key)
-
end
-
-
2
def get(key)
-
44
key = key.name if key.respond_to?(:name)
-
44
@store[key] ||= Inflector.constantize(key)
-
end
-
2
alias :[] :get
-
-
2
def safe_get(key)
-
key = key.name if key.respond_to?(:name)
-
@store[key] || begin
-
klass = Inflector.safe_constantize(key)
-
@store[key] = klass
-
end
-
end
-
-
2
def store(klass)
-
return self unless klass.respond_to?(:name)
-
raise(ArgumentError, 'anonymous classes cannot be cached') if klass.name.empty?
-
@store[klass.name] = klass
-
self
-
end
-
-
2
def clear!
-
@store.clear
-
end
-
end
-
-
2
Reference = ClassCache.new
-
-
# Store a reference to a class +klass+.
-
2
def reference(klass)
-
Reference.store klass
-
end
-
-
# Get the reference for class named +name+.
-
# Raises an exception if referenced class does not exist.
-
2
def constantize(name)
-
40
Reference.get(name)
-
end
-
-
# Get the reference for class named +name+ if one exists.
-
# Otherwise returns nil.
-
2
def safe_constantize(name)
-
Reference.safe_get(name)
-
end
-
-
# Determine if the given constant has been automatically loaded.
-
2
def autoloaded?(desc)
-
# No name => anonymous module.
-
return false if desc.is_a?(Module) && desc.anonymous?
-
name = to_constant_name desc
-
return false unless qualified_const_defined? name
-
return autoloaded_constants.include?(name)
-
end
-
-
# Will the provided constant descriptor be unloaded?
-
2
def will_unload?(const_desc)
-
autoloaded?(const_desc) ||
-
explicitly_unloadable_constants.include?(to_constant_name(const_desc))
-
end
-
-
# Mark the provided constant name for unloading. This constant will be
-
# unloaded on each request, not just the next one.
-
2
def mark_for_unload(const_desc)
-
name = to_constant_name const_desc
-
if explicitly_unloadable_constants.include? name
-
return false
-
else
-
explicitly_unloadable_constants << name
-
return true
-
end
-
end
-
-
# Run the provided block and detect the new constants that were loaded during
-
# its execution. Constants may only be regarded as 'new' once -- so if the
-
# block calls +new_constants_in+ again, then the constants defined within the
-
# inner call will not be reported in this one.
-
#
-
# If the provided block does not run to completion, and instead raises an
-
# exception, any new constants are regarded as being only partially defined
-
# and will be removed immediately.
-
2
def new_constants_in(*descs)
-
log_call(*descs)
-
-
constant_watch_stack.watch_namespaces(descs)
-
aborting = true
-
-
begin
-
yield # Now yield to the code that is to define new constants.
-
aborting = false
-
ensure
-
new_constants = constant_watch_stack.new_constants
-
-
log "New constants: #{new_constants * ', '}"
-
return new_constants unless aborting
-
-
log "Error during loading, removing partially loaded constants "
-
new_constants.each {|c| remove_constant(c) }.clear
-
end
-
-
return []
-
end
-
-
# Convert the provided const desc to a qualified constant name (as a string).
-
# A module, class, symbol, or string may be provided.
-
2
def to_constant_name(desc) #:nodoc:
-
98
case desc
-
when String then desc.sub(/^::/, '')
-
when Symbol then desc.to_s
-
when Module
-
desc.name.presence ||
-
98
raise(ArgumentError, "Anonymous modules have no name to be referenced by")
-
else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
-
end
-
end
-
-
2
def remove_constant(const) #:nodoc:
-
return false unless qualified_const_defined? const
-
-
# Normalize ::Foo, Foo, Object::Foo, and ::Object::Foo to Object::Foo
-
names = const.to_s.sub(/^::(Object)?/, 'Object::').split("::")
-
to_remove = names.pop
-
parent = Inflector.constantize(names * '::')
-
-
log "removing constant #{const}"
-
constantized = constantize(const)
-
constantized.before_remove_const if constantized.respond_to?(:before_remove_const)
-
parent.instance_eval { remove_const to_remove }
-
-
return true
-
end
-
-
2
protected
-
2
def log_call(*args)
-
356
if log_activity?
-
arg_str = args.collect { |arg| arg.inspect } * ', '
-
/in `([a-z_\?\!]+)'/ =~ caller(1).first
-
selector = $1 || '<unknown>'
-
log "called #{selector}(#{arg_str})"
-
end
-
end
-
-
2
def log(msg)
-
130
logger.debug "Dependencies: #{msg}" if log_activity?
-
end
-
-
2
def log_activity?
-
486
logger && log_activity
-
end
-
end
-
end
-
-
2
ActiveSupport::Dependencies.hook!
-
2
require "active_support/inflector/methods"
-
2
require "active_support/lazy_load_hooks"
-
-
2
module ActiveSupport
-
2
module Autoload
-
2
@@autoloads = {}
-
2
@@under_path = nil
-
2
@@at_path = nil
-
2
@@eager_autoload = false
-
-
2
def autoload(const_name, path = @@at_path)
-
636
full = [self.name, @@under_path, const_name.to_s, path].compact.join("::")
-
636
location = path || Inflector.underscore(full)
-
-
636
if @@eager_autoload
-
282
@@autoloads[const_name] = location
-
end
-
636
super const_name, location
-
end
-
-
2
def autoload_under(path)
-
14
@@under_path, old_path = path, @@under_path
-
14
yield
-
ensure
-
14
@@under_path = old_path
-
end
-
-
2
def autoload_at(path)
-
8
@@at_path, old_path = path, @@at_path
-
8
yield
-
ensure
-
8
@@at_path = old_path
-
end
-
-
2
def eager_autoload
-
24
old_eager, @@eager_autoload = @@eager_autoload, true
-
24
yield
-
ensure
-
24
@@eager_autoload = old_eager
-
end
-
-
2
def self.eager_autoload!
-
@@autoloads.values.each { |file| require file }
-
end
-
-
2
def autoloads
-
@@autoloads
-
end
-
end
-
end
-
2
require 'active_support/deprecation/behaviors'
-
2
require 'active_support/deprecation/reporting'
-
2
require 'active_support/deprecation/method_wrappers'
-
2
require 'active_support/deprecation/proxy_wrappers'
-
-
2
module ActiveSupport
-
2
module Deprecation
-
2
class << self
-
# The version the deprecated behavior will be removed, by default.
-
2
attr_accessor :deprecation_horizon
-
end
-
2
self.deprecation_horizon = '4.0'
-
-
# By default, warnings are not silenced and debugging is off.
-
2
self.silenced = false
-
2
self.debug = false
-
end
-
end
-
2
require "active_support/notifications"
-
2
require "active_support/core_ext/array/wrap"
-
-
2
module ActiveSupport
-
2
module Deprecation
-
2
class << self
-
# Whether to print a backtrace along with the warning.
-
2
attr_accessor :debug
-
-
# Returns the set behavior or if one isn't set, defaults to +:stderr+
-
2
def behavior
-
@behavior ||= [DEFAULT_BEHAVIORS[:stderr]]
-
end
-
-
# Sets the behavior to the specified value. Can be a single value or an array.
-
#
-
# Examples
-
#
-
# ActiveSupport::Deprecation.behavior = :stderr
-
# ActiveSupport::Deprecation.behavior = [:stderr, :log]
-
2
def behavior=(behavior)
-
4
@behavior = Array.wrap(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b }
-
end
-
end
-
-
# Default warning behaviors per Rails.env.
-
2
DEFAULT_BEHAVIORS = {
-
:stderr => Proc.new { |message, callstack|
-
$stderr.puts(message)
-
$stderr.puts callstack.join("\n ") if debug
-
},
-
:log => Proc.new { |message, callstack|
-
logger =
-
if defined?(Rails) && Rails.logger
-
Rails.logger
-
else
-
require 'logger'
-
Logger.new($stderr)
-
end
-
logger.warn message
-
logger.debug callstack.join("\n ") if debug
-
},
-
:notify => Proc.new { |message, callstack|
-
ActiveSupport::Notifications.instrument("deprecation.rails",
-
:message => message, :callstack => callstack)
-
}
-
}
-
end
-
end
-
2
require 'active_support/core_ext/module/deprecation'
-
2
require 'active_support/core_ext/module/aliasing'
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
module ActiveSupport
-
2
class << Deprecation
-
# Declare that a method has been deprecated.
-
2
def deprecate_methods(target_module, *method_names)
-
28
options = method_names.extract_options!
-
28
method_names += options.keys
-
-
28
method_names.each do |method_name|
-
28
target_module.alias_method_chain(method_name, :deprecation) do |target, punctuation|
-
28
target_module.module_eval(<<-end_eval, __FILE__, __LINE__ + 1)
-
def #{target}_with_deprecation#{punctuation}(*args, &block)
-
::ActiveSupport::Deprecation.warn(
-
::ActiveSupport::Deprecation.deprecated_method_warning(
-
:#{method_name},
-
#{options[method_name].inspect}),
-
caller
-
)
-
send(:#{target}_without_deprecation#{punctuation}, *args, &block)
-
end
-
end_eval
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/inflector/methods'
-
-
2
module ActiveSupport
-
2
module Deprecation
-
2
class DeprecationProxy #:nodoc:
-
2
def self.new(*args, &block)
-
4
object = args.first
-
-
4
return object unless object
-
4
super
-
end
-
-
134
instance_methods.each { |m| undef_method m unless m =~ /^__|^object_id$/ }
-
-
# Don't give a deprecation warning on inspect since test/unit and error
-
# logs rely on it for diagnostics.
-
2
def inspect
-
target.inspect
-
end
-
-
2
private
-
2
def method_missing(called, *args, &block)
-
warn caller, called, args
-
target.__send__(called, *args, &block)
-
end
-
end
-
-
2
class DeprecatedObjectProxy < DeprecationProxy #:nodoc:
-
2
def initialize(object, message)
-
@object = object
-
@message = message
-
end
-
-
2
private
-
2
def target
-
@object
-
end
-
-
2
def warn(callstack, called, args)
-
ActiveSupport::Deprecation.warn(@message, callstack)
-
end
-
end
-
-
# Stand-in for <tt>@request</tt>, <tt>@attributes</tt>, <tt>@params</tt>, etc.
-
# which emits deprecation warnings on any method call (except +inspect+).
-
2
class DeprecatedInstanceVariableProxy < DeprecationProxy #:nodoc:
-
2
def initialize(instance, method, var = "@#{method}")
-
@instance, @method, @var = instance, method, var
-
end
-
-
2
private
-
2
def target
-
@instance.__send__(@method)
-
end
-
-
2
def warn(callstack, called, args)
-
ActiveSupport::Deprecation.warn("#{@var} is deprecated! Call #{@method}.#{called} instead of #{@var}.#{called}. Args: #{args.inspect}", callstack)
-
end
-
end
-
-
2
class DeprecatedConstantProxy < DeprecationProxy #:nodoc:all
-
2
def initialize(old_const, new_const)
-
4
@old_const = old_const
-
4
@new_const = new_const
-
end
-
-
2
def class
-
target.class
-
end
-
-
2
private
-
2
def target
-
ActiveSupport::Inflector.constantize(@new_const.to_s)
-
end
-
-
2
def warn(callstack, called, args)
-
ActiveSupport::Deprecation.warn("#{@old_const} is deprecated! Use #{@new_const} instead.", callstack)
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
2
module Deprecation
-
2
class << self
-
2
attr_accessor :silenced
-
-
# Outputs a deprecation warning to the output configured by <tt>ActiveSupport::Deprecation.behavior</tt>
-
#
-
# ActiveSupport::Deprecation.warn("something broke!")
-
# # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
-
2
def warn(message = nil, callstack = caller)
-
return if silenced
-
deprecation_message(callstack, message).tap do |m|
-
behavior.each { |b| b.call(m, callstack) }
-
end
-
end
-
-
# Silence deprecation warnings within the block.
-
2
def silence
-
old_silenced, @silenced = @silenced, true
-
yield
-
ensure
-
@silenced = old_silenced
-
end
-
-
2
def deprecated_method_warning(method_name, message = nil)
-
warning = "#{method_name} is deprecated and will be removed from Rails #{deprecation_horizon}"
-
case message
-
when Symbol then "#{warning} (use #{message} instead)"
-
when String then "#{warning} (#{message})"
-
else warning
-
end
-
end
-
-
2
private
-
2
def deprecation_message(callstack, message = nil)
-
message ||= "You are using deprecated behavior which will be removed from the next major or minor release."
-
message += '.' unless message =~ /\.$/
-
"DEPRECATION WARNING: #{message} #{deprecation_caller_message(callstack)}"
-
end
-
-
2
def deprecation_caller_message(callstack)
-
file, line, method = extract_callstack(callstack)
-
if file
-
if line && method
-
"(called from #{method} at #{file}:#{line})"
-
else
-
"(called from #{file}:#{line})"
-
end
-
end
-
end
-
-
2
def extract_callstack(callstack)
-
rails_gem_root = File.expand_path("../../../../..", __FILE__) + "/"
-
offending_line = callstack.find { |line| !line.start_with?(rails_gem_root) } || callstack.first
-
if offending_line
-
if md = offending_line.match(/^(.+?):(\d+)(?::in `(.*?)')?/)
-
md.captures
-
else
-
offending_line
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
# This module provides an internal implementation to track descendants
-
# which is faster than iterating through ObjectSpace.
-
2
module DescendantsTracker
-
90
@@direct_descendants = Hash.new { |h, k| h[k] = [] }
-
-
2
def self.direct_descendants(klass)
-
123
@@direct_descendants[klass]
-
end
-
-
2
def self.descendants(klass)
-
305
@@direct_descendants[klass].inject([]) do |descendants, _klass|
-
18
descendants << _klass
-
18
descendants.concat _klass.descendants
-
end
-
end
-
-
2
def self.clear
-
if defined? ActiveSupport::Dependencies
-
@@direct_descendants.each do |klass, descendants|
-
if ActiveSupport::Dependencies.autoloaded?(klass)
-
@@direct_descendants.delete(klass)
-
else
-
descendants.reject! { |v| ActiveSupport::Dependencies.autoloaded?(v) }
-
end
-
end
-
else
-
@@direct_descendants.clear
-
end
-
end
-
-
2
def inherited(base)
-
123
self.direct_descendants << base
-
123
super
-
end
-
-
2
def direct_descendants
-
123
DescendantsTracker.direct_descendants(self)
-
end
-
-
2
def descendants
-
18
DescendantsTracker.descendants(self)
-
end
-
end
-
end
-
2
require 'active_support/basic_object'
-
2
require 'active_support/core_ext/array/conversions'
-
2
require 'active_support/core_ext/object/acts_like'
-
-
2
module ActiveSupport
-
# Provides accurate date and time measurements using Date#advance and
-
# Time#advance, respectively. It mainly supports the methods on Numeric.
-
# Example:
-
#
-
# 1.month.ago # equivalent to Time.now.advance(:months => -1)
-
2
class Duration < BasicObject
-
2
attr_accessor :value, :parts
-
2
delegate :duplicable?, :to => :value # required when using ActiveSupport's BasicObject on 1.8
-
-
2
def initialize(value, parts) #:nodoc:
-
1307
@value, @parts = value, parts
-
end
-
-
# Adds another Duration or a Numeric to this Duration. Numeric values
-
# are treated as seconds.
-
2
def +(other)
-
if Duration === other
-
Duration.new(value + other.value, @parts + other.parts)
-
else
-
Duration.new(value + other, @parts + [[:seconds, other]])
-
end
-
end
-
-
# Subtracts another Duration or a Numeric from this Duration. Numeric
-
# values are treated as seconds.
-
2
def -(other)
-
self + (-other)
-
end
-
-
2
def -@ #:nodoc:
-
10
Duration.new(-value, parts.map { |type,number| [type, -number] })
-
end
-
-
2
def is_a?(klass) #:nodoc:
-
2614
Duration == klass || value.is_a?(klass)
-
end
-
2
alias :kind_of? :is_a?
-
-
# Returns true if <tt>other</tt> is also a Duration instance with the
-
# same <tt>value</tt>, or if <tt>other == value</tt>.
-
2
def ==(other)
-
12
if Duration === other
-
other.value == value
-
else
-
12
other == value
-
end
-
end
-
-
2
def self.===(other) #:nodoc:
-
11589
other.is_a?(Duration)
-
rescue ::NoMethodError
-
false
-
end
-
-
# Calculates a new Time or Date that is as far in the future
-
# as this Duration represents.
-
2
def since(time = ::Time.current)
-
1363
sum(1, time)
-
end
-
2
alias :from_now :since
-
-
# Calculates a new Time or Date that is as far in the past
-
# as this Duration represents.
-
2
def ago(time = ::Time.current)
-
68
sum(-1, time)
-
end
-
2
alias :until :ago
-
-
2
def inspect #:nodoc:
-
consolidated = parts.inject(::Hash.new(0)) { |h,part| h[part.first] += part.last; h }
-
parts = [:years, :months, :days, :minutes, :seconds].map do |length|
-
n = consolidated[length]
-
"#{n} #{n == 1 ? length.to_s.singularize : length.to_s}" if n.nonzero?
-
end.compact
-
parts = ["0 seconds"] if parts.empty?
-
parts.to_sentence(:locale => :en)
-
end
-
-
2
def as_json(options = nil) #:nodoc:
-
to_i
-
end
-
-
2
protected
-
-
2
def sum(sign, time = ::Time.current) #:nodoc:
-
1431
parts.inject(time) do |t,(type,number)|
-
1431
if t.acts_like?(:time) || t.acts_like?(:date)
-
1431
if type == :seconds
-
626
t.since(sign * number)
-
else
-
805
t.advance(type => sign * number)
-
end
-
else
-
raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
-
end
-
end
-
end
-
-
2
private
-
-
2
def method_missing(method, *args, &block) #:nodoc:
-
777
value.send(method, *args, &block)
-
end
-
end
-
end
-
2
require "active_support/core_ext/array/wrap"
-
2
require "active_support/core_ext/array/extract_options"
-
-
2
module ActiveSupport
-
# \FileUpdateChecker specifies the API used by Rails to watch files
-
# and control reloading. The API depends on four methods:
-
#
-
# * +initialize+ which expects two parameters and one block as
-
# described below;
-
#
-
# * +updated?+ which returns a boolean if there were updates in
-
# the filesystem or not;
-
#
-
# * +execute+ which executes the given block on initialization
-
# and updates the counter to the latest timestamp;
-
#
-
# * +execute_if_updated+ which just executes the block if it was updated;
-
#
-
# After initialization, a call to +execute_if_updated+ must execute
-
# the block only if there was really a change in the filesystem.
-
#
-
# == Examples
-
#
-
# This class is used by Rails to reload the I18n framework whenever
-
# they are changed upon a new request.
-
#
-
# i18n_reloader = ActiveSupport::FileUpdateChecker.new(paths) do
-
# I18n.reload!
-
# end
-
#
-
# ActionDispatch::Reloader.to_prepare do
-
# i18n_reloader.execute_if_updated
-
# end
-
#
-
2
class FileUpdateChecker
-
# It accepts two parameters on initialization. The first is an array
-
# of files and the second is an optional hash of directories. The hash must
-
# have directories as keys and the value is an array of extensions to be
-
# watched under that directory.
-
#
-
# This method must also receive a block that will be called once a path changes.
-
#
-
# == Implementation details
-
#
-
# This particular implementation checks for added and updated files,
-
# but not removed files. Directories lookup are compiled to a glob for
-
# performance. Therefore, while someone can add new files to the +files+
-
# array after initialization (and parts of Rails do depend on this feature),
-
# adding new directories after initialization is not allowed.
-
#
-
# Notice that other objects that implements FileUpdateChecker API may
-
# not even allow new files to be added after initialization. If this
-
# is the case, we recommend freezing the +files+ after initialization to
-
# avoid changes that won't make effect.
-
2
def initialize(files, dirs={}, &block)
-
6
@files = files
-
6
@glob = compile_glob(dirs)
-
6
@block = block
-
6
@updated_at = nil
-
6
@last_update_at = updated_at
-
end
-
-
# Check if any of the entries were updated. If so, the updated_at
-
# value is cached until the block is executed via +execute+ or +execute_if_updated+
-
2
def updated?
-
4
current_updated_at = updated_at
-
4
if @last_update_at < current_updated_at
-
@updated_at = updated_at
-
true
-
else
-
4
false
-
end
-
end
-
-
# Executes the given block and updates the counter to latest timestamp.
-
2
def execute
-
4
@last_update_at = updated_at
-
4
@block.call
-
ensure
-
4
@updated_at = nil
-
end
-
-
# Execute the block given if updated.
-
2
def execute_if_updated
-
4
if updated?
-
execute
-
true
-
else
-
4
false
-
end
-
end
-
-
2
private
-
-
2
def updated_at #:nodoc:
-
@updated_at || begin
-
14
all = []
-
36
all.concat @files.select { |f| File.exists?(f) }
-
14
all.concat Dir[@glob] if @glob
-
136
all.map { |path| File.mtime(path) }.max || Time.at(0)
-
14
end
-
end
-
-
2
def compile_glob(hash) #:nodoc:
-
6
hash.freeze # Freeze so changes aren't accidently pushed
-
6
return if hash.empty?
-
-
2
globs = []
-
2
hash.each do |key, value|
-
14
globs << "#{key}/**/*#{compile_ext(value)}"
-
end
-
2
"{#{globs.join(",")}}"
-
end
-
-
2
def compile_ext(array) #:nodoc:
-
14
array = Array.wrap(array)
-
14
return if array.empty?
-
14
".{#{array.join(",")}}"
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/keys'
-
-
# This class has dubious semantics and we only have it so that
-
# people can write <tt>params[:key]</tt> instead of <tt>params['key']</tt>
-
# and they get the same value for both keys.
-
-
2
module ActiveSupport
-
2
class HashWithIndifferentAccess < Hash
-
-
# Always returns true, so that <tt>Array#extract_options!</tt> finds members of this class.
-
2
def extractable_options?
-
true
-
end
-
-
2
def with_indifferent_access
-
9
dup
-
end
-
-
2
def nested_under_indifferent_access
-
self
-
end
-
-
2
def initialize(constructor = {})
-
99
if constructor.is_a?(Hash)
-
99
super()
-
99
update(constructor)
-
else
-
super(constructor)
-
end
-
end
-
-
2
def default(key = nil)
-
91
if key.is_a?(Symbol) && include?(key = key.to_s)
-
9
self[key]
-
else
-
82
super
-
end
-
end
-
-
2
def self.new_from_hash_copying_default(hash)
-
27
new(hash).tap do |new_hash|
-
27
new_hash.default = hash.default
-
end
-
end
-
-
2
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
-
2
alias_method :regular_update, :update unless method_defined?(:regular_update)
-
-
# Assigns a new value to the hash:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash[:key] = "value"
-
#
-
2
def []=(key, value)
-
2
regular_writer(convert_key(key), convert_value(value))
-
end
-
-
2
alias_method :store, :[]=
-
-
# Updates the instantized hash with values from the second:
-
#
-
# hash_1 = HashWithIndifferentAccess.new
-
# hash_1[:key] = "value"
-
#
-
# hash_2 = HashWithIndifferentAccess.new
-
# hash_2[:key] = "New Value!"
-
#
-
# hash_1.update(hash_2) # => {"key"=>"New Value!"}
-
#
-
2
def update(other_hash)
-
122
if other_hash.is_a? HashWithIndifferentAccess
-
72
super(other_hash)
-
else
-
78
other_hash.each_pair { |key, value| regular_writer(convert_key(key), convert_value(value)) }
-
50
self
-
end
-
end
-
-
2
alias_method :merge!, :update
-
-
# Checks the hash for a key matching the argument passed in:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash["key"] = "value"
-
# hash.key? :key # => true
-
# hash.key? "key" # => true
-
#
-
2
def key?(key)
-
19
super(convert_key(key))
-
end
-
-
2
alias_method :include?, :key?
-
2
alias_method :has_key?, :key?
-
2
alias_method :member?, :key?
-
-
# Same as <tt>Hash#fetch</tt> where the key passed as argument can be
-
# either a string or a symbol:
-
#
-
# counters = HashWithIndifferentAccess.new
-
# counters[:foo] = 1
-
#
-
# counters.fetch("foo") # => 1
-
# counters.fetch(:bar, 0) # => 0
-
# counters.fetch(:bar) {|key| 0} # => 0
-
# counters.fetch(:zoo) # => KeyError: key not found: "zoo"
-
#
-
2
def fetch(key, *extras)
-
super(convert_key(key), *extras)
-
end
-
-
# Returns an array of the values at the specified indices:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash[:a] = "x"
-
# hash[:b] = "y"
-
# hash.values_at("a", "b") # => ["x", "y"]
-
#
-
2
def values_at(*indices)
-
indices.collect {|key| self[convert_key(key)]}
-
end
-
-
# Returns an exact copy of the hash.
-
2
def dup
-
72
self.class.new(self).tap do |new_hash|
-
72
new_hash.default = default
-
end
-
end
-
-
# Merges the instantized and the specified hashes together, giving precedence to the values from the second hash.
-
# Does not overwrite the existing hash.
-
2
def merge(hash)
-
14
self.dup.update(hash)
-
end
-
-
# Performs the opposite of merge, with the keys and values from the first hash taking precedence over the second.
-
# This overloaded definition prevents returning a regular hash, if reverse_merge is called on a <tt>HashWithDifferentAccess</tt>.
-
2
def reverse_merge(other_hash)
-
super self.class.new_from_hash_copying_default(other_hash)
-
end
-
-
2
def reverse_merge!(other_hash)
-
replace(reverse_merge( other_hash ))
-
end
-
-
# Removes a specified key from the hash.
-
2
def delete(key)
-
59
super(convert_key(key))
-
end
-
-
2
def stringify_keys!; self end
-
32
def stringify_keys; dup end
-
2
undef :symbolize_keys!
-
2
def symbolize_keys; to_hash.symbolize_keys end
-
2
def to_options!; self end
-
-
# Convert to a Hash with String keys.
-
2
def to_hash
-
Hash.new(default).merge!(self)
-
end
-
-
2
protected
-
2
def convert_key(key)
-
108
key.kind_of?(Symbol) ? key.to_s : key
-
end
-
-
2
def convert_value(value)
-
30
if value.is_a? Hash
-
2
value.nested_under_indifferent_access
-
28
elsif value.is_a?(Array)
-
value.dup.replace(value.map { |e| convert_value(e) })
-
else
-
28
value
-
end
-
end
-
end
-
end
-
-
2
HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess
-
2
begin
-
2
require 'i18n'
-
2
require 'active_support/lazy_load_hooks'
-
rescue LoadError => e
-
$stderr.puts "The i18n gem is not available. Please add it to your Gemfile and run bundle install"
-
raise e
-
end
-
-
2
I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
-
2
require "active_support"
-
2
require "active_support/file_update_checker"
-
2
require "active_support/core_ext/array/wrap"
-
-
2
module I18n
-
2
class Railtie < Rails::Railtie
-
2
config.i18n = ActiveSupport::OrderedOptions.new
-
2
config.i18n.railties_load_path = []
-
2
config.i18n.load_path = []
-
2
config.i18n.fallbacks = ActiveSupport::OrderedOptions.new
-
-
2
def self.reloader
-
8
@reloader ||= ActiveSupport::FileUpdateChecker.new(reloader_paths){ I18n.reload! }
-
end
-
-
2
def self.reloader_paths
-
4
@reloader_paths ||= []
-
end
-
-
# Add <tt>I18n::Railtie.reloader</tt> to ActionDispatch callbacks. Since, at this
-
# point, no path was added to the reloader, I18n.reload! is not triggered
-
# on to_prepare callbacks. This will only happen on the config.after_initialize
-
# callback below.
-
2
initializer "i18n.callbacks" do |app|
-
2
app.reloaders << I18n::Railtie.reloader
-
2
ActionDispatch::Reloader.to_prepare do
-
2
I18n::Railtie.reloader.execute_if_updated
-
end
-
end
-
-
# Set the i18n configuration after initialization since a lot of
-
# configuration is still usually done in application initializers.
-
2
config.after_initialize do |app|
-
2
I18n::Railtie.initialize_i18n(app)
-
end
-
-
# Trigger i18n config before any eager loading has happened
-
# so it's ready if any classes require it when eager loaded
-
2
config.before_eager_load do |app|
-
2
I18n::Railtie.initialize_i18n(app)
-
end
-
-
2
protected
-
-
2
@i18n_inited = false
-
-
# Setup i18n configuration
-
2
def self.initialize_i18n(app)
-
4
return if @i18n_inited
-
-
2
fallbacks = app.config.i18n.delete(:fallbacks)
-
-
2
app.config.i18n.each do |setting, value|
-
4
case setting
-
when :railties_load_path
-
2
app.config.i18n.load_path.unshift(*value)
-
when :load_path
-
2
I18n.load_path += value
-
else
-
I18n.send("#{setting}=", value)
-
end
-
end
-
-
2
init_fallbacks(fallbacks) if fallbacks && validate_fallbacks(fallbacks)
-
-
2
reloader_paths.concat I18n.load_path
-
2
reloader.execute
-
-
2
@i18n_inited = true
-
end
-
-
2
def self.include_fallbacks_module
-
I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
-
end
-
-
2
def self.init_fallbacks(fallbacks)
-
include_fallbacks_module
-
-
args = case fallbacks
-
when ActiveSupport::OrderedOptions
-
[*(fallbacks[:defaults] || []) << fallbacks[:map]].compact
-
when Hash, Array
-
Array.wrap(fallbacks)
-
else # TrueClass
-
[]
-
end
-
-
I18n.fallbacks = I18n::Locale::Fallbacks.new(*args)
-
end
-
-
2
def self.validate_fallbacks(fallbacks)
-
2
case fallbacks
-
when ActiveSupport::OrderedOptions
-
2
!fallbacks.empty?
-
when TrueClass, Array, Hash
-
true
-
else
-
raise "Unexpected fallback type #{fallbacks.inspect}"
-
end
-
end
-
end
-
end
-
2
require 'active_support/inflector/inflections'
-
-
2
module ActiveSupport
-
2
Inflector.inflections do |inflect|
-
2
inflect.plural(/$/, 's')
-
2
inflect.plural(/s$/i, 's')
-
2
inflect.plural(/(ax|test)is$/i, '\1es')
-
2
inflect.plural(/(octop|vir)us$/i, '\1i')
-
2
inflect.plural(/(octop|vir)i$/i, '\1i')
-
2
inflect.plural(/(alias|status)$/i, '\1es')
-
2
inflect.plural(/(bu)s$/i, '\1ses')
-
2
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
-
2
inflect.plural(/([ti])um$/i, '\1a')
-
2
inflect.plural(/([ti])a$/i, '\1a')
-
2
inflect.plural(/sis$/i, 'ses')
-
2
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
-
2
inflect.plural(/(hive)$/i, '\1s')
-
2
inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
-
2
inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
-
2
inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
-
2
inflect.plural(/(m|l)ouse$/i, '\1ice')
-
2
inflect.plural(/(m|l)ice$/i, '\1ice')
-
2
inflect.plural(/^(ox)$/i, '\1en')
-
2
inflect.plural(/^(oxen)$/i, '\1')
-
2
inflect.plural(/(quiz)$/i, '\1zes')
-
-
2
inflect.singular(/s$/i, '')
-
2
inflect.singular(/(n)ews$/i, '\1ews')
-
2
inflect.singular(/([ti])a$/i, '\1um')
-
2
inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '\1\2sis')
-
2
inflect.singular(/(^analy)ses$/i, '\1sis')
-
2
inflect.singular(/([^f])ves$/i, '\1fe')
-
2
inflect.singular(/(hive)s$/i, '\1')
-
2
inflect.singular(/(tive)s$/i, '\1')
-
2
inflect.singular(/([lr])ves$/i, '\1f')
-
2
inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
-
2
inflect.singular(/(s)eries$/i, '\1eries')
-
2
inflect.singular(/(m)ovies$/i, '\1ovie')
-
2
inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
-
2
inflect.singular(/(m|l)ice$/i, '\1ouse')
-
2
inflect.singular(/(bus)es$/i, '\1')
-
2
inflect.singular(/(o)es$/i, '\1')
-
2
inflect.singular(/(shoe)s$/i, '\1')
-
2
inflect.singular(/(cris|ax|test)es$/i, '\1is')
-
2
inflect.singular(/(octop|vir)i$/i, '\1us')
-
2
inflect.singular(/(alias|status)es$/i, '\1')
-
2
inflect.singular(/^(ox)en/i, '\1')
-
2
inflect.singular(/(vert|ind)ices$/i, '\1ex')
-
2
inflect.singular(/(matr)ices$/i, '\1ix')
-
2
inflect.singular(/(quiz)zes$/i, '\1')
-
2
inflect.singular(/(database)s$/i, '\1')
-
-
2
inflect.irregular('person', 'people')
-
2
inflect.irregular('man', 'men')
-
2
inflect.irregular('child', 'children')
-
2
inflect.irregular('sex', 'sexes')
-
2
inflect.irregular('move', 'moves')
-
2
inflect.irregular('cow', 'kine')
-
2
inflect.irregular('zombie', 'zombies')
-
-
2
inflect.uncountable(%w(equipment information rice money species series fish sheep jeans))
-
end
-
end
-
# in case active_support/inflector is required without the rest of active_support
-
2
require 'active_support/inflector/inflections'
-
2
require 'active_support/inflector/transliterate'
-
2
require 'active_support/inflector/methods'
-
-
2
require 'active_support/inflections'
-
2
require 'active_support/core_ext/string/inflections'
-
2
module ActiveSupport
-
2
module Inflector
-
2
extend self
-
-
# A singleton instance of this class is yielded by Inflector.inflections, which can then be used to specify additional
-
# inflection rules. Examples:
-
#
-
# ActiveSupport::Inflector.inflections do |inflect|
-
# inflect.plural /^(ox)$/i, '\1\2en'
-
# inflect.singular /^(ox)en/i, '\1'
-
#
-
# inflect.irregular 'octopus', 'octopi'
-
#
-
# inflect.uncountable "equipment"
-
# end
-
#
-
# New rules are added at the top. So in the example above, the irregular rule for octopus will now be the first of the
-
# pluralization and singularization rules that is runs. This guarantees that your rules run before any of the rules that may
-
# already have been loaded.
-
2
class Inflections
-
2
def self.instance
-
1841
@__instance__ ||= new
-
end
-
-
2
attr_reader :plurals, :singulars, :uncountables, :humans, :acronyms, :acronym_regex
-
-
2
def initialize
-
2
@plurals, @singulars, @uncountables, @humans, @acronyms, @acronym_regex = [], [], [], [], {}, /(?=a)b/
-
end
-
-
# Specifies a new acronym. An acronym must be specified as it will appear in a camelized string. An underscore
-
# string that contains the acronym will retain the acronym when passed to `camelize`, `humanize`, or `titleize`.
-
# A camelized string that contains the acronym will maintain the acronym when titleized or humanized, and will
-
# convert the acronym into a non-delimited single lowercase word when passed to +underscore+.
-
#
-
# Examples:
-
# acronym 'HTML'
-
# titleize 'html' #=> 'HTML'
-
# camelize 'html' #=> 'HTML'
-
# underscore 'MyHTML' #=> 'my_html'
-
#
-
# The acronym, however, must occur as a delimited unit and not be part of another word for conversions to recognize it:
-
#
-
# acronym 'HTTP'
-
# camelize 'my_http_delimited' #=> 'MyHTTPDelimited'
-
# camelize 'https' #=> 'Https', not 'HTTPs'
-
# underscore 'HTTPS' #=> 'http_s', not 'https'
-
#
-
# acronym 'HTTPS'
-
# camelize 'https' #=> 'HTTPS'
-
# underscore 'HTTPS' #=> 'https'
-
#
-
# Note: Acronyms that are passed to `pluralize` will no longer be recognized, since the acronym will not occur as
-
# a delimited unit in the pluralized result. To work around this, you must specify the pluralized form as an
-
# acronym as well:
-
#
-
# acronym 'API'
-
# camelize(pluralize('api')) #=> 'Apis'
-
#
-
# acronym 'APIs'
-
# camelize(pluralize('api')) #=> 'APIs'
-
#
-
# `acronym` may be used to specify any word that contains an acronym or otherwise needs to maintain a non-standard
-
# capitalization. The only restriction is that the word must begin with a capital letter.
-
#
-
# Examples:
-
# acronym 'RESTful'
-
# underscore 'RESTful' #=> 'restful'
-
# underscore 'RESTfulController' #=> 'restful_controller'
-
# titleize 'RESTfulController' #=> 'RESTful Controller'
-
# camelize 'restful' #=> 'RESTful'
-
# camelize 'restful_controller' #=> 'RESTfulController'
-
#
-
# acronym 'McDonald'
-
# underscore 'McDonald' #=> 'mcdonald'
-
# camelize 'mcdonald' #=> 'McDonald'
-
2
def acronym(word)
-
@acronyms[word.downcase] = word
-
@acronym_regex = /#{@acronyms.values.join("|")}/
-
end
-
-
# Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression.
-
# The replacement should always be a string that may include references to the matched data from the rule.
-
2
def plural(rule, replacement)
-
78
@uncountables.delete(rule) if rule.is_a?(String)
-
78
@uncountables.delete(replacement)
-
78
@plurals.insert(0, [rule, replacement])
-
end
-
-
# Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression.
-
# The replacement should always be a string that may include references to the matched data from the rule.
-
2
def singular(rule, replacement)
-
68
@uncountables.delete(rule) if rule.is_a?(String)
-
68
@uncountables.delete(replacement)
-
68
@singulars.insert(0, [rule, replacement])
-
end
-
-
# Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used
-
# for strings, not regular expressions. You simply pass the irregular in singular and plural form.
-
#
-
# Examples:
-
# irregular 'octopus', 'octopi'
-
# irregular 'person', 'people'
-
2
def irregular(singular, plural)
-
16
@uncountables.delete(singular)
-
16
@uncountables.delete(plural)
-
16
if singular[0,1].upcase == plural[0,1].upcase
-
14
plural(Regexp.new("(#{singular[0,1]})#{singular[1..-1]}$", "i"), '\1' + plural[1..-1])
-
14
plural(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + plural[1..-1])
-
14
singular(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + singular[1..-1])
-
else
-
2
plural(Regexp.new("#{singular[0,1].upcase}(?i)#{singular[1..-1]}$"), plural[0,1].upcase + plural[1..-1])
-
2
plural(Regexp.new("#{singular[0,1].downcase}(?i)#{singular[1..-1]}$"), plural[0,1].downcase + plural[1..-1])
-
2
plural(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), plural[0,1].upcase + plural[1..-1])
-
2
plural(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), plural[0,1].downcase + plural[1..-1])
-
2
singular(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), singular[0,1].upcase + singular[1..-1])
-
2
singular(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), singular[0,1].downcase + singular[1..-1])
-
end
-
end
-
-
# Add uncountable words that shouldn't be attempted inflected.
-
#
-
# Examples:
-
# uncountable "money"
-
# uncountable "money", "information"
-
# uncountable %w( money information rice )
-
2
def uncountable(*words)
-
2
(@uncountables << words).flatten!
-
end
-
-
# Specifies a humanized form of a string by a regular expression rule or by a string mapping.
-
# When using a regular expression based replacement, the normal humanize formatting is called after the replacement.
-
# When a string is used, the human form should be specified as desired (example: 'The name', not 'the_name')
-
#
-
# Examples:
-
# human /_cnt$/i, '\1_count'
-
# human "legacy_col_person_name", "Name"
-
2
def human(rule, replacement)
-
@humans.insert(0, [rule, replacement])
-
end
-
-
# Clears the loaded inflections within a given scope (default is <tt>:all</tt>).
-
# Give the scope as a symbol of the inflection type, the options are: <tt>:plurals</tt>,
-
# <tt>:singulars</tt>, <tt>:uncountables</tt>, <tt>:humans</tt>.
-
#
-
# Examples:
-
# clear :all
-
# clear :plurals
-
2
def clear(scope = :all)
-
case scope
-
when :all
-
@plurals, @singulars, @uncountables, @humans = [], [], [], []
-
else
-
instance_variable_set "@#{scope}", []
-
end
-
end
-
end
-
-
# Yields a singleton instance of Inflector::Inflections so you can specify additional
-
# inflector rules.
-
#
-
# Example:
-
# ActiveSupport::Inflector.inflections do |inflect|
-
# inflect.uncountable "rails"
-
# end
-
2
def inflections
-
1841
if block_given?
-
4
yield Inflections.instance
-
else
-
1837
Inflections.instance
-
end
-
end
-
end
-
end
-
2
require 'active_support/inflector/inflections'
-
2
require 'active_support/inflections'
-
-
2
module ActiveSupport
-
# The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without,
-
# and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept
-
# in inflections.rb.
-
#
-
# The Rails core team has stated patches for the inflections library will not be accepted
-
# in order to avoid breaking legacy applications which may be relying on errant inflections.
-
# If you discover an incorrect inflection and require it for your application, you'll need
-
# to correct it yourself (explained below).
-
2
module Inflector
-
2
extend self
-
-
# Returns the plural form of the word in the string.
-
#
-
# Examples:
-
# "post".pluralize # => "posts"
-
# "octopus".pluralize # => "octopi"
-
# "sheep".pluralize # => "sheep"
-
# "words".pluralize # => "words"
-
# "CamelOctopus".pluralize # => "CamelOctopi"
-
2
def pluralize(word)
-
84
apply_inflections(word, inflections.plurals)
-
end
-
-
# The reverse of +pluralize+, returns the singular form of a word in a string.
-
#
-
# Examples:
-
# "posts".singularize # => "post"
-
# "octopi".singularize # => "octopus"
-
# "sheep".singularize # => "sheep"
-
# "word".singularize # => "word"
-
# "CamelOctopi".singularize # => "CamelOctopus"
-
2
def singularize(word)
-
169
apply_inflections(word, inflections.singulars)
-
end
-
-
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+
-
# is set to <tt>:lower</tt> then +camelize+ produces lowerCamelCase.
-
#
-
# +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
-
#
-
# Examples:
-
# "active_model".camelize # => "ActiveModel"
-
# "active_model".camelize(:lower) # => "activeModel"
-
# "active_model/errors".camelize # => "ActiveModel::Errors"
-
# "active_model/errors".camelize(:lower) # => "activeModel::Errors"
-
#
-
# As a rule of thumb you can think of +camelize+ as the inverse of +underscore+,
-
# though there are cases where that does not hold:
-
#
-
# "SSLError".underscore.camelize # => "SslError"
-
2
def camelize(term, uppercase_first_letter = true)
-
201
string = term.to_s
-
201
if uppercase_first_letter
-
402
string = string.sub(/^[a-z\d]*/) { inflections.acronyms[$&] || $&.capitalize }
-
else
-
string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
-
end
-
356
string.gsub(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }.gsub('/', '::')
-
end
-
-
# Makes an underscored, lowercase form from the expression in the string.
-
#
-
# Changes '::' to '/' to convert namespaces to paths.
-
#
-
# Examples:
-
# "ActiveModel".underscore # => "active_model"
-
# "ActiveModel::Errors".underscore # => "active_model/errors"
-
#
-
# As a rule of thumb you can think of +underscore+ as the inverse of +camelize+,
-
# though there are cases where that does not hold:
-
#
-
# "SSLError".underscore.camelize # => "SslError"
-
2
def underscore(camel_cased_word)
-
913
word = camel_cased_word.to_s.dup
-
913
word.gsub!(/::/, '/')
-
913
word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
-
913
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
-
913
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
-
913
word.tr!("-", "_")
-
913
word.downcase!
-
913
word
-
end
-
-
# Capitalizes the first word and turns underscores into spaces and strips a
-
# trailing "_id", if any. Like +titleize+, this is meant for creating pretty output.
-
#
-
# Examples:
-
# "employee_salary" # => "Employee salary"
-
# "author_id" # => "Author"
-
2
def humanize(lower_case_and_underscored_word)
-
12
result = lower_case_and_underscored_word.to_s.dup
-
12
inflections.humans.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
-
12
result.gsub!(/_id$/, "")
-
12
result.gsub!(/_/, ' ')
-
12
result.gsub(/([a-z\d]*)/i) { |match|
-
50
"#{inflections.acronyms[match] || match.downcase}"
-
12
}.gsub(/^\w/) { $&.upcase }
-
end
-
-
# Capitalizes all the words and replaces some characters in the string to create
-
# a nicer looking title. +titleize+ is meant for creating pretty output. It is not
-
# used in the Rails internals.
-
#
-
# +titleize+ is also aliased as as +titlecase+.
-
#
-
# Examples:
-
# "man from the boondocks".titleize # => "Man From The Boondocks"
-
# "x-men: the last stand".titleize # => "X Men: The Last Stand"
-
# "TheManWithoutAPast".titleize # => "The Man Without A Past"
-
# "raiders_of_the_lost_ark".titleize # => "Raiders Of The Lost Ark"
-
2
def titleize(word)
-
humanize(underscore(word)).gsub(/\b('?[a-z])/) { $1.capitalize }
-
end
-
-
# Create the name of a table like Rails does for models to table names. This method
-
# uses the +pluralize+ method on the last word in the string.
-
#
-
# Examples
-
# "RawScaledScorer".tableize # => "raw_scaled_scorers"
-
# "egg_and_ham".tableize # => "egg_and_hams"
-
# "fancyCategory".tableize # => "fancy_categories"
-
2
def tableize(class_name)
-
pluralize(underscore(class_name))
-
end
-
-
# Create a class name from a plural table name like Rails does for table names to models.
-
# Note that this returns a string and not a Class. (To convert to an actual class
-
# follow +classify+ with +constantize+.)
-
#
-
# Examples:
-
# "egg_and_hams".classify # => "EggAndHam"
-
# "posts".classify # => "Post"
-
#
-
# Singular names are not handled correctly:
-
# "business".classify # => "Busines"
-
2
def classify(table_name)
-
# strip out any leading schema name
-
43
camelize(singularize(table_name.to_s.sub(/.*\./, '')))
-
end
-
-
# Replaces underscores with dashes in the string.
-
#
-
# Example:
-
# "puni_puni" # => "puni-puni"
-
2
def dasherize(underscored_word)
-
152
underscored_word.gsub(/_/, '-')
-
end
-
-
# Removes the module part from the expression in the string:
-
#
-
# "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
-
# "Inflections".demodulize # => "Inflections"
-
#
-
# See also +deconstantize+.
-
2
def demodulize(path)
-
66
path = path.to_s
-
66
if i = path.rindex('::')
-
2
path[(i+2)..-1]
-
else
-
64
path
-
end
-
end
-
-
# Removes the rightmost segment from the constant expression in the string:
-
#
-
# "Net::HTTP".deconstantize # => "Net"
-
# "::Net::HTTP".deconstantize # => "::Net"
-
# "String".deconstantize # => ""
-
# "::String".deconstantize # => ""
-
# "".deconstantize # => ""
-
#
-
# See also +demodulize+.
-
2
def deconstantize(path)
-
path.to_s[0...(path.rindex('::') || 0)] # implementation based on the one in facets' Module#spacename
-
end
-
-
# Creates a foreign key name from a class name.
-
# +separate_class_name_and_id_with_underscore+ sets whether
-
# the method should put '_' between the name and 'id'.
-
#
-
# Examples:
-
# "Message".foreign_key # => "message_id"
-
# "Message".foreign_key(false) # => "messageid"
-
# "Admin::Post".foreign_key # => "post_id"
-
2
def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
-
15
underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
-
end
-
-
# Ruby 1.9 introduces an inherit argument for Module#const_get and
-
# #const_defined? and changes their default behavior.
-
2
if Module.method(:const_get).arity == 1
-
# Tries to find a constant with the name specified in the argument string:
-
#
-
# "Module".constantize # => Module
-
# "Test::Unit".constantize # => Test::Unit
-
#
-
# The name is assumed to be the one of a top-level constant, no matter whether
-
# it starts with "::" or not. No lexical context is taken into account:
-
#
-
# C = 'outside'
-
# module M
-
# C = 'inside'
-
# C # => 'inside'
-
# "C".constantize # => 'outside', same as ::C
-
# end
-
#
-
# NameError is raised when the name is not in CamelCase or the constant is
-
# unknown.
-
def constantize(camel_cased_word)
-
names = camel_cased_word.split('::')
-
names.shift if names.empty? || names.first.empty?
-
-
constant = Object
-
names.each do |name|
-
constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
-
end
-
constant
-
end
-
else
-
2
def constantize(camel_cased_word) #:nodoc:
-
438
names = camel_cased_word.split('::')
-
438
names.shift if names.empty? || names.first.empty?
-
-
438
constant = Object
-
438
names.each do |name|
-
511
constant = constant.const_defined?(name, false) ? constant.const_get(name) : constant.const_missing(name)
-
end
-
369
constant
-
end
-
end
-
-
# Tries to find a constant with the name specified in the argument string:
-
#
-
# "Module".safe_constantize # => Module
-
# "Test::Unit".safe_constantize # => Test::Unit
-
#
-
# The name is assumed to be the one of a top-level constant, no matter whether
-
# it starts with "::" or not. No lexical context is taken into account:
-
#
-
# C = 'outside'
-
# module M
-
# C = 'inside'
-
# C # => 'inside'
-
# "C".safe_constantize # => 'outside', same as ::C
-
# end
-
#
-
# nil is returned when the name is not in CamelCase or the constant (or part of it) is
-
# unknown.
-
#
-
# "blargle".safe_constantize # => nil
-
# "UnknownModule".safe_constantize # => nil
-
# "UnknownModule::Foo::Bar".safe_constantize # => nil
-
#
-
2
def safe_constantize(camel_cased_word)
-
77
begin
-
77
constantize(camel_cased_word)
-
49
rescue NameError => e
-
raise unless e.message =~ /(uninitialized constant|wrong constant name) #{const_regexp(camel_cased_word)}$/ ||
-
49
e.name.to_s == camel_cased_word.to_s
-
rescue ArgumentError => e
-
raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/
-
end
-
end
-
-
# Turns a number into an ordinal string used to denote the position in an
-
# ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# Examples:
-
# ordinalize(1) # => "1st"
-
# ordinalize(2) # => "2nd"
-
# ordinalize(1002) # => "1002nd"
-
# ordinalize(1003) # => "1003rd"
-
# ordinalize(-11) # => "-11th"
-
# ordinalize(-1021) # => "-1021st"
-
2
def ordinalize(number)
-
if (11..13).include?(number.to_i.abs % 100)
-
"#{number}th"
-
else
-
case number.to_i.abs % 10
-
when 1; "#{number}st"
-
when 2; "#{number}nd"
-
when 3; "#{number}rd"
-
else "#{number}th"
-
end
-
end
-
end
-
-
2
private
-
-
# Mount a regular expression that will match part by part of the constant.
-
# For instance, Foo::Bar::Baz will generate Foo(::Bar(::Baz)?)?
-
2
def const_regexp(camel_cased_word) #:nodoc:
-
49
parts = camel_cased_word.split("::")
-
49
last = parts.pop
-
-
49
parts.reverse.inject(last) do |acc, part|
-
3
part.empty? ? acc : "#{part}(::#{acc})?"
-
end
-
end
-
-
# Applies inflection rules for +singularize+ and +pluralize+.
-
#
-
# Examples:
-
# apply_inflections("post", inflections.plurals) # => "posts"
-
# apply_inflections("posts", inflections.singulars) # => "post"
-
2
def apply_inflections(word, rules)
-
253
result = word.to_s.dup
-
-
2530
if word.empty? || inflections.uncountables.any? { |inflection| result =~ /\b#{inflection}\Z/i }
-
result
-
else
-
8915
rules.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
-
253
result
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'active_support/core_ext/string/multibyte'
-
2
require 'active_support/i18n'
-
-
2
module ActiveSupport
-
2
module Inflector
-
-
# Replaces non-ASCII characters with an ASCII approximation, or if none
-
# exists, a replacement character which defaults to "?".
-
#
-
# transliterate("Ærøskøbing")
-
# # => "AEroskobing"
-
#
-
# Default approximations are provided for Western/Latin characters,
-
# e.g, "ø", "ñ", "é", "ß", etc.
-
#
-
# This method is I18n aware, so you can set up custom approximations for a
-
# locale. This can be useful, for example, to transliterate German's "ü"
-
# and "ö" to "ue" and "oe", or to add support for transliterating Russian
-
# to ASCII.
-
#
-
# In order to make your custom transliterations available, you must set
-
# them as the <tt>i18n.transliterate.rule</tt> i18n key:
-
#
-
# # Store the transliterations in locales/de.yml
-
# i18n:
-
# transliterate:
-
# rule:
-
# ü: "ue"
-
# ö: "oe"
-
#
-
# # Or set them using Ruby
-
# I18n.backend.store_translations(:de, :i18n => {
-
# :transliterate => {
-
# :rule => {
-
# "ü" => "ue",
-
# "ö" => "oe"
-
# }
-
# }
-
# })
-
#
-
# The value for <tt>i18n.transliterate.rule</tt> can be a simple Hash that maps
-
# characters to ASCII approximations as shown above, or, for more complex
-
# requirements, a Proc:
-
#
-
# I18n.backend.store_translations(:de, :i18n => {
-
# :transliterate => {
-
# :rule => lambda {|string| MyTransliterator.transliterate(string)}
-
# }
-
# })
-
#
-
# Now you can have different transliterations for each locale:
-
#
-
# I18n.locale = :en
-
# transliterate("Jürgen")
-
# # => "Jurgen"
-
#
-
# I18n.locale = :de
-
# transliterate("Jürgen")
-
# # => "Juergen"
-
2
def transliterate(string, replacement = "?")
-
I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize(
-
ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c),
-
:replacement => replacement)
-
end
-
-
# Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
-
#
-
# ==== Examples
-
#
-
# class Person
-
# def to_param
-
# "#{id}-#{name.parameterize}"
-
# end
-
# end
-
#
-
# @person = Person.find(1)
-
# # => #<Person id: 1, name: "Donald E. Knuth">
-
#
-
# <%= link_to(@person.name, person_path(@person)) %>
-
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
-
2
def parameterize(string, sep = '-')
-
# replace accented chars with their ascii equivalents
-
parameterized_string = transliterate(string)
-
# Turn unwanted chars into the separator
-
parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep)
-
unless sep.nil? || sep.empty?
-
re_sep = Regexp.escape(sep)
-
# No more than one of the separator in a row.
-
parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
-
# Remove leading/trailing separator.
-
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
-
end
-
parameterized_string.downcase
-
end
-
-
end
-
end
-
2
require 'active_support/json/decoding'
-
2
require 'active_support/json/encoding'
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'multi_json'
-
-
2
module ActiveSupport
-
# Look for and parse json strings that look like ISO 8601 times.
-
2
mattr_accessor :parse_json_times
-
-
2
module JSON
-
2
class << self
-
2
def decode(json, options ={})
-
# Can't reliably detect whether MultiJson responds to load, since it's
-
# a reserved word. Use adapter as a proxy for new features.
-
data = if MultiJson.respond_to?(:adapter)
-
MultiJson.load(json, options)
-
else
-
MultiJson.decode(json, options)
-
end
-
if ActiveSupport.parse_json_times
-
convert_dates_from(data)
-
else
-
data
-
end
-
end
-
-
2
def engine
-
if MultiJson.respond_to?(:adapter)
-
MultiJson.adapter
-
else
-
MultiJson.engine
-
end
-
end
-
2
alias :backend :engine
-
-
2
def engine=(name)
-
if MultiJson.respond_to?(:use)
-
MultiJson.use name
-
else
-
MultiJson.engine = name
-
end
-
end
-
2
alias :backend= :engine=
-
-
2
def with_backend(name)
-
old_backend, self.backend = backend, name
-
yield
-
ensure
-
self.backend = old_backend
-
end
-
-
2
def parse_error
-
MultiJson::DecodeError
-
end
-
-
2
private
-
-
2
def convert_dates_from(data)
-
case data
-
when nil
-
nil
-
when DATE_REGEX
-
begin
-
DateTime.parse(data)
-
rescue ArgumentError
-
data
-
end
-
when Array
-
data.map! { |d| convert_dates_from(d) }
-
when Hash
-
data.each do |key, value|
-
data[key] = convert_dates_from(value)
-
end
-
else
-
data
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/to_json'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/json/variable'
-
2
require 'active_support/ordered_hash'
-
-
2
require 'bigdecimal'
-
2
require 'active_support/core_ext/big_decimal/conversions' # for #to_s
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/hash/except'
-
2
require 'active_support/core_ext/hash/slice'
-
2
require 'active_support/core_ext/object/instance_variables'
-
2
require 'time'
-
2
require 'active_support/core_ext/time/conversions'
-
2
require 'active_support/core_ext/date_time/conversions'
-
2
require 'active_support/core_ext/date/conversions'
-
2
require 'set'
-
-
2
module ActiveSupport
-
2
class << self
-
2
delegate :use_standard_json_time_format, :use_standard_json_time_format=,
-
:escape_html_entities_in_json, :escape_html_entities_in_json=,
-
:to => :'ActiveSupport::JSON::Encoding'
-
end
-
-
2
module JSON
-
# matches YAML-formatted dates
-
2
DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
-
-
# Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info.
-
2
def self.encode(value, options = nil)
-
Encoding::Encoder.new(options).encode(value)
-
end
-
-
2
module Encoding #:nodoc:
-
2
class CircularReferenceError < StandardError; end
-
-
2
class Encoder
-
2
attr_reader :options
-
-
2
def initialize(options = nil)
-
@options = options || {}
-
@seen = Set.new
-
end
-
-
2
def encode(value, use_options = true)
-
check_for_circular_references(value) do
-
jsonified = use_options ? value.as_json(options_for(value)) : value.as_json
-
jsonified.encode_json(self)
-
end
-
end
-
-
# like encode, but only calls as_json, without encoding to string
-
2
def as_json(value, use_options = true)
-
check_for_circular_references(value) do
-
use_options ? value.as_json(options_for(value)) : value.as_json
-
end
-
end
-
-
2
def options_for(value)
-
if value.is_a?(Array) || value.is_a?(Hash)
-
# hashes and arrays need to get encoder in the options, so that they can detect circular references
-
options.merge(:encoder => self)
-
else
-
options.dup
-
end
-
end
-
-
2
def escape(string)
-
Encoding.escape(string)
-
end
-
-
2
private
-
2
def check_for_circular_references(value)
-
unless @seen.add?(value.__id__)
-
raise CircularReferenceError, 'object references itself'
-
end
-
yield
-
ensure
-
@seen.delete(value.__id__)
-
end
-
end
-
-
-
2
ESCAPED_CHARS = {
-
"\x00" => '\u0000', "\x01" => '\u0001', "\x02" => '\u0002',
-
"\x03" => '\u0003', "\x04" => '\u0004', "\x05" => '\u0005',
-
"\x06" => '\u0006', "\x07" => '\u0007', "\x0B" => '\u000B',
-
"\x0E" => '\u000E', "\x0F" => '\u000F', "\x10" => '\u0010',
-
"\x11" => '\u0011', "\x12" => '\u0012', "\x13" => '\u0013',
-
"\x14" => '\u0014', "\x15" => '\u0015', "\x16" => '\u0016',
-
"\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019',
-
"\x1A" => '\u001A', "\x1B" => '\u001B', "\x1C" => '\u001C',
-
"\x1D" => '\u001D', "\x1E" => '\u001E', "\x1F" => '\u001F',
-
"\010" => '\b',
-
"\f" => '\f',
-
"\n" => '\n',
-
"\r" => '\r',
-
"\t" => '\t',
-
'"' => '\"',
-
'\\' => '\\\\',
-
'>' => '\u003E',
-
'<' => '\u003C',
-
'&' => '\u0026' }
-
-
2
class << self
-
# If true, use ISO 8601 format for dates and times. Otherwise, fall back to the Active Support legacy format.
-
2
attr_accessor :use_standard_json_time_format
-
-
2
attr_accessor :escape_regex
-
2
attr_reader :escape_html_entities_in_json
-
-
2
def escape_html_entities_in_json=(value)
-
2
self.escape_regex = \
-
if @escape_html_entities_in_json = value
-
/[\x00-\x1F"\\><&]/
-
else
-
2
/[\x00-\x1F"\\]/
-
end
-
end
-
-
2
def escape(string)
-
if string.respond_to?(:force_encoding)
-
string = string.encode(::Encoding::UTF_8, :undef => :replace).force_encoding(::Encoding::BINARY)
-
end
-
json = string.
-
gsub(escape_regex) { |s| ESCAPED_CHARS[s] }.
-
gsub(/([\xC0-\xDF][\x80-\xBF]|
-
[\xE0-\xEF][\x80-\xBF]{2}|
-
[\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s|
-
s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/n, '\\\\u\&')
-
}
-
json = %("#{json}")
-
json.force_encoding(::Encoding::UTF_8) if json.respond_to?(:force_encoding)
-
json
-
end
-
end
-
-
2
self.use_standard_json_time_format = true
-
2
self.escape_html_entities_in_json = false
-
end
-
end
-
end
-
-
2
class Object
-
2
def as_json(options = nil) #:nodoc:
-
if respond_to?(:to_hash)
-
to_hash
-
else
-
instance_values
-
end
-
end
-
end
-
-
2
class Struct #:nodoc:
-
2
def as_json(options = nil)
-
Hash[members.zip(values)]
-
end
-
end
-
-
2
class TrueClass
-
2
def as_json(options = nil) self end #:nodoc:
-
2
def encode_json(encoder) to_s end #:nodoc:
-
end
-
-
2
class FalseClass
-
2
def as_json(options = nil) self end #:nodoc:
-
2
def encode_json(encoder) to_s end #:nodoc:
-
end
-
-
2
class NilClass
-
2
def as_json(options = nil) self end #:nodoc:
-
2
def encode_json(encoder) 'null' end #:nodoc:
-
end
-
-
2
class String
-
2
def as_json(options = nil) self end #:nodoc:
-
2
def encode_json(encoder) encoder.escape(self) end #:nodoc:
-
end
-
-
2
class Symbol
-
2
def as_json(options = nil) to_s end #:nodoc:
-
end
-
-
2
class Numeric
-
2
def as_json(options = nil) self end #:nodoc:
-
2
def encode_json(encoder) to_s end #:nodoc:
-
end
-
-
2
class BigDecimal
-
# A BigDecimal would be naturally represented as a JSON number. Most libraries,
-
# however, parse non-integer JSON numbers directly as floats. Clients using
-
# those libraries would get in general a wrong number and no way to recover
-
# other than manually inspecting the string with the JSON code itself.
-
#
-
# That's why a JSON string is returned. The JSON literal is not numeric, but if
-
# the other end knows by contract that the data is supposed to be a BigDecimal,
-
# it still has the chance to post-process the string and get the real value.
-
2
def as_json(options = nil) to_s end #:nodoc:
-
end
-
-
2
class Regexp
-
2
def as_json(options = nil) to_s end #:nodoc:
-
end
-
-
2
module Enumerable
-
2
def as_json(options = nil) #:nodoc:
-
to_a.as_json(options)
-
end
-
end
-
-
2
class Array
-
2
def as_json(options = nil) #:nodoc:
-
# use encoder as a proxy to call as_json on all elements, to protect from circular references
-
encoder = options && options[:encoder] || ActiveSupport::JSON::Encoding::Encoder.new(options)
-
map { |v| encoder.as_json(v, options) }
-
end
-
-
2
def encode_json(encoder) #:nodoc:
-
# we assume here that the encoder has already run as_json on self and the elements, so we run encode_json directly
-
"[#{map { |v| v.encode_json(encoder) } * ','}]"
-
end
-
end
-
-
2
class Hash
-
2
def as_json(options = nil) #:nodoc:
-
# create a subset of the hash by applying :only or :except
-
subset = if options
-
if attrs = options[:only]
-
slice(*Array.wrap(attrs))
-
elsif attrs = options[:except]
-
except(*Array.wrap(attrs))
-
else
-
self
-
end
-
else
-
self
-
end
-
-
# use encoder as a proxy to call as_json on all values in the subset, to protect from circular references
-
encoder = options && options[:encoder] || ActiveSupport::JSON::Encoding::Encoder.new(options)
-
result = self.is_a?(ActiveSupport::OrderedHash) ? ActiveSupport::OrderedHash : Hash
-
result[subset.map { |k, v| [k.to_s, encoder.as_json(v, options)] }]
-
end
-
-
2
def encode_json(encoder)
-
# values are encoded with use_options = false, because we don't want hash representations from ActiveModel to be
-
# processed once again with as_json with options, as this could cause unexpected results (i.e. missing fields);
-
-
# on the other hand, we need to run as_json on the elements, because the model representation may contain fields
-
# like Time/Date in their original (not jsonified) form, etc.
-
-
"{#{map { |k,v| "#{encoder.encode(k.to_s)}:#{encoder.encode(v, false)}" } * ','}}"
-
end
-
end
-
-
2
class Time
-
2
def as_json(options = nil) #:nodoc:
-
if ActiveSupport.use_standard_json_time_format
-
xmlschema
-
else
-
%(#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
-
end
-
end
-
end
-
-
2
class Date
-
2
def as_json(options = nil) #:nodoc:
-
if ActiveSupport.use_standard_json_time_format
-
strftime("%Y-%m-%d")
-
else
-
strftime("%Y/%m/%d")
-
end
-
end
-
end
-
-
2
class DateTime
-
2
def as_json(options = nil) #:nodoc:
-
if ActiveSupport.use_standard_json_time_format
-
xmlschema
-
else
-
strftime('%Y/%m/%d %H:%M:%S %z')
-
end
-
end
-
end
-
2
module ActiveSupport
-
2
module JSON
-
# A string that returns itself as its JSON-encoded form.
-
2
class Variable < String
-
2
def as_json(options = nil) self end #:nodoc:
-
2
def encode_json(encoder) self end #:nodoc:
-
end
-
end
-
end
-
# lazy_load_hooks allows rails to lazily load a lot of components and thus making the app boot faster. Because of
-
# this feature now there is no need to require <tt>ActiveRecord::Base</tt> at boot time purely to apply configuration. Instead
-
# a hook is registered that applies configuration once <tt>ActiveRecord::Base</tt> is loaded. Here <tt>ActiveRecord::Base</tt> is used
-
# as example but this feature can be applied elsewhere too.
-
#
-
# Here is an example where +on_load+ method is called to register a hook.
-
#
-
# initializer "active_record.initialize_timezone" do
-
# ActiveSupport.on_load(:active_record) do
-
# self.time_zone_aware_attributes = true
-
# self.default_timezone = :utc
-
# end
-
# end
-
#
-
# When the entirety of +activerecord/lib/active_record/base.rb+ has been evaluated then +run_load_hooks+ is invoked.
-
# The very last line of +activerecord/lib/active_record/base.rb+ is:
-
#
-
# ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
-
#
-
2
module ActiveSupport
-
18
@load_hooks = Hash.new { |h,k| h[k] = [] }
-
18
@loaded = Hash.new { |h,k| h[k] = [] }
-
-
2
def self.on_load(name, options = {}, &block)
-
82
@loaded[name].each do |base|
-
50
execute_hook(base, options, block)
-
end
-
-
82
@load_hooks[name] << [block, options]
-
end
-
-
2
def self.execute_hook(base, options, block)
-
82
if options[:yield]
-
16
block.call(base)
-
else
-
66
base.instance_eval(&block)
-
end
-
end
-
-
2
def self.run_load_hooks(name, base = Object)
-
16
@loaded[name] << base
-
16
@load_hooks[name].each do |hook, options|
-
32
execute_hook(base, options, hook)
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
2
require 'active_support/core_ext/class/attribute'
-
-
2
module ActiveSupport
-
# ActiveSupport::LogSubscriber is an object set to consume ActiveSupport::Notifications
-
# with the sole purpose of logging them. The log subscriber dispatches notifications to
-
# a registered object based on its given namespace.
-
#
-
# An example would be Active Record log subscriber responsible for logging queries:
-
#
-
# module ActiveRecord
-
# class LogSubscriber < ActiveSupport::LogSubscriber
-
# def sql(event)
-
# "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}"
-
# end
-
# end
-
# end
-
#
-
# And it's finally registered as:
-
#
-
# ActiveRecord::LogSubscriber.attach_to :active_record
-
#
-
# Since we need to know all instance methods before attaching the log subscriber,
-
# the line above should be called after your <tt>ActiveRecord::LogSubscriber</tt> definition.
-
#
-
# After configured, whenever a "sql.active_record" notification is published,
-
# it will properly dispatch the event (ActiveSupport::Notifications::Event) to
-
# the sql method.
-
#
-
# Log subscriber also has some helpers to deal with logging and automatically flushes
-
# all logs when the request finishes (via action_dispatch.callback notification) in
-
# a Rails environment.
-
2
class LogSubscriber
-
# Embed in a String to clear all previous ANSI sequences.
-
2
CLEAR = "\e[0m"
-
2
BOLD = "\e[1m"
-
-
# Colors
-
2
BLACK = "\e[30m"
-
2
RED = "\e[31m"
-
2
GREEN = "\e[32m"
-
2
YELLOW = "\e[33m"
-
2
BLUE = "\e[34m"
-
2
MAGENTA = "\e[35m"
-
2
CYAN = "\e[36m"
-
2
WHITE = "\e[37m"
-
-
2
mattr_accessor :colorize_logging
-
2
self.colorize_logging = true
-
-
2
class_attribute :logger
-
-
2
class << self
-
2
remove_method :logger
-
2
def logger
-
1989
@logger ||= Rails.logger if defined?(Rails)
-
end
-
-
2
def attach_to(namespace, log_subscriber=new, notifier=ActiveSupport::Notifications)
-
10
log_subscribers << log_subscriber
-
10
@@flushable_loggers = nil
-
-
10
log_subscriber.public_methods(false).each do |event|
-
52
next if 'call' == event.to_s
-
-
52
notifier.subscribe("#{event}.#{namespace}", log_subscriber)
-
end
-
end
-
-
2
def log_subscribers
-
10
@@log_subscribers ||= []
-
end
-
-
2
def flushable_loggers
-
@@flushable_loggers ||= begin
-
loggers = log_subscribers.map(&:logger)
-
loggers.uniq!
-
loggers.select { |l| l.respond_to?(:flush) }
-
end
-
end
-
-
# Flush all log_subscribers' logger.
-
2
def flush_all!
-
flushable_loggers.each { |log| log.flush }
-
end
-
end
-
-
2
def call(message, *args)
-
4022
return unless logger
-
-
4022
method = message.split('.').first
-
4022
begin
-
4022
send(method, ActiveSupport::Notifications::Event.new(message, *args))
-
rescue Exception => e
-
logger.error "Could not log #{message.inspect} event. #{e.class}: #{e.message}"
-
end
-
end
-
-
2
protected
-
-
2
%w(info debug warn error fatal unknown).each do |level|
-
12
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{level}(*args, &block)
-
return unless logger
-
logger.#{level}(*args, &block)
-
end
-
METHOD
-
end
-
-
# Set color by using a string or one of the defined constants. If a third
-
# option is set to true, it also adds bold to the string. This is based
-
# on the Highline implementation and will automatically append CLEAR to the
-
# end of the returned String.
-
#
-
2
def color(text, color, bold=false)
-
2886
return text unless colorize_logging
-
2886
color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol)
-
2886
bold = bold ? BOLD : ""
-
2886
"#{bold}#{color}#{text}#{CLEAR}"
-
end
-
-
2
def format_duration(duration)
-
13
"%.1fms" % duration
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'active_support/core_ext/module/attribute_accessors'
-
-
2
module ActiveSupport #:nodoc:
-
2
module Multibyte
-
2
autoload :EncodingError, 'active_support/multibyte/exceptions'
-
2
autoload :Chars, 'active_support/multibyte/chars'
-
2
autoload :Unicode, 'active_support/multibyte/unicode'
-
-
# The proxy class returned when calling mb_chars. You can use this accessor to configure your own proxy
-
# class so you can support other encodings. See the ActiveSupport::Multibyte::Chars implementation for
-
# an example how to do this.
-
#
-
# Example:
-
# ActiveSupport::Multibyte.proxy_class = CharsForUTF32
-
2
def self.proxy_class=(klass)
-
@proxy_class = klass
-
end
-
-
# Returns the current proxy class
-
2
def self.proxy_class
-
@proxy_class ||= ActiveSupport::Multibyte::Chars
-
end
-
-
# Regular expressions that describe valid byte sequences for a character
-
2
VALID_CHARACTER = {
-
# Borrowed from the Kconv library by Shinji KONO - (also as seen on the W3C site)
-
'UTF-8' => /\A(?:
-
[\x00-\x7f] |
-
[\xc2-\xdf] [\x80-\xbf] |
-
\xe0 [\xa0-\xbf] [\x80-\xbf] |
-
[\xe1-\xef] [\x80-\xbf] [\x80-\xbf] |
-
\xf0 [\x90-\xbf] [\x80-\xbf] [\x80-\xbf] |
-
[\xf1-\xf3] [\x80-\xbf] [\x80-\xbf] [\x80-\xbf] |
-
\xf4 [\x80-\x8f] [\x80-\xbf] [\x80-\xbf])\z /xn,
-
# Quick check for valid Shift-JIS characters, disregards the odd-even pairing
-
'Shift_JIS' => /\A(?:
-
[\x00-\x7e\xa1-\xdf] |
-
[\x81-\x9f\xe0-\xef] [\x40-\x7e\x80-\x9e\x9f-\xfc])\z /xn
-
}
-
end
-
end
-
-
2
require 'active_support/multibyte/utils'
-
# encoding: utf-8
-
2
require 'active_support/core_ext/string/access'
-
2
require 'active_support/core_ext/string/behavior'
-
-
2
module ActiveSupport #:nodoc:
-
2
module Multibyte #:nodoc:
-
# Chars enables you to work transparently with UTF-8 encoding in the Ruby String class without having extensive
-
# knowledge about the encoding. A Chars object accepts a string upon initialization and proxies String methods in an
-
# encoding safe manner. All the normal String methods are also implemented on the proxy.
-
#
-
# String methods are proxied through the Chars object, and can be accessed through the +mb_chars+ method. Methods
-
# which would normally return a String object now return a Chars object so methods can be chained.
-
#
-
# "The Perfect String ".mb_chars.downcase.strip.normalize # => "the perfect string"
-
#
-
# Chars objects are perfectly interchangeable with String objects as long as no explicit class checks are made.
-
# If certain methods do explicitly check the class, call +to_s+ before you pass chars objects to them.
-
#
-
# bad.explicit_checking_method "T".mb_chars.downcase.to_s
-
#
-
# The default Chars implementation assumes that the encoding of the string is UTF-8, if you want to handle different
-
# encodings you can write your own multibyte string handler and configure it through
-
# ActiveSupport::Multibyte.proxy_class.
-
#
-
# class CharsForUTF32
-
# def size
-
# @wrapped_string.size / 4
-
# end
-
#
-
# def self.accepts?(string)
-
# string.length % 4 == 0
-
# end
-
# end
-
#
-
# ActiveSupport::Multibyte.proxy_class = CharsForUTF32
-
2
class Chars
-
2
attr_reader :wrapped_string
-
2
alias to_s wrapped_string
-
2
alias to_str wrapped_string
-
-
2
if RUBY_VERSION >= "1.9"
-
# Creates a new Chars instance by wrapping _string_.
-
2
def initialize(string)
-
@wrapped_string = string
-
@wrapped_string.force_encoding(Encoding::UTF_8) unless @wrapped_string.frozen?
-
end
-
else
-
def initialize(string) #:nodoc:
-
@wrapped_string = string
-
end
-
end
-
-
# Forward all undefined methods to the wrapped string.
-
2
def method_missing(method, *args, &block)
-
if method.to_s =~ /!$/
-
@wrapped_string.__send__(method, *args, &block)
-
self
-
else
-
result = @wrapped_string.__send__(method, *args, &block)
-
result.kind_of?(String) ? chars(result) : result
-
end
-
end
-
-
# Returns +true+ if _obj_ responds to the given method. Private methods are included in the search
-
# only if the optional second parameter evaluates to +true+.
-
2
def respond_to?(method, include_private=false)
-
super || @wrapped_string.respond_to?(method, include_private)
-
end
-
-
# Enable more predictable duck-typing on String-like classes. See Object#acts_like?.
-
2
def acts_like_string?
-
true
-
end
-
-
# Returns +true+ when the proxy class can handle the string. Returns +false+ otherwise.
-
2
def self.consumes?(string)
-
# Unpack is a little bit faster than regular expressions.
-
string.unpack('U*')
-
true
-
rescue ArgumentError
-
false
-
end
-
-
2
include Comparable
-
-
# Returns -1, 0, or 1, depending on whether the Chars object is to be sorted before,
-
# equal or after the object on the right side of the operation. It accepts any object
-
# that implements +to_s+:
-
#
-
# 'é'.mb_chars <=> 'ü'.mb_chars # => -1
-
#
-
# See <tt>String#<=></tt> for more details.
-
2
def <=>(other)
-
@wrapped_string <=> other.to_s
-
end
-
-
2
if RUBY_VERSION < "1.9"
-
# Returns +true+ if the Chars class can and should act as a proxy for the string _string_. Returns
-
# +false+ otherwise.
-
def self.wants?(string)
-
$KCODE == 'UTF8' && consumes?(string)
-
end
-
-
# Returns a new Chars object containing the _other_ object concatenated to the string.
-
#
-
# Example:
-
# ('Café'.mb_chars + ' périferôl').to_s # => "Café périferôl"
-
def +(other)
-
chars(@wrapped_string + other)
-
end
-
-
# Like <tt>String#=~</tt> only it returns the character offset (in codepoints) instead of the byte offset.
-
#
-
# Example:
-
# 'Café périferôl'.mb_chars =~ /ô/ # => 12
-
def =~(other)
-
translate_offset(@wrapped_string =~ other)
-
end
-
-
# Inserts the passed string at specified codepoint offsets.
-
#
-
# Example:
-
# 'Café'.mb_chars.insert(4, ' périferôl').to_s # => "Café périferôl"
-
def insert(offset, fragment)
-
unpacked = Unicode.u_unpack(@wrapped_string)
-
unless offset > unpacked.length
-
@wrapped_string.replace(
-
Unicode.u_unpack(@wrapped_string).insert(offset, *Unicode.u_unpack(fragment)).pack('U*')
-
)
-
else
-
raise IndexError, "index #{offset} out of string"
-
end
-
self
-
end
-
-
# Returns +true+ if contained string contains _other_. Returns +false+ otherwise.
-
#
-
# Example:
-
# 'Café'.mb_chars.include?('é') # => true
-
def include?(other)
-
# We have to redefine this method because Enumerable defines it.
-
@wrapped_string.include?(other)
-
end
-
-
# Returns the position _needle_ in the string, counting in codepoints. Returns +nil+ if _needle_ isn't found.
-
#
-
# Example:
-
# 'Café périferôl'.mb_chars.index('ô') # => 12
-
# 'Café périferôl'.mb_chars.index(/\w/u) # => 0
-
def index(needle, offset=0)
-
wrapped_offset = first(offset).wrapped_string.length
-
index = @wrapped_string.index(needle, wrapped_offset)
-
index ? (Unicode.u_unpack(@wrapped_string.slice(0...index)).size) : nil
-
end
-
-
# Returns the position _needle_ in the string, counting in
-
# codepoints, searching backward from _offset_ or the end of the
-
# string. Returns +nil+ if _needle_ isn't found.
-
#
-
# Example:
-
# 'Café périferôl'.mb_chars.rindex('é') # => 6
-
# 'Café périferôl'.mb_chars.rindex(/\w/u) # => 13
-
def rindex(needle, offset=nil)
-
offset ||= length
-
wrapped_offset = first(offset).wrapped_string.length
-
index = @wrapped_string.rindex(needle, wrapped_offset)
-
index ? (Unicode.u_unpack(@wrapped_string.slice(0...index)).size) : nil
-
end
-
-
# Returns the number of codepoints in the string
-
def size
-
Unicode.u_unpack(@wrapped_string).size
-
end
-
alias_method :length, :size
-
-
# Strips entire range of Unicode whitespace from the right of the string.
-
def rstrip
-
chars(@wrapped_string.gsub(Unicode::TRAILERS_PAT, ''))
-
end
-
-
# Strips entire range of Unicode whitespace from the left of the string.
-
def lstrip
-
chars(@wrapped_string.gsub(Unicode::LEADERS_PAT, ''))
-
end
-
-
# Strips entire range of Unicode whitespace from the right and left of the string.
-
def strip
-
rstrip.lstrip
-
end
-
-
# Returns the codepoint of the first character in the string.
-
#
-
# Example:
-
# 'こんにちは'.mb_chars.ord # => 12371
-
def ord
-
Unicode.u_unpack(@wrapped_string)[0]
-
end
-
-
# Works just like <tt>String#rjust</tt>, only integer specifies characters instead of bytes.
-
#
-
# Example:
-
#
-
# "¾ cup".mb_chars.rjust(8).to_s
-
# # => " ¾ cup"
-
#
-
# "¾ cup".mb_chars.rjust(8, " ").to_s # Use non-breaking whitespace
-
# # => " ¾ cup"
-
def rjust(integer, padstr=' ')
-
justify(integer, :right, padstr)
-
end
-
-
# Works just like <tt>String#ljust</tt>, only integer specifies characters instead of bytes.
-
#
-
# Example:
-
#
-
# "¾ cup".mb_chars.rjust(8).to_s
-
# # => "¾ cup "
-
#
-
# "¾ cup".mb_chars.rjust(8, " ").to_s # Use non-breaking whitespace
-
# # => "¾ cup "
-
def ljust(integer, padstr=' ')
-
justify(integer, :left, padstr)
-
end
-
-
# Works just like <tt>String#center</tt>, only integer specifies characters instead of bytes.
-
#
-
# Example:
-
#
-
# "¾ cup".mb_chars.center(8).to_s
-
# # => " ¾ cup "
-
#
-
# "¾ cup".mb_chars.center(8, " ").to_s # Use non-breaking whitespace
-
# # => " ¾ cup "
-
def center(integer, padstr=' ')
-
justify(integer, :center, padstr)
-
end
-
-
else
-
2
def =~(other)
-
@wrapped_string =~ other
-
end
-
end
-
-
# Works just like <tt>String#split</tt>, with the exception that the items in the resulting list are Chars
-
# instances instead of String. This makes chaining methods easier.
-
#
-
# Example:
-
# 'Café périferôl'.mb_chars.split(/é/).map { |part| part.upcase.to_s } # => ["CAF", " P", "RIFERÔL"]
-
2
def split(*args)
-
@wrapped_string.split(*args).map { |i| i.mb_chars }
-
end
-
-
# Like <tt>String#[]=</tt>, except instead of byte offsets you specify character offsets.
-
#
-
# Example:
-
#
-
# s = "Müller"
-
# s.mb_chars[2] = "e" # Replace character with offset 2
-
# s
-
# # => "Müeler"
-
#
-
# s = "Müller"
-
# s.mb_chars[1, 2] = "ö" # Replace 2 characters at character offset 1
-
# s
-
# # => "Möler"
-
2
def []=(*args)
-
replace_by = args.pop
-
# Indexed replace with regular expressions already works
-
if args.first.is_a?(Regexp)
-
@wrapped_string[*args] = replace_by
-
else
-
result = Unicode.u_unpack(@wrapped_string)
-
case args.first
-
when Fixnum
-
raise IndexError, "index #{args[0]} out of string" if args[0] >= result.length
-
min = args[0]
-
max = args[1].nil? ? min : (min + args[1] - 1)
-
range = Range.new(min, max)
-
replace_by = [replace_by].pack('U') if replace_by.is_a?(Fixnum)
-
when Range
-
raise RangeError, "#{args[0]} out of range" if args[0].min >= result.length
-
range = args[0]
-
else
-
needle = args[0].to_s
-
min = index(needle)
-
max = min + Unicode.u_unpack(needle).length - 1
-
range = Range.new(min, max)
-
end
-
result[range] = Unicode.u_unpack(replace_by)
-
@wrapped_string.replace(result.pack('U*'))
-
end
-
end
-
-
# Reverses all characters in the string.
-
#
-
# Example:
-
# 'Café'.mb_chars.reverse.to_s # => 'éfaC'
-
2
def reverse
-
chars(Unicode.g_unpack(@wrapped_string).reverse.flatten.pack('U*'))
-
end
-
-
# Implements Unicode-aware slice with codepoints. Slicing on one point returns the codepoints for that
-
# character.
-
#
-
# Example:
-
# 'こんにちは'.mb_chars.slice(2..3).to_s # => "にち"
-
2
def slice(*args)
-
if args.size > 2
-
raise ArgumentError, "wrong number of arguments (#{args.size} for 1)" # Do as if we were native
-
elsif (args.size == 2 && !(args.first.is_a?(Numeric) || args.first.is_a?(Regexp)))
-
raise TypeError, "cannot convert #{args.first.class} into Integer" # Do as if we were native
-
elsif (args.size == 2 && !args[1].is_a?(Numeric))
-
raise TypeError, "cannot convert #{args[1].class} into Integer" # Do as if we were native
-
elsif args[0].kind_of? Range
-
cps = Unicode.u_unpack(@wrapped_string).slice(*args)
-
result = cps.nil? ? nil : cps.pack('U*')
-
elsif args[0].kind_of? Regexp
-
result = @wrapped_string.slice(*args)
-
elsif args.size == 1 && args[0].kind_of?(Numeric)
-
character = Unicode.u_unpack(@wrapped_string)[args[0]]
-
result = character && [character].pack('U')
-
else
-
cps = Unicode.u_unpack(@wrapped_string).slice(*args)
-
result = cps && cps.pack('U*')
-
end
-
result && chars(result)
-
end
-
2
alias_method :[], :slice
-
-
# Limit the byte size of the string to a number of bytes without breaking characters. Usable
-
# when the storage for a string is limited for some reason.
-
#
-
# Example:
-
# 'こんにちは'.mb_chars.limit(7).to_s # => "こん"
-
2
def limit(limit)
-
slice(0...translate_offset(limit))
-
end
-
-
# Convert characters in the string to uppercase.
-
#
-
# Example:
-
# 'Laurent, où sont les tests ?'.mb_chars.upcase.to_s # => "LAURENT, OÙ SONT LES TESTS ?"
-
2
def upcase
-
chars(Unicode.apply_mapping @wrapped_string, :uppercase_mapping)
-
end
-
-
# Convert characters in the string to lowercase.
-
#
-
# Example:
-
# 'VĚDA A VÝZKUM'.mb_chars.downcase.to_s # => "věda a výzkum"
-
2
def downcase
-
chars(Unicode.apply_mapping @wrapped_string, :lowercase_mapping)
-
end
-
-
# Converts the first character to uppercase and the remainder to lowercase.
-
#
-
# Example:
-
# 'über'.mb_chars.capitalize.to_s # => "Über"
-
2
def capitalize
-
(slice(0) || chars('')).upcase + (slice(1..-1) || chars('')).downcase
-
end
-
-
# Capitalizes the first letter of every word, when possible.
-
#
-
# Example:
-
# "ÉL QUE SE ENTERÓ".mb_chars.titleize # => "Él Que Se Enteró"
-
# "日本語".mb_chars.titleize # => "日本語"
-
2
def titleize
-
chars(downcase.to_s.gsub(/\b('?[\S])/u) { Unicode.apply_mapping $1, :uppercase_mapping })
-
end
-
2
alias_method :titlecase, :titleize
-
-
# Returns the KC normalization of the string by default. NFKC is considered the best normalization form for
-
# passing strings to databases and validations.
-
#
-
# * <tt>form</tt> - The form you want to normalize in. Should be one of the following:
-
# <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>. Default is
-
# ActiveSupport::Multibyte::Unicode.default_normalization_form
-
2
def normalize(form = nil)
-
chars(Unicode.normalize(@wrapped_string, form))
-
end
-
-
# Performs canonical decomposition on all the characters.
-
#
-
# Example:
-
# 'é'.length # => 2
-
# 'é'.mb_chars.decompose.to_s.length # => 3
-
2
def decompose
-
chars(Unicode.decompose_codepoints(:canonical, Unicode.u_unpack(@wrapped_string)).pack('U*'))
-
end
-
-
# Performs composition on all the characters.
-
#
-
# Example:
-
# 'é'.length # => 3
-
# 'é'.mb_chars.compose.to_s.length # => 2
-
2
def compose
-
chars(Unicode.compose_codepoints(Unicode.u_unpack(@wrapped_string)).pack('U*'))
-
end
-
-
# Returns the number of grapheme clusters in the string.
-
#
-
# Example:
-
# 'क्षि'.mb_chars.length # => 4
-
# 'क्षि'.mb_chars.g_length # => 3
-
2
def g_length
-
Unicode.g_unpack(@wrapped_string).length
-
end
-
-
# Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent resulting in a valid UTF-8 string.
-
#
-
# Passing +true+ will forcibly tidy all bytes, assuming that the string's encoding is entirely CP1252 or ISO-8859-1.
-
2
def tidy_bytes(force = false)
-
chars(Unicode.tidy_bytes(@wrapped_string, force))
-
end
-
-
2
%w(capitalize downcase lstrip reverse rstrip slice strip tidy_bytes upcase).each do |method|
-
# Only define a corresponding bang method for methods defined in the proxy; On 1.9 the proxy will
-
# exclude lstrip!, rstrip! and strip! because they are already work as expected on multibyte strings.
-
18
if public_method_defined?(method)
-
12
define_method("#{method}!") do |*args|
-
@wrapped_string = send(args.nil? ? method : method, *args).to_s
-
self
-
end
-
end
-
end
-
-
2
protected
-
-
2
def translate_offset(byte_offset) #:nodoc:
-
return nil if byte_offset.nil?
-
return 0 if @wrapped_string == ''
-
-
if @wrapped_string.respond_to?(:force_encoding)
-
@wrapped_string = @wrapped_string.dup.force_encoding(Encoding::ASCII_8BIT)
-
end
-
-
begin
-
@wrapped_string[0...byte_offset].unpack('U*').length
-
rescue ArgumentError
-
byte_offset -= 1
-
retry
-
end
-
end
-
-
2
def justify(integer, way, padstr=' ') #:nodoc:
-
raise ArgumentError, "zero width padding" if padstr.length == 0
-
padsize = integer - size
-
padsize = padsize > 0 ? padsize : 0
-
case way
-
when :right
-
result = @wrapped_string.dup.insert(0, padding(padsize, padstr))
-
when :left
-
result = @wrapped_string.dup.insert(-1, padding(padsize, padstr))
-
when :center
-
lpad = padding((padsize / 2.0).floor, padstr)
-
rpad = padding((padsize / 2.0).ceil, padstr)
-
result = @wrapped_string.dup.insert(0, lpad).insert(-1, rpad)
-
end
-
chars(result)
-
end
-
-
2
def padding(padsize, padstr=' ') #:nodoc:
-
if padsize != 0
-
chars(padstr * ((padsize / Unicode.u_unpack(padstr).size) + 1)).slice(0, padsize)
-
else
-
''
-
end
-
end
-
-
2
def chars(string) #:nodoc:
-
self.class.new(string)
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
2
module ActiveSupport #:nodoc:
-
2
module Multibyte #:nodoc:
-
2
if Kernel.const_defined?(:Encoding)
-
# Returns a regular expression that matches valid characters in the current encoding
-
2
def self.valid_character
-
VALID_CHARACTER[Encoding.default_external.to_s]
-
end
-
else
-
def self.valid_character
-
case $KCODE
-
when 'UTF8'
-
VALID_CHARACTER['UTF-8']
-
when 'SJIS'
-
VALID_CHARACTER['Shift_JIS']
-
end
-
end
-
end
-
-
2
if 'string'.respond_to?(:valid_encoding?)
-
# Verifies the encoding of a string
-
2
def self.verify(string)
-
string.valid_encoding?
-
end
-
else
-
def self.verify(string)
-
if expression = valid_character
-
# Splits the string on character boundaries, which are determined based on $KCODE.
-
string.split(//).all? { |c| expression =~ c }
-
else
-
true
-
end
-
end
-
end
-
-
# Verifies the encoding of the string and raises an exception when it's not valid
-
2
def self.verify!(string)
-
raise EncodingError.new("Found characters with invalid encoding") unless verify(string)
-
end
-
-
2
if 'string'.respond_to?(:force_encoding)
-
# Removes all invalid characters from the string.
-
#
-
# Note: this method is a no-op in Ruby 1.9
-
2
def self.clean(string)
-
string
-
end
-
else
-
def self.clean(string)
-
if expression = valid_character
-
# Splits the string on character boundaries, which are determined based on $KCODE.
-
string.split(//).grep(expression).join
-
else
-
string
-
end
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
# = Notifications
-
#
-
# +ActiveSupport::Notifications+ provides an instrumentation API for Ruby.
-
#
-
# == Instrumenters
-
#
-
# To instrument an event you just need to do:
-
#
-
# ActiveSupport::Notifications.instrument("render", :extra => :information) do
-
# render :text => "Foo"
-
# end
-
#
-
# That executes the block first and notifies all subscribers once done.
-
#
-
# In the example above "render" is the name of the event, and the rest is called
-
# the _payload_. The payload is a mechanism that allows instrumenters to pass
-
# extra information to subscribers. Payloads consist of a hash whose contents
-
# are arbitrary and generally depend on the event.
-
#
-
# == Subscribers
-
#
-
# You can consume those events and the information they provide by registering
-
# a subscriber. For instance, let's store all "render" events in an array:
-
#
-
# events = []
-
#
-
# ActiveSupport::Notifications.subscribe("render") do |*args|
-
# events << ActiveSupport::Notifications::Event.new(*args)
-
# end
-
#
-
# That code returns right away, you are just subscribing to "render" events.
-
# The block will be called asynchronously whenever someone instruments "render":
-
#
-
# ActiveSupport::Notifications.instrument("render", :extra => :information) do
-
# render :text => "Foo"
-
# end
-
#
-
# event = events.first
-
# event.name # => "render"
-
# event.duration # => 10 (in milliseconds)
-
# event.payload # => { :extra => :information }
-
#
-
# The block in the +subscribe+ call gets the name of the event, start
-
# timestamp, end timestamp, a string with a unique identifier for that event
-
# (something like "535801666f04d0298cd6"), and a hash with the payload, in
-
# that order.
-
#
-
# If an exception happens during that particular instrumentation the payload will
-
# have a key +:exception+ with an array of two elements as value: a string with
-
# the name of the exception class, and the exception message.
-
#
-
# As the previous example depicts, the class +ActiveSupport::Notifications::Event+
-
# is able to take the arguments as they come and provide an object-oriented
-
# interface to that data.
-
#
-
# You can also subscribe to all events whose name matches a certain regexp:
-
#
-
# ActiveSupport::Notifications.subscribe(/render/) do |*args|
-
# ...
-
# end
-
#
-
# and even pass no argument to +subscribe+, in which case you are subscribing
-
# to all events.
-
#
-
# == Temporary Subscriptions
-
#
-
# Sometimes you do not want to subscribe to an event for the entire life of
-
# the application. There are two ways to unsubscribe.
-
#
-
# WARNING: The instrumentation framework is designed for long-running subscribers,
-
# use this feature sparingly because it wipes some internal caches and that has
-
# a negative impact on performance.
-
#
-
# === Subscribe While a Block Runs
-
#
-
# You can subscribe to some event temporarily while some block runs. For
-
# example, in
-
#
-
# callback = lambda {|*args| ... }
-
# ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
-
# ...
-
# end
-
#
-
# the callback will be called for all "sql.active_record" events instrumented
-
# during the execution of the block. The callback is unsubscribed automatically
-
# after that.
-
#
-
# === Manual Unsubscription
-
#
-
# The +subscribe+ method returns a subscriber object:
-
#
-
# subscriber = ActiveSupport::Notifications.subscribe("render") do |*args|
-
# ...
-
# end
-
#
-
# To prevent that block from being called anymore, just unsubscribe passing
-
# that reference:
-
#
-
# ActiveSupport::Notifications.unsubscribe(subscriber)
-
#
-
# == Default Queue
-
#
-
# Notifications ships with a queue implementation that consumes and publish events
-
# to log subscribers in a thread. You can use any queue implementation you want.
-
#
-
2
module Notifications
-
2
autoload :Instrumenter, 'active_support/notifications/instrumenter'
-
2
autoload :Event, 'active_support/notifications/instrumenter'
-
2
autoload :Fanout, 'active_support/notifications/fanout'
-
-
41
@instrumenters = Hash.new { |h,k| h[k] = notifier.listening?(k) }
-
-
2
class << self
-
2
attr_accessor :notifier
-
-
2
def publish(name, *args)
-
notifier.publish(name, *args)
-
end
-
-
2
def instrument(name, payload = {})
-
48
if @instrumenters[name]
-
88
instrumenter.instrument(name, payload) { yield payload if block_given? }
-
else
-
4
yield payload if block_given?
-
end
-
end
-
-
2
def subscribe(*args, &block)
-
204
notifier.subscribe(*args, &block).tap do
-
204
@instrumenters.clear
-
end
-
end
-
-
2
def subscribed(callback, *args, &block)
-
subscriber = subscribe(*args, &callback)
-
yield
-
ensure
-
unsubscribe(subscriber)
-
end
-
-
2
def unsubscribe(args)
-
150
notifier.unsubscribe(args)
-
150
@instrumenters.clear
-
end
-
-
2
def instrumenter
-
46
Thread.current[:"instrumentation_#{notifier.object_id}"] ||= Instrumenter.new(notifier)
-
end
-
end
-
-
2
self.notifier = Fanout.new
-
end
-
end
-
2
module ActiveSupport
-
2
module Notifications
-
# This is a default queue implementation that ships with Notifications.
-
# It just pushes events to all registered log subscribers.
-
2
class Fanout
-
2
def initialize
-
2
@subscribers = []
-
2
@listeners_for = {}
-
end
-
-
2
def subscribe(pattern = nil, block = Proc.new)
-
204
subscriber = Subscriber.new(pattern, block).tap do |s|
-
204
@subscribers << s
-
end
-
204
@listeners_for.clear
-
204
subscriber
-
end
-
-
2
def unsubscribe(subscriber)
-
4276
@subscribers.reject! {|s| s.matches?(subscriber)}
-
150
@listeners_for.clear
-
end
-
-
2
def publish(name, *args)
-
8044
listeners_for(name).each { |s| s.publish(name, *args) }
-
end
-
-
2
def listeners_for(name)
-
5289
@listeners_for[name] ||= @subscribers.select { |s| s.subscribed_to?(name) }
-
end
-
-
2
def listening?(name)
-
39
listeners_for(name).any?
-
end
-
-
# This is a sync queue, so there is no waiting.
-
2
def wait
-
end
-
-
2
class Subscriber #:nodoc:
-
2
def initialize(pattern, delegate)
-
204
@pattern = pattern
-
204
@delegate = delegate
-
end
-
-
2
def publish(message, *args)
-
6011
@delegate.call(message, *args)
-
end
-
-
2
def subscribed_to?(name)
-
3217
!@pattern || @pattern === name.to_s
-
end
-
-
2
def matches?(subscriber_or_name)
-
self === subscriber_or_name ||
-
4126
@pattern && @pattern === subscriber_or_name
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/module/delegation'
-
-
2
module ActiveSupport
-
2
module Notifications
-
2
class Instrumenter
-
2
attr_reader :id
-
-
2
def initialize(notifier)
-
2
@id = unique_id
-
2
@notifier = notifier
-
end
-
-
# Instrument the given block by measuring the time taken to execute it
-
# and publish it. Notice that events get sent even if an error occurs
-
# in the passed-in block
-
2
def instrument(name, payload={})
-
2033
started = Time.now
-
-
2033
begin
-
2033
yield
-
rescue Exception => e
-
payload[:exception] = [e.class.name, e.message]
-
raise e
-
ensure
-
2033
@notifier.publish(name, started, Time.now, @id, payload)
-
2033
end
-
end
-
-
2
private
-
2
def unique_id
-
2
SecureRandom.hex(10)
-
end
-
end
-
-
2
class Event
-
2
attr_reader :name, :time, :end, :transaction_id, :payload, :duration
-
-
2
def initialize(name, start, ending, transaction_id, payload)
-
4022
@name = name
-
4022
@payload = payload.dup
-
4022
@time = start
-
4022
@transaction_id = transaction_id
-
4022
@end = ending
-
4022
@duration = 1000.0 * (@end - @time)
-
end
-
-
2
def parent_of?(event)
-
start = (time - event.time) * 1000
-
start <= 0 && (start + duration >= event.duration)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/hash/deep_merge'
-
-
2
module ActiveSupport
-
2
class OptionMerger #:nodoc:
-
2
instance_methods.each do |method|
-
180
undef_method(method) if method !~ /^(__|instance_eval|class|object_id)/
-
end
-
-
2
def initialize(context, options)
-
@context, @options = context, options
-
end
-
-
2
private
-
2
def method_missing(method, *arguments, &block)
-
if arguments.last.is_a?(Proc)
-
proc = arguments.pop
-
arguments << lambda { |*args| @options.deep_merge(proc.call(*args)) }
-
else
-
arguments << (arguments.last.respond_to?(:to_hash) ? @options.deep_merge(arguments.pop) : @options.dup)
-
end
-
-
@context.__send__(method, *arguments, &block)
-
end
-
end
-
end
-
2
begin
-
2
require 'psych'
-
rescue LoadError
-
end
-
-
2
require 'yaml'
-
-
2
YAML.add_builtin_type("omap") do |type, val|
-
ActiveSupport::OrderedHash[val.map{ |v| v.to_a.first }]
-
end
-
-
2
module ActiveSupport
-
# The order of iteration over hashes in Ruby 1.8 is undefined. For example, you do not know the
-
# order in which +keys+ will return keys, or +each+ yield pairs. <tt>ActiveSupport::OrderedHash</tt>
-
# implements a hash that preserves insertion order, as in Ruby 1.9:
-
#
-
# oh = ActiveSupport::OrderedHash.new
-
# oh[:a] = 1
-
# oh[:b] = 2
-
# oh.keys # => [:a, :b], this order is guaranteed
-
#
-
# <tt>ActiveSupport::OrderedHash</tt> is namespaced to prevent conflicts with other implementations.
-
2
class OrderedHash < ::Hash
-
2
def to_yaml_type
-
"!tag:yaml.org,2002:omap"
-
end
-
-
2
def encode_with(coder)
-
coder.represent_seq '!omap', map { |k,v| { k => v } }
-
end
-
-
2
def to_yaml(opts = {})
-
if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck?
-
return super
-
end
-
-
YAML.quick_emit(self, opts) do |out|
-
out.seq(taguri) do |seq|
-
each do |k, v|
-
seq.add(k => v)
-
end
-
end
-
end
-
end
-
-
2
def nested_under_indifferent_access
-
self
-
end
-
-
# Returns true to make sure that this hash is extractable via <tt>Array#extract_options!</tt>
-
2
def extractable_options?
-
true
-
end
-
-
# Hash is ordered in Ruby 1.9!
-
2
if RUBY_VERSION < '1.9'
-
-
# In MRI the Hash class is core and written in C. In particular, methods are
-
# programmed with explicit C function calls and polymorphism is not honored.
-
#
-
# For example, []= is crucial in this implementation to maintain the @keys
-
# array but hash.c invokes rb_hash_aset() originally. This prevents method
-
# reuse through inheritance and forces us to reimplement stuff.
-
#
-
# For instance, we cannot use the inherited #merge! because albeit the algorithm
-
# itself would work, our []= is not being called at all by the C code.
-
-
def initialize(*args, &block)
-
super
-
@keys = []
-
end
-
-
def self.[](*args)
-
ordered_hash = new
-
-
if (args.length == 1 && args.first.is_a?(Array))
-
args.first.each do |key_value_pair|
-
next unless (key_value_pair.is_a?(Array))
-
ordered_hash[key_value_pair[0]] = key_value_pair[1]
-
end
-
-
return ordered_hash
-
end
-
-
unless (args.size % 2 == 0)
-
raise ArgumentError.new("odd number of arguments for Hash")
-
end
-
-
args.each_with_index do |val, ind|
-
next if (ind % 2 != 0)
-
ordered_hash[val] = args[ind + 1]
-
end
-
-
ordered_hash
-
end
-
-
def initialize_copy(other)
-
super
-
# make a deep copy of keys
-
@keys = other.keys
-
end
-
-
def []=(key, value)
-
@keys << key unless has_key?(key)
-
super
-
end
-
-
def delete(key)
-
if has_key? key
-
index = @keys.index(key)
-
@keys.delete_at index
-
end
-
super
-
end
-
-
def delete_if
-
super
-
sync_keys!
-
self
-
end
-
-
def reject!
-
super
-
sync_keys!
-
self
-
end
-
-
def reject(&block)
-
dup.reject!(&block)
-
end
-
-
def keys
-
@keys.dup
-
end
-
-
def values
-
@keys.collect { |key| self[key] }
-
end
-
-
def to_hash
-
self
-
end
-
-
def to_a
-
@keys.map { |key| [ key, self[key] ] }
-
end
-
-
def each_key
-
return to_enum(:each_key) unless block_given?
-
@keys.each { |key| yield key }
-
self
-
end
-
-
def each_value
-
return to_enum(:each_value) unless block_given?
-
@keys.each { |key| yield self[key]}
-
self
-
end
-
-
def each
-
return to_enum(:each) unless block_given?
-
@keys.each {|key| yield [key, self[key]]}
-
self
-
end
-
-
def each_pair
-
return to_enum(:each_pair) unless block_given?
-
@keys.each {|key| yield key, self[key]}
-
self
-
end
-
-
alias_method :select, :find_all
-
-
def clear
-
super
-
@keys.clear
-
self
-
end
-
-
def shift
-
k = @keys.first
-
v = delete(k)
-
[k, v]
-
end
-
-
def merge!(other_hash)
-
if block_given?
-
other_hash.each { |k, v| self[k] = key?(k) ? yield(k, self[k], v) : v }
-
else
-
other_hash.each { |k, v| self[k] = v }
-
end
-
self
-
end
-
-
alias_method :update, :merge!
-
-
def merge(other_hash, &block)
-
dup.merge!(other_hash, &block)
-
end
-
-
# When replacing with another hash, the initial order of our keys must come from the other hash -ordered or not.
-
def replace(other)
-
super
-
@keys = other.keys
-
self
-
end
-
-
def invert
-
OrderedHash[self.to_a.map!{|key_value_pair| key_value_pair.reverse}]
-
end
-
-
def inspect
-
"#<OrderedHash #{super}>"
-
end
-
-
private
-
def sync_keys!
-
@keys.delete_if {|k| !has_key?(k)}
-
end
-
end
-
end
-
end
-
2
require 'active_support/ordered_hash'
-
-
# Usually key value pairs are handled something like this:
-
#
-
# h = {}
-
# h[:boy] = 'John'
-
# h[:girl] = 'Mary'
-
# h[:boy] # => 'John'
-
# h[:girl] # => 'Mary'
-
#
-
# Using <tt>OrderedOptions</tt>, the above code could be reduced to:
-
#
-
# h = ActiveSupport::OrderedOptions.new
-
# h.boy = 'John'
-
# h.girl = 'Mary'
-
# h.boy # => 'John'
-
# h.girl # => 'Mary'
-
#
-
2
module ActiveSupport #:nodoc:
-
2
class OrderedOptions < OrderedHash
-
2
alias_method :_get, :[] # preserve the original #[] method
-
2
protected :_get # make it protected
-
-
2
def []=(key, value)
-
174
super(key.to_sym, value)
-
end
-
-
2
def [](key)
-
169
super(key.to_sym)
-
end
-
-
2
def method_missing(name, *args)
-
343
if name.to_s =~ /(.*)=$/
-
174
self[$1] = args.first
-
else
-
169
self[name]
-
end
-
end
-
-
2
def respond_to?(name)
-
4
true
-
end
-
end
-
-
2
class InheritableOptions < OrderedOptions
-
2
def initialize(parent = nil)
-
35
if parent.kind_of?(OrderedOptions)
-
# use the faster _get when dealing with OrderedOptions
-
107
super() { |h,k| parent._get(k) }
-
6
elsif parent
-
super() { |h,k| parent[k] }
-
else
-
6
super()
-
end
-
end
-
-
2
def inheritable_copy
-
29
self.class.new(self)
-
end
-
end
-
end
-
2
require "active_support"
-
2
require "active_support/i18n_railtie"
-
-
2
module ActiveSupport
-
2
class Railtie < Rails::Railtie
-
2
config.active_support = ActiveSupport::OrderedOptions.new
-
-
# Loads support for "whiny nil" (noisy warnings when methods are invoked
-
# on +nil+ values) if Configuration#whiny_nils is true.
-
2
initializer "active_support.initialize_whiny_nils" do |app|
-
2
require 'active_support/whiny_nil' if app.config.whiny_nils
-
end
-
-
2
initializer "active_support.deprecation_behavior" do |app|
-
2
if deprecation = app.config.active_support.deprecation
-
2
ActiveSupport::Deprecation.behavior = deprecation
-
else
-
defaults = {"development" => :log,
-
"production" => :notify,
-
"test" => :stderr}
-
-
env = Rails.env
-
-
if defaults.key?(env)
-
msg = "You did not specify how you would like Rails to report " \
-
"deprecation notices for your #{env} environment, please " \
-
"set config.active_support.deprecation to :#{defaults[env]} " \
-
"at config/environments/#{env}.rb"
-
-
warn msg
-
ActiveSupport::Deprecation.behavior = defaults[env]
-
else
-
msg = "You did not specify how you would like Rails to report " \
-
"deprecation notices for your #{env} environment, please " \
-
"set config.active_support.deprecation to :log, :notify or " \
-
":stderr at config/environments/#{env}.rb"
-
-
warn msg
-
ActiveSupport::Deprecation.behavior = :stderr
-
end
-
end
-
end
-
-
# Sets the default value for Time.zone
-
# If assigned value cannot be matched to a TimeZone, an exception will be raised.
-
2
initializer "active_support.initialize_time_zone" do |app|
-
2
require 'active_support/core_ext/time/zones'
-
2
zone_default = Time.find_zone!(app.config.time_zone)
-
-
2
unless zone_default
-
raise \
-
'Value assigned to config.time_zone not recognized.' +
-
'Run "rake -D time" for a list of tasks for finding appropriate time zone names.'
-
end
-
-
2
Time.zone_default = zone_default
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/core_ext/class/attribute'
-
2
require 'active_support/core_ext/proc'
-
2
require 'active_support/core_ext/string/inflections'
-
2
require 'active_support/core_ext/array/extract_options'
-
-
2
module ActiveSupport
-
# Rescuable module adds support for easier exception handling.
-
2
module Rescuable
-
2
extend Concern
-
-
2
included do
-
2
class_attribute :rescue_handlers
-
2
self.rescue_handlers = []
-
end
-
-
2
module ClassMethods
-
# Rescue exceptions raised in controller actions.
-
#
-
# <tt>rescue_from</tt> receives a series of exception classes or class
-
# names, and a trailing <tt>:with</tt> option with the name of a method
-
# or a Proc object to be called to handle them. Alternatively a block can
-
# be given.
-
#
-
# Handlers that take one argument will be called with the exception, so
-
# that the exception can be inspected when dealing with it.
-
#
-
# Handlers are inherited. They are searched from right to left, from
-
# bottom to top, and up the hierarchy. The handler of the first class for
-
# which <tt>exception.is_a?(klass)</tt> holds true is the one invoked, if
-
# any.
-
#
-
# class ApplicationController < ActionController::Base
-
# rescue_from User::NotAuthorized, :with => :deny_access # self defined exception
-
# rescue_from ActiveRecord::RecordInvalid, :with => :show_errors
-
#
-
# rescue_from 'MyAppError::Base' do |exception|
-
# render :xml => exception, :status => 500
-
# end
-
#
-
# protected
-
# def deny_access
-
# ...
-
# end
-
#
-
# def show_errors(exception)
-
# exception.record.new_record? ? ...
-
# end
-
# end
-
#
-
2
def rescue_from(*klasses, &block)
-
2
options = klasses.extract_options!
-
-
2
unless options.has_key?(:with)
-
2
if block_given?
-
2
options[:with] = block
-
else
-
raise ArgumentError, "Need a handler. Supply an options hash that has a :with key as the last argument."
-
end
-
end
-
-
2
klasses.each do |klass|
-
2
key = if klass.is_a?(Class) && klass <= Exception
-
2
klass.name
-
elsif klass.is_a?(String)
-
klass
-
else
-
raise ArgumentError, "#{klass} is neither an Exception nor a String"
-
end
-
-
# put the new handler at the end because the list is read in reverse
-
2
self.rescue_handlers += [[key, options[:with]]]
-
end
-
end
-
end
-
-
# Tries to rescue the exception by looking up and calling a registered handler.
-
2
def rescue_with_handler(exception)
-
if handler = handler_for_rescue(exception)
-
handler.arity != 0 ? handler.call(exception) : handler.call
-
true # don't rely on the return value of the handler
-
end
-
end
-
-
2
def handler_for_rescue(exception)
-
# We go from right to left because pairs are pushed onto rescue_handlers
-
# as rescue_from declarations are found.
-
_, rescuer = self.class.rescue_handlers.reverse.detect do |klass_name, handler|
-
# The purpose of allowing strings in rescue_from is to support the
-
# declaration of handler associations for exception classes whose
-
# definition is yet unknown.
-
#
-
# Since this loop needs the constants it would be inconsistent to
-
# assume they should exist at this point. An early raised exception
-
# could trigger some other handler and the array could include
-
# precisely a string whose corresponding constant has not yet been
-
# seen. This is why we are tolerant to unknown constants.
-
#
-
# Note that this tolerance only matters if the exception was given as
-
# a string, otherwise a NameError will be raised by the interpreter
-
# itself when rescue_from CONSTANT is executed.
-
klass = self.class.const_get(klass_name) rescue nil
-
klass ||= klass_name.constantize rescue nil
-
exception.is_a?(klass) if klass
-
end
-
-
case rescuer
-
when Symbol
-
method(rescuer)
-
when Proc
-
rescuer.bind(self)
-
end
-
end
-
end
-
end
-
# Backported Ruby builtins so you can code with the latest & greatest
-
# but still run on any Ruby 1.8.x.
-
#
-
# Date next_year, next_month
-
# DateTime to_date, to_datetime, xmlschema
-
# Enumerable group_by, each_with_object, none?
-
# Process Process.daemon
-
# REXML security fix
-
# String ord
-
# Time to_date, to_time, to_datetime
-
2
require 'active_support'
-
2
require 'active_support/core_ext/date/calculations'
-
2
require 'active_support/core_ext/date_time/conversions'
-
2
require 'active_support/core_ext/enumerable'
-
2
require 'active_support/core_ext/process/daemon'
-
2
require 'active_support/core_ext/string/conversions'
-
2
require 'active_support/core_ext/string/interpolation'
-
2
require 'active_support/core_ext/string/encoding'
-
2
require 'active_support/core_ext/rexml'
-
2
require 'active_support/core_ext/time/conversions'
-
2
require 'active_support/core_ext/file/path'
-
2
require 'active_support/core_ext/module/method_names'
-
2
module ActiveSupport
-
# Wrapping a string in this class gives you a prettier way to test
-
# for equality. The value returned by <tt>Rails.env</tt> is wrapped
-
# in a StringInquirer object so instead of calling this:
-
#
-
# Rails.env == "production"
-
#
-
# you can call this:
-
#
-
# Rails.env.production?
-
#
-
2
class StringInquirer < String
-
2
def method_missing(method_name, *arguments)
-
16
if method_name.to_s[-1,1] == "?"
-
16
self == method_name.to_s[0..-2]
-
else
-
super
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/deprecation'
-
2
require 'logger'
-
-
2
module ActiveSupport
-
# Wraps any standard Logger class to provide tagging capabilities. Examples:
-
#
-
# Logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
-
# Logger.tagged("BCX") { Logger.info "Stuff" } # Logs "[BCX] Stuff"
-
# Logger.tagged("BCX", "Jason") { Logger.info "Stuff" } # Logs "[BCX] [Jason] Stuff"
-
# Logger.tagged("BCX") { Logger.tagged("Jason") { Logger.info "Stuff" } } # Logs "[BCX] [Jason] Stuff"
-
#
-
# This is used by the default Rails.logger as configured by Railties to make it easy to stamp log lines
-
# with subdomains, request ids, and anything else to aid debugging of multi-user production applications.
-
2
class TaggedLogging
-
2
def initialize(logger)
-
2
@logger = logger
-
end
-
-
2
def tagged(*tags)
-
new_tags = push_tags(*tags)
-
yield self
-
ensure
-
pop_tags(new_tags.size)
-
end
-
-
2
def push_tags(*tags)
-
tags.flatten.reject(&:blank?).tap do |new_tags|
-
current_tags.concat new_tags
-
end
-
end
-
-
2
def pop_tags(size = 1)
-
current_tags.pop size
-
end
-
-
2
def clear_tags!
-
current_tags.clear
-
end
-
-
2
def silence(temporary_level = Logger::ERROR, &block)
-
@logger.silence(temporary_level, &block)
-
end
-
2
deprecate :silence
-
-
2
def add(severity, message = nil, progname = nil, &block)
-
1999
if message.nil?
-
1999
if block_given?
-
message = block.call
-
else
-
1999
message = progname
-
1999
progname = nil #No instance variable for this like Logger
-
end
-
end
-
1999
@logger.add(severity, "#{tags_text}#{message}", progname)
-
end
-
-
2
%w( fatal error warn info debug unknown ).each do |severity|
-
12
eval <<-EOM, nil, __FILE__, __LINE__ + 1
-
def #{severity}(progname = nil, &block)
-
add(Logger::#{severity.upcase}, nil, progname, &block)
-
end
-
EOM
-
end
-
-
2
def flush
-
clear_tags!
-
@logger.flush if @logger.respond_to?(:flush)
-
end
-
-
2
def method_missing(method, *args)
-
1991
@logger.send(method, *args)
-
end
-
-
2
if RUBY_VERSION < '1.9'
-
def respond_to?(*args)
-
super || @logger.respond_to?(*args)
-
end
-
else
-
2
def respond_to_missing?(*args)
-
@logger.respond_to? *args
-
end
-
end
-
-
2
private
-
2
def tags_text
-
1999
tags = current_tags
-
1999
if tags.any?
-
tags.collect { |tag| "[#{tag}] " }.join
-
end
-
end
-
-
2
def current_tags
-
1999
Thread.current[:activesupport_tagged_logging_tags] ||= []
-
end
-
end
-
end
-
2
require 'test/unit/testcase'
-
2
require 'active_support/testing/setup_and_teardown'
-
2
require 'active_support/testing/assertions'
-
2
require 'active_support/testing/deprecation'
-
2
require 'active_support/testing/declarative'
-
2
require 'active_support/testing/pending'
-
2
require 'active_support/testing/isolation'
-
2
require 'active_support/testing/mochaing'
-
2
require 'active_support/core_ext/kernel/reporting'
-
-
2
module ActiveSupport
-
2
class TestCase < ::Test::Unit::TestCase
-
2
if defined?(MiniTest::Assertions) && TestCase < MiniTest::Assertions
-
2
Assertion = MiniTest::Assertion
-
2
alias_method :method_name, :name if method_defined? :name
-
2
alias_method :method_name, :__name__ if method_defined? :__name__
-
else
-
Assertion = Test::Unit::AssertionFailedError
-
-
undef :default_test
-
end
-
-
2
$tags = {}
-
2
def self.for_tag(tag)
-
yield if $tags[tag]
-
end
-
-
2
include ActiveSupport::Testing::SetupAndTeardown
-
2
include ActiveSupport::Testing::Assertions
-
2
include ActiveSupport::Testing::Deprecation
-
2
include ActiveSupport::Testing::Pending
-
2
extend ActiveSupport::Testing::Declarative
-
end
-
end
-
2
require 'active_support/core_ext/array/wrap'
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module ActiveSupport
-
2
module Testing
-
2
module Assertions
-
# Test numeric difference between the return value of an expression as a result of what is evaluated
-
# in the yielded block.
-
#
-
# assert_difference 'Article.count' do
-
# post :create, :article => {...}
-
# end
-
#
-
# An arbitrary expression is passed in and evaluated.
-
#
-
# assert_difference 'assigns(:article).comments(:reload).size' do
-
# post :create, :comment => {...}
-
# end
-
#
-
# An arbitrary positive or negative difference can be specified. The default is +1.
-
#
-
# assert_difference 'Article.count', -1 do
-
# post :delete, :id => ...
-
# end
-
#
-
# An array of expressions can also be passed in and evaluated.
-
#
-
# assert_difference [ 'Article.count', 'Post.count' ], +2 do
-
# post :create, :article => {...}
-
# end
-
#
-
# A lambda or a list of lambdas can be passed in and evaluated:
-
#
-
# assert_difference lambda { Article.count }, 2 do
-
# post :create, :article => {...}
-
# end
-
#
-
# assert_difference [->{ Article.count }, ->{ Post.count }], 2 do
-
# post :create, :article => {...}
-
# end
-
#
-
# A error message can be specified.
-
#
-
# assert_difference 'Article.count', -1, "An Article should be destroyed" do
-
# post :delete, :id => ...
-
# end
-
2
def assert_difference(expression, difference = 1, message = nil, &block)
-
6
expressions = Array.wrap expression
-
-
6
exps = expressions.map { |e|
-
14
e.respond_to?(:call) ? e : lambda { eval(e, block.binding) }
-
}
-
12
before = exps.map { |e| e.call }
-
-
6
yield
-
-
2
expressions.zip(exps).each_with_index do |(code, e), i|
-
2
error = "#{code.inspect} didn't change by #{difference}"
-
2
error = "#{message}.\n#{error}" if message
-
2
assert_equal(before[i] + difference, e.call, error)
-
end
-
end
-
-
# Assertion that the numeric result of evaluating an expression is not changed before and after
-
# invoking the passed in block.
-
#
-
# assert_no_difference 'Article.count' do
-
# post :create, :article => invalid_attributes
-
# end
-
#
-
# A error message can be specified.
-
#
-
# assert_no_difference 'Article.count', "An Article should not be created" do
-
# post :create, :article => invalid_attributes
-
# end
-
2
def assert_no_difference(expression, message = nil, &block)
-
assert_difference expression, 0, message, &block
-
end
-
-
# Test if an expression is blank. Passes if object.blank? is true.
-
#
-
# assert_blank [] # => true
-
2
def assert_blank(object, message=nil)
-
message ||= "#{object.inspect} is not blank"
-
assert object.blank?, message
-
end
-
-
# Test if an expression is not blank. Passes if object.present? is true.
-
#
-
# assert_present {:data => 'x' } # => true
-
2
def assert_present(object, message=nil)
-
message ||= "#{object.inspect} is blank"
-
assert object.present?, message
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
2
module Testing
-
2
module Declarative
-
-
2
def self.extended(klass)
-
2
klass.class_eval do
-
-
2
unless method_defined?(:describe)
-
2
def self.describe(text)
-
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def self.name
-
"#{text}"
-
end
-
RUBY_EVAL
-
end
-
end
-
-
end
-
end
-
-
2
unless defined?(Spec)
-
# test "verify something" do
-
# ...
-
# end
-
2
def test(name, &block)
-
75
test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
-
75
defined = instance_method(test_name) rescue false
-
75
raise "#{test_name} is already defined in #{self}" if defined
-
75
if block_given?
-
75
define_method(test_name, &block)
-
else
-
define_method(test_name) do
-
flunk "No implementation provided for #{name}"
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support/deprecation'
-
-
2
module ActiveSupport
-
2
module Testing
-
2
module Deprecation #:nodoc:
-
2
def assert_deprecated(match = nil, &block)
-
result, warnings = collect_deprecations(&block)
-
assert !warnings.empty?, "Expected a deprecation warning within the block but received none"
-
if match
-
match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp)
-
assert warnings.any? { |w| w =~ match }, "No deprecation warning matched #{match}: #{warnings.join(', ')}"
-
end
-
result
-
end
-
-
2
def assert_not_deprecated(&block)
-
result, deprecations = collect_deprecations(&block)
-
assert deprecations.empty?, "Expected no deprecation warning within the block but received #{deprecations.size}: \n #{deprecations * "\n "}"
-
result
-
end
-
-
2
private
-
2
def collect_deprecations
-
old_behavior = ActiveSupport::Deprecation.behavior
-
deprecations = []
-
ActiveSupport::Deprecation.behavior = Proc.new do |message, callstack|
-
deprecations << message
-
end
-
result = yield
-
[result, deprecations]
-
ensure
-
ActiveSupport::Deprecation.behavior = old_behavior
-
end
-
end
-
end
-
end
-
-
2
begin
-
2
require 'test/unit/error'
-
rescue LoadError
-
# Using miniunit, ignore.
-
else
-
module Test
-
module Unit
-
class Error #:nodoc:
-
# Silence warnings when reporting test errors.
-
def message_with_silenced_deprecation
-
::ActiveSupport::Deprecation.silence { message_without_silenced_deprecation }
-
end
-
alias_method :message_without_silenced_deprecation, :message
-
alias_method :message, :message_with_silenced_deprecation
-
end
-
end
-
end
-
end
-
2
require 'rbconfig'
-
2
module ActiveSupport
-
2
module Testing
-
2
class RemoteError < StandardError
-
-
2
attr_reader :message, :backtrace
-
-
2
def initialize(exception)
-
@message = "caught #{exception.class.name}: #{exception.message}"
-
@backtrace = exception.backtrace
-
end
-
end
-
-
2
class ProxyTestResult
-
2
def initialize(calls = [])
-
@calls = calls
-
end
-
-
2
def add_error(e)
-
e = Test::Unit::Error.new(e.test_name, RemoteError.new(e.exception))
-
@calls << [:add_error, e]
-
end
-
-
2
def __replay__(result)
-
@calls.each do |name, args|
-
result.send(name, *args)
-
end
-
end
-
-
2
def marshal_dump
-
@calls
-
end
-
-
2
def marshal_load(calls)
-
initialize(calls)
-
end
-
-
2
def method_missing(name, *args)
-
@calls << [name, args]
-
end
-
end
-
-
2
module Isolation
-
2
def self.forking_env?
-
2
!ENV["NO_FORK"] && ((RbConfig::CONFIG['host_os'] !~ /mswin|mingw/) && (RUBY_PLATFORM !~ /java/))
-
end
-
-
2
def self.included(base)
-
if defined?(::MiniTest) && base < ::MiniTest::Unit::TestCase
-
base.send :include, MiniTest
-
elsif defined?(Test::Unit)
-
base.send :include, TestUnit
-
end
-
end
-
-
2
def _run_class_setup # class setup method should only happen in parent
-
unless defined?(@@ran_class_setup) || ENV['ISOLATION_TEST']
-
self.class.setup if self.class.respond_to?(:setup)
-
@@ran_class_setup = true
-
end
-
end
-
-
2
module TestUnit
-
2
def run(result)
-
_run_class_setup
-
-
yield(Test::Unit::TestCase::STARTED, name)
-
-
@_result = result
-
-
serialized = run_in_isolation do |proxy|
-
begin
-
super(proxy) { }
-
rescue Exception => e
-
proxy.add_error(Test::Unit::Error.new(name, e))
-
end
-
end
-
-
retval, proxy = Marshal.load(serialized)
-
proxy.__replay__(@_result)
-
-
yield(Test::Unit::TestCase::FINISHED, name)
-
retval
-
end
-
end
-
-
2
module MiniTest
-
2
def run(runner)
-
_run_class_setup
-
-
serialized = run_in_isolation do |isolated_runner|
-
super(isolated_runner)
-
end
-
-
retval, proxy = Marshal.load(serialized)
-
proxy.__replay__(runner)
-
retval
-
end
-
end
-
-
2
module Forking
-
2
def run_in_isolation(&blk)
-
read, write = IO.pipe
-
-
pid = fork do
-
read.close
-
proxy = ProxyTestResult.new
-
retval = yield proxy
-
write.puts [Marshal.dump([retval, proxy])].pack("m")
-
exit!
-
end
-
-
write.close
-
result = read.read
-
Process.wait2(pid)
-
return result.unpack("m")[0]
-
end
-
end
-
-
2
module Subprocess
-
2
ORIG_ARGV = ARGV.dup unless defined?(ORIG_ARGV)
-
-
# Crazy H4X to get this working in windows / jruby with
-
# no forking.
-
2
def run_in_isolation(&blk)
-
require "tempfile"
-
-
if ENV["ISOLATION_TEST"]
-
proxy = ProxyTestResult.new
-
retval = yield proxy
-
File.open(ENV["ISOLATION_OUTPUT"], "w") do |file|
-
file.puts [Marshal.dump([retval, proxy])].pack("m")
-
end
-
exit!
-
else
-
Tempfile.open("isolation") do |tmpfile|
-
ENV["ISOLATION_TEST"] = @method_name
-
ENV["ISOLATION_OUTPUT"] = tmpfile.path
-
-
load_paths = $-I.map {|p| "-I\"#{File.expand_path(p)}\"" }.join(" ")
-
`#{Gem.ruby} #{load_paths} #{$0} #{ORIG_ARGV.join(" ")} -t\"#{self.class}\"`
-
-
ENV.delete("ISOLATION_TEST")
-
ENV.delete("ISOLATION_OUTPUT")
-
-
return tmpfile.read.unpack("m")[0]
-
end
-
end
-
end
-
end
-
-
2
include forking_env? ? Forking : Subprocess
-
end
-
end
-
end
-
-
# Only in subprocess for windows / jruby.
-
2
if ENV['ISOLATION_TEST']
-
require "test/unit/collector/objectspace"
-
class Test::Unit::Collector::ObjectSpace
-
def include?(test)
-
super && test.method_name == ENV['ISOLATION_TEST']
-
end
-
end
-
end
-
2
begin
-
4
silence_warnings { require 'mocha/setup' }
-
rescue LoadError
-
# Fake Mocha::ExpectationError so we can rescue it in #run. Bleh.
-
2
Object.const_set :Mocha, Module.new
-
2
Mocha.const_set :ExpectationError, Class.new(StandardError)
-
end
-
# Some code from jeremymcanally's "pending"
-
# https://github.com/jeremymcanally/pending/tree/master
-
-
2
module ActiveSupport
-
2
module Testing
-
2
module Pending
-
-
2
unless defined?(Spec)
-
-
2
@@pending_cases = []
-
2
@@at_exit = false
-
-
2
def pending(description = "", &block)
-
if defined?(::MiniTest)
-
skip(description.blank? ? nil : description)
-
else
-
if description.is_a?(Symbol)
-
is_pending = $tags[description]
-
return block.call unless is_pending
-
end
-
-
if block_given?
-
failed = false
-
-
begin
-
block.call
-
rescue Exception
-
failed = true
-
end
-
-
flunk("<#{description}> did not fail.") unless failed
-
end
-
-
caller[0] =~ (/(.*):(.*):in `(.*)'/)
-
@@pending_cases << "#{$3} at #{$1}, line #{$2}"
-
print "P"
-
-
@@at_exit ||= begin
-
at_exit do
-
puts "\nPending Cases:"
-
@@pending_cases.each do |test_case|
-
puts test_case
-
end
-
end
-
end
-
end
-
end
-
end
-
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
2
require 'active_support/callbacks'
-
-
2
module ActiveSupport
-
2
module Testing
-
2
module SetupAndTeardown
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
include ActiveSupport::Callbacks
-
2
define_callbacks :setup, :teardown
-
-
2
if defined?(MiniTest::Assertions) && TestCase < MiniTest::Assertions
-
2
include ForMiniTest
-
else
-
include ForClassicTestUnit
-
end
-
end
-
-
2
module ClassMethods
-
2
def setup(*args, &block)
-
34
set_callback(:setup, :before, *args, &block)
-
end
-
-
2
def teardown(*args, &block)
-
7
set_callback(:teardown, :after, *args, &block)
-
end
-
end
-
-
2
module ForMiniTest
-
2
PASSTHROUGH_EXCEPTIONS = MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS rescue [NoMemoryError, SignalException, Interrupt, SystemExit]
-
2
def run(runner)
-
145
result = '.'
-
145
begin
-
145
run_callbacks :setup do
-
96
result = super
-
end
-
rescue *PASSTHROUGH_EXCEPTIONS => e
-
raise e
-
rescue Exception => e
-
49
result = runner.puke(self.class, method_name, e)
-
ensure
-
145
begin
-
145
run_callbacks :teardown
-
rescue *PASSTHROUGH_EXCEPTIONS => e
-
raise e
-
rescue Exception => e
-
result = runner.puke(self.class, method_name, e)
-
end
-
end
-
145
result
-
end
-
end
-
-
2
module ForClassicTestUnit
-
# For compatibility with Ruby < 1.8.6
-
2
PASSTHROUGH_EXCEPTIONS = Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS rescue [NoMemoryError, SignalException, Interrupt, SystemExit]
-
-
# This redefinition is unfortunate but test/unit shows us no alternative.
-
# Doubly unfortunate: hax to support Mocha's hax.
-
2
def run(result)
-
return if @method_name.to_s == "default_test"
-
-
mocha_counter = retrieve_mocha_counter(self, result)
-
yield(Test::Unit::TestCase::STARTED, name)
-
@_result = result
-
-
begin
-
begin
-
run_callbacks :setup do
-
setup
-
__send__(@method_name)
-
mocha_verify(mocha_counter) if mocha_counter
-
end
-
rescue Mocha::ExpectationError => e
-
add_failure(e.message, e.backtrace)
-
rescue Test::Unit::AssertionFailedError => e
-
add_failure(e.message, e.backtrace)
-
rescue Exception => e
-
raise if PASSTHROUGH_EXCEPTIONS.include?(e.class)
-
add_error(e)
-
ensure
-
begin
-
teardown
-
run_callbacks :teardown
-
rescue Mocha::ExpectationError => e
-
add_failure(e.message, e.backtrace)
-
rescue Test::Unit::AssertionFailedError => e
-
add_failure(e.message, e.backtrace)
-
rescue Exception => e
-
raise if PASSTHROUGH_EXCEPTIONS.include?(e.class)
-
add_error(e)
-
end
-
end
-
ensure
-
mocha_teardown if mocha_counter
-
end
-
-
result.add_run
-
yield(Test::Unit::TestCase::FINISHED, name)
-
end
-
-
2
protected
-
-
2
def retrieve_mocha_counter(test_case, result) #:nodoc:
-
if respond_to?(:mocha_verify) # using mocha
-
if defined?(Mocha::TestCaseAdapter::AssertionCounter)
-
Mocha::TestCaseAdapter::AssertionCounter.new(result)
-
elsif defined?(Mocha::Integration::TestUnit::AssertionCounter)
-
Mocha::Integration::TestUnit::AssertionCounter.new(result)
-
elsif defined?(Mocha::MonkeyPatching::TestUnit::AssertionCounter)
-
Mocha::MonkeyPatching::TestUnit::AssertionCounter.new(result)
-
else
-
Mocha::Integration::AssertionCounter.new(test_case)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'active_support'
-
-
2
module ActiveSupport
-
2
autoload :Duration, 'active_support/duration'
-
2
autoload :TimeWithZone, 'active_support/time_with_zone'
-
2
autoload :TimeZone, 'active_support/values/time_zone'
-
-
2
on_load_all do
-
[Duration, TimeWithZone, TimeZone]
-
end
-
end
-
-
2
require 'date'
-
2
require 'time'
-
-
2
require 'active_support/core_ext/time/publicize_conversion_methods'
-
2
require 'active_support/core_ext/time/marshal'
-
2
require 'active_support/core_ext/time/acts_like'
-
2
require 'active_support/core_ext/time/calculations'
-
2
require 'active_support/core_ext/time/conversions'
-
2
require 'active_support/core_ext/time/zones'
-
-
2
require 'active_support/core_ext/date/acts_like'
-
2
require 'active_support/core_ext/date/freeze'
-
2
require 'active_support/core_ext/date/calculations'
-
2
require 'active_support/core_ext/date/conversions'
-
2
require 'active_support/core_ext/date/zones'
-
-
2
require 'active_support/core_ext/date_time/acts_like'
-
2
require 'active_support/core_ext/date_time/calculations'
-
2
require 'active_support/core_ext/date_time/conversions'
-
2
require 'active_support/core_ext/date_time/zones'
-
-
2
require 'active_support/core_ext/integer/time'
-
2
require 'active_support/core_ext/numeric/time'
-
2
require "active_support/values/time_zone"
-
2
require 'active_support/core_ext/object/acts_like'
-
2
require 'active_support/core_ext/object/inclusion'
-
-
2
module ActiveSupport
-
# A Time-like class that can represent a time in any time zone. Necessary because standard Ruby Time instances are
-
# limited to UTC and the system's <tt>ENV['TZ']</tt> zone.
-
#
-
# You shouldn't ever need to create a TimeWithZone instance directly via <tt>new</tt> . Instead use methods
-
# +local+, +parse+, +at+ and +now+ on TimeZone instances, and +in_time_zone+ on Time and DateTime instances.
-
# Examples:
-
#
-
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
-
# Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.parse('2007-02-10 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00
-
# Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
#
-
# See Time and TimeZone for further documentation of these methods.
-
#
-
# TimeWithZone instances implement the same API as Ruby Time instances, so that Time and TimeWithZone instances are interchangeable.
-
# Examples:
-
#
-
# t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00
-
# t.hour # => 13
-
# t.dst? # => true
-
# t.utc_offset # => -14400
-
# t.zone # => "EDT"
-
# t.to_s(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400"
-
# t + 1.day # => Mon, 19 May 2008 13:27:25 EDT -04:00
-
# t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00 EST -05:00
-
# t > Time.utc(1999) # => true
-
# t.is_a?(Time) # => true
-
# t.is_a?(ActiveSupport::TimeWithZone) # => true
-
#
-
2
class TimeWithZone
-
2
def self.name
-
234
'Time' # Report class name as 'Time' to thwart type checking
-
end
-
-
2
include Comparable
-
2
attr_reader :time_zone
-
-
2
def initialize(utc_time, time_zone, local_time = nil, period = nil)
-
3317
@utc, @time_zone, @time = utc_time, time_zone, local_time
-
3317
@period = @utc ? period : get_period_and_ensure_valid_local_time
-
end
-
-
# Returns a Time or DateTime instance that represents the time in +time_zone+.
-
2
def time
-
11745
@time ||= period.to_local(@utc)
-
end
-
-
# Returns a Time or DateTime instance that represents the time in UTC.
-
2
def utc
-
6348
@utc ||= period.to_utc(@time)
-
end
-
2
alias_method :comparable_time, :utc
-
2
alias_method :getgm, :utc
-
2
alias_method :getutc, :utc
-
2
alias_method :gmtime, :utc
-
-
# Returns the underlying TZInfo::TimezonePeriod.
-
2
def period
-
5262
@period ||= time_zone.period_for_utc(@utc)
-
end
-
-
# Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone.
-
2
def in_time_zone(new_zone = ::Time.zone)
-
1186
return self if time_zone == new_zone
-
utc.in_time_zone(new_zone)
-
end
-
-
# Returns a <tt>Time.local()</tt> instance of the simultaneous time in your system's <tt>ENV['TZ']</tt> zone
-
2
def localtime
-
utc.respond_to?(:getlocal) ? utc.getlocal : utc.to_time.getlocal
-
end
-
2
alias_method :getlocal, :localtime
-
-
2
def dst?
-
period.dst?
-
end
-
2
alias_method :isdst, :dst?
-
-
2
def utc?
-
1231
time_zone.name == 'UTC'
-
end
-
2
alias_method :gmt?, :utc?
-
-
2
def utc_offset
-
1259
period.utc_total_offset
-
end
-
2
alias_method :gmt_offset, :utc_offset
-
2
alias_method :gmtoff, :utc_offset
-
-
2
def formatted_offset(colon = true, alternate_utc_string = nil)
-
1231
utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Time uses +zone+ to display the time zone abbreviation, so we're duck-typing it.
-
2
def zone
-
1217
period.zone_identifier.to_s
-
end
-
-
2
def inspect
-
1216
"#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}"
-
end
-
-
2
def xmlschema(fraction_digits = 0)
-
fraction = if fraction_digits > 0
-
(".%06i" % time.usec)[0, fraction_digits + 1]
-
end
-
-
"#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}"
-
end
-
2
alias_method :iso8601, :xmlschema
-
-
# Coerces time to a string for JSON encoding. The default format is ISO 8601. You can get
-
# %Y/%m/%d %H:%M:%S +offset style by setting <tt>ActiveSupport::JSON::Encoding.use_standard_json_time_format</tt>
-
# to false.
-
#
-
# ==== Examples
-
#
-
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true
-
# Time.utc(2005,2,1,15,15,10).in_time_zone.to_json
-
# # => "2005-02-01T15:15:10Z"
-
#
-
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false
-
# Time.utc(2005,2,1,15,15,10).in_time_zone.to_json
-
# # => "2005/02/01 15:15:10 +0000"
-
#
-
2
def as_json(options = nil)
-
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
-
xmlschema
-
else
-
%(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
-
end
-
end
-
-
2
def encode_with(coder)
-
180
if coder.respond_to?(:represent_object)
-
180
coder.represent_object(nil, utc)
-
else
-
coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ"))
-
end
-
end
-
-
2
def to_yaml(options = {})
-
return super if defined?(YAML::ENGINE) && !YAML::ENGINE.syck?
-
-
utc.to_yaml(options)
-
end
-
-
2
def httpdate
-
utc.httpdate
-
end
-
-
2
def rfc2822
-
to_s(:rfc822)
-
end
-
2
alias_method :rfc822, :rfc2822
-
-
# <tt>:db</tt> format outputs time in UTC; all others output time in local.
-
# Uses TimeWithZone's +strftime+, so <tt>%Z</tt> and <tt>%z</tt> work correctly.
-
2
def to_s(format = :default)
-
68
if format == :db
-
56
utc.to_s(format)
-
12
elsif formatter = ::Time::DATE_FORMATS[format]
-
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
12
"#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format
-
end
-
end
-
2
alias_method :to_formatted_s, :to_s
-
-
# Replaces <tt>%Z</tt> and <tt>%z</tt> directives with +zone+ and +formatted_offset+, respectively, before passing to
-
# Time#strftime, so that zone information is correct
-
2
def strftime(format)
-
1
format = format.gsub('%Z', zone).
-
gsub('%z', formatted_offset(false)).
-
gsub('%:z', formatted_offset(true)).
-
gsub('%::z', formatted_offset(true) + ":00")
-
-
1
time.strftime(format)
-
end
-
-
# Use the time in UTC for comparisons.
-
2
def <=>(other)
-
1073
utc <=> other
-
end
-
-
2
def between?(min, max)
-
utc.between?(min, max)
-
end
-
-
2
def past?
-
utc.past?
-
end
-
-
2
def today?
-
time.today?
-
end
-
-
2
def future?
-
utc.future?
-
end
-
-
2
def eql?(other)
-
utc.eql?(other)
-
end
-
-
2
def hash
-
204
utc.hash
-
end
-
-
2
def +(other)
-
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
-
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
-
1042
if duration_of_variable_length?(other)
-
481
method_missing(:+, other)
-
else
-
561
result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other)
-
561
result.in_time_zone(time_zone)
-
end
-
end
-
-
2
def -(other)
-
# If we're subtracting a Duration of variable length (i.e., years, months, days), move backwards from #time,
-
# otherwise move backwards #utc, for accuracy when moving across DST boundaries
-
260
if other.acts_like?(:time)
-
192
utc.to_f - other.to_f
-
68
elsif duration_of_variable_length?(other)
-
3
method_missing(:-, other)
-
else
-
65
result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other)
-
65
result.in_time_zone(time_zone)
-
end
-
end
-
-
2
def since(other)
-
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
-
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
-
if duration_of_variable_length?(other)
-
method_missing(:since, other)
-
else
-
utc.since(other).in_time_zone(time_zone)
-
end
-
end
-
-
2
def ago(other)
-
since(-other)
-
end
-
-
2
def advance(options)
-
# If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time,
-
# otherwise advance from #utc, for accuracy when moving across DST boundaries
-
if options.values_at(:years, :weeks, :months, :days).any?
-
method_missing(:advance, options)
-
else
-
utc.advance(options).in_time_zone(time_zone)
-
end
-
end
-
-
2
%w(year mon month day mday wday yday hour min sec to_date).each do |method_name|
-
22
class_eval <<-EOV, __FILE__, __LINE__ + 1
-
def #{method_name} # def month
-
time.#{method_name} # time.month
-
end # end
-
EOV
-
end
-
-
2
def usec
-
2079
time.respond_to?(:usec) ? time.usec : 0
-
end
-
-
2
def to_a
-
[time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
-
end
-
-
2
def to_f
-
192
utc.to_f
-
end
-
-
2
def to_i
-
utc.to_i
-
end
-
2
alias_method :tv_sec, :to_i
-
-
# A TimeWithZone acts like a Time, so just return +self+.
-
2
def to_time
-
666
utc
-
end
-
-
2
def to_datetime
-
utc.to_datetime.new_offset(Rational(utc_offset, 86_400))
-
end
-
-
# So that +self+ <tt>acts_like?(:time)</tt>.
-
2
def acts_like_time?
-
true
-
end
-
-
# Say we're a Time to thwart type checking.
-
2
def is_a?(klass)
-
6075
klass == ::Time || super
-
end
-
2
alias_method :kind_of?, :is_a?
-
-
2
def freeze
-
period; utc; time # preload instance variables before freezing
-
super
-
end
-
-
2
def marshal_dump
-
[utc, time_zone.name, time]
-
end
-
-
2
def marshal_load(variables)
-
initialize(variables[0].utc, ::Time.find_zone(variables[1]), variables[2].utc)
-
end
-
-
# Ensure proxy class responds to all methods that underlying time instance responds to.
-
2
def respond_to?(sym, include_priv = false)
-
# consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime
-
12009
return false if sym.to_s == 'acts_like_date?'
-
12009
super || time.respond_to?(sym, include_priv)
-
end
-
-
# Send the missing method to +time+ instance, and wrap result in a new TimeWithZone with the existing +time_zone+.
-
2
def method_missing(sym, *args, &block)
-
491
wrap_with_time_zone time.__send__(sym, *args, &block)
-
end
-
-
2
private
-
2
def get_period_and_ensure_valid_local_time
-
# we don't want a Time.local instance enforcing its own DST rules as well,
-
# so transfer time values to a utc constructor if necessary
-
1122
@time = transfer_time_values_to_utc_constructor(@time) unless @time.utc?
-
1122
begin
-
1122
@time_zone.period_for_local(@time)
-
rescue ::TZInfo::PeriodNotFound
-
# time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again
-
@time += 1.hour
-
retry
-
end
-
end
-
-
2
def transfer_time_values_to_utc_constructor(time)
-
usec = time.respond_to?(:nsec) ? Rational(time.nsec, 1000) : (time.respond_to?(:usec) ? time.usec : 0)
-
::Time.utc_time(time.year, time.month, time.day, time.hour, time.min, time.sec, usec)
-
end
-
-
2
def duration_of_variable_length?(obj)
-
2220
ActiveSupport::Duration === obj && obj.parts.any? {|p| p[0].in?([:years, :months, :days]) }
-
end
-
-
2
def wrap_with_time_zone(time)
-
491
if time.acts_like?(:time)
-
491
self.class.new(nil, time_zone, time)
-
elsif time.is_a?(Range)
-
wrap_with_time_zone(time.begin)..wrap_with_time_zone(time.end)
-
else
-
time
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'active_support/core_ext/object/try'
-
-
# The TimeZone class serves as a wrapper around TZInfo::Timezone instances. It allows us to do the following:
-
#
-
# * Limit the set of zones provided by TZInfo to a meaningful subset of 142 zones.
-
# * Retrieve and display zones with a friendlier name (e.g., "Eastern Time (US & Canada)" instead of "America/New_York").
-
# * Lazily load TZInfo::Timezone instances only when they're needed.
-
# * Create ActiveSupport::TimeWithZone instances via TimeZone's +local+, +parse+, +at+ and +now+ methods.
-
#
-
# If you set <tt>config.time_zone</tt> in the Rails Application, you can access this TimeZone object via <tt>Time.zone</tt>:
-
#
-
# # application.rb:
-
# class Application < Rails::Application
-
# config.time_zone = "Eastern Time (US & Canada)"
-
# end
-
#
-
# Time.zone # => #<TimeZone:0x514834...>
-
# Time.zone.name # => "Eastern Time (US & Canada)"
-
# Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00
-
#
-
# The version of TZInfo bundled with Active Support only includes the definitions necessary to support the zones
-
# defined by the TimeZone class. If you need to use zones that aren't defined by TimeZone, you'll need to install the TZInfo gem
-
# (if a recent version of the gem is installed locally, this will be used instead of the bundled version.)
-
2
module ActiveSupport
-
2
class TimeZone
-
# Keys are Rails TimeZone names, values are TZInfo identifiers
-
2
MAPPING = {
-
"International Date Line West" => "Pacific/Midway",
-
"Midway Island" => "Pacific/Midway",
-
"American Samoa" => "Pacific/Pago_Pago",
-
"Hawaii" => "Pacific/Honolulu",
-
"Alaska" => "America/Juneau",
-
"Pacific Time (US & Canada)" => "America/Los_Angeles",
-
"Tijuana" => "America/Tijuana",
-
"Mountain Time (US & Canada)" => "America/Denver",
-
"Arizona" => "America/Phoenix",
-
"Chihuahua" => "America/Chihuahua",
-
"Mazatlan" => "America/Mazatlan",
-
"Central Time (US & Canada)" => "America/Chicago",
-
"Saskatchewan" => "America/Regina",
-
"Guadalajara" => "America/Mexico_City",
-
"Mexico City" => "America/Mexico_City",
-
"Monterrey" => "America/Monterrey",
-
"Central America" => "America/Guatemala",
-
"Eastern Time (US & Canada)" => "America/New_York",
-
"Indiana (East)" => "America/Indiana/Indianapolis",
-
"Bogota" => "America/Bogota",
-
"Lima" => "America/Lima",
-
"Quito" => "America/Lima",
-
"Atlantic Time (Canada)" => "America/Halifax",
-
"Caracas" => "America/Caracas",
-
"La Paz" => "America/La_Paz",
-
"Santiago" => "America/Santiago",
-
"Newfoundland" => "America/St_Johns",
-
"Brasilia" => "America/Sao_Paulo",
-
"Buenos Aires" => "America/Argentina/Buenos_Aires",
-
"Georgetown" => "America/Guyana",
-
"Greenland" => "America/Godthab",
-
"Mid-Atlantic" => "Atlantic/South_Georgia",
-
"Azores" => "Atlantic/Azores",
-
"Cape Verde Is." => "Atlantic/Cape_Verde",
-
"Dublin" => "Europe/Dublin",
-
"Edinburgh" => "Europe/London",
-
"Lisbon" => "Europe/Lisbon",
-
"London" => "Europe/London",
-
"Casablanca" => "Africa/Casablanca",
-
"Monrovia" => "Africa/Monrovia",
-
"UTC" => "Etc/UTC",
-
"Belgrade" => "Europe/Belgrade",
-
"Bratislava" => "Europe/Bratislava",
-
"Budapest" => "Europe/Budapest",
-
"Ljubljana" => "Europe/Ljubljana",
-
"Prague" => "Europe/Prague",
-
"Sarajevo" => "Europe/Sarajevo",
-
"Skopje" => "Europe/Skopje",
-
"Warsaw" => "Europe/Warsaw",
-
"Zagreb" => "Europe/Zagreb",
-
"Brussels" => "Europe/Brussels",
-
"Copenhagen" => "Europe/Copenhagen",
-
"Madrid" => "Europe/Madrid",
-
"Paris" => "Europe/Paris",
-
"Amsterdam" => "Europe/Amsterdam",
-
"Berlin" => "Europe/Berlin",
-
"Bern" => "Europe/Berlin",
-
"Rome" => "Europe/Rome",
-
"Stockholm" => "Europe/Stockholm",
-
"Vienna" => "Europe/Vienna",
-
"West Central Africa" => "Africa/Algiers",
-
"Bucharest" => "Europe/Bucharest",
-
"Cairo" => "Africa/Cairo",
-
"Helsinki" => "Europe/Helsinki",
-
"Kyiv" => "Europe/Kiev",
-
"Riga" => "Europe/Riga",
-
"Sofia" => "Europe/Sofia",
-
"Tallinn" => "Europe/Tallinn",
-
"Vilnius" => "Europe/Vilnius",
-
"Athens" => "Europe/Athens",
-
"Istanbul" => "Europe/Istanbul",
-
"Minsk" => "Europe/Minsk",
-
"Jerusalem" => "Asia/Jerusalem",
-
"Harare" => "Africa/Harare",
-
"Pretoria" => "Africa/Johannesburg",
-
"Moscow" => "Europe/Moscow",
-
"St. Petersburg" => "Europe/Moscow",
-
"Volgograd" => "Europe/Moscow",
-
"Kuwait" => "Asia/Kuwait",
-
"Riyadh" => "Asia/Riyadh",
-
"Nairobi" => "Africa/Nairobi",
-
"Baghdad" => "Asia/Baghdad",
-
"Tehran" => "Asia/Tehran",
-
"Abu Dhabi" => "Asia/Muscat",
-
"Muscat" => "Asia/Muscat",
-
"Baku" => "Asia/Baku",
-
"Tbilisi" => "Asia/Tbilisi",
-
"Yerevan" => "Asia/Yerevan",
-
"Kabul" => "Asia/Kabul",
-
"Ekaterinburg" => "Asia/Yekaterinburg",
-
"Islamabad" => "Asia/Karachi",
-
"Karachi" => "Asia/Karachi",
-
"Tashkent" => "Asia/Tashkent",
-
"Chennai" => "Asia/Kolkata",
-
"Kolkata" => "Asia/Kolkata",
-
"Mumbai" => "Asia/Kolkata",
-
"New Delhi" => "Asia/Kolkata",
-
"Kathmandu" => "Asia/Kathmandu",
-
"Astana" => "Asia/Dhaka",
-
"Dhaka" => "Asia/Dhaka",
-
"Sri Jayawardenepura" => "Asia/Colombo",
-
"Almaty" => "Asia/Almaty",
-
"Novosibirsk" => "Asia/Novosibirsk",
-
"Rangoon" => "Asia/Rangoon",
-
"Bangkok" => "Asia/Bangkok",
-
"Hanoi" => "Asia/Bangkok",
-
"Jakarta" => "Asia/Jakarta",
-
"Krasnoyarsk" => "Asia/Krasnoyarsk",
-
"Beijing" => "Asia/Shanghai",
-
"Chongqing" => "Asia/Chongqing",
-
"Hong Kong" => "Asia/Hong_Kong",
-
"Urumqi" => "Asia/Urumqi",
-
"Kuala Lumpur" => "Asia/Kuala_Lumpur",
-
"Singapore" => "Asia/Singapore",
-
"Taipei" => "Asia/Taipei",
-
"Perth" => "Australia/Perth",
-
"Irkutsk" => "Asia/Irkutsk",
-
"Ulaan Bataar" => "Asia/Ulaanbaatar",
-
"Seoul" => "Asia/Seoul",
-
"Osaka" => "Asia/Tokyo",
-
"Sapporo" => "Asia/Tokyo",
-
"Tokyo" => "Asia/Tokyo",
-
"Yakutsk" => "Asia/Yakutsk",
-
"Darwin" => "Australia/Darwin",
-
"Adelaide" => "Australia/Adelaide",
-
"Canberra" => "Australia/Melbourne",
-
"Melbourne" => "Australia/Melbourne",
-
"Sydney" => "Australia/Sydney",
-
"Brisbane" => "Australia/Brisbane",
-
"Hobart" => "Australia/Hobart",
-
"Vladivostok" => "Asia/Vladivostok",
-
"Guam" => "Pacific/Guam",
-
"Port Moresby" => "Pacific/Port_Moresby",
-
"Magadan" => "Asia/Magadan",
-
"Solomon Is." => "Asia/Magadan",
-
"New Caledonia" => "Pacific/Noumea",
-
"Fiji" => "Pacific/Fiji",
-
"Kamchatka" => "Asia/Kamchatka",
-
"Marshall Is." => "Pacific/Majuro",
-
"Auckland" => "Pacific/Auckland",
-
"Wellington" => "Pacific/Auckland",
-
"Nuku'alofa" => "Pacific/Tongatapu",
-
"Tokelau Is." => "Pacific/Fakaofo",
-
"Samoa" => "Pacific/Apia"
-
288
}.each { |name, zone| name.freeze; zone.freeze }
-
2
MAPPING.freeze
-
-
2
UTC_OFFSET_WITH_COLON = '%s%02d:%02d'
-
2
UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.sub(':', '')
-
-
# Assumes self represents an offset from UTC in seconds (as returned from Time#utc_offset)
-
# and turns this into an +HH:MM formatted string. Example:
-
#
-
# TimeZone.seconds_to_utc_offset(-21_600) # => "-06:00"
-
2
def self.seconds_to_utc_offset(seconds, colon = true)
-
1231
format = colon ? UTC_OFFSET_WITH_COLON : UTC_OFFSET_WITHOUT_COLON
-
1231
sign = (seconds < 0 ? '-' : '+')
-
1231
hours = seconds.abs / 3600
-
1231
minutes = (seconds.abs % 3600) / 60
-
1231
format % [sign, hours, minutes]
-
end
-
-
2
include Comparable
-
2
attr_reader :name
-
2
attr_reader :tzinfo
-
-
# Create a new TimeZone object with the given name and offset. The
-
# offset is the number of seconds that this time zone is offset from UTC
-
# (GMT). Seconds were chosen as the offset unit because that is the unit that
-
# Ruby uses to represent time zone offsets (see Time#utc_offset).
-
2
def initialize(name, utc_offset = nil, tzinfo = nil)
-
2
self.class.send(:require_tzinfo)
-
-
2
@name = name
-
2
@utc_offset = utc_offset
-
2
@tzinfo = tzinfo || TimeZone.find_tzinfo(name)
-
2
@current_period = nil
-
end
-
-
2
def utc_offset
-
if @utc_offset
-
@utc_offset
-
else
-
@current_period ||= tzinfo.try(:current_period)
-
@current_period.try(:utc_offset)
-
end
-
end
-
-
# Returns the offset of this time zone as a formatted string, of the
-
# format "+HH:MM".
-
2
def formatted_offset(colon=true, alternate_utc_string = nil)
-
utc_offset == 0 && alternate_utc_string || self.class.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Compare this time zone to the parameter. The two are compared first on
-
# their offsets, and then by name.
-
2
def <=>(zone)
-
result = (utc_offset <=> zone.utc_offset)
-
result = (name <=> zone.name) if result == 0
-
result
-
end
-
-
# Compare #name and TZInfo identifier to a supplied regexp, returning true
-
# if a match is found.
-
2
def =~(re)
-
return true if name =~ re || MAPPING[name] =~ re
-
end
-
-
# Returns a textual representation of this time zone.
-
2
def to_s
-
"(GMT#{formatted_offset}) #{name}"
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from given values. Example:
-
#
-
# Time.zone = "Hawaii" # => "Hawaii"
-
# Time.zone.local(2007, 2, 1, 15, 30, 45) # => Thu, 01 Feb 2007 15:30:45 HST -10:00
-
2
def local(*args)
-
547
time = Time.utc_time(*args)
-
547
ActiveSupport::TimeWithZone.new(nil, self, time)
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from number of seconds since the Unix epoch. Example:
-
#
-
# Time.zone = "Hawaii" # => "Hawaii"
-
# Time.utc(2000).to_f # => 946684800.0
-
# Time.zone.at(946684800.0) # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
2
def at(secs)
-
128
utc = Time.at(secs).utc rescue DateTime.civil(1970).since(secs)
-
128
utc.in_time_zone(self)
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from parsed string. Example:
-
#
-
# Time.zone = "Hawaii" # => "Hawaii"
-
# Time.zone.parse('1999-12-31 14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
#
-
# If upper components are missing from the string, they are supplied from TimeZone#now:
-
#
-
# Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
# Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
-
2
def parse(str, now=now)
-
84
parts = Date._parse(str, false)
-
84
return if parts.empty?
-
-
84
time = Time.utc(
-
parts.fetch(:year, now.year),
-
parts.fetch(:mon, now.month),
-
parts.fetch(:mday, now.day),
-
parts.fetch(:hour, 0),
-
parts.fetch(:min, 0),
-
parts.fetch(:sec, 0),
-
parts.fetch(:sec_fraction, 0) * 1000000
-
)
-
-
84
if parts[:offset]
-
TimeWithZone.new(time - parts[:offset], self)
-
else
-
84
TimeWithZone.new(nil, self, time)
-
end
-
end
-
-
# Returns an ActiveSupport::TimeWithZone instance representing the current time
-
# in the time zone represented by +self+. Example:
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.now # => Wed, 23 Jan 2008 20:24:27 HST -10:00
-
2
def now
-
155
Time.now.utc.in_time_zone(self)
-
end
-
-
# Return the current date in this time zone.
-
2
def today
-
191
tzinfo.now.to_date
-
end
-
-
# Adjust the given time to the simultaneous time in the time zone represented by +self+. Returns a
-
# Time.utc() instance -- if you want an ActiveSupport::TimeWithZone instance, use Time#in_time_zone() instead.
-
2
def utc_to_local(time)
-
tzinfo.utc_to_local(time)
-
end
-
-
# Adjust the given time to the simultaneous time in UTC. Returns a Time.utc() instance.
-
2
def local_to_utc(time, dst=true)
-
tzinfo.local_to_utc(time, dst)
-
end
-
-
# Available so that TimeZone instances respond like TZInfo::Timezone instances
-
2
def period_for_utc(time)
-
1281
tzinfo.period_for_utc(time)
-
end
-
-
# Available so that TimeZone instances respond like TZInfo::Timezone instances
-
2
def period_for_local(time, dst=true)
-
1122
tzinfo.period_for_local(time, dst)
-
end
-
-
2
def self.find_tzinfo(name)
-
2
TZInfo::TimezoneProxy.new(MAPPING[name] || name)
-
end
-
-
2
class << self
-
2
alias_method :create, :new
-
-
# Return a TimeZone instance with the given name, or +nil+ if no
-
# such TimeZone instance exists. (This exists to support the use of
-
# this class with the +composed_of+ macro.)
-
2
def new(name)
-
self[name]
-
end
-
-
# Return an array of all TimeZone objects. There are multiple
-
# TimeZone objects per time zone, in many cases, to make it easier
-
# for users to find their own time zone.
-
2
def all
-
@zones ||= zones_map.values.sort
-
end
-
-
2
def zones_map
-
@zones_map ||= begin
-
new_zones_names = MAPPING.keys - lazy_zones_map.keys
-
new_zones = Hash[new_zones_names.map { |place| [place, create(place)] }]
-
-
lazy_zones_map.merge(new_zones)
-
end
-
end
-
-
# Locate a specific time zone object. If the argument is a string, it
-
# is interpreted to mean the name of the timezone to locate. If it is a
-
# numeric value it is either the hour offset, or the second offset, of the
-
# timezone to find. (The first one with that offset will be returned.)
-
# Returns +nil+ if no such time zone is known to the system.
-
2
def [](arg)
-
2
case arg
-
when String
-
2
begin
-
2
lazy_zones_map[arg] ||= lookup(arg).tap { |tz| tz.utc_offset }
-
rescue TZInfo::InvalidTimezoneIdentifier
-
nil
-
end
-
when Numeric, ActiveSupport::Duration
-
arg *= 3600 if arg.abs <= 13
-
all.find { |z| z.utc_offset == arg.to_i }
-
else
-
raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}"
-
end
-
end
-
-
# A convenience method for returning a collection of TimeZone objects
-
# for time zones in the USA.
-
2
def us_zones
-
@us_zones ||= all.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ }
-
end
-
-
2
protected
-
-
2
def require_tzinfo
-
4
require 'tzinfo' unless defined?(::TZInfo)
-
rescue LoadError
-
$stderr.puts "You don't have tzinfo installed in your application. Please add it to your Gemfile and run bundle install"
-
raise
-
end
-
-
2
private
-
-
2
def lookup(name)
-
(tzinfo = find_tzinfo(name)) && create(tzinfo.name.freeze)
-
end
-
-
2
def lazy_zones_map
-
2
require_tzinfo
-
-
@lazy_zones_map ||= Hash.new do |hash, place|
-
2
hash[place] = create(place) if MAPPING.has_key?(place)
-
2
end
-
end
-
end
-
end
-
end
-
2
module ActiveSupport
-
2
module VERSION #:nodoc:
-
2
MAJOR = 3
-
2
MINOR = 2
-
2
TINY = 16
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
-
end
-
end
-
2
require 'active_support/deprecation'
-
-
# Extensions to +nil+ which allow for more helpful error messages for people who
-
# are new to Rails.
-
#
-
# NilClass#id exists in Ruby 1.8 (though it is deprecated). Since +id+ is a fundamental
-
# method of Active Record models NilClass#id is redefined as well to raise a RuntimeError
-
# and warn the user. She probably wanted a model database identifier and the 4
-
# returned by the original method could result in obscure bugs.
-
#
-
# The flag <tt>config.whiny_nils</tt> determines whether this feature is enabled.
-
# By default it is on in development and test modes, and it is off in production
-
# mode.
-
2
class NilClass
-
2
def self.add_whiner(klass)
-
ActiveSupport::Deprecation.warn "NilClass.add_whiner is deprecated and this functionality is " \
-
"removed from Rails versions as it affects Ruby 1.9 performance.", caller
-
end
-
-
# Raises a RuntimeError when you attempt to call +id+ on +nil+.
-
2
def id
-
raise RuntimeError, "Called id for nil, which would mistakenly be #{object_id} -- if you really wanted the id of nil, use object_id", caller
-
end
-
end
-
2
require 'time'
-
2
require 'active_support/base64'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'active_support/core_ext/string/inflections'
-
-
2
module ActiveSupport
-
# = XmlMini
-
#
-
# To use the much faster libxml parser:
-
# gem 'libxml-ruby', '=0.9.7'
-
# XmlMini.backend = 'LibXML'
-
2
module XmlMini
-
2
extend self
-
-
# This module decorates files deserialized using Hash.from_xml with
-
# the <tt>original_filename</tt> and <tt>content_type</tt> methods.
-
2
module FileLike #:nodoc:
-
2
attr_writer :original_filename, :content_type
-
-
2
def original_filename
-
@original_filename || 'untitled'
-
end
-
-
2
def content_type
-
@content_type || 'application/octet-stream'
-
end
-
end
-
-
DEFAULT_ENCODINGS = {
-
"binary" => "base64"
-
2
} unless defined?(DEFAULT_ENCODINGS)
-
-
TYPE_NAMES = {
-
"Symbol" => "symbol",
-
"Fixnum" => "integer",
-
"Bignum" => "integer",
-
"BigDecimal" => "decimal",
-
"Float" => "float",
-
"TrueClass" => "boolean",
-
"FalseClass" => "boolean",
-
"Date" => "date",
-
"DateTime" => "datetime",
-
"Time" => "datetime",
-
"Array" => "array",
-
"Hash" => "hash"
-
2
} unless defined?(TYPE_NAMES)
-
-
FORMATTING = {
-
"symbol" => Proc.new { |symbol| symbol.to_s },
-
"date" => Proc.new { |date| date.to_s(:db) },
-
"datetime" => Proc.new { |time| time.xmlschema },
-
"binary" => Proc.new { |binary| ::Base64.encode64(binary) },
-
"yaml" => Proc.new { |yaml| yaml.to_yaml }
-
2
} unless defined?(FORMATTING)
-
-
# TODO use regexp instead of Date.parse
-
2
unless defined?(PARSING)
-
2
PARSING = {
-
"symbol" => Proc.new { |symbol| symbol.to_sym },
-
"date" => Proc.new { |date| ::Date.parse(date) },
-
"datetime" => Proc.new { |time| Time.xmlschema(time).utc rescue ::DateTime.parse(time).utc },
-
"integer" => Proc.new { |integer| integer.to_i },
-
"float" => Proc.new { |float| float.to_f },
-
"decimal" => Proc.new { |number| BigDecimal(number) },
-
"boolean" => Proc.new { |boolean| %w(1 true).include?(boolean.strip) },
-
"string" => Proc.new { |string| string.to_s },
-
"yaml" => Proc.new { |yaml| YAML::load(yaml) rescue yaml },
-
"base64Binary" => Proc.new { |bin| ::Base64.decode64(bin) },
-
"binary" => Proc.new { |bin, entity| _parse_binary(bin, entity) },
-
"file" => Proc.new { |file, entity| _parse_file(file, entity) }
-
}
-
-
2
PARSING.update(
-
"double" => PARSING["float"],
-
"dateTime" => PARSING["datetime"]
-
)
-
end
-
-
2
attr_reader :backend
-
2
delegate :parse, :to => :backend
-
-
2
def backend=(name)
-
2
if name.is_a?(Module)
-
@backend = name
-
else
-
2
require "active_support/xml_mini/#{name.to_s.downcase}"
-
2
@backend = ActiveSupport.const_get("XmlMini_#{name}")
-
end
-
end
-
-
2
def with_backend(name)
-
old_backend, self.backend = backend, name
-
yield
-
ensure
-
self.backend = old_backend
-
end
-
-
2
def to_tag(key, value, options)
-
type_name = options.delete(:type)
-
merged_options = options.merge(:root => key, :skip_instruct => true)
-
-
if value.is_a?(::Method) || value.is_a?(::Proc)
-
if value.arity == 1
-
value.call(merged_options)
-
else
-
value.call(merged_options, key.to_s.singularize)
-
end
-
elsif value.respond_to?(:to_xml)
-
value.to_xml(merged_options)
-
else
-
type_name ||= TYPE_NAMES[value.class.name]
-
type_name ||= value.class.name if value && !value.respond_to?(:to_str)
-
type_name = type_name.to_s if type_name
-
-
key = rename_key(key.to_s, options)
-
-
attributes = options[:skip_types] || type_name.nil? ? { } : { :type => type_name }
-
attributes[:nil] = true if value.nil?
-
-
encoding = options[:encoding] || DEFAULT_ENCODINGS[type_name]
-
attributes[:encoding] = encoding if encoding
-
-
formatted_value = FORMATTING[type_name] && !value.nil? ?
-
FORMATTING[type_name].call(value) : value
-
-
options[:builder].tag!(key, formatted_value, attributes)
-
end
-
end
-
-
2
def rename_key(key, options = {})
-
camelize = options[:camelize]
-
dasherize = !options.has_key?(:dasherize) || options[:dasherize]
-
if camelize
-
key = true == camelize ? key.camelize : key.camelize(camelize)
-
end
-
key = _dasherize(key) if dasherize
-
key
-
end
-
-
2
protected
-
-
2
def _dasherize(key)
-
# $2 must be a non-greedy regex for this to work
-
left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1,3]
-
"#{left}#{middle.tr('_ ', '--')}#{right}"
-
end
-
-
# TODO: Add support for other encodings
-
2
def _parse_binary(bin, entity) #:nodoc:
-
case entity['encoding']
-
when 'base64'
-
::Base64.decode64(bin)
-
else
-
bin
-
end
-
end
-
-
2
def _parse_file(file, entity)
-
f = StringIO.new(::Base64.decode64(file))
-
f.extend(FileLike)
-
f.original_filename = entity['name']
-
f.content_type = entity['content_type']
-
f
-
end
-
end
-
-
2
XmlMini.backend = 'REXML'
-
end
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'active_support/core_ext/object/blank'
-
2
require 'stringio'
-
-
# = XmlMini ReXML implementation
-
2
module ActiveSupport
-
2
module XmlMini_REXML #:nodoc:
-
2
extend self
-
-
2
CONTENT_KEY = '__content__'.freeze
-
-
# Parse an XML Document string or IO into a simple hash
-
#
-
# Same as XmlSimple::xml_in but doesn't shoot itself in the foot,
-
# and uses the defaults from Active Support.
-
#
-
# data::
-
# XML Document string or IO to parse
-
2
def parse(data)
-
if !data.respond_to?(:read)
-
data = StringIO.new(data || '')
-
end
-
-
char = data.getc
-
if char.nil?
-
{}
-
else
-
data.ungetc(char)
-
silence_warnings { require 'rexml/document' } unless defined?(REXML::Document)
-
doc = REXML::Document.new(data)
-
-
if doc.root
-
merge_element!({}, doc.root)
-
else
-
raise REXML::ParseException,
-
"The document #{doc.to_s.inspect} does not have a valid root"
-
end
-
end
-
end
-
-
2
private
-
# Convert an XML element and merge into the hash
-
#
-
# hash::
-
# Hash to merge the converted element into.
-
# element::
-
# XML element to merge into hash
-
2
def merge_element!(hash, element)
-
merge!(hash, element.name, collapse(element))
-
end
-
-
# Actually converts an XML document element into a data structure.
-
#
-
# element::
-
# The document element to be collapsed.
-
2
def collapse(element)
-
hash = get_attributes(element)
-
-
if element.has_elements?
-
element.each_element {|child| merge_element!(hash, child) }
-
merge_texts!(hash, element) unless empty_content?(element)
-
hash
-
else
-
merge_texts!(hash, element)
-
end
-
end
-
-
# Merge all the texts of an element into the hash
-
#
-
# hash::
-
# Hash to add the converted element to.
-
# element::
-
# XML element whose texts are to me merged into the hash
-
2
def merge_texts!(hash, element)
-
unless element.has_text?
-
hash
-
else
-
# must use value to prevent double-escaping
-
texts = ''
-
element.texts.each { |t| texts << t.value }
-
merge!(hash, CONTENT_KEY, texts)
-
end
-
end
-
-
# Adds a new key/value pair to an existing Hash. If the key to be added
-
# already exists and the existing value associated with key is not
-
# an Array, it will be wrapped in an Array. Then the new value is
-
# appended to that Array.
-
#
-
# hash::
-
# Hash to add key/value pair to.
-
# key::
-
# Key to be added.
-
# value::
-
# Value to be associated with key.
-
2
def merge!(hash, key, value)
-
if hash.has_key?(key)
-
if hash[key].instance_of?(Array)
-
hash[key] << value
-
else
-
hash[key] = [hash[key], value]
-
end
-
elsif value.instance_of?(Array)
-
hash[key] = [value]
-
else
-
hash[key] = value
-
end
-
hash
-
end
-
-
# Converts the attributes array of an XML element into a hash.
-
# Returns an empty Hash if node has no attributes.
-
#
-
# element::
-
# XML element to extract attributes from.
-
2
def get_attributes(element)
-
attributes = {}
-
element.attributes.each { |n,v| attributes[n] = v }
-
attributes
-
end
-
-
# Determines if a document element has text content
-
#
-
# element::
-
# XML element to be checked.
-
2
def empty_content?(element)
-
element.texts.join.blank?
-
end
-
end
-
end
-
2
require 'arel/crud'
-
2
require 'arel/factory_methods'
-
-
2
require 'arel/expressions'
-
2
require 'arel/predications'
-
2
require 'arel/window_predications'
-
2
require 'arel/math'
-
2
require 'arel/alias_predication'
-
2
require 'arel/order_predications'
-
2
require 'arel/table'
-
2
require 'arel/attributes'
-
2
require 'arel/compatibility/wheres'
-
-
#### these are deprecated
-
# The Arel::Relation constant is referenced in Rails
-
2
require 'arel/relation'
-
2
require 'arel/expression'
-
####
-
-
2
require 'arel/visitors'
-
-
2
require 'arel/tree_manager'
-
2
require 'arel/insert_manager'
-
2
require 'arel/select_manager'
-
2
require 'arel/update_manager'
-
2
require 'arel/delete_manager'
-
2
require 'arel/nodes'
-
-
-
#### these are deprecated
-
2
require 'arel/deprecated'
-
2
require 'arel/sql/engine'
-
2
require 'arel/sql_literal'
-
####
-
-
2
module Arel
-
2
VERSION = '3.0.3'
-
-
2
def self.sql raw_sql
-
1807
Arel::Nodes::SqlLiteral.new raw_sql
-
end
-
-
2
def self.star
-
1274
sql '*'
-
end
-
## Convenience Alias
-
2
Node = Arel::Nodes::Node
-
end
-
2
module Arel
-
2
module AliasPredication
-
2
def as other
-
Nodes::As.new self, Nodes::SqlLiteral.new(other)
-
end
-
end
-
end
-
2
require 'arel/attributes/attribute'
-
-
2
module Arel
-
2
module Attributes
-
###
-
# Factory method to wrap a raw database +column+ to an Arel Attribute.
-
2
def self.for column
-
case column.type
-
when :string, :text, :binary then String
-
when :integer then Integer
-
when :float then Float
-
when :decimal then Decimal
-
when :date, :datetime, :timestamp, :time then Time
-
when :boolean then Boolean
-
else
-
Undefined
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Attributes
-
2
class Attribute < Struct.new :relation, :name
-
2
include Arel::Expressions
-
2
include Arel::Predications
-
2
include Arel::AliasPredication
-
2
include Arel::OrderPredications
-
2
include Arel::Math
-
-
###
-
# Create a node for lowering this attribute
-
2
def lower
-
relation.lower self
-
end
-
end
-
-
2
class String < Attribute; end
-
2
class Time < Attribute; end
-
2
class Boolean < Attribute; end
-
2
class Decimal < Attribute; end
-
2
class Float < Attribute; end
-
2
class Integer < Attribute; end
-
2
class Undefined < Attribute; end
-
end
-
-
2
Attribute = Attributes::Attribute
-
end
-
2
module Arel
-
2
module Compatibility # :nodoc:
-
2
class Wheres # :nodoc:
-
2
include Enumerable
-
-
2
module Value # :nodoc:
-
2
attr_accessor :visitor
-
2
def value
-
visitor.accept self
-
end
-
-
2
def name
-
super.to_sym
-
end
-
end
-
-
2
def initialize engine, collection
-
@engine = engine
-
@collection = collection
-
end
-
-
2
def each
-
to_sql = Visitors::ToSql.new @engine
-
-
@collection.each { |c|
-
c.extend(Value)
-
c.visitor = to_sql
-
yield c
-
}
-
end
-
end
-
end
-
end
-
2
module Arel
-
###
-
# FIXME hopefully we can remove this
-
2
module Crud
-
2
def compile_update values
-
54
um = UpdateManager.new @engine
-
-
54
if Nodes::SqlLiteral === values
-
relation = @ctx.from
-
else
-
54
relation = values.first.first.relation
-
end
-
54
um.table relation
-
54
um.set values
-
54
um.take @ast.limit.expr if @ast.limit
-
54
um.order(*@ast.orders)
-
54
um.wheres = @ctx.wheres
-
54
um
-
end
-
-
# FIXME: this method should go away
-
2
def update values
-
if $VERBOSE
-
warn <<-eowarn
-
update (#{caller.first}) is deprecated and will be removed in ARel 4.0.0. Please
-
switch to `compile_update`
-
eowarn
-
end
-
-
um = compile_update values
-
@engine.connection.update um.to_sql, 'AREL'
-
end
-
-
2
def compile_insert values
-
im = create_insert
-
im.insert values
-
im
-
end
-
-
2
def create_insert
-
308
InsertManager.new @engine
-
end
-
-
# FIXME: this method should go away
-
2
def insert values
-
if $VERBOSE
-
warn <<-eowarn
-
insert (#{caller.first}) is deprecated and will be removed in ARel 4.0.0. Please
-
switch to `compile_insert`
-
eowarn
-
end
-
@engine.connection.insert compile_insert(values).to_sql
-
end
-
-
2
def compile_delete
-
24
dm = DeleteManager.new @engine
-
24
dm.wheres = @ctx.wheres
-
24
dm.from @ctx.froms
-
24
dm
-
end
-
-
2
def delete
-
if $VERBOSE
-
warn <<-eowarn
-
delete (#{caller.first}) is deprecated and will be removed in ARel 4.0.0. Please
-
switch to `compile_delete`
-
eowarn
-
end
-
@engine.connection.delete compile_delete.to_sql, 'AREL'
-
end
-
end
-
end
-
2
module Arel
-
2
class DeleteManager < Arel::TreeManager
-
2
def initialize engine
-
24
super
-
24
@ast = Nodes::DeleteStatement.new
-
24
@ctx = @ast
-
end
-
-
2
def from relation
-
24
@ast.relation = relation
-
24
self
-
end
-
-
2
def wheres= list
-
24
@ast.wheres = list
-
end
-
end
-
end
-
2
module Arel
-
2
InnerJoin = Nodes::InnerJoin
-
2
OuterJoin = Nodes::OuterJoin
-
end
-
2
module Arel
-
2
module Expression
-
2
include Arel::OrderPredications
-
end
-
end
-
2
module Arel
-
2
module Expressions
-
2
def count distinct = false
-
28
Nodes::Count.new [self], distinct
-
end
-
-
2
def sum
-
Nodes::Sum.new [self], Nodes::SqlLiteral.new('sum_id')
-
end
-
-
2
def maximum
-
Nodes::Max.new [self], Nodes::SqlLiteral.new('max_id')
-
end
-
-
2
def minimum
-
Nodes::Min.new [self], Nodes::SqlLiteral.new('min_id')
-
end
-
-
2
def average
-
Nodes::Avg.new [self], Nodes::SqlLiteral.new('avg_id')
-
end
-
-
2
def extract field
-
Nodes::Extract.new [self], field
-
end
-
end
-
end
-
2
module Arel
-
###
-
# Methods for creating various nodes
-
2
module FactoryMethods
-
2
def create_true
-
Arel::Nodes::True.new
-
end
-
-
2
def create_false
-
Arel::Nodes::False.new
-
end
-
-
2
def create_table_alias relation, name
-
Nodes::TableAlias.new(relation, name)
-
end
-
-
2
def create_join to, constraint = nil, klass = Nodes::InnerJoin
-
klass.new(to, constraint)
-
end
-
-
2
def create_string_join to
-
create_join to, nil, Nodes::StringJoin
-
end
-
-
2
def create_and clauses
-
Nodes::And.new clauses
-
end
-
-
2
def create_on expr
-
Nodes::On.new expr
-
end
-
-
2
def grouping expr
-
Nodes::Grouping.new expr
-
end
-
-
###
-
# Create a LOWER() function
-
2
def lower column
-
Nodes::NamedFunction.new 'LOWER', [column]
-
end
-
end
-
end
-
2
module Arel
-
2
class InsertManager < Arel::TreeManager
-
2
def initialize engine
-
308
super
-
308
@ast = Nodes::InsertStatement.new
-
end
-
-
2
def into table
-
308
@ast.relation = table
-
308
self
-
end
-
-
2
def columns; @ast.columns end
-
2
def values= val; @ast.values = val; end
-
-
2
def insert fields
-
308
return if fields.empty?
-
-
308
if String === fields
-
@ast.values = SqlLiteral.new(fields)
-
else
-
308
@ast.relation ||= fields.first.first.relation
-
-
308
values = []
-
-
308
fields.each do |column, value|
-
3440
@ast.columns << column
-
3440
values << value
-
end
-
308
@ast.values = create_values values, @ast.columns
-
end
-
end
-
-
2
def create_values values, columns
-
308
Nodes::Values.new values, columns
-
end
-
end
-
end
-
2
module Arel
-
2
module Math
-
2
def *(other)
-
Arel::Nodes::Multiplication.new(self, other)
-
end
-
-
2
def +(other)
-
Arel::Nodes::Grouping.new(Arel::Nodes::Addition.new(self, other))
-
end
-
-
2
def -(other)
-
Arel::Nodes::Grouping.new(Arel::Nodes::Subtraction.new(self, other))
-
end
-
-
2
def /(other)
-
Arel::Nodes::Division.new(self, other)
-
end
-
end
-
end
-
# node
-
2
require 'arel/nodes/node'
-
2
require 'arel/nodes/select_statement'
-
2
require 'arel/nodes/select_core'
-
2
require 'arel/nodes/insert_statement'
-
2
require 'arel/nodes/update_statement'
-
-
# terminal
-
-
2
require 'arel/nodes/terminal'
-
2
require 'arel/nodes/true'
-
2
require 'arel/nodes/false'
-
-
# unary
-
2
require 'arel/nodes/unary'
-
2
require 'arel/nodes/ascending'
-
2
require 'arel/nodes/descending'
-
2
require 'arel/nodes/unqualified_column'
-
2
require 'arel/nodes/with'
-
-
# binary
-
2
require 'arel/nodes/binary'
-
2
require 'arel/nodes/equality'
-
2
require 'arel/nodes/in' # Why is this subclassed from equality?
-
2
require 'arel/nodes/join_source'
-
2
require 'arel/nodes/delete_statement'
-
2
require 'arel/nodes/table_alias'
-
2
require 'arel/nodes/infix_operation'
-
2
require 'arel/nodes/over'
-
-
# nary
-
2
require 'arel/nodes/and'
-
-
# function
-
# FIXME: Function + Alias can be rewritten as a Function and Alias node.
-
# We should make Function a Unary node and deprecate the use of "aliaz"
-
2
require 'arel/nodes/function'
-
2
require 'arel/nodes/count'
-
2
require 'arel/nodes/extract'
-
2
require 'arel/nodes/values'
-
2
require 'arel/nodes/named_function'
-
-
# windows
-
2
require 'arel/nodes/window'
-
-
# joins
-
2
require 'arel/nodes/inner_join'
-
2
require 'arel/nodes/outer_join'
-
2
require 'arel/nodes/string_join'
-
-
2
require 'arel/nodes/sql_literal'
-
2
module Arel
-
2
module Nodes
-
2
class And < Arel::Nodes::Node
-
2
attr_reader :children
-
-
2
def initialize children, right = nil
-
570
unless Array === children
-
warn "(#{caller.first}) AND nodes should be created with a list"
-
children = [children, right]
-
end
-
570
@children = children
-
end
-
-
2
def left
-
children.first
-
end
-
-
2
def right
-
children[1]
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Ascending < Ordering
-
-
2
def reverse
-
Descending.new(expr)
-
end
-
-
2
def direction
-
:asc
-
end
-
-
2
def ascending?
-
true
-
end
-
-
2
def descending?
-
false
-
end
-
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Binary < Arel::Nodes::Node
-
2
attr_accessor :left, :right
-
-
2
def initialize left, right
-
2286
@left = left
-
2286
@right = right
-
end
-
-
2
def initialize_copy other
-
super
-
@left = @left.clone if @left
-
@right = @right.clone if @right
-
end
-
end
-
-
%w{
-
As
-
2
Assignment
-
Between
-
DoesNotMatch
-
GreaterThan
-
GreaterThanOrEqual
-
Join
-
LessThan
-
LessThanOrEqual
-
Matches
-
NotEqual
-
NotIn
-
Or
-
Union
-
UnionAll
-
Intersect
-
Except
-
}.each do |name|
-
34
const_set name, Class.new(Binary)
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Count < Arel::Nodes::Function
-
2
def initialize expr, distinct = false, aliaz = nil
-
28
super(expr, aliaz)
-
28
@distinct = distinct
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class DeleteStatement < Arel::Nodes::Binary
-
2
alias :relation :left
-
2
alias :relation= :left=
-
2
alias :wheres :right
-
2
alias :wheres= :right=
-
-
2
def initialize relation = nil, wheres = []
-
24
super
-
end
-
-
2
def initialize_copy other
-
super
-
@right = @right.clone
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Descending < Ordering
-
-
2
def reverse
-
Ascending.new(expr)
-
end
-
-
2
def direction
-
:desc
-
end
-
-
2
def ascending?
-
false
-
end
-
-
2
def descending?
-
true
-
end
-
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Equality < Arel::Nodes::Binary
-
19
def operator; :== end
-
2
alias :operand1 :left
-
2
alias :operand2 :right
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
-
2
class Extract < Arel::Nodes::Unary
-
2
include Arel::Expression
-
2
include Arel::Predications
-
-
2
attr_accessor :field
-
2
attr_accessor :alias
-
-
2
def initialize expr, field, aliaz = nil
-
super(expr)
-
@field = field
-
@alias = aliaz && SqlLiteral.new(aliaz)
-
end
-
-
2
def as aliaz
-
self.alias = SqlLiteral.new(aliaz)
-
self
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class False < Arel::Nodes::Node
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Function < Arel::Nodes::Node
-
2
include Arel::Expression
-
2
include Arel::Predications
-
2
include Arel::WindowPredications
-
2
attr_accessor :expressions, :alias, :distinct
-
-
2
def initialize expr, aliaz = nil
-
28
@expressions = expr
-
28
@alias = aliaz && SqlLiteral.new(aliaz)
-
28
@distinct = false
-
end
-
-
2
def as aliaz
-
self.alias = SqlLiteral.new(aliaz)
-
self
-
end
-
end
-
-
%w{
-
Sum
-
2
Exists
-
Max
-
Min
-
Avg
-
}.each do |name|
-
10
const_set(name, Class.new(Function))
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class In < Equality
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
-
2
class InfixOperation < Binary
-
2
include Arel::Expressions
-
2
include Arel::Predications
-
2
include Arel::OrderPredications
-
2
include Arel::AliasPredication
-
2
include Arel::Math
-
-
2
attr_reader :operator
-
-
2
def initialize operator, left, right
-
super(left, right)
-
@operator = operator
-
end
-
end
-
-
2
class Multiplication < InfixOperation
-
2
def initialize left, right
-
super(:*, left, right)
-
end
-
end
-
-
2
class Division < InfixOperation
-
2
def initialize left, right
-
super(:/, left, right)
-
end
-
end
-
-
2
class Addition < InfixOperation
-
2
def initialize left, right
-
super(:+, left, right)
-
end
-
end
-
-
2
class Subtraction < InfixOperation
-
2
def initialize left, right
-
super(:-, left, right)
-
end
-
end
-
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class InnerJoin < Arel::Nodes::Join
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class InsertStatement < Arel::Nodes::Node
-
2
attr_accessor :relation, :columns, :values
-
-
2
def initialize
-
308
@relation = nil
-
308
@columns = []
-
308
@values = nil
-
end
-
-
2
def initialize_copy other
-
super
-
@columns = @columns.clone
-
@values = @values.clone if @values
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
###
-
# Class that represents a join source
-
#
-
# http://www.sqlite.org/syntaxdiagrams.html#join-source
-
-
2
class JoinSource < Arel::Nodes::Binary
-
2
def initialize single_source, joinop = []
-
1302
super
-
end
-
-
2
def empty?
-
844
!left && right.empty?
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class NamedFunction < Arel::Nodes::Function
-
2
attr_accessor :name
-
-
2
def initialize name, expr, aliaz = nil
-
super(expr, aliaz)
-
@name = name
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
###
-
# Abstract base class for all AST nodes
-
2
class Node
-
2
include Arel::FactoryMethods
-
2
include Enumerable
-
-
###
-
# Factory method to create a Nodes::Not node that has the recipient of
-
# the caller as a child.
-
2
def not
-
Nodes::Not.new self
-
end
-
-
###
-
# Factory method to create a Nodes::Grouping node that has an Nodes::Or
-
# node as a child.
-
2
def or right
-
Nodes::Grouping.new Nodes::Or.new(self, right)
-
end
-
-
###
-
# Factory method to create an Nodes::And node.
-
2
def and right
-
Nodes::And.new [self, right]
-
end
-
-
# FIXME: this method should go away. I don't like people calling
-
# to_sql on non-head nodes. This forces us to walk the AST until we
-
# can find a node that has a "relation" member.
-
#
-
# Maybe we should just use `Table.engine`? :'(
-
2
def to_sql engine = Table.engine
-
engine.connection.visitor.accept self
-
end
-
-
# Iterate through AST, nodes will be yielded depth-first
-
2
def each &block
-
28
return enum_for(:each) unless block_given?
-
-
28
::Arel::Visitors::DepthFirst.new(block).accept self
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class OuterJoin < Arel::Nodes::Join
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
-
2
class Over < Binary
-
2
include Arel::AliasPredication
-
-
2
def initialize(left, right = nil)
-
super(left, right)
-
end
-
-
2
def operator; 'OVER' end
-
end
-
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class SelectCore < Arel::Nodes::Node
-
2
attr_accessor :top, :projections, :wheres, :groups, :windows
-
2
attr_accessor :having, :source, :set_quantifier
-
-
2
def initialize
-
1302
@source = JoinSource.new nil
-
1302
@top = nil
-
-
# http://savage.net.au/SQL/sql-92.bnf.html#set%20quantifier
-
1302
@set_quantifier = nil
-
1302
@projections = []
-
1302
@wheres = []
-
1302
@groups = []
-
1302
@having = nil
-
1302
@windows = []
-
end
-
-
2
def from
-
24
@source.left
-
end
-
-
2
def from= value
-
@source.left = value
-
end
-
-
2
alias :froms= :from=
-
2
alias :froms :from
-
-
2
def initialize_copy other
-
super
-
@source = @source.clone if @source
-
@projections = @projections.clone
-
@wheres = @wheres.clone
-
@groups = @groups.clone
-
@having = @having.clone if @having
-
@windows = @windows.clone
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class SelectStatement < Arel::Nodes::Node
-
2
attr_reader :cores
-
2
attr_accessor :limit, :orders, :lock, :offset, :with
-
-
2
def initialize cores = [SelectCore.new]
-
#puts caller
-
1302
@cores = cores
-
1302
@orders = []
-
1302
@limit = nil
-
1302
@lock = nil
-
1302
@offset = nil
-
1302
@with = nil
-
end
-
-
2
def initialize_copy other
-
super
-
@cores = @cores.map { |x| x.clone }
-
@orders = @orders.map { |x| x.clone }
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class SqlLiteral < String
-
2
include Arel::Expressions
-
2
include Arel::Predications
-
2
include Arel::AliasPredication
-
2
include Arel::OrderPredications
-
end
-
-
2
class BindParam < SqlLiteral
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class StringJoin < Arel::Nodes::Join
-
2
def initialize left, right = nil
-
super
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class TableAlias < Arel::Nodes::Binary
-
2
alias :name :right
-
2
alias :relation :left
-
2
alias :table_alias :name
-
-
2
def [] name
-
Attribute.new(self, name)
-
end
-
-
2
def table_name
-
relation.respond_to?(:name) ? relation.name : name
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Distinct < Arel::Nodes::Node
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class True < Arel::Nodes::Node
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Unary < Arel::Nodes::Node
-
2
attr_accessor :expr
-
2
alias :value :expr
-
-
2
def initialize expr
-
1301
@expr = expr
-
end
-
end
-
-
%w{
-
Bin
-
2
Group
-
Grouping
-
Having
-
Limit
-
Not
-
Offset
-
On
-
Ordering
-
Top
-
Lock
-
DistinctOn
-
}.each do |name|
-
24
const_set(name, Class.new(Unary))
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class UnqualifiedColumn < Arel::Nodes::Unary
-
2
alias :attribute :expr
-
2
alias :attribute= :expr=
-
-
2
def relation
-
114
@expr.relation
-
end
-
-
2
def column
-
@expr.column
-
end
-
-
2
def name
-
228
@expr.name
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class UpdateStatement < Arel::Nodes::Node
-
2
attr_accessor :relation, :wheres, :values, :orders, :limit
-
2
attr_accessor :key
-
-
2
def initialize
-
98
@relation = nil
-
98
@wheres = []
-
98
@values = []
-
98
@orders = []
-
98
@limit = nil
-
98
@key = nil
-
end
-
-
2
def initialize_copy other
-
super
-
@wheres = @wheres.clone
-
@values = @values.clone
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Values < Arel::Nodes::Binary
-
2
alias :expressions :left
-
2
alias :expressions= :left=
-
2
alias :columns :right
-
2
alias :columns= :right=
-
-
2
def initialize exprs, columns = []
-
308
super
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class Window < Arel::Nodes::Node
-
2
include Arel::Expression
-
2
attr_accessor :orders, :framing
-
-
2
def initialize
-
@orders = []
-
end
-
-
2
def order *expr
-
# FIXME: We SHOULD NOT be converting these to SqlLiteral automatically
-
@orders.concat expr.map { |x|
-
String === x || Symbol === x ? Nodes::SqlLiteral.new(x.to_s) : x
-
}
-
self
-
end
-
-
2
def frame(expr)
-
raise ArgumentError, "Window frame cannot be set more than once" if @frame
-
@framing = expr
-
end
-
-
2
def rows(expr = nil)
-
frame(Rows.new(expr))
-
end
-
-
2
def range(expr = nil)
-
frame(Range.new(expr))
-
end
-
-
2
def initialize_copy other
-
super
-
@orders = @orders.map { |x| x.clone }
-
end
-
end
-
-
2
class NamedWindow < Window
-
2
attr_accessor :name
-
-
2
def initialize name
-
super()
-
@name = name
-
end
-
-
2
def initialize_copy other
-
super
-
@name = other.name.clone
-
end
-
end
-
-
2
class Rows < Unary
-
2
def initialize(expr = nil)
-
super(expr)
-
end
-
end
-
-
2
class Range < Unary
-
2
def initialize(expr = nil)
-
super(expr)
-
end
-
end
-
-
2
class CurrentRow < Arel::Nodes::Node; end
-
-
2
class Preceding < Unary
-
2
def initialize(expr = nil)
-
super(expr)
-
end
-
end
-
-
2
class Following < Unary
-
2
def initialize(expr = nil)
-
super(expr)
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Nodes
-
2
class With < Arel::Nodes::Unary
-
2
alias children expr
-
end
-
-
2
class WithRecursive < With; end
-
end
-
end
-
-
2
module Arel
-
2
module OrderPredications
-
-
2
def asc
-
Nodes::Ascending.new self
-
end
-
-
2
def desc
-
Nodes::Descending.new self
-
end
-
-
end
-
end
-
2
module Arel
-
2
module Predications
-
2
def not_eq other
-
Nodes::NotEqual.new self, other
-
end
-
-
2
def not_eq_any others
-
grouping_any :not_eq, others
-
end
-
-
2
def not_eq_all others
-
grouping_all :not_eq, others
-
end
-
-
2
def eq other
-
538
Nodes::Equality.new self, other
-
end
-
-
2
def eq_any others
-
grouping_any :eq, others
-
end
-
-
2
def eq_all others
-
grouping_all :eq, others
-
end
-
-
2
def in other
-
case other
-
when Arel::SelectManager
-
Arel::Nodes::In.new(self, other.ast)
-
when Range
-
if other.exclude_end?
-
left = Nodes::GreaterThanOrEqual.new(self, other.begin)
-
right = Nodes::LessThan.new(self, other.end)
-
Nodes::And.new [left, right]
-
else
-
Nodes::Between.new(self, Nodes::And.new([other.begin, other.end]))
-
end
-
else
-
Nodes::In.new self, other
-
end
-
end
-
-
2
def in_any others
-
grouping_any :in, others
-
end
-
-
2
def in_all others
-
grouping_all :in, others
-
end
-
-
2
def not_in other
-
case other
-
when Arel::SelectManager
-
Arel::Nodes::NotIn.new(self, other.ast)
-
when Range
-
if other.exclude_end?
-
left = Nodes::LessThan.new(self, other.begin)
-
right = Nodes::GreaterThanOrEqual.new(self, other.end)
-
Nodes::Or.new left, right
-
else
-
left = Nodes::LessThan.new(self, other.begin)
-
right = Nodes::GreaterThan.new(self, other.end)
-
Nodes::Or.new left, right
-
end
-
else
-
Nodes::NotIn.new self, other
-
end
-
end
-
-
2
def not_in_any others
-
grouping_any :not_in, others
-
end
-
-
2
def not_in_all others
-
grouping_all :not_in, others
-
end
-
-
2
def matches other
-
Nodes::Matches.new self, other
-
end
-
-
2
def matches_any others
-
grouping_any :matches, others
-
end
-
-
2
def matches_all others
-
grouping_all :matches, others
-
end
-
-
2
def does_not_match other
-
Nodes::DoesNotMatch.new self, other
-
end
-
-
2
def does_not_match_any others
-
grouping_any :does_not_match, others
-
end
-
-
2
def does_not_match_all others
-
grouping_all :does_not_match, others
-
end
-
-
2
def gteq right
-
Nodes::GreaterThanOrEqual.new self, right
-
end
-
-
2
def gteq_any others
-
grouping_any :gteq, others
-
end
-
-
2
def gteq_all others
-
grouping_all :gteq, others
-
end
-
-
2
def gt right
-
Nodes::GreaterThan.new self, right
-
end
-
-
2
def gt_any others
-
grouping_any :gt, others
-
end
-
-
2
def gt_all others
-
grouping_all :gt, others
-
end
-
-
2
def lt right
-
Nodes::LessThan.new self, right
-
end
-
-
2
def lt_any others
-
grouping_any :lt, others
-
end
-
-
2
def lt_all others
-
grouping_all :lt, others
-
end
-
-
2
def lteq right
-
Nodes::LessThanOrEqual.new self, right
-
end
-
-
2
def lteq_any others
-
grouping_any :lteq, others
-
end
-
-
2
def lteq_all others
-
grouping_all :lteq, others
-
end
-
-
2
private
-
-
2
def grouping_any method_id, others
-
nodes = others.map {|expr| send(method_id, expr)}
-
Nodes::Grouping.new nodes.inject { |memo,node|
-
Nodes::Or.new(memo, node)
-
}
-
end
-
-
2
def grouping_all method_id, others
-
Nodes::Grouping.new Nodes::And.new(others.map {|expr| send(method_id, expr)})
-
end
-
end
-
end
-
2
module Arel
-
###
-
# This is deprecated. Fix rails, then remove this.
-
2
module Relation
-
end
-
end
-
2
module Arel
-
2
class SelectManager < Arel::TreeManager
-
2
include Arel::Crud
-
-
2
def initialize engine, table = nil
-
1302
super(engine)
-
1302
@ast = Nodes::SelectStatement.new
-
1302
@ctx = @ast.cores.last
-
1302
from table
-
end
-
-
2
def initialize_copy other
-
super
-
@ctx = @ast.cores.last
-
end
-
-
2
def limit
-
44
@ast.limit && @ast.limit.expr
-
end
-
2
alias :taken :limit
-
-
2
def constraints
-
44
@ctx.wheres
-
end
-
-
2
def offset
-
@ast.offset && @ast.offset.expr
-
end
-
-
2
def skip amount
-
if amount
-
@ast.offset = Nodes::Offset.new(amount)
-
else
-
@ast.offset = nil
-
end
-
self
-
end
-
2
alias :offset= :skip
-
-
###
-
# Produces an Arel::Nodes::Exists node
-
2
def exists
-
Arel::Nodes::Exists.new @ast
-
end
-
-
2
def as other
-
create_table_alias grouping(@ast), Nodes::SqlLiteral.new(other)
-
end
-
-
2
def where_clauses
-
if $VERBOSE
-
warn "(#{caller.first}) where_clauses is deprecated and will be removed in arel 4.0.0 with no replacement"
-
end
-
to_sql = Visitors::ToSql.new @engine.connection
-
@ctx.wheres.map { |c| to_sql.accept c }
-
end
-
-
2
def lock locking = Arel.sql('FOR UPDATE')
-
case locking
-
when true
-
locking = Arel.sql('FOR UPDATE')
-
when Arel::Nodes::SqlLiteral
-
when String
-
locking = Arel.sql locking
-
end
-
-
@ast.lock = Nodes::Lock.new(locking)
-
self
-
end
-
-
2
def locked
-
@ast.lock
-
end
-
-
2
def on *exprs
-
@ctx.source.right.last.right = Nodes::On.new(collapse(exprs))
-
self
-
end
-
-
2
def group *columns
-
columns.each do |column|
-
# FIXME: backwards compat
-
column = Nodes::SqlLiteral.new(column) if String === column
-
column = Nodes::SqlLiteral.new(column.to_s) if Symbol === column
-
-
@ctx.groups.push Nodes::Group.new column
-
end
-
self
-
end
-
-
2
def from table
-
1302
table = Nodes::SqlLiteral.new(table) if String === table
-
# FIXME: this is a hack to support
-
# test_with_two_tables_in_from_without_getting_double_quoted
-
# from the AR tests.
-
-
1302
case table
-
when Nodes::Join
-
@ctx.source.right << table
-
else
-
1302
@ctx.source.left = table
-
end
-
-
1302
self
-
end
-
-
2
def froms
-
@ast.cores.map { |x| x.from }.compact
-
end
-
-
2
def join relation, klass = Nodes::InnerJoin
-
return self unless relation
-
-
case relation
-
when String, Nodes::SqlLiteral
-
raise if relation.blank?
-
klass = Nodes::StringJoin
-
end
-
-
@ctx.source.right << create_join(relation, nil, klass)
-
self
-
end
-
-
2
def having *exprs
-
@ctx.having = Nodes::Having.new(collapse(exprs, @ctx.having))
-
self
-
end
-
-
2
def window name
-
window = Nodes::NamedWindow.new(name)
-
@ctx.windows.push window
-
window
-
end
-
-
2
def project *projections
-
# FIXME: converting these to SQLLiterals is probably not good, but
-
# rails tests require it.
-
1302
@ctx.projections.concat projections.map { |x|
-
1302
[Symbol, String].include?(x.class) ? SqlLiteral.new(x.to_s) : x
-
}
-
1302
self
-
end
-
-
2
def projections= projections
-
@ctx.projections = projections
-
end
-
-
2
def distinct(value = true)
-
1302
if value
-
@ctx.set_quantifier = Arel::Nodes::Distinct.new
-
else
-
1302
@ctx.set_quantifier = nil
-
end
-
end
-
-
2
def order *expr
-
# FIXME: We SHOULD NOT be converting these to SqlLiteral automatically
-
33
@ast.orders.concat expr.map { |x|
-
5
String === x || Symbol === x ? Nodes::SqlLiteral.new(x.to_s) : x
-
}
-
33
self
-
end
-
-
2
def orders
-
44
@ast.orders
-
end
-
-
2
def wheres
-
warn "#{caller[0]}: SelectManager#wheres is deprecated and will be removed in ARel 4.0.0 with no replacement"
-
Compatibility::Wheres.new @engine.connection, @ctx.wheres
-
end
-
-
2
def where_sql
-
return if @ctx.wheres.empty?
-
-
viz = Visitors::WhereSql.new @engine.connection
-
Nodes::SqlLiteral.new viz.accept @ctx
-
end
-
-
2
def union operation, other = nil
-
if other
-
node_class = Nodes.const_get("Union#{operation.to_s.capitalize}")
-
else
-
other = operation
-
node_class = Nodes::Union
-
end
-
-
node_class.new self.ast, other.ast
-
end
-
-
2
def intersect other
-
Nodes::Intersect.new ast, other.ast
-
end
-
-
2
def except other
-
Nodes::Except.new ast, other.ast
-
end
-
2
alias :minus :except
-
-
2
def with *subqueries
-
if subqueries.first.is_a? Symbol
-
node_class = Nodes.const_get("With#{subqueries.shift.to_s.capitalize}")
-
else
-
node_class = Nodes::With
-
end
-
@ast.with = node_class.new(subqueries.flatten)
-
-
self
-
end
-
-
2
def take limit
-
363
if limit
-
363
@ast.limit = Nodes::Limit.new(limit)
-
363
@ctx.top = Nodes::Top.new(limit)
-
else
-
@ast.limit = nil
-
@ctx.top = nil
-
end
-
363
self
-
end
-
2
alias limit= take
-
-
2
def join_sql
-
return nil if @ctx.source.right.empty?
-
-
sql = visitor.dup.extend(Visitors::JoinSql).accept @ctx
-
Nodes::SqlLiteral.new sql
-
end
-
-
2
def order_clauses
-
visitor = Visitors::OrderClauses.new(@engine.connection)
-
visitor.accept(@ast).map { |x|
-
Nodes::SqlLiteral.new x
-
}
-
end
-
-
2
def join_sources
-
@ctx.source.right
-
end
-
-
2
def source
-
@ctx.source
-
end
-
-
2
def joins manager
-
if $VERBOSE
-
warn "joins is deprecated and will be removed in 4.0.0"
-
warn "please remove your call to joins from #{caller.first}"
-
end
-
manager.join_sql
-
end
-
-
2
class Row < Struct.new(:data) # :nodoc:
-
2
def id
-
data['id']
-
end
-
-
2
def method_missing(name, *args)
-
name = name.to_s
-
return data[name] if data.key?(name)
-
super
-
end
-
end
-
-
2
def to_a # :nodoc:
-
warn "to_a is deprecated. Please remove it from #{caller[0]}"
-
# FIXME: I think `select` should be made public...
-
@engine.connection.send(:select, to_sql, 'AREL').map { |x| Row.new(x) }
-
end
-
-
# FIXME: this method should go away
-
2
def insert values
-
if $VERBOSE
-
warn <<-eowarn
-
insert (#{caller.first}) is deprecated and will be removed in ARel 4.0.0. Please
-
switch to `compile_insert`
-
eowarn
-
end
-
-
im = compile_insert(values)
-
table = @ctx.froms
-
-
primary_key = table.primary_key
-
primary_key_name = primary_key.name if primary_key
-
-
# FIXME: in AR tests values sometimes were Array and not Hash therefore is_a?(Hash) check is added
-
primary_key_value = primary_key && values.is_a?(Hash) && values[primary_key]
-
im.into table
-
# Oracle adapter needs primary key name to generate RETURNING ... INTO ... clause
-
# for tables which assign primary key value using trigger.
-
# RETURNING ... INTO ... clause will be added only if primary_key_value is nil
-
# therefore it is necessary to pass primary key value as well
-
@engine.connection.insert im.to_sql, 'AREL', primary_key_name, primary_key_value
-
end
-
-
2
private
-
2
def collapse exprs, existing = nil
-
exprs = exprs.unshift(existing.expr) if existing
-
exprs = exprs.compact.map { |expr|
-
if String === expr
-
# FIXME: Don't do this automatically
-
Arel.sql(expr)
-
else
-
expr
-
end
-
}
-
-
if exprs.length == 1
-
exprs.first
-
else
-
create_and exprs
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Sql
-
2
class Engine
-
2
def self.new thing
-
#warn "#{caller.first} -- Engine will be removed"
-
thing
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
class SqlLiteral < Nodes::SqlLiteral
-
end
-
end
-
2
module Arel
-
2
class Table
-
2
include Arel::Crud
-
2
include Arel::FactoryMethods
-
-
2
@engine = nil
-
4
class << self; attr_accessor :engine; end
-
-
2
attr_accessor :name, :engine, :aliases, :table_alias
-
-
# TableAlias and Table both have a #table_name which is the name of the underlying table
-
2
alias :table_name :name
-
-
2
def initialize name, engine = Table.engine
-
289
@name = name.to_s
-
289
@engine = engine
-
289
@columns = nil
-
289
@aliases = []
-
289
@table_alias = nil
-
289
@primary_key = nil
-
-
289
if Hash === engine
-
@engine = engine[:engine] || Table.engine
-
-
# Sometime AR sends an :as parameter to table, to let the table know
-
# that it is an Alias. We may want to override new, and return a
-
# TableAlias node?
-
@table_alias = engine[:as] unless engine[:as].to_s == @name
-
end
-
end
-
-
2
def primary_key
-
if $VERBOSE
-
warn <<-eowarn
-
primary_key (#{caller.first}) is deprecated and will be removed in ARel 4.0.0
-
eowarn
-
end
-
@primary_key ||= begin
-
primary_key_name = @engine.connection.primary_key(name)
-
# some tables might be without primary key
-
primary_key_name && self[primary_key_name]
-
end
-
end
-
-
2
def alias name = "#{self.name}_2"
-
Nodes::TableAlias.new(self, name).tap do |node|
-
@aliases << node
-
end
-
end
-
-
2
def from table
-
1302
SelectManager.new(@engine, table)
-
end
-
-
2
def joins manager
-
if $VERBOSE
-
warn "joins is deprecated and will be removed in 4.0.0"
-
warn "please remove your call to joins from #{caller.first}"
-
end
-
nil
-
end
-
-
2
def join relation, klass = Nodes::InnerJoin
-
return from(self) unless relation
-
-
case relation
-
when String, Nodes::SqlLiteral
-
raise if relation.blank?
-
klass = Nodes::StringJoin
-
end
-
-
from(self).join(relation, klass)
-
end
-
-
2
def group *columns
-
from(self).group(*columns)
-
end
-
-
2
def order *expr
-
from(self).order(*expr)
-
end
-
-
2
def where condition
-
from(self).where condition
-
end
-
-
2
def project *things
-
from(self).project(*things)
-
end
-
-
2
def take amount
-
from(self).take amount
-
end
-
-
2
def skip amount
-
from(self).skip amount
-
end
-
-
2
def having expr
-
from(self).having expr
-
end
-
-
2
def columns
-
if $VERBOSE
-
warn <<-eowarn
-
(#{caller.first}) Arel::Table#columns is deprecated and will be removed in
-
Arel 4.0.0 with no replacement. PEW PEW PEW!!!
-
eowarn
-
end
-
@columns ||=
-
attributes_for @engine.connection.columns(@name, "#{@name} Columns")
-
end
-
-
2
def [] name
-
5410
::Arel::Attribute.new self, name
-
end
-
-
2
def select_manager
-
SelectManager.new(@engine)
-
end
-
-
2
def insert_manager
-
InsertManager.new(@engine)
-
end
-
-
2
private
-
-
2
def attributes_for columns
-
return nil unless columns
-
-
columns.map do |column|
-
Attributes.for(column).new self, column.name.to_sym
-
end
-
end
-
-
2
@@table_cache = nil
-
2
def self.table_cache engine # :nodoc:
-
if $VERBOSE
-
warn <<-eowarn
-
(#{caller.first}) Arel::Table.table_cache is deprecated and will be removed in
-
Arel 4.0.0 with no replacement. PEW PEW PEW!!!
-
eowarn
-
end
-
@@table_cache ||= Hash[engine.connection.tables.map { |x| [x,true] }]
-
end
-
end
-
end
-
2
module Arel
-
2
class TreeManager
-
# FIXME: Remove this.
-
2
include Arel::Relation
-
2
include Arel::FactoryMethods
-
-
2
attr_reader :ast, :engine
-
-
2
def initialize engine
-
1732
@engine = engine
-
1732
@ctx = nil
-
end
-
-
2
def to_dot
-
Visitors::Dot.new.accept @ast
-
end
-
-
2
def visitor
-
engine.connection.visitor
-
end
-
-
2
def to_sql
-
visitor.accept @ast
-
end
-
-
2
def initialize_copy other
-
super
-
@ast = @ast.clone
-
end
-
-
2
def where expr
-
1031
if Arel::TreeManager === expr
-
expr = expr.ast
-
end
-
1031
@ctx.wheres << expr
-
1031
self
-
end
-
end
-
end
-
2
module Arel
-
2
class UpdateManager < Arel::TreeManager
-
2
def initialize engine
-
98
super
-
98
@ast = Nodes::UpdateStatement.new
-
98
@ctx = @ast
-
end
-
-
2
def take limit
-
44
@ast.limit = Nodes::Limit.new(limit) if limit
-
44
self
-
end
-
-
2
def key= key
-
44
@ast.key = key
-
end
-
-
2
def key
-
@ast.key
-
end
-
-
2
def order *expr
-
98
@ast.orders = expr
-
98
self
-
end
-
-
###
-
# UPDATE +table+
-
2
def table table
-
98
@ast.relation = table
-
98
self
-
end
-
-
2
def wheres= exprs
-
98
@ast.wheres = exprs
-
end
-
-
2
def where expr
-
@ast.wheres << expr
-
self
-
end
-
-
2
def set values
-
98
if String === values
-
44
@ast.values = [values]
-
else
-
54
@ast.values = values.map { |column,value|
-
114
Nodes::Assignment.new(
-
Nodes::UnqualifiedColumn.new(column),
-
value
-
)
-
}
-
end
-
98
self
-
end
-
end
-
end
-
2
require 'arel/visitors/visitor'
-
2
require 'arel/visitors/depth_first'
-
2
require 'arel/visitors/to_sql'
-
2
require 'arel/visitors/sqlite'
-
2
require 'arel/visitors/postgresql'
-
2
require 'arel/visitors/mysql'
-
2
require 'arel/visitors/mssql'
-
2
require 'arel/visitors/oracle'
-
2
require 'arel/visitors/join_sql'
-
2
require 'arel/visitors/where_sql'
-
2
require 'arel/visitors/order_clauses'
-
2
require 'arel/visitors/dot'
-
2
require 'arel/visitors/ibm_db'
-
2
require 'arel/visitors/informix'
-
-
2
module Arel
-
2
module Visitors
-
2
VISITORS = {
-
'postgresql' => Arel::Visitors::PostgreSQL,
-
'mysql' => Arel::Visitors::MySQL,
-
'mysql2' => Arel::Visitors::MySQL,
-
'mssql' => Arel::Visitors::MSSQL,
-
'sqlserver' => Arel::Visitors::MSSQL,
-
'oracle_enhanced' => Arel::Visitors::Oracle,
-
'sqlite' => Arel::Visitors::SQLite,
-
'sqlite3' => Arel::Visitors::SQLite,
-
'ibm_db' => Arel::Visitors::IBM_DB,
-
'informix' => Arel::Visitors::Informix,
-
}
-
-
2
ENGINE_VISITORS = Hash.new do |hash, engine|
-
pool = engine.connection_pool
-
adapter = pool.spec.config[:adapter]
-
hash[engine] = (VISITORS[adapter] || Visitors::ToSql).new(engine)
-
end
-
-
2
def self.visitor_for engine
-
ENGINE_VISITORS[engine]
-
end
-
4
class << self; alias :for :visitor_for; end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
module BindVisitor
-
2
def initialize target
-
@block = nil
-
super
-
end
-
-
2
def accept node, &block
-
@block = block if block_given?
-
super
-
end
-
-
2
private
-
2
def visit_Arel_Nodes_BindParam o
-
if @block
-
@block.call
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class DepthFirst < Arel::Visitors::Visitor
-
2
def initialize block = nil
-
28
@block = block || Proc.new
-
end
-
-
2
private
-
-
2
def visit o
-
721
super
-
721
@block.call o
-
end
-
-
2
def unary o
-
9
visit o.expr
-
end
-
2
alias :visit_Arel_Nodes_Group :unary
-
2
alias :visit_Arel_Nodes_Grouping :unary
-
2
alias :visit_Arel_Nodes_Having :unary
-
2
alias :visit_Arel_Nodes_Limit :unary
-
2
alias :visit_Arel_Nodes_Not :unary
-
2
alias :visit_Arel_Nodes_Offset :unary
-
2
alias :visit_Arel_Nodes_On :unary
-
2
alias :visit_Arel_Nodes_Ordering :unary
-
2
alias :visit_Arel_Nodes_Ascending :unary
-
2
alias :visit_Arel_Nodes_Descending :unary
-
2
alias :visit_Arel_Nodes_Top :unary
-
2
alias :visit_Arel_Nodes_UnqualifiedColumn :unary
-
-
2
def function o
-
visit o.expressions
-
visit o.alias
-
visit o.distinct
-
end
-
2
alias :visit_Arel_Nodes_Avg :function
-
2
alias :visit_Arel_Nodes_Exists :function
-
2
alias :visit_Arel_Nodes_Max :function
-
2
alias :visit_Arel_Nodes_Min :function
-
2
alias :visit_Arel_Nodes_Sum :function
-
-
2
def visit_Arel_Nodes_NamedFunction o
-
visit o.name
-
visit o.expressions
-
visit o.distinct
-
visit o.alias
-
end
-
-
2
def visit_Arel_Nodes_Count o
-
visit o.expressions
-
visit o.alias
-
visit o.distinct
-
end
-
-
2
def nary o
-
40
o.children.each { |child| visit child }
-
end
-
2
alias :visit_Arel_Nodes_And :nary
-
-
2
def binary o
-
48
visit o.left
-
48
visit o.right
-
end
-
2
alias :visit_Arel_Nodes_As :binary
-
2
alias :visit_Arel_Nodes_Assignment :binary
-
2
alias :visit_Arel_Nodes_Between :binary
-
2
alias :visit_Arel_Nodes_DeleteStatement :binary
-
2
alias :visit_Arel_Nodes_DoesNotMatch :binary
-
2
alias :visit_Arel_Nodes_Equality :binary
-
2
alias :visit_Arel_Nodes_GreaterThan :binary
-
2
alias :visit_Arel_Nodes_GreaterThanOrEqual :binary
-
2
alias :visit_Arel_Nodes_In :binary
-
2
alias :visit_Arel_Nodes_InfixOperation :binary
-
2
alias :visit_Arel_Nodes_JoinSource :binary
-
2
alias :visit_Arel_Nodes_InnerJoin :binary
-
2
alias :visit_Arel_Nodes_LessThan :binary
-
2
alias :visit_Arel_Nodes_LessThanOrEqual :binary
-
2
alias :visit_Arel_Nodes_Matches :binary
-
2
alias :visit_Arel_Nodes_NotEqual :binary
-
2
alias :visit_Arel_Nodes_NotIn :binary
-
2
alias :visit_Arel_Nodes_Or :binary
-
2
alias :visit_Arel_Nodes_OuterJoin :binary
-
2
alias :visit_Arel_Nodes_TableAlias :binary
-
2
alias :visit_Arel_Nodes_Values :binary
-
-
2
def visit_Arel_Nodes_StringJoin o
-
visit o.left
-
end
-
-
2
def visit_Arel_Attribute o
-
48
visit o.relation
-
48
visit o.name
-
end
-
2
alias :visit_Arel_Attributes_Integer :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Float :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_String :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Time :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Attribute :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Decimal :visit_Arel_Attribute
-
-
2
def visit_Arel_Table o
-
76
visit o.name
-
end
-
-
2
def terminal o
-
end
-
2
alias :visit_ActiveSupport_Multibyte_Chars :terminal
-
2
alias :visit_ActiveSupport_StringInquirer :terminal
-
2
alias :visit_Arel_Nodes_Lock :terminal
-
2
alias :visit_Arel_Nodes_Node :terminal
-
2
alias :visit_Arel_Nodes_SqlLiteral :terminal
-
2
alias :visit_Arel_Nodes_BindParam :terminal
-
2
alias :visit_Arel_Nodes_Window :terminal
-
2
alias :visit_Arel_SqlLiteral :terminal
-
2
alias :visit_BigDecimal :terminal
-
2
alias :visit_Bignum :terminal
-
2
alias :visit_Class :terminal
-
2
alias :visit_Date :terminal
-
2
alias :visit_DateTime :terminal
-
2
alias :visit_FalseClass :terminal
-
2
alias :visit_Fixnum :terminal
-
2
alias :visit_Float :terminal
-
2
alias :visit_NilClass :terminal
-
2
alias :visit_String :terminal
-
2
alias :visit_Symbol :terminal
-
2
alias :visit_Time :terminal
-
2
alias :visit_TrueClass :terminal
-
-
2
def visit_Arel_Nodes_InsertStatement o
-
visit o.relation
-
visit o.columns
-
visit o.values
-
end
-
-
2
def visit_Arel_Nodes_SelectCore o
-
28
visit o.projections
-
28
visit o.source
-
28
visit o.wheres
-
28
visit o.groups
-
28
visit o.windows
-
28
visit o.having
-
end
-
-
2
def visit_Arel_Nodes_SelectStatement o
-
28
visit o.cores
-
28
visit o.orders
-
28
visit o.limit
-
28
visit o.lock
-
28
visit o.offset
-
end
-
-
2
def visit_Arel_Nodes_UpdateStatement o
-
visit o.relation
-
visit o.values
-
visit o.wheres
-
visit o.orders
-
visit o.limit
-
end
-
-
2
def visit_Array o
-
284
o.each { |i| visit i }
-
end
-
-
2
def visit_Hash o
-
o.each { |k,v| visit(k); visit(v) }
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class Dot < Arel::Visitors::Visitor
-
2
class Node # :nodoc:
-
2
attr_accessor :name, :id, :fields
-
-
2
def initialize name, id, fields = []
-
@name = name
-
@id = id
-
@fields = fields
-
end
-
end
-
-
2
class Edge < Struct.new :name, :from, :to # :nodoc:
-
end
-
-
2
def initialize
-
@nodes = []
-
@edges = []
-
@node_stack = []
-
@edge_stack = []
-
@seen = {}
-
end
-
-
2
def accept object
-
super
-
to_dot
-
end
-
-
2
private
-
2
def visit_Arel_Nodes_Ordering o
-
visit_edge o, "expr"
-
end
-
-
2
def visit_Arel_Nodes_TableAlias o
-
visit_edge o, "name"
-
visit_edge o, "relation"
-
end
-
-
2
def visit_Arel_Nodes_Count o
-
visit_edge o, "expressions"
-
visit_edge o, "distinct"
-
end
-
-
2
def visit_Arel_Nodes_Values o
-
visit_edge o, "expressions"
-
end
-
-
2
def visit_Arel_Nodes_StringJoin o
-
visit_edge o, "left"
-
end
-
-
2
def visit_Arel_Nodes_InnerJoin o
-
visit_edge o, "left"
-
visit_edge o, "right"
-
end
-
2
alias :visit_Arel_Nodes_OuterJoin :visit_Arel_Nodes_InnerJoin
-
-
2
def visit_Arel_Nodes_DeleteStatement o
-
visit_edge o, "relation"
-
visit_edge o, "wheres"
-
end
-
-
2
def unary o
-
visit_edge o, "expr"
-
end
-
2
alias :visit_Arel_Nodes_Group :unary
-
2
alias :visit_Arel_Nodes_BindParam :unary
-
2
alias :visit_Arel_Nodes_Grouping :unary
-
2
alias :visit_Arel_Nodes_Having :unary
-
2
alias :visit_Arel_Nodes_Limit :unary
-
2
alias :visit_Arel_Nodes_Not :unary
-
2
alias :visit_Arel_Nodes_Offset :unary
-
2
alias :visit_Arel_Nodes_On :unary
-
2
alias :visit_Arel_Nodes_Top :unary
-
2
alias :visit_Arel_Nodes_UnqualifiedColumn :unary
-
2
alias :visit_Arel_Nodes_Preceding :unary
-
2
alias :visit_Arel_Nodes_Following :unary
-
2
alias :visit_Arel_Nodes_Rows :unary
-
2
alias :visit_Arel_Nodes_Range :unary
-
-
2
def window o
-
visit_edge o, "orders"
-
visit_edge o, "framing"
-
end
-
2
alias :visit_Arel_Nodes_Window :window
-
-
2
def named_window o
-
visit_edge o, "orders"
-
visit_edge o, "framing"
-
visit_edge o, "name"
-
end
-
2
alias :visit_Arel_Nodes_NamedWindow :named_window
-
-
2
def function o
-
visit_edge o, "expressions"
-
visit_edge o, "distinct"
-
visit_edge o, "alias"
-
end
-
2
alias :visit_Arel_Nodes_Exists :function
-
2
alias :visit_Arel_Nodes_Min :function
-
2
alias :visit_Arel_Nodes_Max :function
-
2
alias :visit_Arel_Nodes_Avg :function
-
2
alias :visit_Arel_Nodes_Sum :function
-
-
2
def extract o
-
visit_edge o, "expressions"
-
visit_edge o, "alias"
-
end
-
2
alias :visit_Arel_Nodes_Extract :extract
-
-
2
def visit_Arel_Nodes_NamedFunction o
-
visit_edge o, "name"
-
visit_edge o, "expressions"
-
visit_edge o, "distinct"
-
visit_edge o, "alias"
-
end
-
-
2
def visit_Arel_Nodes_InsertStatement o
-
visit_edge o, "relation"
-
visit_edge o, "columns"
-
visit_edge o, "values"
-
end
-
-
2
def visit_Arel_Nodes_SelectCore o
-
visit_edge o, "source"
-
visit_edge o, "projections"
-
visit_edge o, "wheres"
-
visit_edge o, "windows"
-
end
-
-
2
def visit_Arel_Nodes_SelectStatement o
-
visit_edge o, "cores"
-
visit_edge o, "limit"
-
visit_edge o, "orders"
-
visit_edge o, "offset"
-
end
-
-
2
def visit_Arel_Nodes_UpdateStatement o
-
visit_edge o, "relation"
-
visit_edge o, "wheres"
-
visit_edge o, "values"
-
end
-
-
2
def visit_Arel_Table o
-
visit_edge o, "name"
-
end
-
-
2
def visit_Arel_Attribute o
-
visit_edge o, "relation"
-
visit_edge o, "name"
-
end
-
2
alias :visit_Arel_Attributes_Integer :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Float :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_String :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Time :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attribute
-
2
alias :visit_Arel_Attributes_Attribute :visit_Arel_Attribute
-
-
2
def nary o
-
o.children.each_with_index do |x,i|
-
edge(i) { visit x }
-
end
-
end
-
2
alias :visit_Arel_Nodes_And :nary
-
-
2
def binary o
-
visit_edge o, "left"
-
visit_edge o, "right"
-
end
-
2
alias :visit_Arel_Nodes_As :binary
-
2
alias :visit_Arel_Nodes_Assignment :binary
-
2
alias :visit_Arel_Nodes_Between :binary
-
2
alias :visit_Arel_Nodes_DoesNotMatch :binary
-
2
alias :visit_Arel_Nodes_Equality :binary
-
2
alias :visit_Arel_Nodes_GreaterThan :binary
-
2
alias :visit_Arel_Nodes_GreaterThanOrEqual :binary
-
2
alias :visit_Arel_Nodes_In :binary
-
2
alias :visit_Arel_Nodes_JoinSource :binary
-
2
alias :visit_Arel_Nodes_LessThan :binary
-
2
alias :visit_Arel_Nodes_LessThanOrEqual :binary
-
2
alias :visit_Arel_Nodes_Matches :binary
-
2
alias :visit_Arel_Nodes_NotEqual :binary
-
2
alias :visit_Arel_Nodes_NotIn :binary
-
2
alias :visit_Arel_Nodes_Or :binary
-
2
alias :visit_Arel_Nodes_Over :binary
-
-
2
def visit_String o
-
@node_stack.last.fields << o
-
end
-
2
alias :visit_Time :visit_String
-
2
alias :visit_Date :visit_String
-
2
alias :visit_DateTime :visit_String
-
2
alias :visit_NilClass :visit_String
-
2
alias :visit_TrueClass :visit_String
-
2
alias :visit_FalseClass :visit_String
-
2
alias :visit_Arel_SqlLiteral :visit_String
-
2
alias :visit_Fixnum :visit_String
-
2
alias :visit_BigDecimal :visit_String
-
2
alias :visit_Float :visit_String
-
2
alias :visit_Symbol :visit_String
-
2
alias :visit_Arel_Nodes_SqlLiteral :visit_String
-
-
2
def visit_Hash o
-
o.each_with_index do |pair, i|
-
edge("pair_#{i}") { visit pair }
-
end
-
end
-
-
2
def visit_Array o
-
o.each_with_index do |x,i|
-
edge(i) { visit x }
-
end
-
end
-
-
2
def visit_edge o, method
-
edge(method) { visit o.send(method) }
-
end
-
-
2
def visit o
-
if node = @seen[o.object_id]
-
@edge_stack.last.to = node
-
return
-
end
-
-
node = Node.new(o.class.name, o.object_id)
-
@seen[node.id] = node
-
@nodes << node
-
with_node node do
-
super
-
end
-
end
-
-
2
def edge name
-
edge = Edge.new(name, @node_stack.last)
-
@edge_stack.push edge
-
@edges << edge
-
yield
-
@edge_stack.pop
-
end
-
-
2
def with_node node
-
if edge = @edge_stack.last
-
edge.to = node
-
end
-
-
@node_stack.push node
-
yield
-
@node_stack.pop
-
end
-
-
2
def quote string
-
string.to_s.gsub('"', '\"')
-
end
-
-
2
def to_dot
-
"digraph \"ARel\" {\nnode [width=0.375,height=0.25,shape=record];\n" +
-
@nodes.map { |node|
-
label = "<f0>#{node.name}"
-
-
node.fields.each_with_index do |field, i|
-
label << "|<f#{i + 1}>#{quote field}"
-
end
-
-
"#{node.id} [label=\"#{label}\"];"
-
}.join("\n") + "\n" + @edges.map { |edge|
-
"#{edge.from.id} -> #{edge.to.id} [label=\"#{edge.name}\"];"
-
}.join("\n") + "\n}"
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class IBM_DB < Arel::Visitors::ToSql
-
2
private
-
-
2
def visit_Arel_Nodes_Limit o
-
"FETCH FIRST #{visit o.expr} ROWS ONLY"
-
end
-
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class Informix < Arel::Visitors::ToSql
-
2
private
-
2
def visit_Arel_Nodes_SelectStatement o
-
[
-
"SELECT",
-
(visit(o.offset) if o.offset),
-
(visit(o.limit) if o.limit),
-
o.cores.map { |x| visit_Arel_Nodes_SelectCore x }.join,
-
("ORDER BY #{o.orders.map { |x| visit x }.join(', ')}" unless o.orders.empty?),
-
(visit(o.lock) if o.lock),
-
].compact.join ' '
-
end
-
2
def visit_Arel_Nodes_SelectCore o
-
[
-
"#{o.projections.map { |x| visit x }.join ', '}",
-
("FROM #{visit(o.source)}" if o.source && !o.source.empty?),
-
("WHERE #{o.wheres.map { |x| visit x }.join ' AND ' }" unless o.wheres.empty?),
-
("GROUP BY #{o.groups.map { |x| visit x }.join ', ' }" unless o.groups.empty?),
-
(visit(o.having) if o.having),
-
].compact.join ' '
-
end
-
2
def visit_Arel_Nodes_Offset o
-
"SKIP #{visit o.expr}"
-
end
-
2
def visit_Arel_Nodes_Limit o
-
"LIMIT #{visit o.expr}"
-
end
-
end
-
end
-
end
-
-
2
module Arel
-
2
module Visitors
-
###
-
# This class produces SQL for JOIN clauses but omits the "single-source"
-
# part of the Join grammar:
-
#
-
# http://www.sqlite.org/syntaxdiagrams.html#join-source
-
#
-
# This visitor is used in SelectManager#join_sql and is for backwards
-
# compatibility with Arel V1.0
-
2
module JoinSql
-
2
private
-
-
2
def visit_Arel_Nodes_SelectCore o
-
o.source.right.map { |j| visit j }.join ' '
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class MSSQL < Arel::Visitors::ToSql
-
2
private
-
-
# `top` wouldn't really work here. I.e. User.select("distinct first_name").limit(10) would generate
-
# "select top 10 distinct first_name from users", which is invalid query! it should be
-
# "select distinct top 10 first_name from users"
-
2
def visit_Arel_Nodes_Top o
-
""
-
end
-
-
2
def visit_Arel_Nodes_SelectStatement o
-
if !o.limit && !o.offset
-
return super o
-
end
-
-
select_order_by = "ORDER BY #{o.orders.map { |x| visit x }.join(', ')}" unless o.orders.empty?
-
-
is_select_count = false
-
sql = o.cores.map { |x|
-
core_order_by = select_order_by || determine_order_by(x)
-
if select_count? x
-
x.projections = [row_num_literal(core_order_by)]
-
is_select_count = true
-
else
-
x.projections << row_num_literal(core_order_by)
-
end
-
-
visit_Arel_Nodes_SelectCore x
-
}.join
-
-
sql = "SELECT _t.* FROM (#{sql}) as _t WHERE #{get_offset_limit_clause(o)}"
-
# fixme count distinct wouldn't work with limit or offset
-
sql = "SELECT COUNT(1) as count_id FROM (#{sql}) AS subquery" if is_select_count
-
sql
-
end
-
-
2
def get_offset_limit_clause o
-
first_row = o.offset ? o.offset.expr.to_i + 1 : 1
-
last_row = o.limit ? o.limit.expr.to_i - 1 + first_row : nil
-
if last_row
-
" _row_num BETWEEN #{first_row} AND #{last_row}"
-
else
-
" _row_num >= #{first_row}"
-
end
-
end
-
-
2
def determine_order_by x
-
unless x.groups.empty?
-
"ORDER BY #{x.groups.map { |g| visit g }.join ', ' }"
-
else
-
"ORDER BY #{find_left_table_pk(x.froms)}"
-
end
-
end
-
-
2
def row_num_literal order_by
-
Nodes::SqlLiteral.new("ROW_NUMBER() OVER (#{order_by}) as _row_num")
-
end
-
-
2
def select_count? x
-
x.projections.length == 1 && Arel::Nodes::Count === x.projections.first
-
end
-
-
# fixme raise exception of there is no pk?
-
# fixme!! Table.primary_key will be depricated. What is the replacement??
-
2
def find_left_table_pk o
-
return visit o.primary_key if o.instance_of? Arel::Table
-
find_left_table_pk o.left if o.kind_of? Arel::Nodes::Join
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class MySQL < Arel::Visitors::ToSql
-
2
private
-
2
def visit_Arel_Nodes_Union o, suppress_parens = false
-
left_result = case o.left
-
when Arel::Nodes::Union
-
visit_Arel_Nodes_Union o.left, true
-
else
-
visit o.left
-
end
-
-
right_result = case o.right
-
when Arel::Nodes::Union
-
visit_Arel_Nodes_Union o.right, true
-
else
-
visit o.right
-
end
-
-
if suppress_parens
-
"#{left_result} UNION #{right_result}"
-
else
-
"( #{left_result} UNION #{right_result} )"
-
end
-
end
-
-
2
def visit_Arel_Nodes_Bin o
-
"BINARY #{visit o.expr}"
-
end
-
-
###
-
# :'(
-
# http://dev.mysql.com/doc/refman/5.0/en/select.html#id3482214
-
2
def visit_Arel_Nodes_SelectStatement o
-
o.limit = Arel::Nodes::Limit.new(18446744073709551615) if o.offset && !o.limit
-
super
-
end
-
-
2
def visit_Arel_Nodes_SelectCore o
-
o.froms ||= Arel.sql('DUAL')
-
super
-
end
-
-
2
def visit_Arel_Nodes_UpdateStatement o
-
[
-
"UPDATE #{visit o.relation}",
-
("SET #{o.values.map { |value| visit value }.join ', '}" unless o.values.empty?),
-
("WHERE #{o.wheres.map { |x| visit x }.join ' AND '}" unless o.wheres.empty?),
-
("ORDER BY #{o.orders.map { |x| visit x }.join(', ')}" unless o.orders.empty?),
-
(visit(o.limit) if o.limit),
-
].compact.join ' '
-
end
-
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class Oracle < Arel::Visitors::ToSql
-
2
private
-
-
2
def visit_Arel_Nodes_SelectStatement o
-
o = order_hacks(o)
-
-
# if need to select first records without ORDER BY and GROUP BY and without DISTINCT
-
# then can use simple ROWNUM in WHERE clause
-
if o.limit && o.orders.empty? && !o.offset && o.cores.first.projections.first !~ /^DISTINCT /
-
o.cores.last.wheres.push Nodes::LessThanOrEqual.new(
-
Nodes::SqlLiteral.new('ROWNUM'), o.limit.expr
-
)
-
return super
-
end
-
-
if o.limit && o.offset
-
o = o.dup
-
limit = o.limit.expr.to_i
-
offset = o.offset
-
o.offset = nil
-
sql = super(o)
-
return <<-eosql
-
SELECT * FROM (
-
SELECT raw_sql_.*, rownum raw_rnum_
-
FROM (#{sql}) raw_sql_
-
WHERE rownum <= #{offset.expr.to_i + limit}
-
)
-
WHERE #{visit offset}
-
eosql
-
end
-
-
if o.limit
-
o = o.dup
-
limit = o.limit.expr
-
return "SELECT * FROM (#{super(o)}) WHERE ROWNUM <= #{visit limit}"
-
end
-
-
if o.offset
-
o = o.dup
-
offset = o.offset
-
o.offset = nil
-
sql = super(o)
-
return <<-eosql
-
SELECT * FROM (
-
SELECT raw_sql_.*, rownum raw_rnum_
-
FROM (#{sql}) raw_sql_
-
)
-
WHERE #{visit offset}
-
eosql
-
end
-
-
super
-
end
-
-
2
def visit_Arel_Nodes_Limit o
-
end
-
-
2
def visit_Arel_Nodes_Offset o
-
"raw_rnum_ > #{visit o.expr}"
-
end
-
-
2
def visit_Arel_Nodes_Except o
-
"( #{visit o.left} MINUS #{visit o.right} )"
-
end
-
-
2
def visit_Arel_Nodes_UpdateStatement o
-
# Oracle does not allow ORDER BY/LIMIT in UPDATEs.
-
if o.orders.any? && o.limit.nil?
-
# However, there is no harm in silently eating the ORDER BY clause if no LIMIT has been provided,
-
# otherwise let the user deal with the error
-
o = o.dup
-
o.orders = []
-
end
-
-
super
-
end
-
-
###
-
# Hacks for the order clauses specific to Oracle
-
2
def order_hacks o
-
return o if o.orders.empty?
-
return o unless o.cores.any? do |core|
-
core.projections.any? do |projection|
-
/DISTINCT.*FIRST_VALUE/ === projection
-
end
-
end
-
# Previous version with join and split broke ORDER BY clause
-
# if it contained functions with several arguments (separated by ',').
-
#
-
# orders = o.orders.map { |x| visit x }.join(', ').split(',')
-
orders = o.orders.map do |x|
-
string = visit x
-
if string.include?(',')
-
split_order_string(string)
-
else
-
string
-
end
-
end.flatten
-
o.orders = []
-
orders.each_with_index do |order, i|
-
o.orders <<
-
Nodes::SqlLiteral.new("alias_#{i}__#{' DESC' if /\bdesc$/i === order}")
-
end
-
o
-
end
-
-
# Split string by commas but count opening and closing brackets
-
# and ignore commas inside brackets.
-
2
def split_order_string(string)
-
array = []
-
i = 0
-
string.split(',').each do |part|
-
if array[i]
-
array[i] << ',' << part
-
else
-
# to ensure that array[i] will be String and not Arel::Nodes::SqlLiteral
-
array[i] = '' << part
-
end
-
i += 1 if array[i].count('(') == array[i].count(')')
-
end
-
array
-
end
-
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class OrderClauses < Arel::Visitors::ToSql
-
2
private
-
-
2
def visit_Arel_Nodes_SelectStatement o
-
o.orders.map { |x| visit x }
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class PostgreSQL < Arel::Visitors::ToSql
-
2
private
-
-
2
def visit_Arel_Nodes_Matches o
-
"#{visit o.left} ILIKE #{visit o.right}"
-
end
-
-
2
def visit_Arel_Nodes_DoesNotMatch o
-
"#{visit o.left} NOT ILIKE #{visit o.right}"
-
end
-
-
2
def visit_Arel_Nodes_DistinctOn o
-
"DISTINCT ON ( #{visit o.expr} )"
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class SQLite < Arel::Visitors::ToSql
-
2
private
-
-
# Locks are not supported in SQLite
-
2
def visit_Arel_Nodes_Lock o
-
end
-
-
2
def visit_Arel_Nodes_SelectStatement o
-
844
o.limit = Arel::Nodes::Limit.new(-1) if o.offset && !o.limit
-
844
super
-
end
-
end
-
end
-
end
-
2
require 'bigdecimal'
-
2
require 'date'
-
-
2
module Arel
-
2
module Visitors
-
2
class ToSql < Arel::Visitors::Visitor
-
2
attr_accessor :last_column
-
-
2
def initialize connection
-
2
@connection = connection
-
2
@schema_cache = connection.schema_cache
-
2
@quoted_tables = {}
-
2
@quoted_columns = {}
-
2
@last_column = nil
-
end
-
-
2
def accept object
-
1274
self.last_column = nil
-
1274
super
-
end
-
-
2
private
-
2
def visit_Arel_Nodes_DeleteStatement o
-
[
-
24
"DELETE FROM #{visit o.relation}",
-
51
("WHERE #{o.wheres.map { |x| visit x }.join ' AND '}" unless o.wheres.empty?)
-
].compact.join ' '
-
end
-
-
# FIXME: we should probably have a 2-pass visitor for this
-
2
def build_subselect key, o
-
stmt = Nodes::SelectStatement.new
-
core = stmt.cores.first
-
core.froms = o.relation
-
core.wheres = o.wheres
-
core.projections = [key]
-
stmt.limit = o.limit
-
stmt.orders = o.orders
-
stmt
-
end
-
-
2
def visit_Arel_Nodes_UpdateStatement o
-
98
if o.orders.empty? && o.limit.nil?
-
98
wheres = o.wheres
-
else
-
key = o.key
-
unless key
-
warn(<<-eowarn) if $VERBOSE
-
(#{caller.first}) Using UpdateManager without setting UpdateManager#key is
-
deprecated and support will be removed in ARel 4.0.0. Please set the primary
-
key on UpdateManager using UpdateManager#key=
-
eowarn
-
key = o.relation.primary_key
-
end
-
-
wheres = [Nodes::In.new(key, [build_subselect(key, o)])]
-
end
-
-
[
-
98
"UPDATE #{visit o.relation}",
-
256
("SET #{o.values.map { |value| visit value }.join ', '}" unless o.values.empty?),
-
196
("WHERE #{wheres.map { |x| visit x }.join ' AND '}" unless wheres.empty?),
-
].compact.join ' '
-
end
-
-
2
def visit_Arel_Nodes_InsertStatement o
-
[
-
308
"INSERT INTO #{visit o.relation}",
-
-
("(#{o.columns.map { |x|
-
3440
quote_column_name x.name
-
308
}.join ', '})" unless o.columns.empty?),
-
-
308
(visit o.values if o.values),
-
].compact.join ' '
-
end
-
-
2
def visit_Arel_Nodes_Exists o
-
"EXISTS (#{visit o.expressions})#{
-
o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_True o
-
"TRUE"
-
end
-
-
2
def visit_Arel_Nodes_False o
-
"FALSE"
-
end
-
-
2
def table_exists? name
-
1482
@schema_cache.table_exists? name
-
end
-
-
2
def column_for attr
-
1482
name = attr.name.to_s
-
1482
table = attr.relation.table_name
-
-
1482
return nil unless table_exists? table
-
-
1482
column_cache[table][name]
-
end
-
-
2
def column_cache
-
1482
@schema_cache.columns_hash
-
end
-
-
2
def visit_Arel_Nodes_Values o
-
308
"VALUES (#{o.expressions.zip(o.columns).map { |value, attr|
-
3440
if Nodes::SqlLiteral === value
-
3440
visit value
-
else
-
quote(value, attr && column_for(attr))
-
end
-
}.join ', '})"
-
end
-
-
2
def visit_Arel_Nodes_SelectStatement o
-
[
-
844
(visit(o.with) if o.with),
-
844
o.cores.map { |x| visit_Arel_Nodes_SelectCore x }.join,
-
848
("ORDER BY #{o.orders.map { |x| visit x }.join(', ')}" unless o.orders.empty?),
-
844
(visit(o.limit) if o.limit),
-
844
(visit(o.offset) if o.offset),
-
844
(visit(o.lock) if o.lock),
-
].compact.join ' '
-
end
-
-
2
def visit_Arel_Nodes_SelectCore o
-
[
-
844
"SELECT",
-
844
(visit(o.top) if o.top),
-
844
(visit(o.set_quantifier) if o.set_quantifier),
-
1688
("#{o.projections.map { |x| visit x }.join ', '}" unless o.projections.empty?),
-
844
("FROM #{visit(o.source)}" if o.source && !o.source.empty?),
-
1725
("WHERE #{o.wheres.map { |x| visit x }.join ' AND ' }" unless o.wheres.empty?),
-
844
("GROUP BY #{o.groups.map { |x| visit x }.join ', ' }" unless o.groups.empty?),
-
844
(visit(o.having) if o.having),
-
844
("WINDOW #{o.windows.map { |x| visit x }.join ', ' }" unless o.windows.empty?)
-
].compact.join ' '
-
end
-
-
2
def visit_Arel_Nodes_Bin o
-
visit o.expr
-
end
-
-
2
def visit_Arel_Nodes_Distinct o
-
'DISTINCT'
-
end
-
-
2
def visit_Arel_Nodes_DistinctOn o
-
raise NotImplementedError, 'DISTINCT ON not implemented for this db'
-
end
-
-
2
def visit_Arel_Nodes_With o
-
"WITH #{o.children.map { |x| visit x }.join(', ')}"
-
end
-
-
2
def visit_Arel_Nodes_WithRecursive o
-
"WITH RECURSIVE #{o.children.map { |x| visit x }.join(', ')}"
-
end
-
-
2
def visit_Arel_Nodes_Union o
-
"( #{visit o.left} UNION #{visit o.right} )"
-
end
-
-
2
def visit_Arel_Nodes_UnionAll o
-
"( #{visit o.left} UNION ALL #{visit o.right} )"
-
end
-
-
2
def visit_Arel_Nodes_Intersect o
-
"( #{visit o.left} INTERSECT #{visit o.right} )"
-
end
-
-
2
def visit_Arel_Nodes_Except o
-
"( #{visit o.left} EXCEPT #{visit o.right} )"
-
end
-
-
2
def visit_Arel_Nodes_NamedWindow o
-
"#{quote_column_name o.name} AS #{visit_Arel_Nodes_Window o}"
-
end
-
-
2
def visit_Arel_Nodes_Window o
-
s = [
-
("ORDER BY #{o.orders.map { |x| visit(x) }.join(', ')}" unless o.orders.empty?),
-
(visit o.framing if o.framing)
-
].compact.join ' '
-
"(#{s})"
-
end
-
-
2
def visit_Arel_Nodes_Rows o
-
if o.expr
-
"ROWS #{visit o.expr}"
-
else
-
"ROWS"
-
end
-
end
-
-
2
def visit_Arel_Nodes_Range o
-
if o.expr
-
"RANGE #{visit o.expr}"
-
else
-
"RANGE"
-
end
-
end
-
-
2
def visit_Arel_Nodes_Preceding o
-
"#{o.expr ? visit(o.expr) : 'UNBOUNDED'} PRECEDING"
-
end
-
-
2
def visit_Arel_Nodes_Following o
-
"#{o.expr ? visit(o.expr) : 'UNBOUNDED'} FOLLOWING"
-
end
-
-
2
def visit_Arel_Nodes_CurrentRow o
-
"CURRENT ROW"
-
end
-
-
2
def visit_Arel_Nodes_Over o
-
case o.right
-
when nil
-
"#{visit o.left} OVER ()"
-
when Arel::Nodes::SqlLiteral
-
"#{visit o.left} OVER #{visit o.right}"
-
when String, Symbol
-
"#{visit o.left} OVER #{quote_column_name o.right.to_s}"
-
else
-
"#{visit o.left} OVER #{visit o.right}"
-
end
-
end
-
-
2
def visit_Arel_Nodes_Having o
-
"HAVING #{visit o.expr}"
-
end
-
-
2
def visit_Arel_Nodes_Offset o
-
"OFFSET #{visit o.expr}"
-
end
-
-
2
def visit_Arel_Nodes_Limit o
-
363
"LIMIT #{visit o.expr}"
-
end
-
-
# FIXME: this does nothing on most databases, but does on MSSQL
-
2
def visit_Arel_Nodes_Top o
-
363
""
-
end
-
-
2
def visit_Arel_Nodes_Lock o
-
visit o.expr
-
end
-
-
2
def visit_Arel_Nodes_Grouping o
-
454
"(#{visit o.expr})"
-
end
-
-
2
def visit_Arel_Nodes_Ascending o
-
"#{visit o.expr} ASC"
-
end
-
-
2
def visit_Arel_Nodes_Descending o
-
"#{visit o.expr} DESC"
-
end
-
-
2
def visit_Arel_Nodes_Group o
-
visit o.expr
-
end
-
-
2
def visit_Arel_Nodes_NamedFunction o
-
"#{o.name}(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x
-
}.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_Extract o
-
"EXTRACT(#{o.field.to_s.upcase} FROM #{visit o.expr})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_Count o
-
28
"COUNT(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
28
visit x
-
}.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_Sum o
-
"SUM(#{o.expressions.map { |x|
-
visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_Max o
-
"MAX(#{o.expressions.map { |x|
-
visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_Min o
-
"MIN(#{o.expressions.map { |x|
-
visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_Avg o
-
"AVG(#{o.expressions.map { |x|
-
visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
2
def visit_Arel_Nodes_TableAlias o
-
"#{visit o.relation} #{quote_table_name o.name}"
-
end
-
-
2
def visit_Arel_Nodes_Between o
-
"#{visit o.left} BETWEEN #{visit o.right}"
-
end
-
-
2
def visit_Arel_Nodes_GreaterThanOrEqual o
-
"#{visit o.left} >= #{visit o.right}"
-
end
-
-
2
def visit_Arel_Nodes_GreaterThan o
-
"#{visit o.left} > #{visit o.right}"
-
end
-
-
2
def visit_Arel_Nodes_LessThanOrEqual o
-
"#{visit o.left} <= #{visit o.right}"
-
end
-
-
2
def visit_Arel_Nodes_LessThan o
-
"#{visit o.left} < #{visit o.right}"
-
end
-
-
2
def visit_Arel_Nodes_Matches o
-
"#{visit o.left} LIKE #{visit o.right}"
-
end
-
-
2
def visit_Arel_Nodes_DoesNotMatch o
-
"#{visit o.left} NOT LIKE #{visit o.right}"
-
end
-
-
2
def visit_Arel_Nodes_JoinSource o
-
[
-
844
(visit(o.left) if o.left),
-
o.right.map { |j| visit j }.join(' ')
-
].compact.join ' '
-
end
-
-
2
def visit_Arel_Nodes_StringJoin o
-
visit o.left
-
end
-
-
2
def visit_Arel_Nodes_OuterJoin o
-
"LEFT OUTER JOIN #{visit o.left} #{visit o.right}"
-
end
-
-
2
def visit_Arel_Nodes_InnerJoin o
-
"INNER JOIN #{visit o.left} #{visit o.right if o.right}"
-
end
-
-
2
def visit_Arel_Nodes_On o
-
"ON #{visit o.expr}"
-
end
-
-
2
def visit_Arel_Nodes_Not o
-
"NOT (#{visit o.expr})"
-
end
-
-
2
def visit_Arel_Table o
-
1274
if o.table_alias
-
"#{quote_table_name o.name} #{quote_table_name o.table_alias}"
-
else
-
1274
quote_table_name o.name
-
end
-
end
-
-
2
def visit_Arel_Nodes_In o
-
if Array === o.right && o.right.empty?
-
'1=0'
-
else
-
"#{visit o.left} IN (#{visit o.right})"
-
end
-
end
-
-
2
def visit_Arel_Nodes_NotIn o
-
if Array === o.right && o.right.empty?
-
'1=1'
-
else
-
"#{visit o.left} NOT IN (#{visit o.right})"
-
end
-
end
-
-
2
def visit_Arel_Nodes_And o
-
1104
o.children.map { |x| visit x }.join ' AND '
-
end
-
-
2
def visit_Arel_Nodes_Or o
-
"#{visit o.left} OR #{visit o.right}"
-
end
-
-
2
def visit_Arel_Nodes_Assignment o
-
114
right = quote(o.right, column_for(o.left))
-
114
"#{visit o.left} = #{right}"
-
end
-
-
2
def visit_Arel_Nodes_Equality o
-
552
right = o.right
-
-
552
if right.nil?
-
8
"#{visit o.left} IS NULL"
-
else
-
544
"#{visit o.left} = #{visit right}"
-
end
-
end
-
-
2
def visit_Arel_Nodes_NotEqual o
-
right = o.right
-
-
if right.nil?
-
"#{visit o.left} IS NOT NULL"
-
else
-
"#{visit o.left} != #{visit right}"
-
end
-
end
-
-
2
def visit_Arel_Nodes_As o
-
"#{visit o.left} AS #{visit o.right}"
-
end
-
-
2
def visit_Arel_Nodes_UnqualifiedColumn o
-
114
"#{quote_column_name o.name}"
-
end
-
-
2
def visit_Arel_Attributes_Attribute o
-
1368
self.last_column = column_for o
-
1368
join_name = o.relation.table_alias || o.relation.name
-
1368
"#{quote_table_name join_name}.#{quote_column_name o.name}"
-
end
-
2
alias :visit_Arel_Attributes_Integer :visit_Arel_Attributes_Attribute
-
2
alias :visit_Arel_Attributes_Float :visit_Arel_Attributes_Attribute
-
2
alias :visit_Arel_Attributes_Decimal :visit_Arel_Attributes_Attribute
-
2
alias :visit_Arel_Attributes_String :visit_Arel_Attributes_Attribute
-
2
alias :visit_Arel_Attributes_Time :visit_Arel_Attributes_Attribute
-
2
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attributes_Attribute
-
-
4879
def literal o; o end
-
-
2
alias :visit_Arel_Nodes_BindParam :literal
-
2
alias :visit_Arel_Nodes_SqlLiteral :literal
-
2
alias :visit_Arel_SqlLiteral :literal # This is deprecated
-
2
alias :visit_Bignum :literal
-
2
alias :visit_Fixnum :literal
-
-
2
def quoted o
-
quote(o, last_column)
-
end
-
-
2
alias :visit_ActiveSupport_Multibyte_Chars :quoted
-
2
alias :visit_ActiveSupport_StringInquirer :quoted
-
2
alias :visit_BigDecimal :quoted
-
2
alias :visit_Class :quoted
-
2
alias :visit_Date :quoted
-
2
alias :visit_DateTime :quoted
-
2
alias :visit_FalseClass :quoted
-
2
alias :visit_Float :quoted
-
2
alias :visit_Hash :quoted
-
2
alias :visit_NilClass :quoted
-
2
alias :visit_String :quoted
-
2
alias :visit_Symbol :quoted
-
2
alias :visit_Time :quoted
-
2
alias :visit_TrueClass :quoted
-
-
2
def visit_Arel_Nodes_InfixOperation o
-
"#{visit o.left} #{o.operator} #{visit o.right}"
-
end
-
-
2
alias :visit_Arel_Nodes_Addition :visit_Arel_Nodes_InfixOperation
-
2
alias :visit_Arel_Nodes_Subtraction :visit_Arel_Nodes_InfixOperation
-
2
alias :visit_Arel_Nodes_Multiplication :visit_Arel_Nodes_InfixOperation
-
2
alias :visit_Arel_Nodes_Division :visit_Arel_Nodes_InfixOperation
-
-
2
def visit_Array o
-
o.empty? ? 'NULL' : o.map { |x| visit x }.join(', ')
-
end
-
-
2
def quote value, column = nil
-
114
@connection.quote value, column
-
end
-
-
2
def quote_table_name name
-
2642
return name if Arel::Nodes::SqlLiteral === name
-
2642
@quoted_tables[name] ||= @connection.quote_table_name(name)
-
end
-
-
2
def quote_column_name name
-
4922
@quoted_columns[name] ||= Arel::Nodes::SqlLiteral === name ? name : @connection.quote_column_name(name)
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class Visitor
-
2
def accept object
-
1302
visit object
-
end
-
-
2
private
-
-
2
DISPATCH = Hash.new do |hash, klass|
-
39
hash[klass] = "visit_#{(klass.name || '').gsub('::', '_')}"
-
end
-
-
2
def dispatch
-
13206
DISPATCH
-
end
-
-
2
def visit object
-
13206
send dispatch[object.class], object
-
rescue NoMethodError => e
-
raise e if respond_to?(dispatch[object.class], true)
-
superklass = object.class.ancestors.find { |klass|
-
respond_to?(dispatch[klass], true)
-
}
-
raise(TypeError, "Cannot visit #{object.class}") unless superklass
-
dispatch[object.class] = dispatch[superklass]
-
retry
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module Visitors
-
2
class WhereSql < Arel::Visitors::ToSql
-
2
def visit_Arel_Nodes_SelectCore o
-
"WHERE #{o.wheres.map { |x| visit x }.join ' AND ' }"
-
end
-
end
-
end
-
end
-
2
module Arel
-
2
module WindowPredications
-
-
2
def over(expr = nil)
-
Nodes::Over.new(self, expr)
-
end
-
-
end
-
end
-
2
require 'cancan/ability'
-
2
require 'cancan/rule'
-
2
require 'cancan/controller_resource'
-
2
require 'cancan/controller_additions'
-
2
require 'cancan/model_additions'
-
2
require 'cancan/exceptions'
-
2
require 'cancan/inherited_resource'
-
-
2
require 'cancan/model_adapters/abstract_adapter'
-
2
require 'cancan/model_adapters/default_adapter'
-
2
require 'cancan/model_adapters/active_record_adapter' if defined? ActiveRecord
-
2
require 'cancan/model_adapters/data_mapper_adapter' if defined? DataMapper
-
2
require 'cancan/model_adapters/mongoid_adapter' if defined?(Mongoid) && defined?(Mongoid::Document)
-
2
module CanCan
-
-
# This module is designed to be included into an Ability class. This will
-
# provide the "can" methods for defining and checking abilities.
-
#
-
# class Ability
-
# include CanCan::Ability
-
#
-
# def initialize(user)
-
# if user.admin?
-
# can :manage, :all
-
# else
-
# can :read, :all
-
# end
-
# end
-
# end
-
#
-
2
module Ability
-
# Check if the user has permission to perform a given action on an object.
-
#
-
# can? :destroy, @project
-
#
-
# You can also pass the class instead of an instance (if you don't have one handy).
-
#
-
# can? :create, Project
-
#
-
# Nested resources can be passed through a hash, this way conditions which are
-
# dependent upon the association will work when using a class.
-
#
-
# can? :create, @category => Project
-
#
-
# Any additional arguments will be passed into the "can" block definition. This
-
# can be used to pass more information about the user's request for example.
-
#
-
# can? :create, Project, request.remote_ip
-
#
-
# can :create Project do |project, remote_ip|
-
# # ...
-
# end
-
#
-
# Not only can you use the can? method in the controller and view (see ControllerAdditions),
-
# but you can also call it directly on an ability instance.
-
#
-
# ability.can? :destroy, @project
-
#
-
# This makes testing a user's abilities very easy.
-
#
-
# def test "user can only destroy projects which he owns"
-
# user = User.new
-
# ability = Ability.new(user)
-
# assert ability.can?(:destroy, Project.new(:user => user))
-
# assert ability.cannot?(:destroy, Project.new)
-
# end
-
#
-
# Also see the RSpec Matchers to aid in testing.
-
2
def can?(action, subject, *extra_args)
-
match = relevant_rules_for_match(action, subject).detect do |rule|
-
rule.matches_conditions?(action, subject, extra_args)
-
end
-
match ? match.base_behavior : false
-
end
-
-
# Convenience method which works the same as "can?" but returns the opposite value.
-
#
-
# cannot? :destroy, @project
-
#
-
2
def cannot?(*args)
-
!can?(*args)
-
end
-
-
# Defines which abilities are allowed using two arguments. The first one is the action
-
# you're setting the permission for, the second one is the class of object you're setting it on.
-
#
-
# can :update, Article
-
#
-
# You can pass an array for either of these parameters to match any one.
-
# Here the user has the ability to update or destroy both articles and comments.
-
#
-
# can [:update, :destroy], [Article, Comment]
-
#
-
# You can pass :all to match any object and :manage to match any action. Here are some examples.
-
#
-
# can :manage, :all
-
# can :update, :all
-
# can :manage, Project
-
#
-
# You can pass a hash of conditions as the third argument. Here the user can only see active projects which he owns.
-
#
-
# can :read, Project, :active => true, :user_id => user.id
-
#
-
# See ActiveRecordAdditions#accessible_by for how to use this in database queries. These conditions
-
# are also used for initial attributes when building a record in ControllerAdditions#load_resource.
-
#
-
# If the conditions hash does not give you enough control over defining abilities, you can use a block
-
# along with any Ruby code you want.
-
#
-
# can :update, Project do |project|
-
# project.groups.include?(user.group)
-
# end
-
#
-
# If the block returns true then the user has that :update ability for that project, otherwise he
-
# will be denied access. The downside to using a block is that it cannot be used to generate
-
# conditions for database queries.
-
#
-
# You can pass custom objects into this "can" method, this is usually done with a symbol
-
# and is useful if a class isn't available to define permissions on.
-
#
-
# can :read, :stats
-
# can? :read, :stats # => true
-
#
-
# IMPORTANT: Neither a hash of conditions or a block will be used when checking permission on a class.
-
#
-
# can :update, Project, :priority => 3
-
# can? :update, Project # => true
-
#
-
# If you pass no arguments to +can+, the action, class, and object will be passed to the block and the
-
# block will always be executed. This allows you to override the full behavior if the permissions are
-
# defined in an external source such as the database.
-
#
-
# can do |action, object_class, object|
-
# # check the database and return true/false
-
# end
-
#
-
2
def can(action = nil, subject = nil, conditions = nil, &block)
-
rules << Rule.new(true, action, subject, conditions, block)
-
end
-
-
# Defines an ability which cannot be done. Accepts the same arguments as "can".
-
#
-
# can :read, :all
-
# cannot :read, Comment
-
#
-
# A block can be passed just like "can", however if the logic is complex it is recommended
-
# to use the "can" method.
-
#
-
# cannot :read, Product do |product|
-
# product.invisible?
-
# end
-
#
-
2
def cannot(action = nil, subject = nil, conditions = nil, &block)
-
rules << Rule.new(false, action, subject, conditions, block)
-
end
-
-
# Alias one or more actions into another one.
-
#
-
# alias_action :update, :destroy, :to => :modify
-
# can :modify, Comment
-
#
-
# Then :modify permission will apply to both :update and :destroy requests.
-
#
-
# can? :update, Comment # => true
-
# can? :destroy, Comment # => true
-
#
-
# This only works in one direction. Passing the aliased action into the "can?" call
-
# will not work because aliases are meant to generate more generic actions.
-
#
-
# alias_action :update, :destroy, :to => :modify
-
# can :update, Comment
-
# can? :modify, Comment # => false
-
#
-
# Unless that exact alias is used.
-
#
-
# can :modify, Comment
-
# can? :modify, Comment # => true
-
#
-
# The following aliases are added by default for conveniently mapping common controller actions.
-
#
-
# alias_action :index, :show, :to => :read
-
# alias_action :new, :to => :create
-
# alias_action :edit, :to => :update
-
#
-
# This way one can use params[:action] in the controller to determine the permission.
-
2
def alias_action(*args)
-
target = args.pop[:to]
-
validate_target(target)
-
aliased_actions[target] ||= []
-
aliased_actions[target] += args
-
end
-
-
# User shouldn't specify targets with names of real actions or it will cause Seg fault
-
2
def validate_target(target)
-
raise Error, "You can't specify target (#{target}) as alias because it is real action name" if aliased_actions.values.flatten.include? target
-
end
-
-
# Returns a hash of aliased actions. The key is the target and the value is an array of actions aliasing the key.
-
2
def aliased_actions
-
@aliased_actions ||= default_alias_actions
-
end
-
-
# Removes previously aliased actions including the defaults.
-
2
def clear_aliased_actions
-
@aliased_actions = {}
-
end
-
-
2
def model_adapter(model_class, action)
-
adapter_class = ModelAdapters::AbstractAdapter.adapter_class(model_class)
-
adapter_class.new(model_class, relevant_rules_for_query(action, model_class))
-
end
-
-
# See ControllerAdditions#authorize! for documentation.
-
2
def authorize!(action, subject, *args)
-
message = nil
-
if args.last.kind_of?(Hash) && args.last.has_key?(:message)
-
message = args.pop[:message]
-
end
-
if cannot?(action, subject, *args)
-
message ||= unauthorized_message(action, subject)
-
raise AccessDenied.new(message, action, subject)
-
end
-
subject
-
end
-
-
2
def unauthorized_message(action, subject)
-
keys = unauthorized_message_keys(action, subject)
-
variables = {:action => action.to_s}
-
variables[:subject] = (subject.class == Class ? subject : subject.class).to_s.underscore.humanize.downcase
-
message = I18n.translate(nil, variables.merge(:scope => :unauthorized, :default => keys + [""]))
-
message.blank? ? nil : message
-
end
-
-
2
def attributes_for(action, subject)
-
attributes = {}
-
relevant_rules(action, subject).map do |rule|
-
attributes.merge!(rule.attributes_from_conditions) if rule.base_behavior
-
end
-
attributes
-
end
-
-
2
def has_block?(action, subject)
-
relevant_rules(action, subject).any?(&:only_block?)
-
end
-
-
2
def has_raw_sql?(action, subject)
-
relevant_rules(action, subject).any?(&:only_raw_sql?)
-
end
-
-
2
def merge(ability)
-
ability.send(:rules).each do |rule|
-
rules << rule.dup
-
end
-
self
-
end
-
-
2
private
-
-
2
def unauthorized_message_keys(action, subject)
-
subject = (subject.class == Class ? subject : subject.class).name.underscore unless subject.kind_of? Symbol
-
[subject, :all].map do |try_subject|
-
[aliases_for_action(action), :manage].flatten.map do |try_action|
-
:"#{try_action}.#{try_subject}"
-
end
-
end.flatten
-
end
-
-
# Accepts an array of actions and returns an array of actions which match.
-
# This should be called before "matches?" and other checking methods since they
-
# rely on the actions to be expanded.
-
2
def expand_actions(actions)
-
actions.map do |action|
-
aliased_actions[action] ? [action, *expand_actions(aliased_actions[action])] : action
-
end.flatten
-
end
-
-
# Given an action, it will try to find all of the actions which are aliased to it.
-
# This does the opposite kind of lookup as expand_actions.
-
2
def aliases_for_action(action)
-
results = [action]
-
aliased_actions.each do |aliased_action, actions|
-
results += aliases_for_action(aliased_action) if actions.include? action
-
end
-
results
-
end
-
-
2
def rules
-
@rules ||= []
-
end
-
-
# Returns an array of Rule instances which match the action and subject
-
# This does not take into consideration any hash conditions or block statements
-
2
def relevant_rules(action, subject)
-
rules.reverse.select do |rule|
-
rule.expanded_actions = expand_actions(rule.actions)
-
rule.relevant? action, subject
-
end
-
end
-
-
2
def relevant_rules_for_match(action, subject)
-
relevant_rules(action, subject).each do |rule|
-
if rule.only_raw_sql?
-
raise Error, "The can? and cannot? call cannot be used with a raw sql 'can' definition. The checking code cannot be determined for #{action.inspect} #{subject.inspect}"
-
end
-
end
-
end
-
-
2
def relevant_rules_for_query(action, subject)
-
relevant_rules(action, subject).each do |rule|
-
if rule.only_block?
-
raise Error, "The accessible_by call cannot be used with a block 'can' definition. The SQL cannot be determined for #{action.inspect} #{subject.inspect}"
-
end
-
end
-
end
-
-
2
def default_alias_actions
-
{
-
:read => [:index, :show],
-
:create => [:new],
-
:update => [:edit],
-
}
-
end
-
end
-
end
-
2
module CanCan
-
-
# This module is automatically included into all controllers.
-
# It also makes the "can?" and "cannot?" methods available to all views.
-
2
module ControllerAdditions
-
2
module ClassMethods
-
# Sets up a before filter which loads and authorizes the current resource. This performs both
-
# load_resource and authorize_resource and accepts the same arguments. See those methods for details.
-
#
-
# class BooksController < ApplicationController
-
# load_and_authorize_resource
-
# end
-
#
-
2
def load_and_authorize_resource(*args)
-
16
cancan_resource_class.add_before_filter(self, :load_and_authorize_resource, *args)
-
end
-
-
# Sets up a before filter which loads the model resource into an instance variable.
-
# For example, given an ArticlesController it will load the current article into the @article
-
# instance variable. It does this by either calling Article.find(params[:id]) or
-
# Article.new(params[:article]) depending upon the action. The index action will
-
# automatically set @articles to Article.accessible_by(current_ability).
-
#
-
# If a conditions hash is used in the Ability, the +new+ and +create+ actions will set
-
# the initial attributes based on these conditions. This way these actions will satisfy
-
# the ability restrictions.
-
#
-
# Call this method directly on the controller class.
-
#
-
# class BooksController < ApplicationController
-
# load_resource
-
# end
-
#
-
# A resource is not loaded if the instance variable is already set. This makes it easy to override
-
# the behavior through a before_filter on certain actions.
-
#
-
# class BooksController < ApplicationController
-
# before_filter :find_book_by_permalink, :only => :show
-
# load_resource
-
#
-
# private
-
#
-
# def find_book_by_permalink
-
# @book = Book.find_by_permalink!(params[:id)
-
# end
-
# end
-
#
-
# If a name is provided which does not match the controller it assumes it is a parent resource. Child
-
# resources can then be loaded through it.
-
#
-
# class BooksController < ApplicationController
-
# load_resource :author
-
# load_resource :book, :through => :author
-
# end
-
#
-
# Here the author resource will be loaded before each action using params[:author_id]. The book resource
-
# will then be loaded through the @author instance variable.
-
#
-
# That first argument is optional and will default to the singular name of the controller.
-
# A hash of options (see below) can also be passed to this method to further customize it.
-
#
-
# See load_and_authorize_resource to automatically authorize the resource too.
-
#
-
# Options:
-
# [:+only+]
-
# Only applies before filter to given actions.
-
#
-
# [:+except+]
-
# Does not apply before filter to given actions.
-
#
-
# [:+through+]
-
# Load this resource through another one. This should match the name of the parent instance variable or method.
-
#
-
# [:+through_association+]
-
# The name of the association to fetch the child records through the parent resource. This is normally not needed
-
# because it defaults to the pluralized resource name.
-
#
-
# [:+shallow+]
-
# Pass +true+ to allow this resource to be loaded directly when parent is +nil+. Defaults to +false+.
-
#
-
# [:+singleton+]
-
# Pass +true+ if this is a singleton resource through a +has_one+ association.
-
#
-
# [:+parent+]
-
# True or false depending on if the resource is considered a parent resource. This defaults to +true+ if a resource
-
# name is given which does not match the controller.
-
#
-
# [:+class+]
-
# The class to use for the model (string or constant).
-
#
-
# [:+instance_name+]
-
# The name of the instance variable to load the resource into.
-
#
-
# [:+find_by+]
-
# Find using a different attribute other than id. For example.
-
#
-
# load_resource :find_by => :permalink # will use find_by_permalink!(params[:id])
-
#
-
# [:+id_param+]
-
# Find using a param key other than :id. For example:
-
#
-
# load_resource :id_key => :url # will use find(params[:url])
-
#
-
# [:+collection+]
-
# Specify which actions are resource collection actions in addition to :+index+. This
-
# is usually not necessary because it will try to guess depending on if the id param is present.
-
#
-
# load_resource :collection => [:sort, :list]
-
#
-
# [:+new+]
-
# Specify which actions are new resource actions in addition to :+new+ and :+create+.
-
# Pass an action name into here if you would like to build a new resource instead of
-
# fetch one.
-
#
-
# load_resource :new => :build
-
#
-
# [:+prepend+]
-
# Passing +true+ will use prepend_before_filter instead of a normal before_filter.
-
#
-
2
def load_resource(*args)
-
cancan_resource_class.add_before_filter(self, :load_resource, *args)
-
end
-
-
# Sets up a before filter which authorizes the resource using the instance variable.
-
# For example, if you have an ArticlesController it will check the @article instance variable
-
# and ensure the user can perform the current action on it. Under the hood it is doing
-
# something like the following.
-
#
-
# authorize!(params[:action].to_sym, @article || Article)
-
#
-
# Call this method directly on the controller class.
-
#
-
# class BooksController < ApplicationController
-
# authorize_resource
-
# end
-
#
-
# If you pass in the name of a resource which does not match the controller it will assume
-
# it is a parent resource.
-
#
-
# class BooksController < ApplicationController
-
# authorize_resource :author
-
# authorize_resource :book
-
# end
-
#
-
# Here it will authorize :+show+, @+author+ on every action before authorizing the book.
-
#
-
# That first argument is optional and will default to the singular name of the controller.
-
# A hash of options (see below) can also be passed to this method to further customize it.
-
#
-
# See load_and_authorize_resource to automatically load the resource too.
-
#
-
# Options:
-
# [:+only+]
-
# Only applies before filter to given actions.
-
#
-
# [:+except+]
-
# Does not apply before filter to given actions.
-
#
-
# [:+singleton+]
-
# Pass +true+ if this is a singleton resource through a +has_one+ association.
-
#
-
# [:+parent+]
-
# True or false depending on if the resource is considered a parent resource. This defaults to +true+ if a resource
-
# name is given which does not match the controller.
-
#
-
# [:+class+]
-
# The class to use for the model (string or constant). This passed in when the instance variable is not set.
-
# Pass +false+ if there is no associated class for this resource and it will use a symbol of the resource name.
-
#
-
# [:+instance_name+]
-
# The name of the instance variable for this resource.
-
#
-
# [:+through+]
-
# Authorize conditions on this parent resource when instance isn't available.
-
#
-
# [:+prepend+]
-
# Passing +true+ will use prepend_before_filter instead of a normal before_filter.
-
#
-
2
def authorize_resource(*args)
-
4
cancan_resource_class.add_before_filter(self, :authorize_resource, *args)
-
end
-
-
# Skip both the loading and authorization behavior of CanCan for this given controller. This is primarily
-
# useful to skip the behavior of a superclass. You can pass :only and :except options to specify which actions
-
# to skip the effects on. It will apply to all actions by default.
-
#
-
# class ProjectsController < SomeOtherController
-
# skip_load_and_authorize_resource :only => :index
-
# end
-
#
-
# You can also pass the resource name as the first argument to skip that resource.
-
2
def skip_load_and_authorize_resource(*args)
-
skip_load_resource(*args)
-
skip_authorize_resource(*args)
-
end
-
-
# Skip the loading behavior of CanCan. This is useful when using +load_and_authorize_resource+ but want to
-
# only do authorization on certain actions. You can pass :only and :except options to specify which actions to
-
# skip the effects on. It will apply to all actions by default.
-
#
-
# class ProjectsController < ApplicationController
-
# load_and_authorize_resource
-
# skip_load_resource :only => :index
-
# end
-
#
-
# You can also pass the resource name as the first argument to skip that resource.
-
2
def skip_load_resource(*args)
-
options = args.extract_options!
-
name = args.first
-
cancan_skipper[:load][name] = options
-
end
-
-
# Skip the authorization behavior of CanCan. This is useful when using +load_and_authorize_resource+ but want to
-
# only do loading on certain actions. You can pass :only and :except options to specify which actions to
-
# skip the effects on. It will apply to all actions by default.
-
#
-
# class ProjectsController < ApplicationController
-
# load_and_authorize_resource
-
# skip_authorize_resource :only => :index
-
# end
-
#
-
# You can also pass the resource name as the first argument to skip that resource.
-
2
def skip_authorize_resource(*args)
-
8
options = args.extract_options!
-
8
name = args.first
-
8
cancan_skipper[:authorize][name] = options
-
end
-
-
# Add this to a controller to ensure it performs authorization through +authorized+! or +authorize_resource+ call.
-
# If neither of these authorization methods are called, a CanCan::AuthorizationNotPerformed exception will be raised.
-
# This is normally added to the ApplicationController to ensure all controller actions do authorization.
-
#
-
# class ApplicationController < ActionController::Base
-
# check_authorization
-
# end
-
#
-
# See skip_authorization_check to bypass this check on specific controller actions.
-
#
-
# Options:
-
# [:+only+]
-
# Only applies to given actions.
-
#
-
# [:+except+]
-
# Does not apply to given actions.
-
#
-
# [:+if+]
-
# Supply the name of a controller method to be called. The authorization check only takes place if this returns true.
-
#
-
# check_authorization :if => :admin_controller?
-
#
-
# [:+unless+]
-
# Supply the name of a controller method to be called. The authorization check only takes place if this returns false.
-
#
-
# check_authorization :unless => :devise_controller?
-
#
-
2
def check_authorization(options = {})
-
self.after_filter(options.slice(:only, :except)) do |controller|
-
next if controller.instance_variable_defined?(:@_authorized)
-
next if options[:if] && !controller.send(options[:if])
-
next if options[:unless] && controller.send(options[:unless])
-
raise AuthorizationNotPerformed, "This action failed the check_authorization because it does not authorize_resource. Add skip_authorization_check to bypass this check."
-
end
-
end
-
-
# Call this in the class of a controller to skip the check_authorization behavior on the actions.
-
#
-
# class HomeController < ApplicationController
-
# skip_authorization_check :only => :index
-
# end
-
#
-
# Any arguments are passed to the +before_filter+ it triggers.
-
2
def skip_authorization_check(*args)
-
self.before_filter(*args) do |controller|
-
controller.instance_variable_set(:@_authorized, true)
-
end
-
end
-
-
2
def skip_authorization(*args)
-
raise ImplementationRemoved, "The CanCan skip_authorization method has been renamed to skip_authorization_check. Please update your code."
-
end
-
-
2
def cancan_resource_class
-
20
if ancestors.map(&:to_s).include? "InheritedResources::Actions"
-
InheritedResource
-
else
-
20
ControllerResource
-
end
-
end
-
-
2
def cancan_skipper
-
8
@_cancan_skipper ||= {:authorize => {}, :load => {}}
-
end
-
end
-
-
2
def self.included(base)
-
2
base.extend ClassMethods
-
2
base.helper_method :can?, :cannot?, :current_ability
-
end
-
-
# Raises a CanCan::AccessDenied exception if the current_ability cannot
-
# perform the given action. This is usually called in a controller action or
-
# before filter to perform the authorization.
-
#
-
# def show
-
# @article = Article.find(params[:id])
-
# authorize! :read, @article
-
# end
-
#
-
# A :message option can be passed to specify a different message.
-
#
-
# authorize! :read, @article, :message => "Not authorized to read #{@article.name}"
-
#
-
# You can also use I18n to customize the message. Action aliases defined in Ability work here.
-
#
-
# en:
-
# unauthorized:
-
# manage:
-
# all: "Not authorized to %{action} %{subject}."
-
# user: "Not allowed to manage other user accounts."
-
# update:
-
# project: "Not allowed to update this project."
-
#
-
# You can rescue from the exception in the controller to customize how unauthorized
-
# access is displayed to the user.
-
#
-
# class ApplicationController < ActionController::Base
-
# rescue_from CanCan::AccessDenied do |exception|
-
# redirect_to root_url, :alert => exception.message
-
# end
-
# end
-
#
-
# See the CanCan::AccessDenied exception for more details on working with the exception.
-
#
-
# See the load_and_authorize_resource method to automatically add the authorize! behavior
-
# to the default RESTful actions.
-
2
def authorize!(*args)
-
@_authorized = true
-
current_ability.authorize!(*args)
-
end
-
-
2
def unauthorized!(message = nil)
-
raise ImplementationRemoved, "The unauthorized! method has been removed from CanCan, use authorize! instead."
-
end
-
-
# Creates and returns the current user's ability and caches it. If you
-
# want to override how the Ability is defined then this is the place.
-
# Just define the method in the controller to change behavior.
-
#
-
# def current_ability
-
# # instead of Ability.new(current_user)
-
# @current_ability ||= UserAbility.new(current_account)
-
# end
-
#
-
# Notice it is important to cache the ability object so it is not
-
# recreated every time.
-
2
def current_ability
-
@current_ability ||= ::Ability.new(current_user)
-
end
-
-
# Use in the controller or view to check the user's permission for a given action
-
# and object.
-
#
-
# can? :destroy, @project
-
#
-
# You can also pass the class instead of an instance (if you don't have one handy).
-
#
-
# <% if can? :create, Project %>
-
# <%= link_to "New Project", new_project_path %>
-
# <% end %>
-
#
-
# If it's a nested resource, you can pass the parent instance in a hash. This way it will
-
# check conditions which reach through that association.
-
#
-
# <% if can? :create, @category => Project %>
-
# <%= link_to "New Project", new_project_path %>
-
# <% end %>
-
#
-
# This simply calls "can?" on the current_ability. See Ability#can?.
-
2
def can?(*args)
-
current_ability.can?(*args)
-
end
-
-
# Convenience method which works the same as "can?" but returns the opposite value.
-
#
-
# cannot? :destroy, @project
-
#
-
2
def cannot?(*args)
-
current_ability.cannot?(*args)
-
end
-
end
-
end
-
-
2
if defined? ActionController::Base
-
2
ActionController::Base.class_eval do
-
2
include CanCan::ControllerAdditions
-
end
-
end
-
2
module CanCan
-
# Handle the load and authorization controller logic so we don't clutter up all controllers with non-interface methods.
-
# This class is used internally, so you do not need to call methods directly on it.
-
2
class ControllerResource # :nodoc:
-
2
def self.add_before_filter(controller_class, method, *args)
-
20
options = args.extract_options!
-
20
resource_name = args.first
-
20
before_filter_method = options.delete(:prepend) ? :prepend_before_filter : :before_filter
-
20
controller_class.send(before_filter_method, options.slice(:only, :except, :if, :unless)) do |controller|
-
controller.class.cancan_resource_class.new(controller, resource_name, options.except(:only, :except, :if, :unless)).send(method)
-
end
-
end
-
-
2
def initialize(controller, *args)
-
@controller = controller
-
@params = controller.params
-
@options = args.extract_options!
-
@name = args.first
-
raise CanCan::ImplementationRemoved, "The :nested option is no longer supported, instead use :through with separate load/authorize call." if @options[:nested]
-
raise CanCan::ImplementationRemoved, "The :name option is no longer supported, instead pass the name as the first argument." if @options[:name]
-
raise CanCan::ImplementationRemoved, "The :resource option has been renamed back to :class, use false if no class." if @options[:resource]
-
end
-
-
2
def load_and_authorize_resource
-
load_resource
-
authorize_resource
-
end
-
-
2
def load_resource
-
unless skip?(:load)
-
if load_instance?
-
self.resource_instance ||= load_resource_instance
-
elsif load_collection?
-
self.collection_instance ||= load_collection
-
end
-
end
-
end
-
-
2
def authorize_resource
-
unless skip?(:authorize)
-
@controller.authorize!(authorization_action, resource_instance || resource_class_with_parent)
-
end
-
end
-
-
2
def parent?
-
@options.has_key?(:parent) ? @options[:parent] : @name && @name != name_from_controller.to_sym
-
end
-
-
2
def skip?(behavior) # This could probably use some refactoring
-
options = @controller.class.cancan_skipper[behavior][@name]
-
if options.nil?
-
false
-
elsif options == {}
-
true
-
elsif options[:except] && ![options[:except]].flatten.include?(@params[:action].to_sym)
-
true
-
elsif [options[:only]].flatten.include?(@params[:action].to_sym)
-
true
-
end
-
end
-
-
2
protected
-
-
2
def load_resource_instance
-
if !parent? && new_actions.include?(@params[:action].to_sym)
-
build_resource
-
elsif id_param || @options[:singleton]
-
find_resource
-
end
-
end
-
-
2
def load_instance?
-
parent? || member_action?
-
end
-
-
2
def load_collection?
-
resource_base.respond_to?(:accessible_by) && !current_ability.has_block?(authorization_action, resource_class)
-
end
-
-
2
def load_collection
-
resource_base.accessible_by(current_ability, authorization_action)
-
end
-
-
2
def build_resource
-
resource = resource_base.new(resource_params || {})
-
assign_attributes(resource)
-
end
-
-
2
def assign_attributes(resource)
-
resource.send("#{parent_name}=", parent_resource) if @options[:singleton] && parent_resource
-
initial_attributes.each do |attr_name, value|
-
resource.send("#{attr_name}=", value)
-
end
-
resource
-
end
-
-
2
def initial_attributes
-
current_ability.attributes_for(@params[:action].to_sym, resource_class).delete_if do |key, value|
-
resource_params && resource_params.include?(key)
-
end
-
end
-
-
2
def find_resource
-
if @options[:singleton] && parent_resource.respond_to?(name)
-
parent_resource.send(name)
-
else
-
if @options[:find_by]
-
if resource_base.respond_to? "find_by_#{@options[:find_by]}!"
-
resource_base.send("find_by_#{@options[:find_by]}!", id_param)
-
elsif resource_base.respond_to? "find_by"
-
resource_base.send("find_by", { @options[:find_by].to_sym => id_param })
-
else
-
resource_base.send(@options[:find_by], id_param)
-
end
-
else
-
adapter.find(resource_base, id_param)
-
end
-
end
-
end
-
-
2
def adapter
-
ModelAdapters::AbstractAdapter.adapter_class(resource_class)
-
end
-
-
2
def authorization_action
-
parent? ? :show : @params[:action].to_sym
-
end
-
-
2
def id_param
-
if @options[:id_param]
-
@params[@options[:id_param]]
-
else
-
@params[parent? ? :"#{name}_id" : :id]
-
end.to_s
-
end
-
-
2
def member_action?
-
new_actions.include?(@params[:action].to_sym) || @options[:singleton] || ( (@params[:id] || @params[@options[:id_param]]) && !collection_actions.include?(@params[:action].to_sym))
-
end
-
-
# Returns the class used for this resource. This can be overriden by the :class option.
-
# If +false+ is passed in it will use the resource name as a symbol in which case it should
-
# only be used for authorization, not loading since there's no class to load through.
-
2
def resource_class
-
case @options[:class]
-
when false then name.to_sym
-
when nil then namespaced_name.to_s.camelize.constantize
-
when String then @options[:class].constantize
-
else @options[:class]
-
end
-
end
-
-
2
def resource_class_with_parent
-
parent_resource ? {parent_resource => resource_class} : resource_class
-
end
-
-
2
def resource_instance=(instance)
-
@controller.instance_variable_set("@#{instance_name}", instance)
-
end
-
-
2
def resource_instance
-
@controller.instance_variable_get("@#{instance_name}") if load_instance?
-
end
-
-
2
def collection_instance=(instance)
-
@controller.instance_variable_set("@#{instance_name.to_s.pluralize}", instance)
-
end
-
-
2
def collection_instance
-
@controller.instance_variable_get("@#{instance_name.to_s.pluralize}")
-
end
-
-
# The object that methods (such as "find", "new" or "build") are called on.
-
# If the :through option is passed it will go through an association on that instance.
-
# If the :shallow option is passed it will use the resource_class if there's no parent
-
# If the :singleton option is passed it won't use the association because it needs to be handled later.
-
2
def resource_base
-
if @options[:through]
-
if parent_resource
-
@options[:singleton] ? resource_class : parent_resource.send(@options[:through_association] || name.to_s.pluralize)
-
elsif @options[:shallow]
-
resource_class
-
else
-
raise AccessDenied.new(nil, authorization_action, resource_class) # maybe this should be a record not found error instead?
-
end
-
else
-
resource_class
-
end
-
end
-
-
2
def parent_name
-
@options[:through] && [@options[:through]].flatten.detect { |i| fetch_parent(i) }
-
end
-
-
# The object to load this resource through.
-
2
def parent_resource
-
parent_name && fetch_parent(parent_name)
-
end
-
-
2
def fetch_parent(name)
-
if @controller.instance_variable_defined? "@#{name}"
-
@controller.instance_variable_get("@#{name}")
-
elsif @controller.respond_to?(name, true)
-
@controller.send(name)
-
end
-
end
-
-
2
def current_ability
-
@controller.send(:current_ability)
-
end
-
-
2
def name
-
@name || name_from_controller
-
end
-
-
2
def resource_params
-
if @options[:class]
-
params_key = extract_key(@options[:class])
-
return @params[params_key] if @params[params_key]
-
end
-
-
resource_params_by_namespaced_name
-
end
-
-
2
def resource_params_by_namespaced_name
-
@params[extract_key(namespaced_name)]
-
end
-
-
2
def namespace
-
@params[:controller].split(/::|\//)[0..-2]
-
end
-
-
2
def namespaced_name
-
[namespace, name.camelize].join('::').singularize.camelize.constantize
-
rescue NameError
-
name
-
end
-
-
2
def name_from_controller
-
@params[:controller].sub("Controller", "").underscore.split('/').last.singularize
-
end
-
-
2
def instance_name
-
@options[:instance_name] || name
-
end
-
-
2
def collection_actions
-
[:index] + [@options[:collection]].flatten
-
end
-
-
2
def new_actions
-
[:new, :create] + [@options[:new]].flatten
-
end
-
-
2
private
-
-
2
def extract_key(value)
-
value.to_s.underscore.gsub('/', '_')
-
end
-
end
-
end
-
2
module CanCan
-
# A general CanCan exception
-
2
class Error < StandardError; end
-
-
# Raised when behavior is not implemented, usually used in an abstract class.
-
2
class NotImplemented < Error; end
-
-
# Raised when removed code is called, an alternative solution is provided in message.
-
2
class ImplementationRemoved < Error; end
-
-
# Raised when using check_authorization without calling authorized!
-
2
class AuthorizationNotPerformed < Error; end
-
-
# This error is raised when a user isn't allowed to access a given controller action.
-
# This usually happens within a call to ControllerAdditions#authorize! but can be
-
# raised manually.
-
#
-
# raise CanCan::AccessDenied.new("Not authorized!", :read, Article)
-
#
-
# The passed message, action, and subject are optional and can later be retrieved when
-
# rescuing from the exception.
-
#
-
# exception.message # => "Not authorized!"
-
# exception.action # => :read
-
# exception.subject # => Article
-
#
-
# If the message is not specified (or is nil) it will default to "You are not authorized
-
# to access this page." This default can be overridden by setting default_message.
-
#
-
# exception.default_message = "Default error message"
-
# exception.message # => "Default error message"
-
#
-
# See ControllerAdditions#authorized! for more information on rescuing from this exception
-
# and customizing the message using I18n.
-
2
class AccessDenied < Error
-
2
attr_reader :action, :subject
-
2
attr_writer :default_message
-
-
2
def initialize(message = nil, action = nil, subject = nil)
-
@message = message
-
@action = action
-
@subject = subject
-
@default_message = I18n.t(:"unauthorized.default", :default => "You are not authorized to access this page.")
-
end
-
-
2
def to_s
-
@message || @default_message
-
end
-
end
-
end
-
2
module CanCan
-
# For use with Inherited Resources
-
2
class InheritedResource < ControllerResource # :nodoc:
-
2
def load_resource_instance
-
if parent?
-
@controller.send :association_chain
-
@controller.instance_variable_get("@#{instance_name}")
-
elsif new_actions.include? @params[:action].to_sym
-
resource = @controller.send :build_resource
-
assign_attributes(resource)
-
else
-
@controller.send :resource
-
end
-
end
-
-
2
def resource_base
-
@controller.send :end_of_association_chain
-
end
-
end
-
end
-
2
module CanCan
-
2
module ModelAdapters
-
2
class AbstractAdapter
-
2
def self.inherited(subclass)
-
4
@subclasses ||= []
-
4
@subclasses << subclass
-
end
-
-
2
def self.adapter_class(model_class)
-
@subclasses.detect { |subclass| subclass.for_class?(model_class) } || DefaultAdapter
-
end
-
-
# Used to determine if the given adapter should be used for the passed in class.
-
2
def self.for_class?(member_class)
-
false # override in subclass
-
end
-
-
# Override if you need custom find behavior
-
2
def self.find(model_class, id)
-
model_class.find(id)
-
end
-
-
# Used to determine if this model adapter will override the matching behavior for a hash of conditions.
-
# If this returns true then matches_conditions_hash? will be called. See Rule#matches_conditions_hash
-
2
def self.override_conditions_hash_matching?(subject, conditions)
-
false
-
end
-
-
# Override if override_conditions_hash_matching? returns true
-
2
def self.matches_conditions_hash?(subject, conditions)
-
raise NotImplemented, "This model adapter does not support matching on a conditions hash."
-
end
-
-
# Used to determine if this model adapter will override the matching behavior for a specific condition.
-
# If this returns true then matches_condition? will be called. See Rule#matches_conditions_hash
-
2
def self.override_condition_matching?(subject, name, value)
-
false
-
end
-
-
# Override if override_condition_matching? returns true
-
2
def self.matches_condition?(subject, name, value)
-
raise NotImplemented, "This model adapter does not support matching on a specific condition."
-
end
-
-
2
def initialize(model_class, rules)
-
@model_class = model_class
-
@rules = rules
-
end
-
-
2
def database_records
-
# This should be overridden in a subclass to return records which match @rules
-
raise NotImplemented, "This model adapter does not support fetching records from the database."
-
end
-
end
-
end
-
end
-
2
module CanCan
-
2
module ModelAdapters
-
2
class ActiveRecordAdapter < AbstractAdapter
-
2
def self.for_class?(model_class)
-
model_class <= ActiveRecord::Base
-
end
-
-
2
def self.override_condition_matching?(subject, name, value)
-
name.kind_of?(MetaWhere::Column) if defined? MetaWhere
-
end
-
-
2
def self.matches_condition?(subject, name, value)
-
subject_value = subject.send(name.column)
-
if name.method.to_s.ends_with? "_any"
-
value.any? { |v| meta_where_match? subject_value, name.method.to_s.sub("_any", ""), v }
-
elsif name.method.to_s.ends_with? "_all"
-
value.all? { |v| meta_where_match? subject_value, name.method.to_s.sub("_all", ""), v }
-
else
-
meta_where_match? subject_value, name.method, value
-
end
-
end
-
-
2
def self.meta_where_match?(subject_value, method, value)
-
case method.to_sym
-
when :eq then subject_value == value
-
when :not_eq then subject_value != value
-
when :in then value.include?(subject_value)
-
when :not_in then !value.include?(subject_value)
-
when :lt then subject_value < value
-
when :lteq then subject_value <= value
-
when :gt then subject_value > value
-
when :gteq then subject_value >= value
-
when :matches then subject_value =~ Regexp.new("^" + Regexp.escape(value).gsub("%", ".*") + "$", true)
-
when :does_not_match then !meta_where_match?(subject_value, :matches, value)
-
else raise NotImplemented, "The #{method} MetaWhere condition is not supported."
-
end
-
end
-
-
# Returns conditions intended to be used inside a database query. Normally you will not call this
-
# method directly, but instead go through ModelAdditions#accessible_by.
-
#
-
# If there is only one "can" definition, a hash of conditions will be returned matching the one defined.
-
#
-
# can :manage, User, :id => 1
-
# query(:manage, User).conditions # => { :id => 1 }
-
#
-
# If there are multiple "can" definitions, a SQL string will be returned to handle complex cases.
-
#
-
# can :manage, User, :id => 1
-
# can :manage, User, :manager_id => 1
-
# cannot :manage, User, :self_managed => true
-
# query(:manage, User).conditions # => "not (self_managed = 't') AND ((manager_id = 1) OR (id = 1))"
-
#
-
2
def conditions
-
if @rules.size == 1 && @rules.first.base_behavior
-
# Return the conditions directly if there's just one definition
-
tableized_conditions(@rules.first.conditions).dup
-
else
-
@rules.reverse.inject(false_sql) do |sql, rule|
-
merge_conditions(sql, tableized_conditions(rule.conditions).dup, rule.base_behavior)
-
end
-
end
-
end
-
-
2
def tableized_conditions(conditions, model_class = @model_class)
-
return conditions unless conditions.kind_of? Hash
-
conditions.inject({}) do |result_hash, (name, value)|
-
if value.kind_of? Hash
-
value = value.dup
-
association_class = model_class.reflect_on_association(name).class_name.constantize
-
nested = value.inject({}) do |nested,(k,v)|
-
if v.kind_of? Hash
-
value.delete(k)
-
nested[k] = v
-
else
-
name = model_class.reflect_on_association(name).table_name.to_sym
-
result_hash[name] = value
-
end
-
nested
-
end
-
result_hash.merge!(tableized_conditions(nested,association_class))
-
else
-
result_hash[name] = value
-
end
-
result_hash
-
end
-
end
-
-
# Returns the associations used in conditions for the :joins option of a search.
-
# See ModelAdditions#accessible_by
-
2
def joins
-
joins_hash = {}
-
@rules.each do |rule|
-
merge_joins(joins_hash, rule.associations_hash)
-
end
-
clean_joins(joins_hash) unless joins_hash.empty?
-
end
-
-
2
def database_records
-
if override_scope
-
@model_class.scoped.merge(override_scope)
-
elsif @model_class.respond_to?(:where) && @model_class.respond_to?(:joins)
-
mergeable_conditions = @rules.select {|rule| rule.unmergeable? }.blank?
-
if mergeable_conditions
-
@model_class.where(conditions).joins(joins)
-
else
-
@model_class.where(*(@rules.map(&:conditions))).joins(joins)
-
end
-
else
-
@model_class.scoped(:conditions => conditions, :joins => joins)
-
end
-
end
-
-
2
private
-
-
2
def override_scope
-
conditions = @rules.map(&:conditions).compact
-
if defined?(ActiveRecord::Relation) && conditions.any? { |c| c.kind_of?(ActiveRecord::Relation) }
-
if conditions.size == 1
-
conditions.first
-
else
-
rule = @rules.detect { |rule| rule.conditions.kind_of?(ActiveRecord::Relation) }
-
raise Error, "Unable to merge an Active Record scope with other conditions. Instead use a hash or SQL for #{rule.actions.first} #{rule.subjects.first} ability."
-
end
-
end
-
end
-
-
2
def merge_conditions(sql, conditions_hash, behavior)
-
if conditions_hash.blank?
-
behavior ? true_sql : false_sql
-
else
-
conditions = sanitize_sql(conditions_hash)
-
case sql
-
when true_sql
-
behavior ? true_sql : "not (#{conditions})"
-
when false_sql
-
behavior ? conditions : false_sql
-
else
-
behavior ? "(#{conditions}) OR (#{sql})" : "not (#{conditions}) AND (#{sql})"
-
end
-
end
-
end
-
-
2
def false_sql
-
sanitize_sql(['?=?', true, false])
-
end
-
-
2
def true_sql
-
sanitize_sql(['?=?', true, true])
-
end
-
-
2
def sanitize_sql(conditions)
-
@model_class.send(:sanitize_sql, conditions)
-
end
-
-
# Takes two hashes and does a deep merge.
-
2
def merge_joins(base, add)
-
add.each do |name, nested|
-
if base[name].is_a?(Hash)
-
merge_joins(base[name], nested) unless nested.empty?
-
else
-
base[name] = nested
-
end
-
end
-
end
-
-
# Removes empty hashes and moves everything into arrays.
-
2
def clean_joins(joins_hash)
-
joins = []
-
joins_hash.each do |name, nested|
-
joins << (nested.empty? ? name : {name => clean_joins(nested)})
-
end
-
joins
-
end
-
end
-
end
-
end
-
-
2
ActiveRecord::Base.class_eval do
-
2
include CanCan::ModelAdditions
-
end
-
2
module CanCan
-
2
module ModelAdapters
-
2
class DefaultAdapter < AbstractAdapter
-
# This adapter is used when no matching adapter is found
-
end
-
end
-
end
-
2
module CanCan
-
-
# This module adds the accessible_by class method to a model. It is included in the model adapters.
-
2
module ModelAdditions
-
2
module ClassMethods
-
# Returns a scope which fetches only the records that the passed ability
-
# can perform a given action on. The action defaults to :index. This
-
# is usually called from a controller and passed the +current_ability+.
-
#
-
# @articles = Article.accessible_by(current_ability)
-
#
-
# Here only the articles which the user is able to read will be returned.
-
# If the user does not have permission to read any articles then an empty
-
# result is returned. Since this is a scope it can be combined with any
-
# other scopes or pagination.
-
#
-
# An alternative action can optionally be passed as a second argument.
-
#
-
# @articles = Article.accessible_by(current_ability, :update)
-
#
-
# Here only the articles which the user can update are returned.
-
2
def accessible_by(ability, action = :index)
-
ability.model_adapter(self, action).database_records
-
end
-
end
-
-
2
def self.included(base)
-
2
base.extend ClassMethods
-
end
-
end
-
end
-
2
module CanCan
-
# This class is used internally and should only be called through Ability.
-
# it holds the information about a "can" call made on Ability and provides
-
# helpful methods to determine permission checking and conditions hash generation.
-
2
class Rule # :nodoc:
-
2
attr_reader :base_behavior, :subjects, :actions, :conditions
-
2
attr_writer :expanded_actions
-
-
# The first argument when initializing is the base_behavior which is a true/false
-
# value. True for "can" and false for "cannot". The next two arguments are the action
-
# and subject respectively (such as :read, @project). The third argument is a hash
-
# of conditions and the last one is the block passed to the "can" call.
-
2
def initialize(base_behavior, action, subject, conditions, block)
-
raise Error, "You are not able to supply a block with a hash of conditions in #{action} #{subject} ability. Use either one." if conditions.kind_of?(Hash) && !block.nil?
-
@match_all = action.nil? && subject.nil?
-
@base_behavior = base_behavior
-
@actions = [action].flatten
-
@subjects = [subject].flatten
-
@conditions = conditions || {}
-
@block = block
-
end
-
-
# Matches both the subject and action, not necessarily the conditions
-
2
def relevant?(action, subject)
-
subject = subject.values.first if subject.class == Hash
-
@match_all || (matches_action?(action) && matches_subject?(subject))
-
end
-
-
# Matches the block or conditions hash
-
2
def matches_conditions?(action, subject, extra_args)
-
if @match_all
-
call_block_with_all(action, subject, extra_args)
-
elsif @block && !subject_class?(subject)
-
@block.call(subject, *extra_args)
-
elsif @conditions.kind_of?(Hash) && subject.class == Hash
-
nested_subject_matches_conditions?(subject)
-
elsif @conditions.kind_of?(Hash) && !subject_class?(subject)
-
matches_conditions_hash?(subject)
-
else
-
# Don't stop at "cannot" definitions when there are conditions.
-
@conditions.empty? ? true : @base_behavior
-
end
-
end
-
-
2
def only_block?
-
conditions_empty? && !@block.nil?
-
end
-
-
2
def only_raw_sql?
-
@block.nil? && !conditions_empty? && !@conditions.kind_of?(Hash)
-
end
-
-
2
def conditions_empty?
-
@conditions == {} || @conditions.nil?
-
end
-
-
2
def unmergeable?
-
@conditions.respond_to?(:keys) && @conditions.present? &&
-
(!@conditions.keys.first.kind_of? Symbol)
-
end
-
-
2
def associations_hash(conditions = @conditions)
-
hash = {}
-
conditions.map do |name, value|
-
hash[name] = associations_hash(value) if value.kind_of? Hash
-
end if conditions.kind_of? Hash
-
hash
-
end
-
-
2
def attributes_from_conditions
-
attributes = {}
-
@conditions.each do |key, value|
-
attributes[key] = value unless [Array, Range, Hash].include? value.class
-
end if @conditions.kind_of? Hash
-
attributes
-
end
-
-
2
private
-
-
2
def subject_class?(subject)
-
klass = (subject.kind_of?(Hash) ? subject.values.first : subject).class
-
klass == Class || klass == Module
-
end
-
-
2
def matches_action?(action)
-
@expanded_actions.include?(:manage) || @expanded_actions.include?(action)
-
end
-
-
2
def matches_subject?(subject)
-
@subjects.include?(:all) || @subjects.include?(subject) || matches_subject_class?(subject)
-
end
-
-
2
def matches_subject_class?(subject)
-
@subjects.any? { |sub| sub.kind_of?(Module) && (subject.kind_of?(sub) || subject.class.to_s == sub.to_s || subject.kind_of?(Module) && subject.ancestors.include?(sub)) }
-
end
-
-
# Checks if the given subject matches the given conditions hash.
-
# This behavior can be overriden by a model adapter by defining two class methods:
-
# override_matching_for_conditions?(subject, conditions) and
-
# matches_conditions_hash?(subject, conditions)
-
2
def matches_conditions_hash?(subject, conditions = @conditions)
-
if conditions.empty?
-
true
-
else
-
if model_adapter(subject).override_conditions_hash_matching? subject, conditions
-
model_adapter(subject).matches_conditions_hash? subject, conditions
-
else
-
conditions.all? do |name, value|
-
if model_adapter(subject).override_condition_matching? subject, name, value
-
model_adapter(subject).matches_condition? subject, name, value
-
else
-
attribute = subject.send(name)
-
if value.kind_of?(Hash)
-
if attribute.kind_of? Array
-
attribute.any? { |element| matches_conditions_hash? element, value }
-
else
-
!attribute.nil? && matches_conditions_hash?(attribute, value)
-
end
-
elsif !value.is_a?(String) && value.kind_of?(Enumerable)
-
value.include? attribute
-
else
-
attribute == value
-
end
-
end
-
end
-
end
-
end
-
end
-
-
2
def nested_subject_matches_conditions?(subject_hash)
-
parent, child = subject_hash.first
-
matches_conditions_hash?(parent, @conditions[parent.class.name.downcase.to_sym] || {})
-
end
-
-
2
def call_block_with_all(action, subject, extra_args)
-
if subject.class == Class
-
@block.call(action, subject, nil, *extra_args)
-
else
-
@block.call(action, subject.class, subject, *extra_args)
-
end
-
end
-
-
2
def model_adapter(subject)
-
CanCan::ModelAdapters::AbstractAdapter.adapter_class(subject_class?(subject) ? subject : subject.class)
-
end
-
end
-
end
-
2
require 'time'
-
2
require 'date'
-
-
2
require 'chronic/parser'
-
2
require 'chronic/date'
-
2
require 'chronic/time'
-
-
2
require 'chronic/handler'
-
2
require 'chronic/handlers'
-
2
require 'chronic/mini_date'
-
2
require 'chronic/tag'
-
2
require 'chronic/span'
-
2
require 'chronic/token'
-
2
require 'chronic/grabber'
-
2
require 'chronic/pointer'
-
2
require 'chronic/scalar'
-
2
require 'chronic/ordinal'
-
2
require 'chronic/separator'
-
2
require 'chronic/sign'
-
2
require 'chronic/time_zone'
-
2
require 'chronic/numerizer'
-
2
require 'chronic/season'
-
-
2
require 'chronic/repeater'
-
2
require 'chronic/repeaters/repeater_year'
-
2
require 'chronic/repeaters/repeater_season'
-
2
require 'chronic/repeaters/repeater_season_name'
-
2
require 'chronic/repeaters/repeater_month'
-
2
require 'chronic/repeaters/repeater_month_name'
-
2
require 'chronic/repeaters/repeater_fortnight'
-
2
require 'chronic/repeaters/repeater_week'
-
2
require 'chronic/repeaters/repeater_weekend'
-
2
require 'chronic/repeaters/repeater_weekday'
-
2
require 'chronic/repeaters/repeater_day'
-
2
require 'chronic/repeaters/repeater_day_name'
-
2
require 'chronic/repeaters/repeater_day_portion'
-
2
require 'chronic/repeaters/repeater_hour'
-
2
require 'chronic/repeaters/repeater_minute'
-
2
require 'chronic/repeaters/repeater_second'
-
2
require 'chronic/repeaters/repeater_time'
-
-
# Parse natural language dates and times into Time or Chronic::Span objects.
-
#
-
# Examples:
-
#
-
# require 'chronic'
-
#
-
# Time.now #=> Sun Aug 27 23:18:25 PDT 2006
-
#
-
# Chronic.parse('tomorrow')
-
# #=> Mon Aug 28 12:00:00 PDT 2006
-
#
-
# Chronic.parse('monday', :context => :past)
-
# #=> Mon Aug 21 12:00:00 PDT 2006
-
2
module Chronic
-
2
VERSION = "0.10.2"
-
-
2
class << self
-
-
# Returns true when debug mode is enabled.
-
2
attr_accessor :debug
-
-
# Examples:
-
#
-
# require 'chronic'
-
# require 'active_support/time'
-
#
-
# Time.zone = 'UTC'
-
# Chronic.time_class = Time.zone
-
# Chronic.parse('June 15 2006 at 5:54 AM')
-
# # => Thu, 15 Jun 2006 05:45:00 UTC +00:00
-
#
-
# Returns The Time class Chronic uses internally.
-
2
attr_accessor :time_class
-
end
-
-
2
self.debug = false
-
2
self.time_class = ::Time
-
-
-
# Parses a string containing a natural language date or time.
-
#
-
# If the parser can find a date or time, either a Time or Chronic::Span
-
# will be returned (depending on the value of `:guess`). If no
-
# date or time can be found, `nil` will be returned.
-
#
-
# text - The String text to parse.
-
# opts - An optional Hash of configuration options passed to Parser::new.
-
2
def self.parse(text, options = {})
-
Parser.new(options).parse(text)
-
end
-
-
# Construct a new time object determining possible month overflows
-
# and leap years.
-
#
-
# year - Integer year.
-
# month - Integer month.
-
# day - Integer day.
-
# hour - Integer hour.
-
# minute - Integer minute.
-
# second - Integer second.
-
#
-
# Returns a new Time object constructed from these params.
-
2
def self.construct(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, offset = nil)
-
if second >= 60
-
minute += second / 60
-
second = second % 60
-
end
-
-
if minute >= 60
-
hour += minute / 60
-
minute = minute % 60
-
end
-
-
if hour >= 24
-
day += hour / 24
-
hour = hour % 24
-
end
-
-
# determine if there is a day overflow. this is complicated by our crappy calendar
-
# system (non-constant number of days per month)
-
day <= 56 || raise("day must be no more than 56 (makes month resolution easier)")
-
if day > 28 # no month ever has fewer than 28 days, so only do this if necessary
-
days_this_month = ::Date.leap?(year) ? Date::MONTH_DAYS_LEAP[month] : Date::MONTH_DAYS[month]
-
if day > days_this_month
-
month += day / days_this_month
-
day = day % days_this_month
-
end
-
end
-
-
if month > 12
-
if month % 12 == 0
-
year += (month - 12) / 12
-
month = 12
-
else
-
year += month / 12
-
month = month % 12
-
end
-
end
-
if Chronic.time_class.name == "Date"
-
Chronic.time_class.new(year, month, day)
-
elsif not Chronic.time_class.respond_to?(:new) or (RUBY_VERSION.to_f < 1.9 and Chronic.time_class.name == "Time")
-
Chronic.time_class.local(year, month, day, hour, minute, second)
-
else
-
offset = Time::normalize_offset(offset) if Chronic.time_class.name == "DateTime"
-
Chronic.time_class.new(year, month, day, hour, minute, second, offset)
-
end
-
end
-
-
end
-
2
module Chronic
-
2
class Date
-
2
YEAR_MONTHS = 12
-
2
MONTH_DAYS = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-
2
MONTH_DAYS_LEAP = [nil, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-
2
YEAR_SECONDS = 31_536_000 # 365 * 24 * 60 * 60
-
2
SEASON_SECONDS = 7_862_400 # 91 * 24 * 60 * 60
-
2
MONTH_SECONDS = 2_592_000 # 30 * 24 * 60 * 60
-
2
FORTNIGHT_SECONDS = 1_209_600 # 14 * 24 * 60 * 60
-
2
WEEK_SECONDS = 604_800 # 7 * 24 * 60 * 60
-
2
WEEKEND_SECONDS = 172_800 # 2 * 24 * 60 * 60
-
2
DAY_SECONDS = 86_400 # 24 * 60 * 60
-
2
MONTHS = {
-
:january => 1,
-
:february => 2,
-
:march => 3,
-
:april => 4,
-
:may => 5,
-
:june => 6,
-
:july => 7,
-
:august => 8,
-
:september => 9,
-
:october => 10,
-
:november => 11,
-
:december => 12
-
}
-
2
DAYS = {
-
:sunday => 0,
-
:monday => 1,
-
:tuesday => 2,
-
:wednesday => 3,
-
:thursday => 4,
-
:friday => 5,
-
:saturday => 6
-
}
-
-
# Checks if given number could be day
-
2
def self.could_be_day?(day)
-
day >= 1 && day <= 31
-
end
-
-
# Checks if given number could be month
-
2
def self.could_be_month?(month)
-
month >= 1 && month <= 12
-
end
-
-
# Checks if given number could be year
-
2
def self.could_be_year?(year)
-
year >= 1 && year <= 9999
-
end
-
-
# Build a year from a 2 digit suffix.
-
#
-
# year - The two digit Integer year to build from.
-
# bias - The Integer amount of future years to bias.
-
#
-
# Examples:
-
#
-
# make_year(96, 50) #=> 1996
-
# make_year(79, 20) #=> 2079
-
# make_year(00, 50) #=> 2000
-
#
-
# Returns The Integer 4 digit year.
-
2
def self.make_year(year, bias)
-
return year if year.to_s.size > 2
-
start_year = Chronic.time_class.now.year - bias
-
century = (start_year / 100) * 100
-
full_year = century + year
-
full_year += 100 if full_year < start_year
-
full_year
-
end
-
-
2
def self.month_overflow?(year, month, day)
-
if ::Date.leap?(year)
-
day > Date::MONTH_DAYS_LEAP[month]
-
else
-
day > Date::MONTH_DAYS[month]
-
end
-
end
-
-
end
-
end
-
2
module Chronic
-
2
class Grabber < Tag
-
-
# Scan an Array of Tokens and apply any necessary Grabber tags to
-
# each token.
-
#
-
# tokens - An Array of Token objects to scan.
-
# options - The Hash of options specified in Chronic::parse.
-
#
-
# Returns an Array of Token objects.
-
2
def self.scan(tokens, options)
-
tokens.each do |token|
-
if t = scan_for_all(token) then token.tag(t); next end
-
end
-
end
-
-
# token - The Token object to scan.
-
#
-
# Returns a new Grabber object.
-
2
def self.scan_for_all(token)
-
scan_for token, self,
-
{
-
/last/ => :last,
-
/this/ => :this,
-
/next/ => :next
-
}
-
end
-
-
2
def to_s
-
'grabber-' << @type.to_s
-
end
-
end
-
end
-
2
module Chronic
-
2
class Handler
-
-
2
attr_reader :pattern
-
-
2
attr_reader :handler_method
-
-
# pattern - An Array of patterns to match tokens against.
-
# handler_method - A Symbol representing the method to be invoked
-
# when a pattern matches.
-
2
def initialize(pattern, handler_method)
-
@pattern = pattern
-
@handler_method = handler_method
-
end
-
-
# tokens - An Array of tokens to process.
-
# definitions - A Hash of definitions to check against.
-
#
-
# Returns true if a match is found.
-
2
def match(tokens, definitions)
-
token_index = 0
-
@pattern.each do |elements|
-
was_optional = false
-
elements = [elements] unless elements.is_a?(Array)
-
-
elements.each_index do |i|
-
name = elements[i].to_s
-
optional = name[-1, 1] == '?'
-
name = name.chop if optional
-
-
case elements[i]
-
when Symbol
-
if tags_match?(name, tokens, token_index)
-
token_index += 1
-
break
-
else
-
if optional
-
was_optional = true
-
next
-
elsif i + 1 < elements.count
-
next
-
else
-
return false unless was_optional
-
end
-
end
-
-
when String
-
return true if optional && token_index == tokens.size
-
-
if definitions.key?(name.to_sym)
-
sub_handlers = definitions[name.to_sym]
-
else
-
raise "Invalid subset #{name} specified"
-
end
-
-
sub_handlers.each do |sub_handler|
-
return true if sub_handler.match(tokens[token_index..tokens.size], definitions)
-
end
-
else
-
raise "Invalid match type: #{elements[i].class}"
-
end
-
end
-
-
end
-
-
return false if token_index != tokens.size
-
return true
-
end
-
-
2
def invoke(type, tokens, parser, options)
-
if Chronic.debug
-
puts "-#{type}"
-
puts "Handler: #{@handler_method}"
-
end
-
-
parser.send(@handler_method, tokens, options)
-
end
-
-
# other - The other Handler object to compare.
-
#
-
# Returns true if these Handlers match.
-
2
def ==(other)
-
@pattern == other.pattern
-
end
-
-
2
private
-
-
2
def tags_match?(name, tokens, token_index)
-
klass = Chronic.const_get(name.to_s.gsub(/(?:^|_)(.)/) { $1.upcase })
-
-
if tokens[token_index]
-
!tokens[token_index].tags.select { |o| o.kind_of?(klass) }.empty?
-
end
-
end
-
-
end
-
end
-
2
module Chronic
-
2
module Handlers
-
2
module_function
-
-
# Handle month/day
-
2
def handle_m_d(month, day, time_tokens, options)
-
month.start = self.now
-
span = month.this(options[:context])
-
year, month = span.begin.year, span.begin.month
-
day_start = Chronic.time_class.local(year, month, day)
-
-
day_or_time(day_start, time_tokens, options)
-
end
-
-
# Handle repeater-month-name/scalar-day
-
2
def handle_rmn_sd(tokens, options)
-
month = tokens[0].get_tag(RepeaterMonthName)
-
day = tokens[1].get_tag(ScalarDay).type
-
-
return if month_overflow?(self.now.year, month.index, day)
-
-
handle_m_d(month, day, tokens[2..tokens.size], options)
-
end
-
-
# Handle repeater-month-name/scalar-day with separator-on
-
2
def handle_rmn_sd_on(tokens, options)
-
if tokens.size > 3
-
month = tokens[2].get_tag(RepeaterMonthName)
-
day = tokens[3].get_tag(ScalarDay).type
-
token_range = 0..1
-
else
-
month = tokens[1].get_tag(RepeaterMonthName)
-
day = tokens[2].get_tag(ScalarDay).type
-
token_range = 0..0
-
end
-
-
return if month_overflow?(self.now.year, month.index, day)
-
-
handle_m_d(month, day, tokens[token_range], options)
-
end
-
-
# Handle repeater-month-name/ordinal-day
-
2
def handle_rmn_od(tokens, options)
-
month = tokens[0].get_tag(RepeaterMonthName)
-
day = tokens[1].get_tag(OrdinalDay).type
-
-
return if month_overflow?(self.now.year, month.index, day)
-
-
handle_m_d(month, day, tokens[2..tokens.size], options)
-
end
-
-
# Handle ordinal this month
-
2
def handle_od_rm(tokens, options)
-
day = tokens[0].get_tag(OrdinalDay).type
-
month = tokens[2].get_tag(RepeaterMonth)
-
handle_m_d(month, day, tokens[3..tokens.size], options)
-
end
-
-
# Handle ordinal-day/repeater-month-name
-
2
def handle_od_rmn(tokens, options)
-
month = tokens[1].get_tag(RepeaterMonthName)
-
day = tokens[0].get_tag(OrdinalDay).type
-
-
return if month_overflow?(self.now.year, month.index, day)
-
-
handle_m_d(month, day, tokens[2..tokens.size], options)
-
end
-
-
2
def handle_sy_rmn_od(tokens, options)
-
year = tokens[0].get_tag(ScalarYear).type
-
month = tokens[1].get_tag(RepeaterMonthName).index
-
day = tokens[2].get_tag(OrdinalDay).type
-
time_tokens = tokens.last(tokens.size - 3)
-
-
return if month_overflow?(year, month, day)
-
-
begin
-
day_start = Chronic.time_class.local(year, month, day)
-
day_or_time(day_start, time_tokens, options)
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
# Handle scalar-day/repeater-month-name
-
2
def handle_sd_rmn(tokens, options)
-
month = tokens[1].get_tag(RepeaterMonthName)
-
day = tokens[0].get_tag(ScalarDay).type
-
-
return if month_overflow?(self.now.year, month.index, day)
-
-
handle_m_d(month, day, tokens[2..tokens.size], options)
-
end
-
-
# Handle repeater-month-name/ordinal-day with separator-on
-
2
def handle_rmn_od_on(tokens, options)
-
if tokens.size > 3
-
month = tokens[2].get_tag(RepeaterMonthName)
-
day = tokens[3].get_tag(OrdinalDay).type
-
token_range = 0..1
-
else
-
month = tokens[1].get_tag(RepeaterMonthName)
-
day = tokens[2].get_tag(OrdinalDay).type
-
token_range = 0..0
-
end
-
-
return if month_overflow?(self.now.year, month.index, day)
-
-
handle_m_d(month, day, tokens[token_range], options)
-
end
-
-
# Handle repeater-month-name/scalar-year
-
2
def handle_rmn_sy(tokens, options)
-
month = tokens[0].get_tag(RepeaterMonthName).index
-
year = tokens[1].get_tag(ScalarYear).type
-
-
if month == 12
-
next_month_year = year + 1
-
next_month_month = 1
-
else
-
next_month_year = year
-
next_month_month = month + 1
-
end
-
-
begin
-
end_time = Chronic.time_class.local(next_month_year, next_month_month)
-
Span.new(Chronic.time_class.local(year, month), end_time)
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
# Handle generic timestamp (ruby 1.8)
-
2
def handle_generic(tokens, options)
-
t = Chronic.time_class.parse(options[:text])
-
Span.new(t, t + 1)
-
rescue ArgumentError => e
-
raise e unless e.message =~ /out of range/
-
end
-
-
# Handle repeater-month-name/scalar-day/scalar-year
-
2
def handle_rmn_sd_sy(tokens, options)
-
month = tokens[0].get_tag(RepeaterMonthName).index
-
day = tokens[1].get_tag(ScalarDay).type
-
year = tokens[2].get_tag(ScalarYear).type
-
time_tokens = tokens.last(tokens.size - 3)
-
-
return if month_overflow?(year, month, day)
-
-
begin
-
day_start = Chronic.time_class.local(year, month, day)
-
day_or_time(day_start, time_tokens, options)
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
# Handle repeater-month-name/ordinal-day/scalar-year
-
2
def handle_rmn_od_sy(tokens, options)
-
month = tokens[0].get_tag(RepeaterMonthName).index
-
day = tokens[1].get_tag(OrdinalDay).type
-
year = tokens[2].get_tag(ScalarYear).type
-
time_tokens = tokens.last(tokens.size - 3)
-
-
return if month_overflow?(year, month, day)
-
-
begin
-
day_start = Chronic.time_class.local(year, month, day)
-
day_or_time(day_start, time_tokens, options)
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
# Handle oridinal-day/repeater-month-name/scalar-year
-
2
def handle_od_rmn_sy(tokens, options)
-
day = tokens[0].get_tag(OrdinalDay).type
-
month = tokens[1].get_tag(RepeaterMonthName).index
-
year = tokens[2].get_tag(ScalarYear).type
-
time_tokens = tokens.last(tokens.size - 3)
-
-
return if month_overflow?(year, month, day)
-
-
begin
-
day_start = Chronic.time_class.local(year, month, day)
-
day_or_time(day_start, time_tokens, options)
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
# Handle scalar-day/repeater-month-name/scalar-year
-
2
def handle_sd_rmn_sy(tokens, options)
-
new_tokens = [tokens[1], tokens[0], tokens[2]]
-
time_tokens = tokens.last(tokens.size - 3)
-
handle_rmn_sd_sy(new_tokens + time_tokens, options)
-
end
-
-
# Handle scalar-month/scalar-day/scalar-year (endian middle)
-
2
def handle_sm_sd_sy(tokens, options)
-
month = tokens[0].get_tag(ScalarMonth).type
-
day = tokens[1].get_tag(ScalarDay).type
-
year = tokens[2].get_tag(ScalarYear).type
-
time_tokens = tokens.last(tokens.size - 3)
-
-
return if month_overflow?(year, month, day)
-
-
begin
-
day_start = Chronic.time_class.local(year, month, day)
-
day_or_time(day_start, time_tokens, options)
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
# Handle scalar-day/scalar-month/scalar-year (endian little)
-
2
def handle_sd_sm_sy(tokens, options)
-
new_tokens = [tokens[1], tokens[0], tokens[2]]
-
time_tokens = tokens.last(tokens.size - 3)
-
handle_sm_sd_sy(new_tokens + time_tokens, options)
-
end
-
-
# Handle scalar-year/scalar-month/scalar-day
-
2
def handle_sy_sm_sd(tokens, options)
-
new_tokens = [tokens[1], tokens[2], tokens[0]]
-
time_tokens = tokens.last(tokens.size - 3)
-
handle_sm_sd_sy(new_tokens + time_tokens, options)
-
end
-
-
# Handle scalar-month/scalar-day
-
2
def handle_sm_sd(tokens, options)
-
month = tokens[0].get_tag(ScalarMonth).type
-
day = tokens[1].get_tag(ScalarDay).type
-
year = self.now.year
-
time_tokens = tokens.last(tokens.size - 2)
-
-
return if month_overflow?(year, month, day)
-
-
begin
-
day_start = Chronic.time_class.local(year, month, day)
-
day_start = Chronic.time_class.local(year + 1, month, day) if options[:context] == :future && day_start < now
-
day_or_time(day_start, time_tokens, options)
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
# Handle scalar-day/scalar-month
-
2
def handle_sd_sm(tokens, options)
-
new_tokens = [tokens[1], tokens[0]]
-
time_tokens = tokens.last(tokens.size - 2)
-
handle_sm_sd(new_tokens + time_tokens, options)
-
end
-
-
2
def handle_year_and_month(year, month)
-
if month == 12
-
next_month_year = year + 1
-
next_month_month = 1
-
else
-
next_month_year = year
-
next_month_month = month + 1
-
end
-
-
begin
-
end_time = Chronic.time_class.local(next_month_year, next_month_month)
-
Span.new(Chronic.time_class.local(year, month), end_time)
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
# Handle scalar-month/scalar-year
-
2
def handle_sm_sy(tokens, options)
-
month = tokens[0].get_tag(ScalarMonth).type
-
year = tokens[1].get_tag(ScalarYear).type
-
handle_year_and_month(year, month)
-
end
-
-
# Handle scalar-year/scalar-month
-
2
def handle_sy_sm(tokens, options)
-
year = tokens[0].get_tag(ScalarYear).type
-
month = tokens[1].get_tag(ScalarMonth).type
-
handle_year_and_month(year, month)
-
end
-
-
# Handle RepeaterDayName RepeaterMonthName OrdinalDay
-
2
def handle_rdn_rmn_od(tokens, options)
-
month = tokens[1].get_tag(RepeaterMonthName)
-
day = tokens[2].get_tag(OrdinalDay).type
-
time_tokens = tokens.last(tokens.size - 3)
-
year = self.now.year
-
-
return if month_overflow?(year, month.index, day)
-
-
begin
-
if time_tokens.empty?
-
start_time = Chronic.time_class.local(year, month.index, day)
-
end_time = time_with_rollover(year, month.index, day + 1)
-
Span.new(start_time, end_time)
-
else
-
day_start = Chronic.time_class.local(year, month.index, day)
-
day_or_time(day_start, time_tokens, options)
-
end
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
# Handle RepeaterDayName RepeaterMonthName OrdinalDay ScalarYear
-
2
def handle_rdn_rmn_od_sy(tokens, options)
-
month = tokens[1].get_tag(RepeaterMonthName)
-
day = tokens[2].get_tag(OrdinalDay).type
-
year = tokens[3].get_tag(ScalarYear).type
-
-
return if month_overflow?(year, month.index, day)
-
-
begin
-
start_time = Chronic.time_class.local(year, month.index, day)
-
end_time = time_with_rollover(year, month.index, day + 1)
-
Span.new(start_time, end_time)
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
# Handle RepeaterDayName OrdinalDay
-
2
def handle_rdn_od(tokens, options)
-
day = tokens[1].get_tag(OrdinalDay).type
-
time_tokens = tokens.last(tokens.size - 2)
-
year = self.now.year
-
month = self.now.month
-
if options[:context] == :future
-
self.now.day > day ? month += 1 : month
-
end
-
-
return if month_overflow?(year, month, day)
-
-
begin
-
if time_tokens.empty?
-
start_time = Chronic.time_class.local(year, month, day)
-
end_time = time_with_rollover(year, month, day + 1)
-
Span.new(start_time, end_time)
-
else
-
day_start = Chronic.time_class.local(year, month, day)
-
day_or_time(day_start, time_tokens, options)
-
end
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
# Handle RepeaterDayName RepeaterMonthName ScalarDay
-
2
def handle_rdn_rmn_sd(tokens, options)
-
month = tokens[1].get_tag(RepeaterMonthName)
-
day = tokens[2].get_tag(ScalarDay).type
-
time_tokens = tokens.last(tokens.size - 3)
-
year = self.now.year
-
-
return if month_overflow?(year, month.index, day)
-
-
begin
-
if time_tokens.empty?
-
start_time = Chronic.time_class.local(year, month.index, day)
-
end_time = time_with_rollover(year, month.index, day + 1)
-
Span.new(start_time, end_time)
-
else
-
day_start = Chronic.time_class.local(year, month.index, day)
-
day_or_time(day_start, time_tokens, options)
-
end
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
# Handle RepeaterDayName RepeaterMonthName ScalarDay ScalarYear
-
2
def handle_rdn_rmn_sd_sy(tokens, options)
-
month = tokens[1].get_tag(RepeaterMonthName)
-
day = tokens[2].get_tag(ScalarDay).type
-
year = tokens[3].get_tag(ScalarYear).type
-
-
return if month_overflow?(year, month.index, day)
-
-
begin
-
start_time = Chronic.time_class.local(year, month.index, day)
-
end_time = time_with_rollover(year, month.index, day + 1)
-
Span.new(start_time, end_time)
-
rescue ArgumentError
-
nil
-
end
-
end
-
-
2
def handle_sm_rmn_sy(tokens, options)
-
day = tokens[0].get_tag(ScalarDay).type
-
month = tokens[1].get_tag(RepeaterMonthName).index
-
year = tokens[2].get_tag(ScalarYear).type
-
if tokens.size > 3
-
time = get_anchor([tokens.last], options).begin
-
h, m, s = time.hour, time.min, time.sec
-
time = Chronic.time_class.local(year, month, day, h, m, s)
-
end_time = Chronic.time_class.local(year, month, day + 1, h, m, s)
-
else
-
time = Chronic.time_class.local(year, month, day)
-
day += 1 unless day >= 31
-
end_time = Chronic.time_class.local(year, month, day)
-
end
-
Span.new(time, end_time)
-
end
-
-
# anchors
-
-
# Handle repeaters
-
2
def handle_r(tokens, options)
-
dd_tokens = dealias_and_disambiguate_times(tokens, options)
-
get_anchor(dd_tokens, options)
-
end
-
-
# Handle repeater/grabber/repeater
-
2
def handle_r_g_r(tokens, options)
-
new_tokens = [tokens[1], tokens[0], tokens[2]]
-
handle_r(new_tokens, options)
-
end
-
-
# arrows
-
-
# Handle scalar/repeater/pointer helper
-
2
def handle_srp(tokens, span, options)
-
distance = tokens[0].get_tag(Scalar).type
-
repeater = tokens[1].get_tag(Repeater)
-
pointer = tokens[2].get_tag(Pointer).type
-
-
repeater.offset(span, distance, pointer) if repeater.respond_to?(:offset)
-
end
-
-
# Handle scalar/repeater/pointer
-
2
def handle_s_r_p(tokens, options)
-
span = Span.new(self.now, self.now + 1)
-
-
handle_srp(tokens, span, options)
-
end
-
-
# Handle pointer/scalar/repeater
-
2
def handle_p_s_r(tokens, options)
-
new_tokens = [tokens[1], tokens[2], tokens[0]]
-
handle_s_r_p(new_tokens, options)
-
end
-
-
# Handle scalar/repeater/pointer/anchor
-
2
def handle_s_r_p_a(tokens, options)
-
anchor_span = get_anchor(tokens[3..tokens.size - 1], options)
-
handle_srp(tokens, anchor_span, options)
-
end
-
-
2
def handle_s_r_a_s_r_p_a(tokens, options)
-
anchor_span = get_anchor(tokens[4..tokens.size - 1], options)
-
-
span = handle_srp(tokens[0..1]+tokens[4..6], anchor_span, options)
-
handle_srp(tokens[2..3]+tokens[4..6], span, options)
-
end
-
-
# narrows
-
-
# Handle oridinal repeaters
-
2
def handle_orr(tokens, outer_span, options)
-
repeater = tokens[1].get_tag(Repeater)
-
repeater.start = outer_span.begin - 1
-
ordinal = tokens[0].get_tag(Ordinal).type
-
span = nil
-
-
ordinal.times do
-
span = repeater.next(:future)
-
-
if span.begin >= outer_span.end
-
span = nil
-
break
-
end
-
end
-
-
span
-
end
-
-
# Handle ordinal/repeater/separator/repeater
-
2
def handle_o_r_s_r(tokens, options)
-
outer_span = get_anchor([tokens[3]], options)
-
handle_orr(tokens[0..1], outer_span, options)
-
end
-
-
# Handle ordinal/repeater/grabber/repeater
-
2
def handle_o_r_g_r(tokens, options)
-
outer_span = get_anchor(tokens[2..3], options)
-
handle_orr(tokens[0..1], outer_span, options)
-
end
-
-
# support methods
-
-
2
def day_or_time(day_start, time_tokens, options)
-
outer_span = Span.new(day_start, day_start + (24 * 60 * 60))
-
-
unless time_tokens.empty?
-
self.now = outer_span.begin
-
get_anchor(dealias_and_disambiguate_times(time_tokens, options), options.merge(:context => :future))
-
else
-
outer_span
-
end
-
end
-
-
2
def get_anchor(tokens, options)
-
grabber = Grabber.new(:this)
-
pointer = :future
-
repeaters = get_repeaters(tokens)
-
repeaters.size.times { tokens.pop }
-
-
if tokens.first && tokens.first.get_tag(Grabber)
-
grabber = tokens.shift.get_tag(Grabber)
-
end
-
-
head = repeaters.shift
-
head.start = self.now
-
-
case grabber.type
-
when :last
-
outer_span = head.next(:past)
-
when :this
-
if options[:context] != :past and repeaters.size > 0
-
outer_span = head.this(:none)
-
else
-
outer_span = head.this(options[:context])
-
end
-
when :next
-
outer_span = head.next(:future)
-
else
-
raise "Invalid grabber"
-
end
-
-
if Chronic.debug
-
puts "Handler-class: #{head.class}"
-
puts "--#{outer_span}"
-
end
-
-
find_within(repeaters, outer_span, pointer)
-
end
-
-
2
def get_repeaters(tokens)
-
tokens.map { |token| token.get_tag(Repeater) }.compact.sort.reverse
-
end
-
-
2
def month_overflow?(year, month, day)
-
if ::Date.leap?(year)
-
day > RepeaterMonth::MONTH_DAYS_LEAP[month - 1]
-
else
-
day > RepeaterMonth::MONTH_DAYS[month - 1]
-
end
-
rescue ArgumentError
-
false
-
end
-
-
# Recursively finds repeaters within other repeaters.
-
# Returns a Span representing the innermost time span
-
# or nil if no repeater union could be found
-
2
def find_within(tags, span, pointer)
-
puts "--#{span}" if Chronic.debug
-
return span if tags.empty?
-
-
head = tags.shift
-
head.start = (pointer == :future ? span.begin : span.end)
-
h = head.this(:none)
-
-
if span.cover?(h.begin) || span.cover?(h.end)
-
find_within(tags, h, pointer)
-
end
-
end
-
-
2
def time_with_rollover(year, month, day)
-
date_parts =
-
if month_overflow?(year, month, day)
-
if month == 12
-
[year + 1, 1, 1]
-
else
-
[year, month + 1, 1]
-
end
-
else
-
[year, month, day]
-
end
-
Chronic.time_class.local(*date_parts)
-
end
-
-
2
def dealias_and_disambiguate_times(tokens, options)
-
# handle aliases of am/pm
-
# 5:00 in the morning -> 5:00 am
-
# 7:00 in the evening -> 7:00 pm
-
-
day_portion_index = nil
-
tokens.each_with_index do |t, i|
-
if t.get_tag(RepeaterDayPortion)
-
day_portion_index = i
-
break
-
end
-
end
-
-
time_index = nil
-
tokens.each_with_index do |t, i|
-
if t.get_tag(RepeaterTime)
-
time_index = i
-
break
-
end
-
end
-
-
if day_portion_index && time_index
-
t1 = tokens[day_portion_index]
-
t1tag = t1.get_tag(RepeaterDayPortion)
-
-
case t1tag.type
-
when :morning
-
puts '--morning->am' if Chronic.debug
-
t1.untag(RepeaterDayPortion)
-
t1.tag(RepeaterDayPortion.new(:am))
-
when :afternoon, :evening, :night
-
puts "--#{t1tag.type}->pm" if Chronic.debug
-
t1.untag(RepeaterDayPortion)
-
t1.tag(RepeaterDayPortion.new(:pm))
-
end
-
end
-
-
# handle ambiguous times if :ambiguous_time_range is specified
-
if options[:ambiguous_time_range] != :none
-
ambiguous_tokens = []
-
-
tokens.each_with_index do |token, i|
-
ambiguous_tokens << token
-
next_token = tokens[i + 1]
-
-
if token.get_tag(RepeaterTime) && token.get_tag(RepeaterTime).type.ambiguous? && (!next_token || !next_token.get_tag(RepeaterDayPortion))
-
distoken = Token.new('disambiguator')
-
-
distoken.tag(RepeaterDayPortion.new(options[:ambiguous_time_range]))
-
ambiguous_tokens << distoken
-
end
-
end
-
-
tokens = ambiguous_tokens
-
end
-
-
tokens
-
end
-
-
end
-
-
end
-
2
module Chronic
-
2
class MiniDate
-
2
attr_accessor :month, :day
-
-
2
def self.from_time(time)
-
new(time.month, time.day)
-
end
-
-
2
def initialize(month, day)
-
16
unless (1..12).include?(month)
-
raise ArgumentError, "1..12 are valid months"
-
end
-
-
16
@month = month
-
16
@day = day
-
end
-
-
2
def is_between?(md_start, md_end)
-
return false if (@month == md_start.month && @month == md_end.month) &&
-
(@day < md_start.day || @day > md_end.day)
-
return true if (@month == md_start.month && @day >= md_start.day) ||
-
(@month == md_end.month && @day <= md_end.day)
-
-
i = (md_start.month % 12) + 1
-
-
until i == md_end.month
-
return true if @month == i
-
i = (i % 12) + 1
-
end
-
-
return false
-
end
-
-
2
def equals?(other)
-
@month == other.month and @day == other.day
-
end
-
end
-
end
-
2
require 'strscan'
-
-
2
module Chronic
-
2
class Numerizer
-
-
2
DIRECT_NUMS = [
-
['eleven', '11'],
-
['twelve', '12'],
-
['thirteen', '13'],
-
['fourteen', '14'],
-
['fifteen', '15'],
-
['sixteen', '16'],
-
['seventeen', '17'],
-
['eighteen', '18'],
-
['nineteen', '19'],
-
['ninteen', '19'], # Common mis-spelling
-
['zero', '0'],
-
['one', '1'],
-
['two', '2'],
-
['three', '3'],
-
['four(\W|$)', '4\1'], # The weird regex is so that it matches four but not fourty
-
['five', '5'],
-
['six(\W|$)', '6\1'],
-
['seven(\W|$)', '7\1'],
-
['eight(\W|$)', '8\1'],
-
['nine(\W|$)', '9\1'],
-
['ten', '10'],
-
['\ba[\b^$]', '1'] # doesn't make sense for an 'a' at the end to be a 1
-
]
-
-
2
ORDINALS = [
-
['first', '1'],
-
['third', '3'],
-
['fourth', '4'],
-
['fifth', '5'],
-
['sixth', '6'],
-
['seventh', '7'],
-
['eighth', '8'],
-
['ninth', '9'],
-
['tenth', '10'],
-
['twelfth', '12'],
-
['twentieth', '20'],
-
['thirtieth', '30'],
-
['fourtieth', '40'],
-
['fiftieth', '50'],
-
['sixtieth', '60'],
-
['seventieth', '70'],
-
['eightieth', '80'],
-
['ninetieth', '90']
-
]
-
-
2
TEN_PREFIXES = [
-
['twenty', 20],
-
['thirty', 30],
-
['forty', 40],
-
['fourty', 40], # Common mis-spelling
-
['fifty', 50],
-
['sixty', 60],
-
['seventy', 70],
-
['eighty', 80],
-
['ninety', 90]
-
]
-
-
2
BIG_PREFIXES = [
-
['hundred', 100],
-
['thousand', 1000],
-
['million', 1_000_000],
-
['billion', 1_000_000_000],
-
['trillion', 1_000_000_000_000],
-
]
-
-
2
def self.numerize(string)
-
string = string.dup
-
-
# preprocess
-
string.gsub!(/ +|([^\d])-([^\d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction
-
string.gsub!(/a half/, 'haAlf') # take the 'a' out so it doesn't turn into a 1, save the half for the end
-
-
# easy/direct replacements
-
-
DIRECT_NUMS.each do |dn|
-
string.gsub!(/#{dn[0]}/i, '<num>' + dn[1])
-
end
-
-
ORDINALS.each do |on|
-
string.gsub!(/#{on[0]}/i, '<num>' + on[1] + on[0][-2, 2])
-
end
-
-
# ten, twenty, etc.
-
-
TEN_PREFIXES.each do |tp|
-
string.gsub!(/(?:#{tp[0]}) *<num>(\d(?=[^\d]|$))*/i) { '<num>' + (tp[1] + $1.to_i).to_s }
-
end
-
-
TEN_PREFIXES.each do |tp|
-
string.gsub!(/#{tp[0]}/i) { '<num>' + tp[1].to_s }
-
end
-
-
# hundreds, thousands, millions, etc.
-
-
BIG_PREFIXES.each do |bp|
-
string.gsub!(/(?:<num>)?(\d*) *#{bp[0]}/i) { $1.empty? ? bp[1] : '<num>' + (bp[1] * $1.to_i).to_s}
-
andition(string)
-
end
-
-
# fractional addition
-
# I'm not combining this with the previous block as using float addition complicates the strings
-
# (with extraneous .0's and such )
-
string.gsub!(/(\d+)(?: | and |-)*haAlf/i) { ($1.to_f + 0.5).to_s }
-
-
string.gsub(/<num>/, '')
-
end
-
-
2
class << self
-
2
private
-
-
2
def andition(string)
-
sc = StringScanner.new(string)
-
-
while sc.scan_until(/<num>(\d+)( | and )<num>(\d+)(?=[^\w]|$)/i)
-
if sc[2] =~ /and/ || sc[1].size > sc[3].size
-
string[(sc.pos - sc.matched_size)..(sc.pos-1)] = '<num>' + (sc[1].to_i + sc[3].to_i).to_s
-
sc.reset
-
end
-
end
-
end
-
-
end
-
end
-
end
-
2
module Chronic
-
2
class Ordinal < Tag
-
-
# Scan an Array of Token objects and apply any necessary Ordinal
-
# tags to each token.
-
#
-
# tokens - An Array of tokens to scan.
-
# options - The Hash of options specified in Chronic::parse.
-
#
-
# Returns an Array of tokens.
-
2
def self.scan(tokens, options)
-
tokens.each_index do |i|
-
if tokens[i].word =~ /^(\d+)(st|nd|rd|th|\.)$/
-
ordinal = $1.to_i
-
tokens[i].tag(Ordinal.new(ordinal))
-
tokens[i].tag(OrdinalDay.new(ordinal)) if Chronic::Date::could_be_day?(ordinal)
-
tokens[i].tag(OrdinalMonth.new(ordinal)) if Chronic::Date::could_be_month?(ordinal)
-
if Chronic::Date::could_be_year?(ordinal)
-
year = Chronic::Date::make_year(ordinal, options[:ambiguous_year_future_bias])
-
tokens[i].tag(OrdinalYear.new(year.to_i))
-
end
-
end
-
end
-
end
-
-
2
def to_s
-
'ordinal'
-
end
-
end
-
-
2
class OrdinalDay < Ordinal #:nodoc:
-
2
def to_s
-
super << '-day-' << @type.to_s
-
end
-
end
-
-
2
class OrdinalMonth < Ordinal #:nodoc:
-
2
def to_s
-
super << '-month-' << @type.to_s
-
end
-
end
-
-
2
class OrdinalYear < Ordinal #:nodoc:
-
2
def to_s
-
super << '-year-' << @type.to_s
-
end
-
end
-
-
end
-
2
require 'chronic/handlers'
-
-
2
module Chronic
-
2
class Parser
-
2
include Handlers
-
-
# Hash of default configuration options.
-
2
DEFAULT_OPTIONS = {
-
:context => :future,
-
:now => nil,
-
:hours24 => nil,
-
:guess => true,
-
:ambiguous_time_range => 6,
-
:endian_precedence => [:middle, :little],
-
:ambiguous_year_future_bias => 50
-
}
-
-
2
attr_accessor :now
-
2
attr_reader :options
-
-
# options - An optional Hash of configuration options:
-
# :context - If your string represents a birthday, you can set
-
# this value to :past and if an ambiguous string is
-
# given, it will assume it is in the past.
-
# :now - Time, all computations will be based off of time
-
# instead of Time.now.
-
# :hours24 - Time will be parsed as it would be 24 hour clock.
-
# :guess - By default the parser will guess a single point in time
-
# for the given date or time. If you'd rather have the
-
# entire time span returned, set this to false
-
# and a Chronic::Span will be returned. Setting :guess to :end
-
# will return last time from Span, to :middle for middle (same as just true)
-
# and :begin for first time from span.
-
# :ambiguous_time_range - If an Integer is given, ambiguous times
-
# (like 5:00) will be assumed to be within the range of
-
# that time in the AM to that time in the PM. For
-
# example, if you set it to `7`, then the parser will
-
# look for the time between 7am and 7pm. In the case of
-
# 5:00, it would assume that means 5:00pm. If `:none`
-
# is given, no assumption will be made, and the first
-
# matching instance of that time will be used.
-
# :endian_precedence - By default, Chronic will parse "03/04/2011"
-
# as the fourth day of the third month. Alternatively you
-
# can tell Chronic to parse this as the third day of the
-
# fourth month by setting this to [:little, :middle].
-
# :ambiguous_year_future_bias - When parsing two digit years
-
# (ie 79) unlike Rubys Time class, Chronic will attempt
-
# to assume the full year using this figure. Chronic will
-
# look x amount of years into the future and past. If the
-
# two digit year is `now + x years` it's assumed to be the
-
# future, `now - x years` is assumed to be the past.
-
2
def initialize(options = {})
-
@options = DEFAULT_OPTIONS.merge(options)
-
@now = options.delete(:now) || Chronic.time_class.now
-
end
-
-
# Parse "text" with the given options
-
# Returns either a Time or Chronic::Span, depending on the value of options[:guess]
-
2
def parse(text)
-
tokens = tokenize(text, options)
-
span = tokens_to_span(tokens, options.merge(:text => text))
-
-
puts "+#{'-' * 51}\n| #{tokens}\n+#{'-' * 51}" if Chronic.debug
-
-
guess(span, options[:guess]) if span
-
end
-
-
# Clean up the specified text ready for parsing.
-
#
-
# Clean up the string by stripping unwanted characters, converting
-
# idioms to their canonical form, converting number words to numbers
-
# (three => 3), and converting ordinal words to numeric
-
# ordinals (third => 3rd)
-
#
-
# text - The String text to normalize.
-
#
-
# Examples:
-
#
-
# Chronic.pre_normalize('first day in May')
-
# #=> "1st day in may"
-
#
-
# Chronic.pre_normalize('tomorrow after noon')
-
# #=> "next day future 12:00"
-
#
-
# Chronic.pre_normalize('one hundred and thirty six days from now')
-
# #=> "136 days future this second"
-
#
-
# Returns a new String ready for Chronic to parse.
-
2
def pre_normalize(text)
-
text = text.to_s.downcase
-
text.gsub!(/\b(\d{2})\.(\d{2})\.(\d{4})\b/, '\3 / \2 / \1')
-
text.gsub!(/\b([ap])\.m\.?/, '\1m')
-
text.gsub!(/(\s+|:\d{2}|:\d{2}\.\d{3})\-(\d{2}:?\d{2})\b/, '\1tzminus\2')
-
text.gsub!(/\./, ':')
-
text.gsub!(/([ap]):m:?/, '\1m')
-
text.gsub!(/['"]/, '')
-
text.gsub!(/,/, ' ')
-
text.gsub!(/^second /, '2nd ')
-
text.gsub!(/\bsecond (of|day|month|hour|minute|second)\b/, '2nd \1')
-
text = Numerizer.numerize(text)
-
text.gsub!(/([\/\-\,\@])/) { ' ' + $1 + ' ' }
-
text.gsub!(/(?:^|\s)0(\d+:\d+\s*pm?\b)/, ' \1')
-
text.gsub!(/\btoday\b/, 'this day')
-
text.gsub!(/\btomm?orr?ow\b/, 'next day')
-
text.gsub!(/\byesterday\b/, 'last day')
-
text.gsub!(/\bnoon\b/, '12:00pm')
-
text.gsub!(/\bmidnight\b/, '24:00')
-
text.gsub!(/\bnow\b/, 'this second')
-
text.gsub!('quarter', '15')
-
text.gsub!('half', '30')
-
text.gsub!(/(\d{1,2}) (to|till|prior to|before)\b/, '\1 minutes past')
-
text.gsub!(/(\d{1,2}) (after|past)\b/, '\1 minutes future')
-
text.gsub!(/\b(?:ago|before(?: now)?)\b/, 'past')
-
text.gsub!(/\bthis (?:last|past)\b/, 'last')
-
text.gsub!(/\b(?:in|during) the (morning)\b/, '\1')
-
text.gsub!(/\b(?:in the|during the|at) (afternoon|evening|night)\b/, '\1')
-
text.gsub!(/\btonight\b/, 'this night')
-
text.gsub!(/\b\d+:?\d*[ap]\b/,'\0m')
-
text.gsub!(/\b(\d{2})(\d{2})(am|pm)\b/, '\1:\2\3')
-
text.gsub!(/(\d)([ap]m|oclock)\b/, '\1 \2')
-
text.gsub!(/\b(hence|after|from)\b/, 'future')
-
text.gsub!(/^\s?an? /i, '1 ')
-
text.gsub!(/\b(\d{4}):(\d{2}):(\d{2})\b/, '\1 / \2 / \3') # DTOriginal
-
text.gsub!(/\b0(\d+):(\d{2}):(\d{2}) ([ap]m)\b/, '\1:\2:\3 \4')
-
text
-
end
-
-
# Guess a specific time within the given span.
-
#
-
# span - The Chronic::Span object to calcuate a guess from.
-
#
-
# Returns a new Time object.
-
2
def guess(span, mode = :middle)
-
return span if not mode
-
return span.begin + span.width / 2 if span.width > 1 and (mode == true or mode == :middle)
-
return span.end if mode == :end
-
span.begin
-
end
-
-
# List of Handler definitions. See Chronic.parse for a list of options this
-
# method accepts.
-
#
-
# options - An optional Hash of configuration options.
-
#
-
# Returns a Hash of Handler definitions.
-
2
def definitions(options = {})
-
options[:endian_precedence] ||= [:middle, :little]
-
-
@@definitions ||= {
-
:time => [
-
Handler.new([:repeater_time, :repeater_day_portion?], nil)
-
],
-
-
:date => [
-
Handler.new([:repeater_day_name, :repeater_month_name, :scalar_day, :repeater_time, [:separator_slash?, :separator_dash?], :time_zone, :scalar_year], :handle_generic),
-
Handler.new([:repeater_day_name, :repeater_month_name, :scalar_day], :handle_rdn_rmn_sd),
-
Handler.new([:repeater_day_name, :repeater_month_name, :scalar_day, :scalar_year], :handle_rdn_rmn_sd_sy),
-
Handler.new([:repeater_day_name, :repeater_month_name, :ordinal_day], :handle_rdn_rmn_od),
-
Handler.new([:repeater_day_name, :repeater_month_name, :ordinal_day, :scalar_year], :handle_rdn_rmn_od_sy),
-
Handler.new([:repeater_day_name, :repeater_month_name, :scalar_day, :separator_at?, 'time?'], :handle_rdn_rmn_sd),
-
Handler.new([:repeater_day_name, :repeater_month_name, :ordinal_day, :separator_at?, 'time?'], :handle_rdn_rmn_od),
-
Handler.new([:repeater_day_name, :ordinal_day, :separator_at?, 'time?'], :handle_rdn_od),
-
Handler.new([:scalar_year, [:separator_slash, :separator_dash], :scalar_month, [:separator_slash, :separator_dash], :scalar_day, :repeater_time, :time_zone], :handle_generic),
-
Handler.new([:ordinal_day], :handle_generic),
-
Handler.new([:repeater_month_name, :scalar_day, :scalar_year], :handle_rmn_sd_sy),
-
Handler.new([:repeater_month_name, :ordinal_day, :scalar_year], :handle_rmn_od_sy),
-
Handler.new([:repeater_month_name, :scalar_day, :scalar_year, :separator_at?, 'time?'], :handle_rmn_sd_sy),
-
Handler.new([:repeater_month_name, :ordinal_day, :scalar_year, :separator_at?, 'time?'], :handle_rmn_od_sy),
-
Handler.new([:repeater_month_name, [:separator_slash?, :separator_dash?], :scalar_day, :separator_at?, 'time?'], :handle_rmn_sd),
-
Handler.new([:repeater_time, :repeater_day_portion?, :separator_on?, :repeater_month_name, :scalar_day], :handle_rmn_sd_on),
-
Handler.new([:repeater_month_name, :ordinal_day, :separator_at?, 'time?'], :handle_rmn_od),
-
Handler.new([:ordinal_day, :repeater_month_name, :scalar_year, :separator_at?, 'time?'], :handle_od_rmn_sy),
-
Handler.new([:ordinal_day, :repeater_month_name, :separator_at?, 'time?'], :handle_od_rmn),
-
Handler.new([:ordinal_day, :grabber?, :repeater_month, :separator_at?, 'time?'], :handle_od_rm),
-
Handler.new([:scalar_year, :repeater_month_name, :ordinal_day], :handle_sy_rmn_od),
-
Handler.new([:repeater_time, :repeater_day_portion?, :separator_on?, :repeater_month_name, :ordinal_day], :handle_rmn_od_on),
-
Handler.new([:repeater_month_name, :scalar_year], :handle_rmn_sy),
-
Handler.new([:scalar_day, :repeater_month_name, :scalar_year, :separator_at?, 'time?'], :handle_sd_rmn_sy),
-
Handler.new([:scalar_day, [:separator_slash?, :separator_dash?], :repeater_month_name, :separator_at?, 'time?'], :handle_sd_rmn),
-
Handler.new([:scalar_year, [:separator_slash, :separator_dash], :scalar_month, [:separator_slash, :separator_dash], :scalar_day, :separator_at?, 'time?'], :handle_sy_sm_sd),
-
Handler.new([:scalar_year, [:separator_slash, :separator_dash], :scalar_month], :handle_sy_sm),
-
Handler.new([:scalar_month, [:separator_slash, :separator_dash], :scalar_year], :handle_sm_sy),
-
Handler.new([:scalar_day, [:separator_slash, :separator_dash], :repeater_month_name, [:separator_slash, :separator_dash], :scalar_year, :repeater_time?], :handle_sm_rmn_sy),
-
Handler.new([:scalar_year, [:separator_slash, :separator_dash], :scalar_month, [:separator_slash, :separator_dash], :scalar?, :time_zone], :handle_generic),
-
],
-
-
:anchor => [
-
Handler.new([:separator_on?, :grabber?, :repeater, :separator_at?, :repeater?, :repeater?], :handle_r),
-
Handler.new([:grabber?, :repeater, :repeater, :separator?, :repeater?, :repeater?], :handle_r),
-
Handler.new([:repeater, :grabber, :repeater], :handle_r_g_r)
-
],
-
-
:arrow => [
-
Handler.new([:scalar, :repeater, :pointer], :handle_s_r_p),
-
Handler.new([:scalar, :repeater, :separator_and?, :scalar, :repeater, :pointer, :separator_at?, 'anchor'], :handle_s_r_a_s_r_p_a),
-
Handler.new([:pointer, :scalar, :repeater], :handle_p_s_r),
-
Handler.new([:scalar, :repeater, :pointer, :separator_at?, 'anchor'], :handle_s_r_p_a)
-
],
-
-
:narrow => [
-
Handler.new([:ordinal, :repeater, :separator_in, :repeater], :handle_o_r_s_r),
-
Handler.new([:ordinal, :repeater, :grabber, :repeater], :handle_o_r_g_r)
-
]
-
}
-
-
endians = [
-
Handler.new([:scalar_month, [:separator_slash, :separator_dash], :scalar_day, [:separator_slash, :separator_dash], :scalar_year, :separator_at?, 'time?'], :handle_sm_sd_sy),
-
Handler.new([:scalar_month, [:separator_slash, :separator_dash], :scalar_day, :separator_at?, 'time?'], :handle_sm_sd),
-
Handler.new([:scalar_day, [:separator_slash, :separator_dash], :scalar_month, :separator_at?, 'time?'], :handle_sd_sm),
-
Handler.new([:scalar_day, [:separator_slash, :separator_dash], :scalar_month, [:separator_slash, :separator_dash], :scalar_year, :separator_at?, 'time?'], :handle_sd_sm_sy)
-
]
-
-
case endian = Array(options[:endian_precedence]).first
-
when :little
-
@@definitions.merge(:endian => endians.reverse)
-
when :middle
-
@@definitions.merge(:endian => endians)
-
else
-
raise ArgumentError, "Unknown endian option '#{endian}'"
-
end
-
end
-
-
2
private
-
-
2
def tokenize(text, options)
-
text = pre_normalize(text)
-
tokens = text.split(' ').map { |word| Token.new(word) }
-
[Repeater, Grabber, Pointer, Scalar, Ordinal, Separator, Sign, TimeZone].each do |tok|
-
tok.scan(tokens, options)
-
end
-
tokens.select { |token| token.tagged? }
-
end
-
-
2
def tokens_to_span(tokens, options)
-
definitions = definitions(options)
-
-
(definitions[:endian] + definitions[:date]).each do |handler|
-
if handler.match(tokens, definitions)
-
good_tokens = tokens.select { |o| !o.get_tag Separator }
-
return handler.invoke(:date, good_tokens, self, options)
-
end
-
end
-
-
definitions[:anchor].each do |handler|
-
if handler.match(tokens, definitions)
-
good_tokens = tokens.select { |o| !o.get_tag Separator }
-
return handler.invoke(:anchor, good_tokens, self, options)
-
end
-
end
-
-
definitions[:arrow].each do |handler|
-
if handler.match(tokens, definitions)
-
good_tokens = tokens.reject { |o| o.get_tag(SeparatorAt) || o.get_tag(SeparatorSlash) || o.get_tag(SeparatorDash) || o.get_tag(SeparatorComma) || o.get_tag(SeparatorAnd) }
-
return handler.invoke(:arrow, good_tokens, self, options)
-
end
-
end
-
-
definitions[:narrow].each do |handler|
-
if handler.match(tokens, definitions)
-
return handler.invoke(:narrow, tokens, self, options)
-
end
-
end
-
-
puts "-none" if Chronic.debug
-
return nil
-
end
-
end
-
end
-
2
module Chronic
-
2
class Pointer < Tag
-
-
# Scan an Array of Token objects and apply any necessary Pointer
-
# tags to each token.
-
#
-
# tokens - An Array of tokens to scan.
-
# options - The Hash of options specified in Chronic::parse.
-
#
-
# Returns an Array of tokens.
-
2
def self.scan(tokens, options)
-
tokens.each do |token|
-
if t = scan_for_all(token) then token.tag(t) end
-
end
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new Pointer object.
-
2
def self.scan_for_all(token)
-
scan_for token, self,
-
{
-
/\bpast\b/ => :past,
-
/\b(?:future|in)\b/ => :future,
-
}
-
end
-
-
2
def to_s
-
'pointer-' << @type.to_s
-
end
-
end
-
end
-
2
module Chronic
-
2
class Repeater < Tag
-
-
# Scan an Array of Token objects and apply any necessary Repeater
-
# tags to each token.
-
#
-
# tokens - An Array of tokens to scan.
-
# options - The Hash of options specified in Chronic::parse.
-
#
-
# Returns an Array of tokens.
-
2
def self.scan(tokens, options)
-
tokens.each do |token|
-
if t = scan_for_season_names(token, options) then token.tag(t); next end
-
if t = scan_for_month_names(token, options) then token.tag(t); next end
-
if t = scan_for_day_names(token, options) then token.tag(t); next end
-
if t = scan_for_day_portions(token, options) then token.tag(t); next end
-
if t = scan_for_times(token, options) then token.tag(t); next end
-
if t = scan_for_units(token, options) then token.tag(t); next end
-
end
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new Repeater object.
-
2
def self.scan_for_season_names(token, options = {})
-
scan_for token, RepeaterSeasonName,
-
{
-
/^springs?$/ => :spring,
-
/^summers?$/ => :summer,
-
/^(autumn)|(fall)s?$/ => :autumn,
-
/^winters?$/ => :winter
-
}, options
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new Repeater object.
-
2
def self.scan_for_month_names(token, options = {})
-
scan_for token, RepeaterMonthName,
-
{
-
/^jan[:\.]?(uary)?$/ => :january,
-
/^feb[:\.]?(ruary)?$/ => :february,
-
/^mar[:\.]?(ch)?$/ => :march,
-
/^apr[:\.]?(il)?$/ => :april,
-
/^may$/ => :may,
-
/^jun[:\.]?e?$/ => :june,
-
/^jul[:\.]?y?$/ => :july,
-
/^aug[:\.]?(ust)?$/ => :august,
-
/^sep[:\.]?(t[:\.]?|tember)?$/ => :september,
-
/^oct[:\.]?(ober)?$/ => :october,
-
/^nov[:\.]?(ember)?$/ => :november,
-
/^dec[:\.]?(ember)?$/ => :december
-
}, options
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new Repeater object.
-
2
def self.scan_for_day_names(token, options = {})
-
scan_for token, RepeaterDayName,
-
{
-
/^m[ou]n(day)?$/ => :monday,
-
/^t(ue|eu|oo|u|)s?(day)?$/ => :tuesday,
-
/^we(d|dnes|nds|nns)(day)?$/ => :wednesday,
-
/^th(u|ur|urs|ers)(day)?$/ => :thursday,
-
/^fr[iy](day)?$/ => :friday,
-
/^sat(t?[ue]rday)?$/ => :saturday,
-
/^su[nm](day)?$/ => :sunday
-
}, options
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new Repeater object.
-
2
def self.scan_for_day_portions(token, options = {})
-
scan_for token, RepeaterDayPortion,
-
{
-
/^ams?$/ => :am,
-
/^pms?$/ => :pm,
-
/^mornings?$/ => :morning,
-
/^afternoons?$/ => :afternoon,
-
/^evenings?$/ => :evening,
-
/^(night|nite)s?$/ => :night
-
}, options
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new Repeater object.
-
2
def self.scan_for_times(token, options = {})
-
scan_for token, RepeaterTime, /^\d{1,2}(:?\d{1,2})?([\.:]?\d{1,2}([\.:]\d{1,6})?)?$/, options
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new Repeater object.
-
2
def self.scan_for_units(token, options = {})
-
{
-
/^years?$/ => :year,
-
/^seasons?$/ => :season,
-
/^months?$/ => :month,
-
/^fortnights?$/ => :fortnight,
-
/^weeks?$/ => :week,
-
/^weekends?$/ => :weekend,
-
/^(week|business)days?$/ => :weekday,
-
/^days?$/ => :day,
-
/^hrs?$/ => :hour,
-
/^hours?$/ => :hour,
-
/^mins?$/ => :minute,
-
/^minutes?$/ => :minute,
-
/^secs?$/ => :second,
-
/^seconds?$/ => :second
-
}.each do |item, symbol|
-
if item =~ token.word
-
klass_name = 'Repeater' + symbol.to_s.capitalize
-
klass = Chronic.const_get(klass_name)
-
return klass.new(symbol, options)
-
end
-
end
-
return nil
-
end
-
-
2
def <=>(other)
-
width <=> other.width
-
end
-
-
# returns the width (in seconds or months) of this repeatable.
-
2
def width
-
raise("Repeater#width must be overridden in subclasses")
-
end
-
-
# returns the next occurance of this repeatable.
-
2
def next(pointer)
-
raise("Start point must be set before calling #next") unless @now
-
end
-
-
2
def this(pointer)
-
raise("Start point must be set before calling #this") unless @now
-
end
-
-
2
def to_s
-
'repeater'
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterDay < Repeater #:nodoc:
-
2
DAY_SECONDS = 86_400 # (24 * 60 * 60)
-
-
2
def initialize(type, options = {})
-
super
-
@current_day_start = nil
-
end
-
-
2
def next(pointer)
-
super
-
-
unless @current_day_start
-
@current_day_start = Chronic.time_class.local(@now.year, @now.month, @now.day)
-
end
-
-
direction = pointer == :future ? 1 : -1
-
@current_day_start += direction * DAY_SECONDS
-
-
Span.new(@current_day_start, @current_day_start + DAY_SECONDS)
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
case pointer
-
when :future
-
day_begin = Chronic.construct(@now.year, @now.month, @now.day, @now.hour)
-
day_end = Chronic.construct(@now.year, @now.month, @now.day) + DAY_SECONDS
-
when :past
-
day_begin = Chronic.construct(@now.year, @now.month, @now.day)
-
day_end = Chronic.construct(@now.year, @now.month, @now.day, @now.hour)
-
when :none
-
day_begin = Chronic.construct(@now.year, @now.month, @now.day)
-
day_end = Chronic.construct(@now.year, @now.month, @now.day) + DAY_SECONDS
-
end
-
-
Span.new(day_begin, day_end)
-
end
-
-
2
def offset(span, amount, pointer)
-
direction = pointer == :future ? 1 : -1
-
span + direction * amount * DAY_SECONDS
-
end
-
-
2
def width
-
DAY_SECONDS
-
end
-
-
2
def to_s
-
super << '-day'
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterDayName < Repeater #:nodoc:
-
2
DAY_SECONDS = 86400 # (24 * 60 * 60)
-
-
2
def initialize(type, options = {})
-
super
-
@current_date = nil
-
end
-
-
2
def next(pointer)
-
super
-
-
direction = pointer == :future ? 1 : -1
-
-
unless @current_date
-
@current_date = ::Date.new(@now.year, @now.month, @now.day)
-
@current_date += direction
-
-
day_num = symbol_to_number(@type)
-
-
while @current_date.wday != day_num
-
@current_date += direction
-
end
-
else
-
@current_date += direction * 7
-
end
-
next_date = @current_date.succ
-
Span.new(Chronic.construct(@current_date.year, @current_date.month, @current_date.day), Chronic.construct(next_date.year, next_date.month, next_date.day))
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
pointer = :future if pointer == :none
-
self.next(pointer)
-
end
-
-
2
def width
-
DAY_SECONDS
-
end
-
-
2
def to_s
-
super << '-dayname-' << @type.to_s
-
end
-
-
2
private
-
-
2
def symbol_to_number(sym)
-
lookup = {:sunday => 0, :monday => 1, :tuesday => 2, :wednesday => 3, :thursday => 4, :friday => 5, :saturday => 6}
-
lookup[sym] || raise("Invalid symbol specified")
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterDayPortion < Repeater #:nodoc:
-
2
PORTIONS = {
-
2
:am => 0..(12 * 60 * 60 - 1),
-
2
:pm => (12 * 60 * 60)..(24 * 60 * 60 - 1),
-
2
:morning => (6 * 60 * 60)..(12 * 60 * 60), # 6am-12am,
-
2
:afternoon => (13 * 60 * 60)..(17 * 60 * 60), # 1pm-5pm,
-
2
:evening => (17 * 60 * 60)..(20 * 60 * 60), # 5pm-8pm,
-
2
:night => (20 * 60 * 60)..(24 * 60 * 60), # 8pm-12pm
-
}
-
-
2
def initialize(type, options = {})
-
super
-
@current_span = nil
-
-
if type.kind_of? Integer
-
@range = (@type * 60 * 60)..((@type + 12) * 60 * 60)
-
else
-
@range = PORTIONS[type]
-
@range || raise("Invalid type '#{type}' for RepeaterDayPortion")
-
end
-
-
@range || raise("Range should have been set by now")
-
end
-
-
2
def next(pointer)
-
super
-
-
unless @current_span
-
now_seconds = @now - Chronic.construct(@now.year, @now.month, @now.day)
-
if now_seconds < @range.begin
-
case pointer
-
when :future
-
range_start = Chronic.construct(@now.year, @now.month, @now.day) + @range.begin
-
when :past
-
range_start = Chronic.construct(@now.year, @now.month, @now.day - 1) + @range.begin
-
end
-
elsif now_seconds > @range.end
-
case pointer
-
when :future
-
range_start = Chronic.construct(@now.year, @now.month, @now.day + 1) + @range.begin
-
when :past
-
range_start = Chronic.construct(@now.year, @now.month, @now.day) + @range.begin
-
end
-
else
-
case pointer
-
when :future
-
range_start = Chronic.construct(@now.year, @now.month, @now.day + 1) + @range.begin
-
when :past
-
range_start = Chronic.construct(@now.year, @now.month, @now.day - 1) + @range.begin
-
end
-
end
-
offset = (@range.end - @range.begin)
-
range_end = construct_date_from_reference_and_offset(range_start, offset)
-
@current_span = Span.new(range_start, range_end)
-
else
-
days_to_shift_window =
-
case pointer
-
when :future
-
1
-
when :past
-
-1
-
end
-
-
new_begin = Chronic.construct(@current_span.begin.year, @current_span.begin.month, @current_span.begin.day + days_to_shift_window, @current_span.begin.hour, @current_span.begin.min, @current_span.begin.sec)
-
new_end = Chronic.construct(@current_span.end.year, @current_span.end.month, @current_span.end.day + days_to_shift_window, @current_span.end.hour, @current_span.end.min, @current_span.end.sec)
-
@current_span = Span.new(new_begin, new_end)
-
end
-
end
-
-
2
def this(context = :future)
-
super
-
-
range_start = Chronic.construct(@now.year, @now.month, @now.day) + @range.begin
-
range_end = construct_date_from_reference_and_offset(range_start)
-
@current_span = Span.new(range_start, range_end)
-
end
-
-
2
def offset(span, amount, pointer)
-
@now = span.begin
-
portion_span = self.next(pointer)
-
direction = pointer == :future ? 1 : -1
-
portion_span + (direction * (amount - 1) * RepeaterDay::DAY_SECONDS)
-
end
-
-
2
def width
-
@range || raise("Range has not been set")
-
return @current_span.width if @current_span
-
if @type.kind_of? Integer
-
return (12 * 60 * 60)
-
else
-
@range.end - @range.begin
-
end
-
end
-
-
2
def to_s
-
super << '-dayportion-' << @type.to_s
-
end
-
-
2
private
-
2
def construct_date_from_reference_and_offset(reference, offset = nil)
-
elapsed_seconds_for_range = offset || (@range.end - @range.begin)
-
second_hand = ((elapsed_seconds_for_range - (12 * 60))) % 60
-
minute_hand = (elapsed_seconds_for_range - second_hand) / (60) % 60
-
hour_hand = (elapsed_seconds_for_range - minute_hand - second_hand) / (60 * 60) + reference.hour % 24
-
Chronic.construct(reference.year, reference.month, reference.day, hour_hand, minute_hand, second_hand)
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterFortnight < Repeater #:nodoc:
-
2
FORTNIGHT_SECONDS = 1_209_600 # (14 * 24 * 60 * 60)
-
-
2
def initialize(type, options = {})
-
super
-
@current_fortnight_start = nil
-
end
-
-
2
def next(pointer)
-
super
-
-
unless @current_fortnight_start
-
case pointer
-
when :future
-
sunday_repeater = RepeaterDayName.new(:sunday)
-
sunday_repeater.start = @now
-
next_sunday_span = sunday_repeater.next(:future)
-
@current_fortnight_start = next_sunday_span.begin
-
when :past
-
sunday_repeater = RepeaterDayName.new(:sunday)
-
sunday_repeater.start = (@now + RepeaterDay::DAY_SECONDS)
-
2.times { sunday_repeater.next(:past) }
-
last_sunday_span = sunday_repeater.next(:past)
-
@current_fortnight_start = last_sunday_span.begin
-
end
-
else
-
direction = pointer == :future ? 1 : -1
-
@current_fortnight_start += direction * FORTNIGHT_SECONDS
-
end
-
-
Span.new(@current_fortnight_start, @current_fortnight_start + FORTNIGHT_SECONDS)
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
pointer = :future if pointer == :none
-
-
case pointer
-
when :future
-
this_fortnight_start = Chronic.construct(@now.year, @now.month, @now.day, @now.hour) + RepeaterHour::HOUR_SECONDS
-
sunday_repeater = RepeaterDayName.new(:sunday)
-
sunday_repeater.start = @now
-
sunday_repeater.this(:future)
-
this_sunday_span = sunday_repeater.this(:future)
-
this_fortnight_end = this_sunday_span.begin
-
Span.new(this_fortnight_start, this_fortnight_end)
-
when :past
-
this_fortnight_end = Chronic.construct(@now.year, @now.month, @now.day, @now.hour)
-
sunday_repeater = RepeaterDayName.new(:sunday)
-
sunday_repeater.start = @now
-
last_sunday_span = sunday_repeater.next(:past)
-
this_fortnight_start = last_sunday_span.begin
-
Span.new(this_fortnight_start, this_fortnight_end)
-
end
-
end
-
-
2
def offset(span, amount, pointer)
-
direction = pointer == :future ? 1 : -1
-
span + direction * amount * FORTNIGHT_SECONDS
-
end
-
-
2
def width
-
FORTNIGHT_SECONDS
-
end
-
-
2
def to_s
-
super << '-fortnight'
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterHour < Repeater #:nodoc:
-
2
HOUR_SECONDS = 3600 # 60 * 60
-
-
2
def initialize(type, options = {})
-
super
-
@current_hour_start = nil
-
end
-
-
2
def next(pointer)
-
super
-
-
unless @current_hour_start
-
case pointer
-
when :future
-
@current_hour_start = Chronic.construct(@now.year, @now.month, @now.day, @now.hour + 1)
-
when :past
-
@current_hour_start = Chronic.construct(@now.year, @now.month, @now.day, @now.hour - 1)
-
end
-
else
-
direction = pointer == :future ? 1 : -1
-
@current_hour_start += direction * HOUR_SECONDS
-
end
-
-
Span.new(@current_hour_start, @current_hour_start + HOUR_SECONDS)
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
case pointer
-
when :future
-
hour_start = Chronic.construct(@now.year, @now.month, @now.day, @now.hour, @now.min + 1)
-
hour_end = Chronic.construct(@now.year, @now.month, @now.day, @now.hour + 1)
-
when :past
-
hour_start = Chronic.construct(@now.year, @now.month, @now.day, @now.hour)
-
hour_end = Chronic.construct(@now.year, @now.month, @now.day, @now.hour, @now.min)
-
when :none
-
hour_start = Chronic.construct(@now.year, @now.month, @now.day, @now.hour)
-
hour_end = hour_start + HOUR_SECONDS
-
end
-
-
Span.new(hour_start, hour_end)
-
end
-
-
2
def offset(span, amount, pointer)
-
direction = pointer == :future ? 1 : -1
-
span + direction * amount * HOUR_SECONDS
-
end
-
-
2
def width
-
HOUR_SECONDS
-
end
-
-
2
def to_s
-
super << '-hour'
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterMinute < Repeater #:nodoc:
-
2
MINUTE_SECONDS = 60
-
-
2
def initialize(type, options = {})
-
super
-
@current_minute_start = nil
-
end
-
-
2
def next(pointer = :future)
-
super
-
-
unless @current_minute_start
-
case pointer
-
when :future
-
@current_minute_start = Chronic.construct(@now.year, @now.month, @now.day, @now.hour, @now.min + 1)
-
when :past
-
@current_minute_start = Chronic.construct(@now.year, @now.month, @now.day, @now.hour, @now.min - 1)
-
end
-
else
-
direction = pointer == :future ? 1 : -1
-
@current_minute_start += direction * MINUTE_SECONDS
-
end
-
-
Span.new(@current_minute_start, @current_minute_start + MINUTE_SECONDS)
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
case pointer
-
when :future
-
minute_begin = @now
-
minute_end = Chronic.construct(@now.year, @now.month, @now.day, @now.hour, @now.min)
-
when :past
-
minute_begin = Chronic.construct(@now.year, @now.month, @now.day, @now.hour, @now.min)
-
minute_end = @now
-
when :none
-
minute_begin = Chronic.construct(@now.year, @now.month, @now.day, @now.hour, @now.min)
-
minute_end = Chronic.construct(@now.year, @now.month, @now.day, @now.hour, @now.min) + MINUTE_SECONDS
-
end
-
-
Span.new(minute_begin, minute_end)
-
end
-
-
2
def offset(span, amount, pointer)
-
direction = pointer == :future ? 1 : -1
-
span + direction * amount * MINUTE_SECONDS
-
end
-
-
2
def width
-
MINUTE_SECONDS
-
end
-
-
2
def to_s
-
super << '-minute'
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterMonth < Repeater #:nodoc:
-
2
MONTH_SECONDS = 2_592_000 # 30 * 24 * 60 * 60
-
2
YEAR_MONTHS = 12
-
2
MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-
2
MONTH_DAYS_LEAP = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-
-
2
def initialize(type, options = {})
-
super
-
@current_month_start = nil
-
end
-
-
2
def next(pointer)
-
super
-
-
unless @current_month_start
-
@current_month_start = offset_by(Chronic.construct(@now.year, @now.month), 1, pointer)
-
else
-
@current_month_start = offset_by(Chronic.construct(@current_month_start.year, @current_month_start.month), 1, pointer)
-
end
-
-
Span.new(@current_month_start, Chronic.construct(@current_month_start.year, @current_month_start.month + 1))
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
case pointer
-
when :future
-
month_start = Chronic.construct(@now.year, @now.month, @now.day + 1)
-
month_end = self.offset_by(Chronic.construct(@now.year, @now.month), 1, :future)
-
when :past
-
month_start = Chronic.construct(@now.year, @now.month)
-
month_end = Chronic.construct(@now.year, @now.month, @now.day)
-
when :none
-
month_start = Chronic.construct(@now.year, @now.month)
-
month_end = self.offset_by(Chronic.construct(@now.year, @now.month), 1, :future)
-
end
-
-
Span.new(month_start, month_end)
-
end
-
-
2
def offset(span, amount, pointer)
-
Span.new(offset_by(span.begin, amount, pointer), offset_by(span.end, amount, pointer))
-
end
-
-
2
def offset_by(time, amount, pointer)
-
direction = pointer == :future ? 1 : -1
-
-
amount_years = direction * amount / YEAR_MONTHS
-
amount_months = direction * amount % YEAR_MONTHS
-
-
new_year = time.year + amount_years
-
new_month = time.month + amount_months
-
if new_month > YEAR_MONTHS
-
new_year += 1
-
new_month -= YEAR_MONTHS
-
end
-
-
days = month_days(new_year, new_month)
-
new_day = time.day > days ? days : time.day
-
-
Chronic.construct(new_year, new_month, new_day, time.hour, time.min, time.sec)
-
end
-
-
2
def width
-
MONTH_SECONDS
-
end
-
-
2
def to_s
-
super << '-month'
-
end
-
-
2
private
-
-
2
def month_days(year, month)
-
::Date.leap?(year) ? MONTH_DAYS_LEAP[month - 1] : MONTH_DAYS[month - 1]
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterMonthName < Repeater #:nodoc:
-
2
MONTH_SECONDS = 2_592_000 # 30 * 24 * 60 * 60
-
2
MONTHS = {
-
:january => 1,
-
:february => 2,
-
:march => 3,
-
:april => 4,
-
:may => 5,
-
:june => 6,
-
:july => 7,
-
:august => 8,
-
:september => 9,
-
:october => 10,
-
:november => 11,
-
:december => 12
-
}
-
-
2
def initialize(type, options = {})
-
super
-
@current_month_begin = nil
-
end
-
-
2
def next(pointer)
-
super
-
-
unless @current_month_begin
-
case pointer
-
when :future
-
if @now.month < index
-
@current_month_begin = Chronic.construct(@now.year, index)
-
elsif @now.month > index
-
@current_month_begin = Chronic.construct(@now.year + 1, index)
-
end
-
when :none
-
if @now.month <= index
-
@current_month_begin = Chronic.construct(@now.year, index)
-
elsif @now.month > index
-
@current_month_begin = Chronic.construct(@now.year + 1, index)
-
end
-
when :past
-
if @now.month >= index
-
@current_month_begin = Chronic.construct(@now.year, index)
-
elsif @now.month < index
-
@current_month_begin = Chronic.construct(@now.year - 1, index)
-
end
-
end
-
@current_month_begin || raise("Current month should be set by now")
-
else
-
case pointer
-
when :future
-
@current_month_begin = Chronic.construct(@current_month_begin.year + 1, @current_month_begin.month)
-
when :past
-
@current_month_begin = Chronic.construct(@current_month_begin.year - 1, @current_month_begin.month)
-
end
-
end
-
-
cur_month_year = @current_month_begin.year
-
cur_month_month = @current_month_begin.month
-
-
if cur_month_month == 12
-
next_month_year = cur_month_year + 1
-
next_month_month = 1
-
else
-
next_month_year = cur_month_year
-
next_month_month = cur_month_month + 1
-
end
-
-
Span.new(@current_month_begin, Chronic.construct(next_month_year, next_month_month))
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
case pointer
-
when :past
-
self.next(pointer)
-
when :future, :none
-
self.next(:none)
-
end
-
end
-
-
2
def width
-
MONTH_SECONDS
-
end
-
-
2
def index
-
@index ||= MONTHS[@type]
-
end
-
-
2
def to_s
-
super << '-monthname-' << @type.to_s
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterSeason < Repeater #:nodoc:
-
2
SEASON_SECONDS = 7_862_400 # 91 * 24 * 60 * 60
-
2
SEASONS = {
-
:spring => Season.new(MiniDate.new(3,20), MiniDate.new(6,20)),
-
:summer => Season.new(MiniDate.new(6,21), MiniDate.new(9,22)),
-
:autumn => Season.new(MiniDate.new(9,23), MiniDate.new(12,21)),
-
:winter => Season.new(MiniDate.new(12,22), MiniDate.new(3,19))
-
}
-
-
2
def initialize(type, options = {})
-
super
-
@next_season_start = nil
-
@next_season_end = nil
-
end
-
-
2
def next(pointer)
-
super
-
-
direction = pointer == :future ? 1 : -1
-
next_season = Season.find_next_season(find_current_season(MiniDate.from_time(@now)), direction)
-
-
find_next_season_span(direction, next_season)
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
direction = pointer == :future ? 1 : -1
-
-
today = Chronic.construct(@now.year, @now.month, @now.day)
-
this_ssn = find_current_season(MiniDate.from_time(@now))
-
case pointer
-
when :past
-
this_ssn_start = today + direction * num_seconds_til_start(this_ssn, direction)
-
this_ssn_end = today
-
when :future
-
this_ssn_start = today + RepeaterDay::DAY_SECONDS
-
this_ssn_end = today + direction * num_seconds_til_end(this_ssn, direction)
-
when :none
-
this_ssn_start = today + direction * num_seconds_til_start(this_ssn, direction)
-
this_ssn_end = today + direction * num_seconds_til_end(this_ssn, direction)
-
end
-
-
construct_season(this_ssn_start, this_ssn_end)
-
end
-
-
2
def offset(span, amount, pointer)
-
Span.new(offset_by(span.begin, amount, pointer), offset_by(span.end, amount, pointer))
-
end
-
-
2
def offset_by(time, amount, pointer)
-
direction = pointer == :future ? 1 : -1
-
time + amount * direction * SEASON_SECONDS
-
end
-
-
2
def width
-
SEASON_SECONDS
-
end
-
-
2
def to_s
-
super << '-season'
-
end
-
-
2
private
-
-
2
def find_next_season_span(direction, next_season)
-
unless @next_season_start || @next_season_end
-
@next_season_start = Chronic.construct(@now.year, @now.month, @now.day)
-
@next_season_end = Chronic.construct(@now.year, @now.month, @now.day)
-
end
-
-
@next_season_start += direction * num_seconds_til_start(next_season, direction)
-
@next_season_end += direction * num_seconds_til_end(next_season, direction)
-
-
construct_season(@next_season_start, @next_season_end)
-
end
-
-
2
def find_current_season(md)
-
[:spring, :summer, :autumn, :winter].find do |season|
-
md.is_between?(SEASONS[season].start, SEASONS[season].end)
-
end
-
end
-
-
2
def num_seconds_til(goal, direction)
-
start = Chronic.construct(@now.year, @now.month, @now.day)
-
seconds = 0
-
-
until MiniDate.from_time(start + direction * seconds).equals?(goal)
-
seconds += RepeaterDay::DAY_SECONDS
-
end
-
-
seconds
-
end
-
-
2
def num_seconds_til_start(season_symbol, direction)
-
num_seconds_til(SEASONS[season_symbol].start, direction)
-
end
-
-
2
def num_seconds_til_end(season_symbol, direction)
-
num_seconds_til(SEASONS[season_symbol].end, direction)
-
end
-
-
2
def construct_season(start, finish)
-
Span.new(
-
Chronic.construct(start.year, start.month, start.day),
-
Chronic.construct(finish.year, finish.month, finish.day)
-
)
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterSeasonName < RepeaterSeason #:nodoc:
-
2
SEASON_SECONDS = 7_862_400 # 91 * 24 * 60 * 60
-
2
DAY_SECONDS = 86_400 # (24 * 60 * 60)
-
-
2
def next(pointer)
-
direction = pointer == :future ? 1 : -1
-
find_next_season_span(direction, @type)
-
end
-
-
2
def this(pointer = :future)
-
direction = pointer == :future ? 1 : -1
-
-
today = Chronic.construct(@now.year, @now.month, @now.day)
-
goal_ssn_start = today + direction * num_seconds_til_start(@type, direction)
-
goal_ssn_end = today + direction * num_seconds_til_end(@type, direction)
-
curr_ssn = find_current_season(MiniDate.from_time(@now))
-
case pointer
-
when :past
-
this_ssn_start = goal_ssn_start
-
this_ssn_end = (curr_ssn == @type) ? today : goal_ssn_end
-
when :future
-
this_ssn_start = (curr_ssn == @type) ? today + RepeaterDay::DAY_SECONDS : goal_ssn_start
-
this_ssn_end = goal_ssn_end
-
when :none
-
this_ssn_start = goal_ssn_start
-
this_ssn_end = goal_ssn_end
-
end
-
-
construct_season(this_ssn_start, this_ssn_end)
-
end
-
-
2
def offset(span, amount, pointer)
-
Span.new(offset_by(span.begin, amount, pointer), offset_by(span.end, amount, pointer))
-
end
-
-
2
def offset_by(time, amount, pointer)
-
direction = pointer == :future ? 1 : -1
-
time + amount * direction * RepeaterYear::YEAR_SECONDS
-
end
-
-
end
-
end
-
2
module Chronic
-
2
class RepeaterSecond < Repeater #:nodoc:
-
2
SECOND_SECONDS = 1 # haha, awesome
-
-
2
def initialize(type, options = {})
-
super
-
@second_start = nil
-
end
-
-
2
def next(pointer = :future)
-
super
-
-
direction = pointer == :future ? 1 : -1
-
-
unless @second_start
-
@second_start = @now + (direction * SECOND_SECONDS)
-
else
-
@second_start += SECOND_SECONDS * direction
-
end
-
-
Span.new(@second_start, @second_start + SECOND_SECONDS)
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
Span.new(@now, @now + 1)
-
end
-
-
2
def offset(span, amount, pointer)
-
direction = pointer == :future ? 1 : -1
-
span + direction * amount * SECOND_SECONDS
-
end
-
-
2
def width
-
SECOND_SECONDS
-
end
-
-
2
def to_s
-
super << '-second'
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterTime < Repeater #:nodoc:
-
2
class Tick #:nodoc:
-
2
attr_accessor :time
-
-
2
def initialize(time, ambiguous = false)
-
@time = time
-
@ambiguous = ambiguous
-
end
-
-
2
def ambiguous?
-
@ambiguous
-
end
-
-
2
def *(other)
-
Tick.new(@time * other, @ambiguous)
-
end
-
-
2
def to_f
-
@time.to_f
-
end
-
-
2
def to_s
-
@time.to_s + (@ambiguous ? '?' : '')
-
end
-
-
end
-
-
2
def initialize(time, options = {})
-
@current_time = nil
-
@options = options
-
time_parts = time.split(':')
-
raise ArgumentError, "Time cannot have more than 4 groups of ':'" if time_parts.count > 4
-
-
if time_parts.first.length > 2 and time_parts.count == 1
-
if time_parts.first.length > 4
-
second_index = time_parts.first.length - 2
-
time_parts.insert(1, time_parts.first[second_index..time_parts.first.length])
-
time_parts[0] = time_parts.first[0..second_index - 1]
-
end
-
minute_index = time_parts.first.length - 2
-
time_parts.insert(1, time_parts.first[minute_index..time_parts.first.length])
-
time_parts[0] = time_parts.first[0..minute_index - 1]
-
end
-
-
ambiguous = false
-
hours = time_parts.first.to_i
-
-
if @options[:hours24].nil? or (not @options[:hours24].nil? and @options[:hours24] != true)
-
ambiguous = true if (time_parts.first.length == 1 and hours > 0) or (hours >= 10 and hours <= 12) or (@options[:hours24] == false and hours > 0)
-
hours = 0 if hours == 12 and ambiguous
-
end
-
-
hours *= 60 * 60
-
minutes = 0
-
seconds = 0
-
subseconds = 0
-
-
minutes = time_parts[1].to_i * 60 if time_parts.count > 1
-
seconds = time_parts[2].to_i if time_parts.count > 2
-
subseconds = time_parts[3].to_f / (10 ** time_parts[3].length) if time_parts.count > 3
-
-
@type = Tick.new(hours + minutes + seconds + subseconds, ambiguous)
-
end
-
-
# Return the next past or future Span for the time that this Repeater represents
-
# pointer - Symbol representing which temporal direction to fetch the next day
-
# must be either :past or :future
-
2
def next(pointer)
-
super
-
-
half_day = 60 * 60 * 12
-
full_day = 60 * 60 * 24
-
-
first = false
-
-
unless @current_time
-
first = true
-
midnight = Chronic.time_class.local(@now.year, @now.month, @now.day)
-
-
yesterday_midnight = midnight - full_day
-
tomorrow_midnight = midnight + full_day
-
-
offset_fix = midnight.gmt_offset - tomorrow_midnight.gmt_offset
-
tomorrow_midnight += offset_fix
-
-
catch :done do
-
if pointer == :future
-
if @type.ambiguous?
-
[midnight + @type.time + offset_fix, midnight + half_day + @type.time + offset_fix, tomorrow_midnight + @type.time].each do |t|
-
(@current_time = t; throw :done) if t >= @now
-
end
-
else
-
[midnight + @type.time + offset_fix, tomorrow_midnight + @type.time].each do |t|
-
(@current_time = t; throw :done) if t >= @now
-
end
-
end
-
else # pointer == :past
-
if @type.ambiguous?
-
[midnight + half_day + @type.time + offset_fix, midnight + @type.time + offset_fix, yesterday_midnight + @type.time + half_day].each do |t|
-
(@current_time = t; throw :done) if t <= @now
-
end
-
else
-
[midnight + @type.time + offset_fix, yesterday_midnight + @type.time].each do |t|
-
(@current_time = t; throw :done) if t <= @now
-
end
-
end
-
end
-
end
-
-
@current_time || raise("Current time cannot be nil at this point")
-
end
-
-
unless first
-
increment = @type.ambiguous? ? half_day : full_day
-
@current_time += pointer == :future ? increment : -increment
-
end
-
-
Span.new(@current_time, @current_time + width)
-
end
-
-
2
def this(context = :future)
-
super
-
-
context = :future if context == :none
-
-
self.next(context)
-
end
-
-
2
def width
-
1
-
end
-
-
2
def to_s
-
super << '-time-' << @type.to_s
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterWeek < Repeater #:nodoc:
-
2
WEEK_SECONDS = 604800 # (7 * 24 * 60 * 60)
-
-
2
def initialize(type, options = {})
-
super
-
@current_week_start = nil
-
end
-
-
2
def next(pointer)
-
super
-
-
unless @current_week_start
-
case pointer
-
when :future
-
sunday_repeater = RepeaterDayName.new(:sunday)
-
sunday_repeater.start = @now
-
next_sunday_span = sunday_repeater.next(:future)
-
@current_week_start = next_sunday_span.begin
-
when :past
-
sunday_repeater = RepeaterDayName.new(:sunday)
-
sunday_repeater.start = (@now + RepeaterDay::DAY_SECONDS)
-
sunday_repeater.next(:past)
-
last_sunday_span = sunday_repeater.next(:past)
-
@current_week_start = last_sunday_span.begin
-
end
-
else
-
direction = pointer == :future ? 1 : -1
-
@current_week_start += direction * WEEK_SECONDS
-
end
-
-
Span.new(@current_week_start, @current_week_start + WEEK_SECONDS)
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
case pointer
-
when :future
-
this_week_start = Chronic.time_class.local(@now.year, @now.month, @now.day, @now.hour) + RepeaterHour::HOUR_SECONDS
-
sunday_repeater = RepeaterDayName.new(:sunday)
-
sunday_repeater.start = @now
-
this_sunday_span = sunday_repeater.this(:future)
-
this_week_end = this_sunday_span.begin
-
Span.new(this_week_start, this_week_end)
-
when :past
-
this_week_end = Chronic.time_class.local(@now.year, @now.month, @now.day, @now.hour)
-
sunday_repeater = RepeaterDayName.new(:sunday)
-
sunday_repeater.start = @now
-
last_sunday_span = sunday_repeater.next(:past)
-
this_week_start = last_sunday_span.begin
-
Span.new(this_week_start, this_week_end)
-
when :none
-
sunday_repeater = RepeaterDayName.new(:sunday)
-
sunday_repeater.start = @now
-
last_sunday_span = sunday_repeater.next(:past)
-
this_week_start = last_sunday_span.begin
-
Span.new(this_week_start, this_week_start + WEEK_SECONDS)
-
end
-
end
-
-
2
def offset(span, amount, pointer)
-
direction = pointer == :future ? 1 : -1
-
span + direction * amount * WEEK_SECONDS
-
end
-
-
2
def width
-
WEEK_SECONDS
-
end
-
-
2
def to_s
-
super << '-week'
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterWeekday < Repeater #:nodoc:
-
2
DAY_SECONDS = 86400 # (24 * 60 * 60)
-
2
DAYS = {
-
:sunday => 0,
-
:monday => 1,
-
:tuesday => 2,
-
:wednesday => 3,
-
:thursday => 4,
-
:friday => 5,
-
:saturday => 6
-
}
-
-
2
def initialize(type, options = {})
-
super
-
@current_weekday_start = nil
-
end
-
-
2
def next(pointer)
-
super
-
-
direction = pointer == :future ? 1 : -1
-
-
unless @current_weekday_start
-
@current_weekday_start = Chronic.construct(@now.year, @now.month, @now.day)
-
@current_weekday_start += direction * DAY_SECONDS
-
-
until is_weekday?(@current_weekday_start.wday)
-
@current_weekday_start += direction * DAY_SECONDS
-
end
-
else
-
loop do
-
@current_weekday_start += direction * DAY_SECONDS
-
break if is_weekday?(@current_weekday_start.wday)
-
end
-
end
-
-
Span.new(@current_weekday_start, @current_weekday_start + DAY_SECONDS)
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
case pointer
-
when :past
-
self.next(:past)
-
when :future, :none
-
self.next(:future)
-
end
-
end
-
-
2
def offset(span, amount, pointer)
-
direction = pointer == :future ? 1 : -1
-
-
num_weekdays_passed = 0; offset = 0
-
until num_weekdays_passed == amount
-
offset += direction * DAY_SECONDS
-
num_weekdays_passed += 1 if is_weekday?((span.begin+offset).wday)
-
end
-
-
span + offset
-
end
-
-
2
def width
-
DAY_SECONDS
-
end
-
-
2
def to_s
-
super << '-weekday'
-
end
-
-
2
private
-
-
2
def is_weekend?(day)
-
day == symbol_to_number(:saturday) || day == symbol_to_number(:sunday)
-
end
-
-
2
def is_weekday?(day)
-
!is_weekend?(day)
-
end
-
-
2
def symbol_to_number(sym)
-
DAYS[sym] || raise("Invalid symbol specified")
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterWeekend < Repeater #:nodoc:
-
2
WEEKEND_SECONDS = 172_800 # (2 * 24 * 60 * 60)
-
-
2
def initialize(type, options = {})
-
super
-
@current_week_start = nil
-
end
-
-
2
def next(pointer)
-
super
-
-
unless @current_week_start
-
case pointer
-
when :future
-
saturday_repeater = RepeaterDayName.new(:saturday)
-
saturday_repeater.start = @now
-
next_saturday_span = saturday_repeater.next(:future)
-
@current_week_start = next_saturday_span.begin
-
when :past
-
saturday_repeater = RepeaterDayName.new(:saturday)
-
saturday_repeater.start = (@now + RepeaterDay::DAY_SECONDS)
-
last_saturday_span = saturday_repeater.next(:past)
-
@current_week_start = last_saturday_span.begin
-
end
-
else
-
direction = pointer == :future ? 1 : -1
-
@current_week_start += direction * RepeaterWeek::WEEK_SECONDS
-
end
-
-
Span.new(@current_week_start, @current_week_start + WEEKEND_SECONDS)
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
case pointer
-
when :future, :none
-
saturday_repeater = RepeaterDayName.new(:saturday)
-
saturday_repeater.start = @now
-
this_saturday_span = saturday_repeater.this(:future)
-
Span.new(this_saturday_span.begin, this_saturday_span.begin + WEEKEND_SECONDS)
-
when :past
-
saturday_repeater = RepeaterDayName.new(:saturday)
-
saturday_repeater.start = @now
-
last_saturday_span = saturday_repeater.this(:past)
-
Span.new(last_saturday_span.begin, last_saturday_span.begin + WEEKEND_SECONDS)
-
end
-
end
-
-
2
def offset(span, amount, pointer)
-
direction = pointer == :future ? 1 : -1
-
weekend = RepeaterWeekend.new(:weekend)
-
weekend.start = span.begin
-
start = weekend.next(pointer).begin + (amount - 1) * direction * RepeaterWeek::WEEK_SECONDS
-
Span.new(start, start + (span.end - span.begin))
-
end
-
-
2
def width
-
WEEKEND_SECONDS
-
end
-
-
2
def to_s
-
super << '-weekend'
-
end
-
end
-
end
-
2
module Chronic
-
2
class RepeaterYear < Repeater #:nodoc:
-
2
YEAR_SECONDS = 31536000 # 365 * 24 * 60 * 60
-
-
2
def initialize(type, options = {})
-
super
-
@current_year_start = nil
-
end
-
-
2
def next(pointer)
-
super
-
-
unless @current_year_start
-
case pointer
-
when :future
-
@current_year_start = Chronic.construct(@now.year + 1)
-
when :past
-
@current_year_start = Chronic.construct(@now.year - 1)
-
end
-
else
-
diff = pointer == :future ? 1 : -1
-
@current_year_start = Chronic.construct(@current_year_start.year + diff)
-
end
-
-
Span.new(@current_year_start, Chronic.construct(@current_year_start.year + 1))
-
end
-
-
2
def this(pointer = :future)
-
super
-
-
case pointer
-
when :future
-
this_year_start = Chronic.construct(@now.year, @now.month, @now.day + 1)
-
this_year_end = Chronic.construct(@now.year + 1, 1, 1)
-
when :past
-
this_year_start = Chronic.construct(@now.year, 1, 1)
-
this_year_end = Chronic.construct(@now.year, @now.month, @now.day)
-
when :none
-
this_year_start = Chronic.construct(@now.year, 1, 1)
-
this_year_end = Chronic.construct(@now.year + 1, 1, 1)
-
end
-
-
Span.new(this_year_start, this_year_end)
-
end
-
-
2
def offset(span, amount, pointer)
-
direction = pointer == :future ? 1 : -1
-
new_begin = build_offset_time(span.begin, amount, direction)
-
new_end = build_offset_time(span.end, amount, direction)
-
Span.new(new_begin, new_end)
-
end
-
-
2
def width
-
YEAR_SECONDS
-
end
-
-
2
def to_s
-
super << '-year'
-
end
-
-
2
private
-
-
2
def build_offset_time(time, amount, direction)
-
year = time.year + (amount * direction)
-
days = month_days(year, time.month)
-
day = time.day > days ? days : time.day
-
Chronic.construct(year, time.month, day, time.hour, time.min, time.sec)
-
end
-
-
2
def month_days(year, month)
-
if ::Date.leap?(year)
-
RepeaterMonth::MONTH_DAYS_LEAP[month - 1]
-
else
-
RepeaterMonth::MONTH_DAYS[month - 1]
-
end
-
end
-
end
-
end
-
2
module Chronic
-
2
class Scalar < Tag
-
2
DAY_PORTIONS = %w( am pm morning afternoon evening night )
-
-
# Scan an Array of Token objects and apply any necessary Scalar
-
# tags to each token.
-
#
-
# tokens - An Array of tokens to scan.
-
# options - The Hash of options specified in Chronic::parse.
-
#
-
# Returns an Array of tokens.
-
2
def self.scan(tokens, options)
-
tokens.each_index do |i|
-
token = tokens[i]
-
post_token = tokens[i + 1]
-
if token.word =~ /^\d+$/
-
scalar = token.word.to_i
-
token.tag(Scalar.new(scalar))
-
token.tag(ScalarSubsecond.new(scalar)) if Chronic::Time::could_be_subsecond?(scalar)
-
token.tag(ScalarSecond.new(scalar)) if Chronic::Time::could_be_second?(scalar)
-
token.tag(ScalarMinute.new(scalar)) if Chronic::Time::could_be_minute?(scalar)
-
token.tag(ScalarHour.new(scalar)) if Chronic::Time::could_be_hour?(scalar)
-
unless post_token and DAY_PORTIONS.include?(post_token.word)
-
token.tag(ScalarDay.new(scalar)) if Chronic::Date::could_be_day?(scalar)
-
token.tag(ScalarMonth.new(scalar)) if Chronic::Date::could_be_month?(scalar)
-
if Chronic::Date::could_be_year?(scalar)
-
year = Chronic::Date::make_year(scalar, options[:ambiguous_year_future_bias])
-
token.tag(ScalarYear.new(year.to_i))
-
end
-
end
-
end
-
end
-
end
-
-
2
def to_s
-
'scalar'
-
end
-
end
-
-
2
class ScalarSubsecond < Scalar #:nodoc:
-
2
def to_s
-
super << '-subsecond-' << @type.to_s
-
end
-
end
-
-
2
class ScalarSecond < Scalar #:nodoc:
-
2
def to_s
-
super << '-second-' << @type.to_s
-
end
-
end
-
-
2
class ScalarMinute < Scalar #:nodoc:
-
2
def to_s
-
super << '-minute-' << @type.to_s
-
end
-
end
-
-
2
class ScalarHour < Scalar #:nodoc:
-
2
def to_s
-
super << '-hour-' << @type.to_s
-
end
-
end
-
-
2
class ScalarDay < Scalar #:nodoc:
-
2
def to_s
-
super << '-day-' << @type.to_s
-
end
-
end
-
-
2
class ScalarMonth < Scalar #:nodoc:
-
2
def to_s
-
super << '-month-' << @type.to_s
-
end
-
end
-
-
2
class ScalarYear < Scalar #:nodoc:
-
2
def to_s
-
super << '-year-' << @type.to_s
-
end
-
end
-
end
-
2
module Chronic
-
2
class Season
-
-
2
attr_reader :start
-
2
attr_reader :end
-
-
2
def initialize(start_date, end_date)
-
8
@start = start_date
-
8
@end = end_date
-
end
-
-
2
def self.find_next_season(season, pointer)
-
lookup = [:spring, :summer, :autumn, :winter]
-
next_season_num = (lookup.index(season) + 1 * pointer) % 4
-
lookup[next_season_num]
-
end
-
-
2
def self.season_after(season)
-
find_next_season(season, +1)
-
end
-
-
2
def self.season_before(season)
-
find_next_season(season, -1)
-
end
-
end
-
end
-
2
module Chronic
-
2
class Separator < Tag
-
-
# Scan an Array of Token objects and apply any necessary Separator
-
# tags to each token.
-
#
-
# tokens - An Array of tokens to scan.
-
# options - The Hash of options specified in Chronic::parse.
-
#
-
# Returns an Array of tokens.
-
2
def self.scan(tokens, options)
-
tokens.each do |token|
-
if t = scan_for_commas(token) then token.tag(t); next end
-
if t = scan_for_dots(token) then token.tag(t); next end
-
if t = scan_for_colon(token) then token.tag(t); next end
-
if t = scan_for_space(token) then token.tag(t); next end
-
if t = scan_for_slash(token) then token.tag(t); next end
-
if t = scan_for_dash(token) then token.tag(t); next end
-
if t = scan_for_quote(token) then token.tag(t); next end
-
if t = scan_for_at(token) then token.tag(t); next end
-
if t = scan_for_in(token) then token.tag(t); next end
-
if t = scan_for_on(token) then token.tag(t); next end
-
if t = scan_for_and(token) then token.tag(t); next end
-
if t = scan_for_t(token) then token.tag(t); next end
-
if t = scan_for_w(token) then token.tag(t); next end
-
end
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeparatorComma object.
-
2
def self.scan_for_commas(token)
-
scan_for token, SeparatorComma, { /^,$/ => :comma }
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeparatorDot object.
-
2
def self.scan_for_dots(token)
-
scan_for token, SeparatorDot, { /^\.$/ => :dot }
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeparatorColon object.
-
2
def self.scan_for_colon(token)
-
scan_for token, SeparatorColon, { /^:$/ => :colon }
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeparatorSpace object.
-
2
def self.scan_for_space(token)
-
scan_for token, SeparatorSpace, { /^ $/ => :space }
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeparatorSlash object.
-
2
def self.scan_for_slash(token)
-
scan_for token, SeparatorSlash, { /^\/$/ => :slash }
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeparatorDash object.
-
2
def self.scan_for_dash(token)
-
scan_for token, SeparatorDash, { /^-$/ => :dash }
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeparatorQuote object.
-
2
def self.scan_for_quote(token)
-
scan_for token, SeparatorQuote,
-
{
-
/^'$/ => :single_quote,
-
/^"$/ => :double_quote
-
}
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeparatorAt object.
-
2
def self.scan_for_at(token)
-
scan_for token, SeparatorAt, { /^(at|@)$/ => :at }
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeparatorIn object.
-
2
def self.scan_for_in(token)
-
scan_for token, SeparatorIn, { /^in$/ => :in }
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeparatorOn object.
-
2
def self.scan_for_on(token)
-
scan_for token, SeparatorOn, { /^on$/ => :on }
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeperatorAnd Object object.
-
2
def self.scan_for_and(token)
-
scan_for token, SeparatorAnd, { /^and$/ => :and }
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeperatorT Object object.
-
2
def self.scan_for_t(token)
-
scan_for token, SeparatorT, { /^t$/ => :T }
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SeperatorW Object object.
-
2
def self.scan_for_w(token)
-
scan_for token, SeparatorW, { /^w$/ => :W }
-
end
-
-
2
def to_s
-
'separator'
-
end
-
end
-
-
2
class SeparatorComma < Separator #:nodoc:
-
2
def to_s
-
super << '-comma'
-
end
-
end
-
-
2
class SeparatorDot < Separator #:nodoc:
-
2
def to_s
-
super << '-dot'
-
end
-
end
-
-
2
class SeparatorColon < Separator #:nodoc:
-
2
def to_s
-
super << '-colon'
-
end
-
end
-
-
2
class SeparatorSpace < Separator #:nodoc:
-
2
def to_s
-
super << '-space'
-
end
-
end
-
-
2
class SeparatorSlash < Separator #:nodoc:
-
2
def to_s
-
super << '-slash'
-
end
-
end
-
-
2
class SeparatorDash < Separator #:nodoc:
-
2
def to_s
-
super << '-dash'
-
end
-
end
-
-
2
class SeparatorQuote < Separator #:nodoc:
-
2
def to_s
-
super << '-quote-' << @type.to_s
-
end
-
end
-
-
2
class SeparatorAt < Separator #:nodoc:
-
2
def to_s
-
super << '-at'
-
end
-
end
-
-
2
class SeparatorIn < Separator #:nodoc:
-
2
def to_s
-
super << '-in'
-
end
-
end
-
-
2
class SeparatorOn < Separator #:nodoc:
-
2
def to_s
-
super << '-on'
-
end
-
end
-
-
2
class SeparatorAnd < Separator #:nodoc:
-
2
def to_s
-
super << '-and'
-
end
-
end
-
-
2
class SeparatorT < Separator #:nodoc:
-
2
def to_s
-
super << '-T'
-
end
-
end
-
-
2
class SeparatorW < Separator #:nodoc:
-
2
def to_s
-
super << '-W'
-
end
-
end
-
-
end
-
2
module Chronic
-
2
class Sign < Tag
-
-
# Scan an Array of Token objects and apply any necessary Sign
-
# tags to each token.
-
#
-
# tokens - An Array of tokens to scan.
-
# options - The Hash of options specified in Chronic::parse.
-
#
-
# Returns an Array of tokens.
-
2
def self.scan(tokens, options)
-
tokens.each do |token|
-
if t = scan_for_plus(token) then token.tag(t); next end
-
if t = scan_for_minus(token) then token.tag(t); next end
-
end
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SignPlus object.
-
2
def self.scan_for_plus(token)
-
scan_for token, SignPlus, { /^\+$/ => :plus }
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new SignMinus object.
-
2
def self.scan_for_minus(token)
-
scan_for token, SignMinus, { /^-$/ => :minus }
-
end
-
-
2
def to_s
-
'sign'
-
end
-
end
-
-
2
class SignPlus < Sign #:nodoc:
-
2
def to_s
-
super << '-plus'
-
end
-
end
-
-
2
class SignMinus < Sign #:nodoc:
-
2
def to_s
-
super << '-minus'
-
end
-
end
-
-
end
-
2
module Chronic
-
# A Span represents a range of time. Since this class extends
-
# Range, you can use #begin and #end to get the beginning and
-
# ending times of the span (they will be of class Time)
-
2
class Span < Range
-
# Returns the width of this span in seconds
-
2
def width
-
(self.end - self.begin).to_i
-
end
-
-
# Add a number of seconds to this span, returning the
-
# resulting Span
-
2
def +(seconds)
-
Span.new(self.begin + seconds, self.end + seconds)
-
end
-
-
# Subtract a number of seconds to this span, returning the
-
# resulting Span
-
2
def -(seconds)
-
self + -seconds
-
end
-
-
# Prints this span in a nice fashion
-
2
def to_s
-
'(' << self.begin.to_s << '..' << self.end.to_s << ')'
-
end
-
-
2
alias :cover? :include? if RUBY_VERSION =~ /^1.8/
-
-
end
-
end
-
2
module Chronic
-
# Tokens are tagged with subclassed instances of this class when
-
# they match specific criteria.
-
2
class Tag
-
-
2
attr_accessor :type
-
-
# type - The Symbol type of this tag.
-
2
def initialize(type, options = {})
-
@type = type
-
@options = options
-
end
-
-
# time - Set the start Time for this Tag.
-
2
def start=(time)
-
@now = time
-
end
-
-
2
class << self
-
2
private
-
-
2
def scan_for(token, klass, items={}, options = {})
-
case items
-
when Regexp
-
return klass.new(token.word, options) if items =~ token.word
-
when Hash
-
items.each do |item, symbol|
-
return klass.new(symbol, options) if item =~ token.word
-
end
-
end
-
nil
-
end
-
-
end
-
-
end
-
end
-
2
module Chronic
-
2
class Time
-
2
HOUR_SECONDS = 3600 # 60 * 60
-
2
MINUTE_SECONDS = 60
-
2
SECOND_SECONDS = 1 # haha, awesome
-
2
SUBSECOND_SECONDS = 0.001
-
-
# Checks if given number could be hour
-
2
def self.could_be_hour?(hour)
-
hour >= 0 && hour <= 24
-
end
-
-
# Checks if given number could be minute
-
2
def self.could_be_minute?(minute)
-
minute >= 0 && minute <= 60
-
end
-
-
# Checks if given number could be second
-
2
def self.could_be_second?(second)
-
second >= 0 && second <= 60
-
end
-
-
# Checks if given number could be subsecond
-
2
def self.could_be_subsecond?(subsecond)
-
subsecond >= 0 && subsecond <= 999999
-
end
-
-
# normalize offset in seconds to offset as string +mm:ss or -mm:ss
-
2
def self.normalize_offset(offset)
-
return offset if offset.is_a?(String)
-
offset = Chronic.time_class.now.to_time.utc_offset unless offset # get current system's UTC offset if offset is nil
-
sign = '+'
-
sign = '-' if offset < 0
-
hours = (offset.abs / 3600).to_i.to_s.rjust(2,'0')
-
minutes = (offset.abs % 3600).to_s.rjust(2,'0')
-
sign + hours + minutes
-
end
-
-
end
-
end
-
2
module Chronic
-
2
class TimeZone < Tag
-
-
# Scan an Array of Token objects and apply any necessary TimeZone
-
# tags to each token.
-
#
-
# tokens - An Array of tokens to scan.
-
# options - The Hash of options specified in Chronic::parse.
-
#
-
# Returns an Array of tokens.
-
2
def self.scan(tokens, options)
-
tokens.each do |token|
-
if t = scan_for_all(token) then token.tag(t); next end
-
end
-
end
-
-
# token - The Token object we want to scan.
-
#
-
# Returns a new Pointer object.
-
2
def self.scan_for_all(token)
-
scan_for token, self,
-
{
-
/[PMCE][DS]T|UTC/i => :tz,
-
/(tzminus)?\d{2}:?\d{2}/ => :tz
-
}
-
end
-
-
2
def to_s
-
'timezone'
-
end
-
end
-
end
-
2
module Chronic
-
2
class Token
-
-
2
attr_accessor :word
-
2
attr_accessor :tags
-
-
2
def initialize(word)
-
@word = word
-
@tags = []
-
end
-
-
# Tag this token with the specified tag.
-
#
-
# new_tag - The new Tag object.
-
#
-
# Returns nothing.
-
2
def tag(new_tag)
-
@tags << new_tag
-
end
-
-
# Remove all tags of the given class.
-
#
-
# tag_class - The tag Class to remove.
-
#
-
# Returns nothing.
-
2
def untag(tag_class)
-
@tags.delete_if { |m| m.kind_of? tag_class }
-
end
-
-
# Returns true if this token has any tags.
-
2
def tagged?
-
@tags.size > 0
-
end
-
-
# tag_class - The tag Class to search for.
-
#
-
# Returns The first Tag that matches the given class.
-
2
def get_tag(tag_class)
-
@tags.find { |m| m.kind_of? tag_class }
-
end
-
-
# Print this Token in a pretty way
-
2
def to_s
-
@word << '(' << @tags.join(', ') << ') '
-
end
-
-
2
def inspect
-
to_s
-
end
-
end
-
end
-
2
require 'coffee-script'
-
2
require 'coffee/rails/engine'
-
2
require 'coffee/rails/template_handler'
-
2
require 'coffee/rails/version'
-
2
require 'rails/engine'
-
-
2
module Coffee
-
2
module Rails
-
2
class Engine < ::Rails::Engine
-
2
config.app_generators.javascript_engine :coffee
-
end
-
end
-
end
-
2
module Coffee
-
2
module Rails
-
2
class TemplateHandler
-
2
def self.erb_handler
-
@@erb_handler ||= ActionView::Template.registered_template_handler(:erb)
-
end
-
-
2
def self.call(template)
-
compiled_source = erb_handler.call(template)
-
"CoffeeScript.compile(begin;#{compiled_source};end)"
-
end
-
end
-
end
-
end
-
-
2
ActiveSupport.on_load(:action_view) do
-
2
ActionView::Template.register_template_handler :coffee, Coffee::Rails::TemplateHandler
-
end
-
2
module Coffee
-
2
module Rails
-
2
VERSION = "3.2.2"
-
end
-
end
-
2
require 'coffee_script'
-
2
require 'execjs'
-
2
require 'coffee_script/source'
-
-
2
module CoffeeScript
-
2
EngineError = ExecJS::RuntimeError
-
2
CompilationError = ExecJS::ProgramError
-
-
2
module Source
-
2
def self.path
-
@path ||= ENV['COFFEESCRIPT_SOURCE_PATH'] || bundled_path
-
end
-
-
2
def self.path=(path)
-
@contents = @version = @bare_option = @context = nil
-
@path = path
-
end
-
-
2
def self.contents
-
@contents ||= File.read(path)
-
end
-
-
2
def self.version
-
@version ||= contents[/CoffeeScript Compiler v([\d.]+)/, 1]
-
end
-
-
2
def self.bare_option
-
@bare_option ||= contents.match(/noWrap/) ? 'noWrap' : 'bare'
-
end
-
-
2
def self.context
-
@context ||= ExecJS.compile(contents)
-
end
-
end
-
-
2
class << self
-
2
def engine
-
end
-
-
2
def engine=(engine)
-
end
-
-
2
def version
-
Source.version
-
end
-
-
# Compile a script (String or IO) to JavaScript.
-
2
def compile(script, options = {})
-
script = script.read if script.respond_to?(:read)
-
-
if options.key?(:bare)
-
elsif options.key?(:no_wrap)
-
options[:bare] = options[:no_wrap]
-
else
-
options[:bare] = false
-
end
-
-
Source.context.call("CoffeeScript.compile", script, options)
-
end
-
end
-
end
-
2
module CoffeeScript
-
2
module Source
-
2
def self.bundled_path
-
File.expand_path("../coffee-script.js", __FILE__)
-
end
-
end
-
end
-
2
require "commonjs/version"
-
-
2
module CommonJS
-
2
autoload :Environment, 'commonjs/environment'
-
2
autoload :Module, 'commonjs/module'
-
end
-
2
require 'pathname'
-
2
module CommonJS
-
2
class Environment
-
-
2
attr_reader :runtime
-
-
2
def initialize(runtime, options = {})
-
2
@runtime = runtime
-
4
@paths = [options[:path]].flatten.map {|path| Pathname(path)}
-
2
@modules = {}
-
end
-
-
2
def require(module_id)
-
190
unless mod = @modules[module_id]
-
76
filepath = find(module_id) or fail LoadError, "no such module '#{module_id}'"
-
76
load = @runtime.eval("(function(module, require, exports) {#{File.read(filepath)}})", filepath.expand_path.to_s)
-
76
@modules[module_id] = mod = Module.new(module_id, self)
-
76
load.call(mod, mod.require_function, mod.exports)
-
end
-
190
return mod.exports
-
end
-
-
2
def native(module_id, impl)
-
10
@modules[module_id] = Module::Native.new(impl)
-
end
-
-
2
def new_object
-
76
@runtime['Object'].new
-
end
-
-
2
private
-
-
2
def find(module_id)
-
# Add `.js` extension if neccessary.
-
76
target = if File.extname(module_id) == '.js' then module_id else "#{module_id}.js" end
-
152
if loadpath = @paths.find { |path| path.join(target).exist? }
-
76
loadpath.join(target)
-
end
-
end
-
-
end
-
end
-
2
module CommonJS
-
2
class Module
-
-
2
attr_reader :id
-
2
attr_accessor :exports
-
-
2
def initialize(id, env)
-
76
@id = id
-
76
@env = env
-
76
@exports = env.new_object
-
76
@segments = id.split('/')
-
end
-
-
2
def require_function
-
@require_function ||= lambda do |*args|
-
158
this, module_id = *args
-
158
module_id ||= this #backwards compatibility with TRR < 0.10
-
158
@env.require(expand(module_id))
-
76
end
-
end
-
-
2
private
-
-
2
def expand(module_id)
-
158
return module_id unless module_id =~ /(\.|\..)/
-
150
module_id.split('/').inject(@segments[0..-2]) do |path, element|
-
356
path.tap do
-
356
if element == '.'
-
#do nothing
-
elsif element == '..'
-
56
path.pop
-
else
-
206
path.push element
-
end
-
end
-
end.join('/')
-
end
-
-
-
2
class Native
-
-
2
attr_reader :exports
-
-
2
def initialize(impl)
-
10
@exports = impl
-
end
-
end
-
end
-
end
-
2
module CommonJS
-
2
VERSION = "0.2.7"
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
##
-
## an implementation of eRuby
-
##
-
## ex.
-
## input = <<'END'
-
## <ul>
-
## <% for item in @list %>
-
## <li><%= item %>
-
## <%== item %></li>
-
## <% end %>
-
## </ul>
-
## END
-
## list = ['<aaa>', 'b&b', '"ccc"']
-
## eruby = Erubis::Eruby.new(input)
-
## puts "--- code ---"
-
## puts eruby.src
-
## puts "--- result ---"
-
## context = Erubis::Context.new() # or new(:list=>list)
-
## context[:list] = list
-
## puts eruby.evaluate(context)
-
##
-
## result:
-
## --- source ---
-
## _buf = ''; _buf << '<ul>
-
## '; for item in @list
-
## _buf << ' <li>'; _buf << ( item ).to_s; _buf << '
-
## '; _buf << ' '; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</li>
-
## '; end
-
## _buf << '</ul>
-
## ';
-
## _buf.to_s
-
## --- result ---
-
## <ul>
-
## <li><aaa>
-
## <aaa></li>
-
## <li>b&b
-
## b&b</li>
-
## <li>"ccc"
-
## "ccc"</li>
-
## </ul>
-
##
-
-
-
2
module Erubis
-
2
VERSION = ('$Release: 2.7.0 $' =~ /([.\d]+)/) && $1
-
end
-
-
2
require 'erubis/engine'
-
#require 'erubis/generator'
-
#require 'erubis/converter'
-
#require 'erubis/evaluator'
-
#require 'erubis/error'
-
#require 'erubis/context'
-
#requier 'erubis/util'
-
2
require 'erubis/helper'
-
2
require 'erubis/enhancer'
-
#require 'erubis/tiny'
-
2
require 'erubis/engine/eruby'
-
#require 'erubis/engine/enhanced' # enhanced eruby engines
-
#require 'erubis/engine/optimized' # generates optimized ruby code
-
#require 'erubis/engine/ephp'
-
#require 'erubis/engine/ec'
-
#require 'erubis/engine/ejava'
-
#require 'erubis/engine/escheme'
-
#require 'erubis/engine/eperl'
-
#require 'erubis/engine/ejavascript'
-
-
2
require 'erubis/local-setting'
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
2
module Erubis
-
-
-
##
-
## context object for Engine#evaluate
-
##
-
## ex.
-
## template = <<'END'
-
## Hello <%= @user %>!
-
## <% for item in @list %>
-
## - <%= item %>
-
## <% end %>
-
## END
-
##
-
## context = Erubis::Context.new(:user=>'World', :list=>['a','b','c'])
-
## # or
-
## # context = Erubis::Context.new
-
## # context[:user] = 'World'
-
## # context[:list] = ['a', 'b', 'c']
-
##
-
## eruby = Erubis::Eruby.new(template)
-
## print eruby.evaluate(context)
-
##
-
2
class Context
-
2
include Enumerable
-
-
2
def initialize(hash=nil)
-
hash.each do |name, value|
-
self[name] = value
-
end if hash
-
end
-
-
2
def [](key)
-
return instance_variable_get("@#{key}")
-
end
-
-
2
def []=(key, value)
-
return instance_variable_set("@#{key}", value)
-
end
-
-
2
def keys
-
return instance_variables.collect { |name| name[1..-1] }
-
end
-
-
2
def each
-
instance_variables.each do |name|
-
key = name[1..-1]
-
value = instance_variable_get(name)
-
yield(key, value)
-
end
-
end
-
-
2
def to_hash
-
hash = {}
-
self.keys.each { |key| hash[key] = self[key] }
-
return hash
-
end
-
-
2
def update(context_or_hash)
-
arg = context_or_hash
-
if arg.is_a?(Hash)
-
arg.each do |key, val|
-
self[key] = val
-
end
-
else
-
arg.instance_variables.each do |varname|
-
key = varname[1..-1]
-
val = arg.instance_variable_get(varname)
-
self[key] = val
-
end
-
end
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
2
require 'erubis/util'
-
-
2
module Erubis
-
-
-
##
-
## convert
-
##
-
2
module Converter
-
-
2
attr_accessor :preamble, :postamble, :escape
-
-
2
def self.supported_properties # :nodoc:
-
return [
-
[:preamble, nil, "preamble (no preamble when false)"],
-
[:postamble, nil, "postamble (no postamble when false)"],
-
[:escape, nil, "escape expression or not in default"],
-
]
-
end
-
-
2
def init_converter(properties={})
-
1
@preamble = properties[:preamble]
-
1
@postamble = properties[:postamble]
-
1
@escape = properties[:escape]
-
end
-
-
## convert input string into target language
-
2
def convert(input)
-
1
codebuf = "" # or []
-
1
@preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble))
-
1
convert_input(codebuf, input)
-
1
@postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble))
-
1
@_proc = nil # clear cached proc object
-
1
return codebuf # or codebuf.join()
-
end
-
-
2
protected
-
-
##
-
## detect spaces at beginning of line
-
##
-
2
def detect_spaces_at_bol(text, is_bol)
-
2
lspace = nil
-
2
if text.empty?
-
lspace = "" if is_bol
-
elsif text[-1] == ?\n
-
2
lspace = ""
-
else
-
rindex = text.rindex(?\n)
-
if rindex
-
s = text[rindex+1..-1]
-
if s =~ /\A[ \t]*\z/
-
lspace = s
-
#text = text[0..rindex]
-
text[rindex+1..-1] = ''
-
end
-
else
-
if is_bol && text =~ /\A[ \t]*\z/
-
#lspace = text
-
#text = nil
-
lspace = text.dup
-
text[0..-1] = ''
-
end
-
end
-
end
-
2
return lspace
-
end
-
-
##
-
## (abstract) convert input to code
-
##
-
2
def convert_input(codebuf, input)
-
not_implemented
-
end
-
-
end
-
-
-
2
module Basic
-
end
-
-
-
##
-
## basic converter which supports '<% ... %>' notation.
-
##
-
2
module Basic::Converter
-
2
include Erubis::Converter
-
-
2
def self.supported_properties # :nodoc:
-
return [
-
[:pattern, '<% %>', "embed pattern"],
-
[:trim, true, "trim spaces around <% ... %>"],
-
]
-
end
-
-
2
attr_accessor :pattern, :trim
-
-
2
def init_converter(properties={})
-
1
super(properties)
-
1
@pattern = properties[:pattern]
-
1
@trim = properties[:trim] != false
-
end
-
-
2
protected
-
-
## return regexp of pattern to parse eRuby script
-
2
def pattern_regexp(pattern)
-
2
@prefix, @postfix = pattern.split() # '<% %>' => '<%', '%>'
-
#return /(.*?)(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
-
#return /(^[ \t]*)?#{@prefix}(=+|\#)?(.*?)-?#{@postfix}([ \t]*\r?\n)?/m
-
2
return /#{@prefix}(=+|-|\#|%)?(.*?)([-=])?#{@postfix}([ \t]*\r?\n)?/m
-
end
-
2
module_function :pattern_regexp
-
-
#DEFAULT_REGEXP = /(.*?)(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
#DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
#DEFAULT_REGEXP = /<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
2
DEFAULT_REGEXP = pattern_regexp('<% %>')
-
-
2
public
-
-
2
def convert_input(src, input)
-
1
pat = @pattern
-
1
regexp = pat.nil? || pat == '<% %>' ? DEFAULT_REGEXP : pattern_regexp(pat)
-
1
pos = 0
-
1
is_bol = true # is beginning of line
-
1
input.scan(regexp) do |indicator, code, tailch, rspace|
-
5
match = Regexp.last_match()
-
5
len = match.begin(0) - pos
-
5
text = input[pos, len]
-
5
pos = match.end(0)
-
5
ch = indicator ? indicator[0] : nil
-
5
lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
-
5
is_bol = rspace ? true : false
-
5
add_text(src, text) if text && !text.empty?
-
## * when '<%= %>', do nothing
-
## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
-
5
if ch == ?= # <%= %>
-
3
rspace = nil if tailch && !tailch.empty?
-
3
add_text(src, lspace) if lspace
-
3
add_expr(src, code, indicator)
-
3
add_text(src, rspace) if rspace
-
elsif ch == ?\# # <%# %>
-
n = code.count("\n") + (rspace ? 1 : 0)
-
if @trim && lspace && rspace
-
add_stmt(src, "\n" * n)
-
else
-
add_text(src, lspace) if lspace
-
add_stmt(src, "\n" * n)
-
add_text(src, rspace) if rspace
-
end
-
elsif ch == ?% # <%% %>
-
s = "#{lspace}#{@prefix||='<%'}#{code}#{tailch}#{@postfix||='%>'}#{rspace}"
-
add_text(src, s)
-
else # <% %>
-
2
if @trim && lspace && rspace
-
1
add_stmt(src, "#{lspace}#{code}#{rspace}")
-
else
-
1
add_text(src, lspace) if lspace
-
1
add_stmt(src, code)
-
1
add_text(src, rspace) if rspace
-
end
-
end
-
end
-
#rest = $' || input # ruby1.8
-
1
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
1
add_text(src, rest)
-
end
-
-
## add expression code to src
-
2
def add_expr(src, code, indicator)
-
3
case indicator
-
when '='
-
3
@escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
-
when '=='
-
@escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
-
when '==='
-
add_expr_debug(src, code)
-
end
-
end
-
-
end
-
-
-
2
module PI
-
end
-
-
##
-
## Processing Instructions (PI) converter for XML.
-
## this class converts '<?rb ... ?>' and '${...}' notation.
-
##
-
2
module PI::Converter
-
2
include Erubis::Converter
-
-
2
def self.desc # :nodoc:
-
"use processing instructions (PI) instead of '<% %>'"
-
end
-
-
2
def self.supported_properties # :nodoc:
-
return [
-
[:trim, true, "trim spaces around <% ... %>"],
-
[:pi, 'rb', "PI (Processing Instrunctions) name"],
-
[:embchar, '@', "char for embedded expression pattern('@{...}@')"],
-
[:pattern, '<% %>', "embed pattern"],
-
]
-
end
-
-
2
attr_accessor :pi, :prefix
-
-
2
def init_converter(properties={})
-
super(properties)
-
@trim = properties.fetch(:trim, true)
-
@pi = properties[:pi] if properties[:pi]
-
@embchar = properties[:embchar] || '@'
-
@pattern = properties[:pattern]
-
@pattern = '<% %>' if @pattern.nil? #|| @pattern == true
-
end
-
-
2
def convert(input)
-
code = super(input)
-
return @header || @footer ? "#{@header}#{code}#{@footer}" : code
-
end
-
-
2
protected
-
-
2
def convert_input(codebuf, input)
-
unless @regexp
-
@pi ||= 'e'
-
ch = Regexp.escape(@embchar)
-
if @pattern
-
left, right = @pattern.split(' ')
-
@regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/m
-
else
-
@regexp = /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?|#{ch}(!*)?\{(.*?)\}#{ch}/m
-
end
-
end
-
#
-
is_bol = true
-
pos = 0
-
input.scan(@regexp) do |pi_arg, stmt, rspace,
-
indicator1, expr1, indicator2, expr2|
-
match = Regexp.last_match
-
len = match.begin(0) - pos
-
text = input[pos, len]
-
pos = match.end(0)
-
lspace = stmt ? detect_spaces_at_bol(text, is_bol) : nil
-
is_bol = stmt && rspace ? true : false
-
add_text(codebuf, text) # unless text.empty?
-
#
-
if stmt
-
if @trim && lspace && rspace
-
add_pi_stmt(codebuf, "#{lspace}#{stmt}#{rspace}", pi_arg)
-
else
-
add_text(codebuf, lspace) if lspace
-
add_pi_stmt(codebuf, stmt, pi_arg)
-
add_text(codebuf, rspace) if rspace
-
end
-
else
-
add_pi_expr(codebuf, expr1 || expr2, indicator1 || indicator2)
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
add_text(codebuf, rest)
-
end
-
-
#--
-
#def convert_input(codebuf, input)
-
# parse_stmts(codebuf, input)
-
# #parse_stmts2(codebuf, input)
-
#end
-
#
-
#def parse_stmts(codebuf, input)
-
# #regexp = pattern_regexp(@pattern)
-
# @pi ||= 'e'
-
# @stmt_pattern ||= /<\?#{@pi}(?:-(\w+))?(\s.*?)\?>([ \t]*\r?\n)?/m
-
# is_bol = true
-
# pos = 0
-
# input.scan(@stmt_pattern) do |pi_arg, code, rspace|
-
# match = Regexp.last_match
-
# len = match.begin(0) - pos
-
# text = input[pos, len]
-
# pos = match.end(0)
-
# lspace = detect_spaces_at_bol(text, is_bol)
-
# is_bol = rspace ? true : false
-
# parse_exprs(codebuf, text) # unless text.empty?
-
# if @trim && lspace && rspace
-
# add_pi_stmt(codebuf, "#{lspace}#{code}#{rspace}", pi_arg)
-
# else
-
# add_text(codebuf, lspace)
-
# add_pi_stmt(codebuf, code, pi_arg)
-
# add_text(codebuf, rspace)
-
# end
-
# end
-
# rest = $' || input
-
# parse_exprs(codebuf, rest)
-
#end
-
#
-
#def parse_exprs(codebuf, input)
-
# unless @expr_pattern
-
# ch = Regexp.escape(@embchar)
-
# if @pattern
-
# left, right = @pattern.split(' ')
-
# @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}|#{left}(=+)(.*?)#{right}/
-
# else
-
# @expr_pattern = /#{ch}(!*)?\{(.*?)\}#{ch}/
-
# end
-
# end
-
# pos = 0
-
# input.scan(@expr_pattern) do |indicator1, code1, indicator2, code2|
-
# indicator = indicator1 || indicator2
-
# code = code1 || code2
-
# match = Regexp.last_match
-
# len = match.begin(0) - pos
-
# text = input[pos, len]
-
# pos = match.end(0)
-
# add_text(codebuf, text) # unless text.empty?
-
# add_pi_expr(codebuf, code, indicator)
-
# end
-
# rest = $' || input
-
# add_text(codebuf, rest)
-
#end
-
#++
-
-
2
def add_pi_stmt(codebuf, code, pi_arg) # :nodoc:
-
case pi_arg
-
when nil ; add_stmt(codebuf, code)
-
when 'header' ; @header = code
-
when 'footer' ; @footer = code
-
when 'comment'; add_stmt(codebuf, "\n" * code.count("\n"))
-
when 'value' ; add_expr_literal(codebuf, code)
-
else ; add_stmt(codebuf, code)
-
end
-
end
-
-
2
def add_pi_expr(codebuf, code, indicator) # :nodoc:
-
case indicator
-
when nil, '', '==' # @{...}@ or <%== ... %>
-
@escape == false ? add_expr_literal(codebuf, code) : add_expr_escaped(codebuf, code)
-
when '!', '=' # @!{...}@ or <%= ... %>
-
@escape == false ? add_expr_escaped(codebuf, code) : add_expr_literal(codebuf, code)
-
when '!!', '===' # @!!{...}@ or <%=== ... %>
-
add_expr_debug(codebuf, code)
-
else
-
# ignore
-
end
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
2
require 'erubis/generator'
-
2
require 'erubis/converter'
-
2
require 'erubis/evaluator'
-
2
require 'erubis/context'
-
-
-
2
module Erubis
-
-
-
##
-
## (abstract) abstract engine class.
-
## subclass must include evaluator and converter module.
-
##
-
2
class Engine
-
#include Evaluator
-
#include Converter
-
#include Generator
-
-
2
def initialize(input=nil, properties={})
-
#@input = input
-
1
init_generator(properties)
-
1
init_converter(properties)
-
1
init_evaluator(properties)
-
1
@src = convert(input) if input
-
end
-
-
-
##
-
## convert input string and set it to @src
-
##
-
2
def convert!(input)
-
@src = convert(input)
-
end
-
-
-
##
-
## load file, write cache file, and return engine object.
-
## this method create code cache file automatically.
-
## cachefile name can be specified with properties[:cachename],
-
## or filname + 'cache' is used as default.
-
##
-
2
def self.load_file(filename, properties={})
-
cachename = properties[:cachename] || (filename + '.cache')
-
properties[:filename] = filename
-
timestamp = File.mtime(filename)
-
if test(?f, cachename) && timestamp == File.mtime(cachename)
-
engine = self.new(nil, properties)
-
engine.src = File.read(cachename)
-
else
-
input = File.open(filename, 'rb') {|f| f.read }
-
engine = self.new(input, properties)
-
tmpname = cachename + rand().to_s[1,8]
-
File.open(tmpname, 'wb') {|f| f.write(engine.src) }
-
File.rename(tmpname, cachename)
-
File.utime(timestamp, timestamp, cachename)
-
end
-
engine.src.untaint # ok?
-
return engine
-
end
-
-
-
##
-
## helper method to convert and evaluate input text with context object.
-
## context may be Binding, Hash, or Object.
-
##
-
2
def process(input, context=nil, filename=nil)
-
code = convert(input)
-
filename ||= '(erubis)'
-
if context.is_a?(Binding)
-
return eval(code, context, filename)
-
else
-
context = Context.new(context) if context.is_a?(Hash)
-
return context.instance_eval(code, filename)
-
end
-
end
-
-
-
##
-
## helper method evaluate Proc object with contect object.
-
## context may be Binding, Hash, or Object.
-
##
-
2
def process_proc(proc_obj, context=nil, filename=nil)
-
if context.is_a?(Binding)
-
filename ||= '(erubis)'
-
return eval(proc_obj, context, filename)
-
else
-
context = Context.new(context) if context.is_a?(Hash)
-
return context.instance_eval(&proc_obj)
-
end
-
end
-
-
-
end # end of class Engine
-
-
-
##
-
## (abstract) base engine class for Eruby, Eperl, Ejava, and so on.
-
## subclass must include generator.
-
##
-
2
class Basic::Engine < Engine
-
2
include Evaluator
-
2
include Basic::Converter
-
2
include Generator
-
end
-
-
-
2
class PI::Engine < Engine
-
2
include Evaluator
-
2
include PI::Converter
-
2
include Generator
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
2
require 'erubis/engine'
-
2
require 'erubis/enhancer'
-
-
-
2
module Erubis
-
-
-
##
-
## code generator for Ruby
-
##
-
2
module RubyGenerator
-
2
include Generator
-
#include ArrayBufferEnhancer
-
2
include StringBufferEnhancer
-
-
2
def init_generator(properties={})
-
1
super
-
1
@escapefunc ||= "Erubis::XmlHelper.escape_xml"
-
1
@bufvar = properties[:bufvar] || "_buf"
-
end
-
-
2
def self.supported_properties() # :nodoc:
-
return []
-
end
-
-
2
def escape_text(text)
-
7
text.gsub(/['\\]/, '\\\\\&') # "'" => "\\'", '\\' => '\\\\'
-
end
-
-
2
def escaped_expr(code)
-
return "#{@escapefunc}(#{code})"
-
end
-
-
#--
-
#def add_preamble(src)
-
# src << "#{@bufvar} = [];"
-
#end
-
#++
-
-
2
def add_text(src, text)
-
src << " #{@bufvar} << '" << escape_text(text) << "';" unless text.empty?
-
end
-
-
2
def add_stmt(src, code)
-
#src << code << ';'
-
2
src << code
-
2
src << ';' unless code[-1] == ?\n
-
end
-
-
2
def add_expr_literal(src, code)
-
src << " #{@bufvar} << (" << code << ').to_s;'
-
end
-
-
2
def add_expr_escaped(src, code)
-
src << " #{@bufvar} << " << escaped_expr(code) << ';'
-
end
-
-
2
def add_expr_debug(src, code)
-
code.strip!
-
s = (code.dump =~ /\A"(.*)"\z/) && $1
-
src << ' $stderr.puts("*** debug: ' << s << '=#{(' << code << ').inspect}");'
-
end
-
-
#--
-
#def add_postamble(src)
-
# src << "\n#{@bufvar}.join\n"
-
#end
-
#++
-
-
end
-
-
-
##
-
## engine for Ruby
-
##
-
2
class Eruby < Basic::Engine
-
2
include RubyEvaluator
-
2
include RubyGenerator
-
end
-
-
-
##
-
## fast engine for Ruby
-
##
-
2
class FastEruby < Eruby
-
2
include InterpolationEnhancer
-
end
-
-
-
##
-
## swtich '<%= %>' to escaped and '<%== %>' to not escaped
-
##
-
2
class EscapedEruby < Eruby
-
2
include EscapeEnhancer
-
end
-
-
-
##
-
## sanitize expression (<%= ... %>) by default
-
##
-
## this is equivalent to EscapedEruby and is prepared only for compatibility.
-
##
-
2
class XmlEruby < Eruby
-
2
include EscapeEnhancer
-
end
-
-
-
2
class PI::Eruby < PI::Engine
-
2
include RubyEvaluator
-
2
include RubyGenerator
-
-
2
def init_converter(properties={})
-
@pi = 'rb'
-
super(properties)
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
2
module Erubis
-
-
-
##
-
## switch '<%= ... %>' to escaped and '<%== ... %>' to unescaped
-
##
-
## ex.
-
## class XmlEruby < Eruby
-
## include EscapeEnhancer
-
## end
-
##
-
## this is language-indenedent.
-
##
-
2
module EscapeEnhancer
-
-
2
def self.desc # :nodoc:
-
"switch '<%= %>' to escaped and '<%== %>' to unescaped"
-
end
-
-
#--
-
#def self.included(klass)
-
# klass.class_eval <<-END
-
# alias _add_expr_literal add_expr_literal
-
# alias _add_expr_escaped add_expr_escaped
-
# alias add_expr_literal _add_expr_escaped
-
# alias add_expr_escaped _add_expr_literal
-
# END
-
#end
-
#++
-
-
2
def add_expr(src, code, indicator)
-
case indicator
-
when '='
-
@escape ? add_expr_literal(src, code) : add_expr_escaped(src, code)
-
when '=='
-
@escape ? add_expr_escaped(src, code) : add_expr_literal(src, code)
-
when '==='
-
add_expr_debug(src, code)
-
end
-
end
-
-
end
-
-
-
#--
-
## (obsolete)
-
#module FastEnhancer
-
#end
-
#++
-
-
-
##
-
## use $stdout instead of string
-
##
-
## this is only for Eruby.
-
##
-
2
module StdoutEnhancer
-
-
2
def self.desc # :nodoc:
-
"use $stdout instead of array buffer or string buffer"
-
end
-
-
2
def add_preamble(src)
-
src << "#{@bufvar} = $stdout;"
-
end
-
-
2
def add_postamble(src)
-
src << "\n''\n"
-
end
-
-
end
-
-
-
##
-
## use print statement instead of '_buf << ...'
-
##
-
## this is only for Eruby.
-
##
-
2
module PrintOutEnhancer
-
-
2
def self.desc # :nodoc:
-
"use print statement instead of '_buf << ...'"
-
end
-
-
2
def add_preamble(src)
-
end
-
-
2
def add_text(src, text)
-
src << " print '#{escape_text(text)}';" unless text.empty?
-
end
-
-
2
def add_expr_literal(src, code)
-
src << " print((#{code}).to_s);"
-
end
-
-
2
def add_expr_escaped(src, code)
-
src << " print #{escaped_expr(code)};"
-
end
-
-
2
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
end
-
-
end
-
-
-
##
-
## enable print function
-
##
-
## Notice: use Eruby#evaluate() and don't use Eruby#result()
-
## to be enable print function.
-
##
-
## this is only for Eruby.
-
##
-
2
module PrintEnabledEnhancer
-
-
2
def self.desc # :nodoc:
-
"enable to use print function in '<% %>'"
-
end
-
-
2
def add_preamble(src)
-
src << "@_buf = "
-
super
-
end
-
-
2
def print(*args)
-
args.each do |arg|
-
@_buf << arg.to_s
-
end
-
end
-
-
2
def evaluate(context=nil)
-
_src = @src
-
if context.is_a?(Hash)
-
context.each do |key, val| instance_variable_set("@#{key}", val) end
-
elsif context
-
context.instance_variables.each do |name|
-
instance_variable_set(name, context.instance_variable_get(name))
-
end
-
end
-
return instance_eval(_src, (@filename || '(erubis)'))
-
end
-
-
end
-
-
-
##
-
## return array instead of string
-
##
-
## this is only for Eruby.
-
##
-
2
module ArrayEnhancer
-
-
2
def self.desc # :nodoc:
-
"return array instead of string"
-
end
-
-
2
def add_preamble(src)
-
src << "#{@bufvar} = [];"
-
end
-
-
2
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}\n"
-
end
-
-
end
-
-
-
##
-
## use an Array object as buffer (included in Eruby by default)
-
##
-
## this is only for Eruby.
-
##
-
2
module ArrayBufferEnhancer
-
-
2
def self.desc # :nodoc:
-
"use an Array object for buffering (included in Eruby class)"
-
end
-
-
2
def add_preamble(src)
-
src << "_buf = [];"
-
end
-
-
2
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "_buf.join\n"
-
end
-
-
end
-
-
-
##
-
## use String class for buffering
-
##
-
## this is only for Eruby.
-
##
-
2
module StringBufferEnhancer
-
-
2
def self.desc # :nodoc:
-
"use a String object for buffering"
-
end
-
-
2
def add_preamble(src)
-
src << "#{@bufvar} = '';"
-
end
-
-
2
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}.to_s\n"
-
end
-
-
end
-
-
-
##
-
## use StringIO class for buffering
-
##
-
## this is only for Eruby.
-
##
-
2
module StringIOEnhancer # :nodoc:
-
-
2
def self.desc # :nodoc:
-
"use a StringIO object for buffering"
-
end
-
-
2
def add_preamble(src)
-
src << "#{@bufvar} = StringIO.new;"
-
end
-
-
2
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}.string\n"
-
end
-
-
end
-
-
-
##
-
## set buffer variable name to '_erbout' as well as '_buf'
-
##
-
## this is only for Eruby.
-
##
-
2
module ErboutEnhancer
-
-
2
def self.desc # :nodoc:
-
"set '_erbout = _buf = \"\";' to be compatible with ERB."
-
end
-
-
2
def add_preamble(src)
-
src << "_erbout = #{@bufvar} = '';"
-
end
-
-
2
def add_postamble(src)
-
src << "\n" unless src[-1] == ?\n
-
src << "#{@bufvar}.to_s\n"
-
end
-
-
end
-
-
-
##
-
## remove text and leave code, especially useful when debugging.
-
##
-
## ex.
-
## $ erubis -s -E NoText file.eruby | more
-
##
-
## this is language independent.
-
##
-
2
module NoTextEnhancer
-
-
2
def self.desc # :nodoc:
-
"remove text and leave code (useful when debugging)"
-
end
-
-
2
def add_text(src, text)
-
src << ("\n" * text.count("\n"))
-
if text[-1] != ?\n
-
text =~ /^(.*?)\z/
-
src << (' ' * $1.length)
-
end
-
end
-
-
end
-
-
-
##
-
## remove code and leave text, especially useful when validating HTML tags.
-
##
-
## ex.
-
## $ erubis -s -E NoCode file.eruby | tidy -errors
-
##
-
## this is language independent.
-
##
-
2
module NoCodeEnhancer
-
-
2
def self.desc # :nodoc:
-
"remove code and leave text (useful when validating HTML)"
-
end
-
-
2
def add_preamble(src)
-
end
-
-
2
def add_postamble(src)
-
end
-
-
2
def add_text(src, text)
-
src << text
-
end
-
-
2
def add_expr(src, code, indicator)
-
src << "\n" * code.count("\n")
-
end
-
-
2
def add_stmt(src, code)
-
src << "\n" * code.count("\n")
-
end
-
-
end
-
-
-
##
-
## get convert faster, but spaces around '<%...%>' are not trimmed.
-
##
-
## this is language-independent.
-
##
-
2
module SimplifyEnhancer
-
-
2
def self.desc # :nodoc:
-
"get convert faster but leave spaces around '<% %>'"
-
end
-
-
#DEFAULT_REGEXP = /(^[ \t]*)?<%(=+|\#)?(.*?)-?%>([ \t]*\r?\n)?/m
-
2
SIMPLE_REGEXP = /<%(=+|\#)?(.*?)-?%>/m
-
-
2
def convert(input)
-
src = ""
-
add_preamble(src)
-
#regexp = pattern_regexp(@pattern)
-
pos = 0
-
input.scan(SIMPLE_REGEXP) do |indicator, code|
-
match = Regexp.last_match
-
index = match.begin(0)
-
text = input[pos, index - pos]
-
pos = match.end(0)
-
add_text(src, text)
-
if !indicator # <% %>
-
add_stmt(src, code)
-
elsif indicator[0] == ?\# # <%# %>
-
n = code.count("\n")
-
add_stmt(src, "\n" * n)
-
else # <%= %>
-
add_expr(src, code, indicator)
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
add_text(src, rest)
-
add_postamble(src)
-
return src
-
end
-
-
end
-
-
-
##
-
## enable to use other embedded expression pattern (default is '\[= =\]').
-
##
-
## notice! this is an experimental. spec may change in the future.
-
##
-
## ex.
-
## input = <<END
-
## <% for item in list %>
-
## <%= item %> : <%== item %>
-
## [= item =] : [== item =]
-
## <% end %>
-
## END
-
##
-
## class BiPatternEruby
-
## include BiPatternEnhancer
-
## end
-
## eruby = BiPatternEruby.new(input, :bipattern=>'\[= =\]')
-
## list = ['<a>', 'b&b', '"c"']
-
## print eruby.result(binding())
-
##
-
## ## output
-
## <a> : <a>
-
## <a> : <a>
-
## b&b : b&b
-
## b&b : b&b
-
## "c" : "c"
-
## "c" : "c"
-
##
-
## this is language independent.
-
##
-
2
module BiPatternEnhancer
-
-
2
def self.desc # :nodoc:
-
"another embedded expression pattern (default '\[= =\]')."
-
end
-
-
2
def initialize(input, properties={})
-
self.bipattern = properties[:bipattern] # or '\$\{ \}'
-
super
-
end
-
-
## when pat is nil then '\[= =\]' is used
-
2
def bipattern=(pat) # :nodoc:
-
@bipattern = pat || '\[= =\]'
-
pre, post = @bipattern.split()
-
@bipattern_regexp = /(.*?)#{pre}(=*)(.*?)#{post}/m
-
end
-
-
2
def add_text(src, text)
-
return unless text
-
m = nil
-
text.scan(@bipattern_regexp) do |txt, indicator, code|
-
m = Regexp.last_match
-
super(src, txt)
-
add_expr(src, code, '=' + indicator)
-
end
-
#rest = $' || text # ruby1.8
-
rest = m ? text[m.end(0)..-1] : text # ruby1.9
-
super(src, rest)
-
end
-
-
end
-
-
-
##
-
## regards lines starting with '^[ \t]*%' as program code
-
##
-
## in addition you can specify prefix character (default '%')
-
##
-
## this is language-independent.
-
##
-
2
module PrefixedLineEnhancer
-
-
2
def self.desc # :nodoc:
-
"regard lines matched to '^[ \t]*%' as program code"
-
end
-
-
2
def init_generator(properties={})
-
super
-
@prefixchar = properties[:prefixchar]
-
end
-
-
2
def add_text(src, text)
-
unless @prefixrexp
-
@prefixchar ||= '%'
-
@prefixrexp = Regexp.compile("^([ \\t]*)\\#{@prefixchar}(.*?\\r?\\n)")
-
end
-
pos = 0
-
text2 = ''
-
text.scan(@prefixrexp) do
-
space = $1
-
line = $2
-
space, line = '', $1 unless $2
-
match = Regexp.last_match
-
len = match.begin(0) - pos
-
str = text[pos, len]
-
pos = match.end(0)
-
if text2.empty?
-
text2 = str
-
else
-
text2 << str
-
end
-
if line[0, 1] == @prefixchar
-
text2 << space << line
-
else
-
super(src, text2)
-
text2 = ''
-
add_stmt(src, space + line)
-
end
-
end
-
#rest = pos == 0 ? text : $' # ruby1.8
-
rest = pos == 0 ? text : text[pos..-1] # ruby1.9
-
unless text2.empty?
-
text2 << rest if rest
-
rest = text2
-
end
-
super(src, rest)
-
end
-
-
end
-
-
-
##
-
## regards lines starting with '%' as program code
-
##
-
## this is for compatibility to eruby and ERB.
-
##
-
## this is language-independent.
-
##
-
2
module PercentLineEnhancer
-
2
include PrefixedLineEnhancer
-
-
2
def self.desc # :nodoc:
-
"regard lines starting with '%' as program code"
-
end
-
-
#--
-
#def init_generator(properties={})
-
# super
-
# @prefixchar = '%'
-
# @prefixrexp = /^\%(.*?\r?\n)/
-
#end
-
#++
-
-
2
def add_text(src, text)
-
unless @prefixrexp
-
@prefixchar = '%'
-
@prefixrexp = /^\%(.*?\r?\n)/
-
end
-
super(src, text)
-
end
-
-
end
-
-
-
##
-
## [experimental] allow header and footer in eRuby script
-
##
-
## ex.
-
## ====================
-
## ## without header and footer
-
## $ cat ex1.eruby
-
## <% def list_items(list) %>
-
## <% for item in list %>
-
## <li><%= item %></li>
-
## <% end %>
-
## <% end %>
-
##
-
## $ erubis -s ex1.eruby
-
## _buf = []; def list_items(list)
-
## ; for item in list
-
## ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
-
## '; end
-
## ; end
-
## ;
-
## _buf.join
-
##
-
## ## with header and footer
-
## $ cat ex2.eruby
-
## <!--#header:
-
## def list_items(list)
-
## #-->
-
## <% for item in list %>
-
## <li><%= item %></li>
-
## <% end %>
-
## <!--#footer:
-
## end
-
## #-->
-
##
-
## $ erubis -s -c HeaderFooterEruby ex4.eruby
-
##
-
## def list_items(list)
-
## _buf = []; _buf << '
-
## '; for item in list
-
## ; _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
-
## '; end
-
## ; _buf << '
-
## ';
-
## _buf.join
-
## end
-
##
-
## ====================
-
##
-
## this is language-independent.
-
##
-
2
module HeaderFooterEnhancer
-
-
2
def self.desc # :nodoc:
-
"allow header/footer in document (ex. '<!--#header: #-->')"
-
end
-
-
2
HEADER_FOOTER_PATTERN = /(.*?)(^[ \t]*)?<!--\#(\w+):(.*?)\#-->([ \t]*\r?\n)?/m
-
-
2
def add_text(src, text)
-
m = nil
-
text.scan(HEADER_FOOTER_PATTERN) do |txt, lspace, word, content, rspace|
-
m = Regexp.last_match
-
flag_trim = @trim && lspace && rspace
-
super(src, txt)
-
content = "#{lspace}#{content}#{rspace}" if flag_trim
-
super(src, lspace) if !flag_trim && lspace
-
instance_variable_set("@#{word}", content)
-
super(src, rspace) if !flag_trim && rspace
-
end
-
#rest = $' || text # ruby1.8
-
rest = m ? text[m.end(0)..-1] : text # ruby1.9
-
super(src, rest)
-
end
-
-
2
attr_accessor :header, :footer
-
-
2
def convert(input)
-
source = super
-
return @src = "#{@header}#{source}#{@footer}"
-
end
-
-
end
-
-
-
##
-
## delete indentation of HTML.
-
##
-
## this is language-independent.
-
##
-
2
module DeleteIndentEnhancer
-
-
2
def self.desc # :nodoc:
-
"delete indentation of HTML."
-
end
-
-
2
def convert_input(src, input)
-
input = input.gsub(/^[ \t]+</, '<')
-
super(src, input)
-
end
-
-
end
-
-
-
##
-
## convert "<h1><%=title%></h1>" into "_buf << %Q`<h1>#{title}</h1>`"
-
##
-
## this is only for Eruby.
-
##
-
2
module InterpolationEnhancer
-
-
2
def self.desc # :nodoc:
-
"convert '<p><%=text%></p>' into '_buf << %Q`<p>\#{text}</p>`'"
-
end
-
-
2
def convert_input(src, input)
-
pat = @pattern
-
regexp = pat.nil? || pat == '<% %>' ? Basic::Converter::DEFAULT_REGEXP : pattern_regexp(pat)
-
pos = 0
-
is_bol = true # is beginning of line
-
str = ''
-
input.scan(regexp) do |indicator, code, tailch, rspace|
-
match = Regexp.last_match()
-
len = match.begin(0) - pos
-
text = input[pos, len]
-
pos = match.end(0)
-
ch = indicator ? indicator[0] : nil
-
lspace = ch == ?= ? nil : detect_spaces_at_bol(text, is_bol)
-
is_bol = rspace ? true : false
-
_add_text_to_str(str, text)
-
## * when '<%= %>', do nothing
-
## * when '<% %>' or '<%# %>', delete spaces iff only spaces are around '<% %>'
-
if ch == ?= # <%= %>
-
rspace = nil if tailch && !tailch.empty?
-
str << lspace if lspace
-
add_expr(str, code, indicator)
-
str << rspace if rspace
-
elsif ch == ?\# # <%# %>
-
n = code.count("\n") + (rspace ? 1 : 0)
-
if @trim && lspace && rspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, "\n" * n)
-
else
-
str << lspace if lspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, "\n" * n)
-
str << rspace if rspace
-
end
-
else # <% %>
-
if @trim && lspace && rspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, "#{lspace}#{code}#{rspace}")
-
else
-
str << lspace if lspace
-
add_text(src, str)
-
str = ''
-
add_stmt(src, code)
-
str << rspace if rspace
-
end
-
end
-
end
-
#rest = $' || input # ruby1.8
-
rest = pos == 0 ? input : input[pos..-1] # ruby1.9
-
_add_text_to_str(str, rest)
-
add_text(src, str)
-
end
-
-
2
def add_text(src, text)
-
return if !text || text.empty?
-
#src << " _buf << %Q`" << text << "`;"
-
if text[-1] == ?\n
-
text[-1] = "\\n"
-
src << " #{@bufvar} << %Q`#{text}`\n"
-
else
-
src << " #{@bufvar} << %Q`#{text}`;"
-
end
-
end
-
-
2
def _add_text_to_str(str, text)
-
return if !text || text.empty?
-
str << text.gsub(/[`\#\\]/, '\\\\\&')
-
end
-
-
2
def add_expr_escaped(str, code)
-
str << "\#{#{escaped_expr(code)}}"
-
end
-
-
2
def add_expr_literal(str, code)
-
str << "\#{#{code}}"
-
end
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
2
module Erubis
-
-
-
##
-
## base error class
-
##
-
2
class ErubisError < StandardError
-
end
-
-
-
##
-
## raised when method or function is not supported
-
##
-
2
class NotSupportedError < ErubisError
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
2
require 'erubis/error'
-
2
require 'erubis/context'
-
-
-
2
module Erubis
-
-
2
EMPTY_BINDING = binding()
-
-
-
##
-
## evaluate code
-
##
-
2
module Evaluator
-
-
2
def self.supported_properties # :nodoc:
-
return []
-
end
-
-
2
attr_accessor :src, :filename
-
-
2
def init_evaluator(properties)
-
1
@filename = properties[:filename]
-
end
-
-
2
def result(*args)
-
raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
-
end
-
-
2
def evaluate(*args)
-
raise NotSupportedError.new("evaluation of code except Ruby is not supported.")
-
end
-
-
end
-
-
-
##
-
## evaluator for Ruby
-
##
-
2
module RubyEvaluator
-
2
include Evaluator
-
-
2
def self.supported_properties # :nodoc:
-
list = Evaluator.supported_properties
-
return list
-
end
-
-
## eval(@src) with binding object
-
2
def result(_binding_or_hash=TOPLEVEL_BINDING)
-
_arg = _binding_or_hash
-
if _arg.is_a?(Hash)
-
_b = binding()
-
eval _arg.collect{|k,v| "#{k} = _arg[#{k.inspect}]; "}.join, _b
-
elsif _arg.is_a?(Binding)
-
_b = _arg
-
elsif _arg.nil?
-
_b = binding()
-
else
-
raise ArgumentError.new("#{self.class.name}#result(): argument should be Binding or Hash but passed #{_arg.class.name} object.")
-
end
-
return eval(@src, _b, (@filename || '(erubis'))
-
end
-
-
## invoke context.instance_eval(@src)
-
2
def evaluate(_context=Context.new)
-
_context = Context.new(_context) if _context.is_a?(Hash)
-
#return _context.instance_eval(@src, @filename || '(erubis)')
-
#@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)')
-
@_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)')
-
return _context.instance_eval(&@_proc)
-
end
-
-
## if object is an Class or Module then define instance method to it,
-
## else define singleton method to it.
-
2
def def_method(object, method_name, filename=nil)
-
m = object.is_a?(Module) ? :module_eval : :instance_eval
-
object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)')
-
end
-
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
2
require 'erubis/util'
-
-
2
module Erubis
-
-
-
##
-
## code generator, called by Converter module
-
##
-
2
module Generator
-
-
2
def self.supported_properties() # :nodoc:
-
return [
-
[:escapefunc, nil, "escape function name"],
-
]
-
end
-
-
2
attr_accessor :escapefunc
-
-
2
def init_generator(properties={})
-
1
@escapefunc = properties[:escapefunc]
-
end
-
-
-
## (abstract) escape text string
-
##
-
## ex.
-
## def escape_text(text)
-
## return text.dump
-
## # or return "'" + text.gsub(/['\\]/, '\\\\\&') + "'"
-
## end
-
2
def escape_text(text)
-
not_implemented
-
end
-
-
## return escaped expression code (ex. 'h(...)' or 'htmlspecialchars(...)')
-
2
def escaped_expr(code)
-
code.strip!
-
return "#{@escapefunc}(#{code})"
-
end
-
-
## (abstract) add @preamble to src
-
2
def add_preamble(src)
-
not_implemented
-
end
-
-
## (abstract) add text string to src
-
2
def add_text(src, text)
-
not_implemented
-
end
-
-
## (abstract) add statement code to src
-
2
def add_stmt(src, code)
-
not_implemented
-
end
-
-
## (abstract) add expression literal code to src. this is called by add_expr().
-
2
def add_expr_literal(src, code)
-
not_implemented
-
end
-
-
## (abstract) add escaped expression code to src. this is called by add_expr().
-
2
def add_expr_escaped(src, code)
-
not_implemented
-
end
-
-
## (abstract) add expression code to src for debug. this is called by add_expr().
-
2
def add_expr_debug(src, code)
-
not_implemented
-
end
-
-
## (abstract) add @postamble to src
-
2
def add_postamble(src)
-
not_implemented
-
end
-
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
-
2
module Erubis
-
-
##
-
## helper for xml
-
##
-
2
module XmlHelper
-
-
2
module_function
-
-
2
ESCAPE_TABLE = {
-
'&' => '&',
-
'<' => '<',
-
'>' => '>',
-
'"' => '"',
-
"'" => ''',
-
}
-
-
2
def escape_xml(value)
-
value.to_s.gsub(/[&<>"]/) { |s| ESCAPE_TABLE[s] } # or /[&<>"']/
-
#value.to_s.gsub(/[&<>"]/) { ESCAPE_TABLE[$&] }
-
end
-
-
2
def escape_xml2(value)
-
return value.to_s.gsub(/\&/,'&').gsub(/</,'<').gsub(/>/,'>').gsub(/"/,'"')
-
end
-
-
2
alias h escape_xml
-
2
alias html_escape escape_xml
-
-
2
def url_encode(str)
-
return str.gsub(/[^-_.a-zA-Z0-9]+/) { |s|
-
s.unpack('C*').collect { |i| "%%%02X" % i }.join
-
}
-
end
-
-
2
alias u url_encode
-
-
end
-
-
-
end
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
##
-
## you can add site-local settings here.
-
## this files is required by erubis.rb
-
##
-
##
-
## $Release: 2.7.0 $
-
## copyright(c) 2006-2011 kuwata-lab.com all rights reserved.
-
##
-
-
2
module Kernel
-
-
##
-
## raise NotImplementedError
-
##
-
2
def not_implemented #:doc:
-
backtrace = caller()
-
method_name = (backtrace.shift =~ /`(\w+)'$/) && $1
-
mesg = "class #{self.class.name} must implement abstract method '#{method_name}()'."
-
#mesg = "#{self.class.name}##{method_name}() is not implemented."
-
err = NotImplementedError.new mesg
-
err.set_backtrace backtrace
-
raise err
-
end
-
2
private :not_implemented
-
-
end
-
2
require "execjs/module"
-
2
require "execjs/runtimes"
-
-
2
module ExecJS
-
2
self.runtime ||= Runtimes.autodetect
-
end
-
2
require "execjs/runtime"
-
-
2
module ExecJS
-
2
class DisabledRuntime < Runtime
-
2
def name
-
"Disabled"
-
end
-
-
2
def exec(source)
-
raise Error, "ExecJS disabled"
-
end
-
-
2
def eval(source)
-
raise Error, "ExecJS disabled"
-
end
-
-
2
def compile(source)
-
raise Error, "ExecJS disabled"
-
end
-
-
2
def deprecated?
-
true
-
end
-
-
2
def available?
-
true
-
end
-
end
-
end
-
2
module ExecJS
-
# Encodes strings as UTF-8
-
2
module Encoding
-
2
if "".respond_to?(:encode)
-
2
if RUBY_ENGINE == 'jruby' || RUBY_ENGINE == 'rbx'
-
# workaround for jruby bug http://jira.codehaus.org/browse/JRUBY-6588
-
# workaround for rbx bug https://github.com/rubinius/rubinius/issues/1729
-
def encode(string)
-
if string.encoding.name == 'ASCII-8BIT'
-
data = string.dup
-
data.force_encoding('UTF-8')
-
-
unless data.valid_encoding?
-
raise ::Encoding::UndefinedConversionError, "Could not encode ASCII-8BIT data #{string.dump} as UTF-8"
-
end
-
else
-
data = string.encode('UTF-8')
-
end
-
data
-
end
-
else
-
2
def encode(string)
-
string.encode('UTF-8')
-
end
-
end
-
else
-
# Define no-op on 1.8
-
def encode(string)
-
string
-
end
-
end
-
end
-
end
-
2
require "shellwords"
-
2
require "tempfile"
-
2
require "execjs/runtime"
-
-
2
module ExecJS
-
2
class ExternalRuntime < Runtime
-
2
class Context < Runtime::Context
-
2
def initialize(runtime, source = "")
-
source = encode(source)
-
-
@runtime = runtime
-
@source = source
-
end
-
-
2
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
exec("return eval(#{::JSON.generate("(#{source})", :quirks_mode => true)})")
-
end
-
end
-
-
2
def exec(source, options = {})
-
source = encode(source)
-
source = "#{@source}\n#{source}" if @source
-
-
compile_to_tempfile(source) do |file|
-
extract_result(@runtime.send(:exec_runtime, file.path))
-
end
-
end
-
-
2
def call(identifier, *args)
-
eval "#{identifier}.apply(this, #{::JSON.generate(args)})"
-
end
-
-
2
protected
-
2
def compile_to_tempfile(source)
-
tempfile = Tempfile.open(['execjs', '.js'])
-
tempfile.write compile(source)
-
tempfile.close
-
yield tempfile
-
ensure
-
tempfile.close!
-
end
-
-
2
def compile(source)
-
@runtime.send(:runner_source).dup.tap do |output|
-
output.sub!('#{source}') do
-
source
-
end
-
output.sub!('#{encoded_source}') do
-
encoded_source = encode_unicode_codepoints(source)
-
::JSON.generate("(function(){ #{encoded_source} })()", :quirks_mode => true)
-
end
-
output.sub!('#{json2_source}') do
-
IO.read(ExecJS.root + "/support/json2.js")
-
end
-
end
-
end
-
-
2
def extract_result(output)
-
status, value = output.empty? ? [] : ::JSON.parse(output, :create_additions => false)
-
if status == "ok"
-
value
-
elsif value =~ /SyntaxError:/
-
raise RuntimeError, value
-
else
-
raise ProgramError, value
-
end
-
end
-
-
2
if "".respond_to?(:codepoints)
-
2
def encode_unicode_codepoints(str)
-
str.gsub(/[\u0080-\uffff]/) do |ch|
-
"\\u%04x" % ch.codepoints.to_a
-
end
-
end
-
else
-
def encode_unicode_codepoints(str)
-
str.gsub(/([\xC0-\xDF][\x80-\xBF]|
-
[\xE0-\xEF][\x80-\xBF]{2}|
-
[\xF0-\xF7][\x80-\xBF]{3})+/nx) do |ch|
-
"\\u%04x" % ch.unpack("U*")
-
end
-
end
-
end
-
end
-
-
2
attr_reader :name
-
-
2
def initialize(options)
-
8
@name = options[:name]
-
8
@command = options[:command]
-
8
@runner_path = options[:runner_path]
-
8
@test_args = options[:test_args]
-
8
@test_match = options[:test_match]
-
8
@encoding = options[:encoding]
-
8
@deprecated = !!options[:deprecated]
-
8
@binary = nil
-
end
-
-
2
def available?
-
require 'json'
-
binary ? true : false
-
end
-
-
2
def deprecated?
-
8
@deprecated
-
end
-
-
2
private
-
2
def binary
-
@binary ||= locate_binary
-
end
-
-
2
def locate_executable(cmd)
-
if ExecJS.windows? && File.extname(cmd) == ""
-
cmd << ".exe"
-
end
-
-
if File.executable? cmd
-
cmd
-
else
-
path = ENV['PATH'].split(File::PATH_SEPARATOR).find { |p|
-
full_path = File.join(p, cmd)
-
File.executable?(full_path) && File.file?(full_path)
-
}
-
path && File.expand_path(cmd, path)
-
end
-
end
-
-
2
protected
-
2
def runner_source
-
@runner_source ||= IO.read(@runner_path)
-
end
-
-
2
def exec_runtime(filename)
-
output = sh("#{shell_escape(*(binary.split(' ') << filename))} 2>&1")
-
if $?.success?
-
output
-
else
-
raise RuntimeError, output
-
end
-
end
-
-
2
def locate_binary
-
if binary = which(@command)
-
if @test_args
-
output = `#{shell_escape(binary, @test_args)} 2>&1`
-
binary if output.match(@test_match)
-
else
-
binary
-
end
-
end
-
end
-
-
2
def which(command)
-
Array(command).find do |name|
-
name, args = name.split(/\s+/, 2)
-
path = locate_executable(name)
-
-
next unless path
-
-
args ? "#{path} #{args}" : path
-
end
-
end
-
-
2
if "".respond_to?(:force_encoding)
-
2
def sh(command)
-
output, options = nil, {}
-
options[:external_encoding] = @encoding if @encoding
-
options[:internal_encoding] = ::Encoding.default_internal || 'UTF-8'
-
IO.popen(command, options) { |f| output = f.read }
-
output
-
end
-
else
-
require "iconv"
-
-
def sh(command)
-
output = nil
-
IO.popen(command) { |f| output = f.read }
-
-
if @encoding
-
Iconv.new('UTF-8', @encoding).iconv(output)
-
else
-
output
-
end
-
end
-
end
-
-
2
if ExecJS.windows?
-
def shell_escape(*args)
-
# see http://technet.microsoft.com/en-us/library/cc723564.aspx#XSLTsection123121120120
-
args.map { |arg|
-
arg = %Q("#{arg.gsub('"','""')}") if arg.match(/[&|()<>^ "]/)
-
arg
-
}.join(" ")
-
end
-
else
-
2
def shell_escape(*args)
-
Shellwords.join(args)
-
end
-
end
-
end
-
end
-
2
require "execjs/runtime"
-
-
2
module ExecJS
-
2
class JohnsonRuntime < Runtime
-
2
class Context < Runtime::Context
-
2
def initialize(runtime, source = "")
-
source = encode(source)
-
-
@runtime = Johnson::Runtime.new
-
@runtime.evaluate(source)
-
end
-
-
2
def exec(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
eval "(function(){#{source}})()", options
-
end
-
end
-
-
2
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
unbox @runtime.evaluate("(#{source})")
-
end
-
rescue Johnson::Error => e
-
if syntax_error?(e)
-
raise RuntimeError, e.message
-
else
-
raise ProgramError, e.message
-
end
-
end
-
-
2
def call(properties, *args)
-
unbox @runtime.evaluate(properties).call(*args)
-
rescue Johnson::Error => e
-
if syntax_error?(e)
-
raise RuntimeError, e.message
-
else
-
raise ProgramError, e.message
-
end
-
end
-
-
2
def unbox(value)
-
case
-
when function?(value)
-
nil
-
when string?(value)
-
value.respond_to?(:force_encoding) ?
-
value.force_encoding('UTF-8') :
-
value
-
when array?(value)
-
value.map { |v| unbox(v) }
-
when object?(value)
-
value.inject({}) do |vs, (k, v)|
-
vs[k] = unbox(v) unless function?(v)
-
vs
-
end
-
else
-
value
-
end
-
end
-
-
2
private
-
2
def syntax_error?(error)
-
error.message =~ /^syntax error at /
-
end
-
-
2
def function?(value)
-
value.respond_to?(:function?) && value.function?
-
end
-
-
2
def string?(value)
-
value.is_a?(String)
-
end
-
-
2
def array?(value)
-
array_test.call(value)
-
end
-
-
2
def object?(value)
-
value.respond_to?(:inject)
-
end
-
-
2
def array_test
-
@array_test ||= @runtime.evaluate("(function(a) {return a instanceof [].constructor})")
-
end
-
end
-
-
2
def name
-
"Johnson (SpiderMonkey)"
-
end
-
-
2
def available?
-
require "johnson"
-
true
-
rescue LoadError
-
false
-
end
-
-
2
def deprecated?
-
2
true
-
end
-
end
-
end
-
2
require "execjs/version"
-
2
require "rbconfig"
-
-
2
module ExecJS
-
2
class Error < ::StandardError; end
-
2
class RuntimeError < Error; end
-
2
class ProgramError < Error; end
-
2
class RuntimeUnavailable < RuntimeError; end
-
-
2
class << self
-
2
attr_reader :runtime
-
-
2
def runtime=(runtime)
-
2
raise RuntimeUnavailable, "#{runtime.name} is unavailable on this system" unless runtime.available?
-
2
@runtime = runtime
-
end
-
-
2
def exec(source)
-
runtime.exec(source)
-
end
-
-
2
def eval(source)
-
runtime.eval(source)
-
end
-
-
2
def compile(source)
-
runtime.compile(source)
-
end
-
-
2
def root
-
8
@root ||= File.expand_path("..", __FILE__)
-
end
-
-
2
def windows?
-
2
@windows ||= RbConfig::CONFIG["host_os"] =~ /mswin|mingw/
-
end
-
end
-
end
-
2
require "execjs/runtime"
-
-
2
module ExecJS
-
2
class MustangRuntime < Runtime
-
2
class Context < Runtime::Context
-
2
def initialize(runtime, source = "")
-
source = encode(source)
-
-
@v8_context = ::Mustang::Context.new
-
@v8_context.eval(source)
-
end
-
-
2
def exec(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
eval "(function(){#{source}})()", options
-
end
-
end
-
-
2
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
unbox @v8_context.eval("(#{source})")
-
end
-
end
-
-
2
def call(properties, *args)
-
unbox @v8_context.eval(properties).call(*args)
-
rescue NoMethodError => e
-
raise ProgramError, e.message
-
end
-
-
2
def unbox(value)
-
case value
-
when Mustang::V8::Array
-
value.map { |v| unbox(v) }
-
when Mustang::V8::Boolean
-
value.to_bool
-
when Mustang::V8::NullClass, Mustang::V8::UndefinedClass
-
nil
-
when Mustang::V8::Function
-
nil
-
when Mustang::V8::SyntaxError
-
raise RuntimeError, value.message
-
when Mustang::V8::Error
-
raise ProgramError, value.message
-
when Mustang::V8::Object
-
value.inject({}) { |h, (k, v)|
-
v = unbox(v)
-
h[k] = v if v
-
h
-
}
-
else
-
value.respond_to?(:delegate) ? value.delegate : value
-
end
-
end
-
end
-
-
2
def name
-
"Mustang (V8)"
-
end
-
-
2
def available?
-
require "mustang"
-
true
-
rescue LoadError
-
false
-
end
-
-
2
def deprecated?
-
2
true
-
end
-
end
-
end
-
2
require "execjs/runtime"
-
-
2
module ExecJS
-
2
class RubyRacerRuntime < Runtime
-
2
class Context < Runtime::Context
-
2
def initialize(runtime, source = "")
-
source = encode(source)
-
-
lock do
-
@v8_context = ::V8::Context.new
-
@v8_context.eval(source)
-
end
-
end
-
-
2
def exec(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
eval "(function(){#{source}})()", options
-
end
-
end
-
-
2
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
lock do
-
begin
-
unbox @v8_context.eval("(#{source})")
-
rescue ::V8::JSError => e
-
if e.value["name"] == "SyntaxError"
-
raise RuntimeError, e.value.to_s
-
else
-
raise ProgramError, e.value.to_s
-
end
-
end
-
end
-
end
-
end
-
-
2
def call(properties, *args)
-
lock do
-
begin
-
unbox @v8_context.eval(properties).call(*args)
-
rescue ::V8::JSError => e
-
if e.value["name"] == "SyntaxError"
-
raise RuntimeError, e.value.to_s
-
else
-
raise ProgramError, e.value.to_s
-
end
-
end
-
end
-
end
-
-
2
def unbox(value)
-
case value
-
when ::V8::Function
-
nil
-
when ::V8::Array
-
value.map { |v| unbox(v) }
-
when ::V8::Object
-
value.inject({}) do |vs, (k, v)|
-
vs[k] = unbox(v) unless v.is_a?(::V8::Function)
-
vs
-
end
-
when String
-
value.respond_to?(:force_encoding) ?
-
value.force_encoding('UTF-8') :
-
value
-
else
-
value
-
end
-
end
-
-
2
private
-
2
def lock
-
result, exception = nil, nil
-
V8::C::Locker() do
-
begin
-
result = yield
-
rescue Exception => e
-
exception = e
-
end
-
end
-
-
if exception
-
raise exception
-
else
-
result
-
end
-
end
-
end
-
-
2
def name
-
"therubyracer (V8)"
-
end
-
-
2
def available?
-
4
require "v8"
-
4
true
-
rescue LoadError
-
false
-
end
-
end
-
end
-
2
require "execjs/runtime"
-
-
2
module ExecJS
-
2
class RubyRhinoRuntime < Runtime
-
2
class Context < Runtime::Context
-
2
def initialize(runtime, source = "")
-
source = encode(source)
-
-
@rhino_context = ::Rhino::Context.new
-
fix_memory_limit! @rhino_context
-
@rhino_context.eval(source)
-
end
-
-
2
def exec(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
eval "(function(){#{source}})()", options
-
end
-
end
-
-
2
def eval(source, options = {})
-
source = encode(source)
-
-
if /\S/ =~ source
-
unbox @rhino_context.eval("(#{source})")
-
end
-
rescue ::Rhino::JSError => e
-
if e.message =~ /^syntax error/
-
raise RuntimeError, e.message
-
else
-
raise ProgramError, e.message
-
end
-
end
-
-
2
def call(properties, *args)
-
unbox @rhino_context.eval(properties).call(*args)
-
rescue ::Rhino::JSError => e
-
if e.message == "syntax error"
-
raise RuntimeError, e.message
-
else
-
raise ProgramError, e.message
-
end
-
end
-
-
2
def unbox(value)
-
case value = ::Rhino::to_ruby(value)
-
when Java::OrgMozillaJavascript::NativeFunction
-
nil
-
when Java::OrgMozillaJavascript::NativeObject
-
value.inject({}) do |vs, (k, v)|
-
case v
-
when Java::OrgMozillaJavascript::NativeFunction, ::Rhino::JS::Function
-
nil
-
else
-
vs[k] = unbox(v)
-
end
-
vs
-
end
-
when Array
-
value.map { |v| unbox(v) }
-
else
-
value
-
end
-
end
-
-
2
private
-
# Disables bytecode compiling which limits you to 64K scripts
-
2
def fix_memory_limit!(context)
-
if context.respond_to?(:optimization_level=)
-
context.optimization_level = -1
-
else
-
context.instance_eval { @native.setOptimizationLevel(-1) }
-
end
-
end
-
end
-
-
2
def name
-
"therubyrhino (Rhino)"
-
end
-
-
2
def available?
-
require "rhino"
-
true
-
rescue LoadError
-
false
-
end
-
end
-
end
-
2
require "execjs/encoding"
-
-
2
module ExecJS
-
# Abstract base class for runtimes
-
2
class Runtime
-
2
class Context
-
2
include Encoding
-
-
2
def initialize(runtime, source = "")
-
end
-
-
2
def exec(source, options = {})
-
raise NotImplementedError
-
end
-
-
2
def eval(source, options = {})
-
raise NotImplementedError
-
end
-
-
2
def call(properties, *args)
-
raise NotImplementedError
-
end
-
end
-
-
2
def name
-
raise NotImplementedError
-
end
-
-
2
def context_class
-
self.class::Context
-
end
-
-
2
def exec(source)
-
context = context_class.new(self)
-
context.exec(source)
-
end
-
-
2
def eval(source)
-
context = context_class.new(self)
-
context.eval(source)
-
end
-
-
2
def compile(source)
-
context_class.new(self, source)
-
end
-
-
2
def deprecated?
-
4
false
-
end
-
-
2
def available?
-
raise NotImplementedError
-
end
-
end
-
end
-
2
require "execjs/module"
-
2
require "execjs/disabled_runtime"
-
2
require "execjs/external_runtime"
-
2
require "execjs/johnson_runtime"
-
2
require "execjs/mustang_runtime"
-
2
require "execjs/ruby_racer_runtime"
-
2
require "execjs/ruby_rhino_runtime"
-
-
2
module ExecJS
-
2
module Runtimes
-
2
Disabled = DisabledRuntime.new
-
-
2
RubyRacer = RubyRacerRuntime.new
-
-
2
RubyRhino = RubyRhinoRuntime.new
-
-
2
Johnson = JohnsonRuntime.new
-
-
2
Mustang = MustangRuntime.new
-
-
2
Node = ExternalRuntime.new(
-
:name => "Node.js (V8)",
-
:command => ["nodejs", "node"],
-
:runner_path => ExecJS.root + "/support/node_runner.js",
-
:encoding => 'UTF-8'
-
)
-
-
2
JavaScriptCore = ExternalRuntime.new(
-
:name => "JavaScriptCore",
-
:command => "/System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc",
-
:runner_path => ExecJS.root + "/support/jsc_runner.js"
-
)
-
-
2
SpiderMonkey = Spidermonkey = ExternalRuntime.new(
-
:name => "SpiderMonkey",
-
:command => "js",
-
:runner_path => ExecJS.root + "/support/spidermonkey_runner.js",
-
:deprecated => true
-
)
-
-
2
JScript = ExternalRuntime.new(
-
:name => "JScript",
-
:command => "cscript //E:jscript //Nologo //U",
-
:runner_path => ExecJS.root + "/support/jscript_runner.js",
-
:encoding => 'UTF-16LE' # CScript with //U returns UTF-16LE
-
)
-
-
-
2
def self.autodetect
-
2
from_environment || best_available ||
-
raise(RuntimeUnavailable, "Could not find a JavaScript runtime. " +
-
"See https://github.com/sstephenson/execjs for a list of available runtimes.")
-
end
-
-
2
def self.best_available
-
2
runtimes.reject(&:deprecated?).find(&:available?)
-
end
-
-
2
def self.from_environment
-
2
if name = ENV["EXECJS_RUNTIME"]
-
if runtime = const_get(name)
-
if runtime.available?
-
runtime if runtime.available?
-
else
-
raise RuntimeUnavailable, "#{runtime.name} runtime is not available on this system"
-
end
-
elsif !name.empty?
-
raise RuntimeUnavailable, "#{name} runtime is not defined"
-
end
-
end
-
end
-
-
2
def self.names
-
@names ||= constants.inject({}) { |h, name| h.merge(const_get(name) => name) }.values
-
end
-
-
2
def self.runtimes
-
@runtimes ||= [
-
RubyRacer,
-
RubyRhino,
-
Johnson,
-
Mustang,
-
Node,
-
JavaScriptCore,
-
SpiderMonkey,
-
JScript
-
2
]
-
end
-
end
-
-
2
def self.runtimes
-
Runtimes.runtimes
-
end
-
end
-
2
module ExecJS
-
2
VERSION = "2.0.2"
-
end
-
2
module Hike
-
2
VERSION = "1.2.0"
-
-
2
autoload :Extensions, "hike/extensions"
-
2
autoload :Index, "hike/index"
-
2
autoload :NormalizedArray, "hike/normalized_array"
-
2
autoload :Paths, "hike/paths"
-
2
autoload :Trail, "hike/trail"
-
end
-
2
require 'hike/normalized_array'
-
-
2
module Hike
-
# `Extensions` is an internal collection for tracking extension names.
-
2
class Extensions < NormalizedArray
-
# Extensions added to this array are normalized with a leading
-
# `.`.
-
#
-
# extensions << "js"
-
# extensions << ".css"
-
#
-
# extensions
-
# # => [".js", ".css"]
-
#
-
2
def normalize_element(extension)
-
22
if extension[/^\./]
-
22
extension
-
else
-
".#{extension}"
-
end
-
end
-
end
-
end
-
2
require 'pathname'
-
-
2
module Hike
-
# `Index` is an internal cached variant of `Trail`. It assumes the
-
# file system does not change between `find` calls. All `stat` and
-
# `entries` calls are cached for the lifetime of the `Index` object.
-
2
class Index
-
# `Index#paths` is an immutable `Paths` collection.
-
2
attr_reader :paths
-
-
# `Index#extensions` is an immutable `Extensions` collection.
-
2
attr_reader :extensions
-
-
# `Index#aliases` is an immutable `Hash` mapping an extension to
-
# an `Array` of aliases.
-
2
attr_reader :aliases
-
-
# `Index.new` is an internal method. Instead of constructing it
-
# directly, create a `Trail` and call `Trail#index`.
-
2
def initialize(root, paths, extensions, aliases)
-
@root = root
-
-
# Freeze is used here so an error is throw if a mutator method
-
# is called on the array. Mutating `@paths`, `@extensions`, or
-
# `@aliases` would have unpredictable results.
-
@paths = paths.dup.freeze
-
@extensions = extensions.dup.freeze
-
@aliases = aliases.inject({}) { |h, (k, a)|
-
h[k] = a.dup.freeze; h
-
}.freeze
-
@pathnames = paths.map { |path| Pathname.new(path) }
-
-
@stats = {}
-
@entries = {}
-
@patterns = {}
-
end
-
-
# `Index#root` returns root path as a `String`. This attribute is immutable.
-
2
def root
-
@root.to_s
-
end
-
-
# `Index#index` returns `self` to be compatable with the `Trail` interface.
-
2
def index
-
self
-
end
-
-
# The real implementation of `find`. `Trail#find` generates a one
-
# time index and delegates here.
-
#
-
# See `Trail#find` for usage.
-
2
def find(*logical_paths, &block)
-
if block_given?
-
options = extract_options!(logical_paths)
-
base_path = Pathname.new(options[:base_path] || @root)
-
-
logical_paths.each do |logical_path|
-
logical_path = Pathname.new(logical_path.sub(/^\//, ''))
-
-
if relative?(logical_path)
-
find_in_base_path(logical_path, base_path, &block)
-
else
-
find_in_paths(logical_path, &block)
-
end
-
end
-
-
nil
-
else
-
find(*logical_paths) do |path|
-
return path
-
end
-
end
-
end
-
-
# A cached version of `Dir.entries` that filters out `.` files and
-
# `~` swap files. Returns an empty `Array` if the directory does
-
# not exist.
-
2
def entries(path)
-
@entries[path.to_s] ||= begin
-
pathname = Pathname.new(path)
-
if pathname.directory?
-
pathname.entries.reject { |entry| entry.to_s =~ /^\.|~$|^\#.*\#$/ }.sort
-
else
-
[]
-
end
-
end
-
end
-
-
# A cached version of `File.stat`. Returns nil if the file does
-
# not exist.
-
2
def stat(path)
-
key = path.to_s
-
if @stats.key?(key)
-
@stats[key]
-
elsif File.exist?(path)
-
@stats[key] = File.stat(path)
-
else
-
@stats[key] = nil
-
end
-
end
-
-
2
protected
-
2
def extract_options!(arguments)
-
arguments.last.is_a?(Hash) ? arguments.pop.dup : {}
-
end
-
-
2
def relative?(logical_path)
-
logical_path.to_s =~ /^\.\.?\//
-
end
-
-
# Finds logical path across all `paths`
-
2
def find_in_paths(logical_path, &block)
-
dirname, basename = logical_path.split
-
@pathnames.each do |base_path|
-
match(base_path.join(dirname), basename, &block)
-
end
-
end
-
-
# Finds relative logical path, `../test/test_trail`. Requires a
-
# `base_path` for reference.
-
2
def find_in_base_path(logical_path, base_path, &block)
-
candidate = base_path.join(logical_path)
-
dirname, basename = candidate.split
-
match(dirname, basename, &block) if paths_contain?(dirname)
-
end
-
-
# Checks if the path is actually on the file system and performs
-
# any syscalls if necessary.
-
2
def match(dirname, basename)
-
# Potential `entries` syscall
-
matches = entries(dirname)
-
-
pattern = pattern_for(basename)
-
matches = matches.select { |m| m.to_s =~ pattern }
-
-
sort_matches(matches, basename).each do |path|
-
pathname = dirname.join(path)
-
-
# Potential `stat` syscall
-
stat = stat(pathname)
-
-
# Exclude directories
-
if stat && stat.file?
-
yield pathname.to_s
-
end
-
end
-
end
-
-
# Returns true if `dirname` is a subdirectory of any of the `paths`
-
2
def paths_contain?(dirname)
-
paths.any? { |path| dirname.to_s[0, path.length] == path }
-
end
-
-
# Cache results of `build_pattern_for`
-
2
def pattern_for(basename)
-
@patterns[basename] ||= build_pattern_for(basename)
-
end
-
-
# Returns a `Regexp` that matches the allowed extensions.
-
#
-
# pattern_for("index.html") #=> /^index(.html|.htm)(.builder|.erb)*$/
-
2
def build_pattern_for(basename)
-
extname = basename.extname
-
aliases = find_aliases_for(extname)
-
-
if aliases.any?
-
basename = basename.basename(extname)
-
aliases = [extname] + aliases
-
aliases_pattern = aliases.map { |e| Regexp.escape(e) }.join("|")
-
basename_re = Regexp.escape(basename.to_s) + "(?:#{aliases_pattern})"
-
else
-
basename_re = Regexp.escape(basename.to_s)
-
end
-
-
extension_pattern = extensions.map { |e| Regexp.escape(e) }.join("|")
-
/^#{basename_re}(?:#{extension_pattern})*$/
-
end
-
-
# Sorts candidate matches by their extension
-
# priority. Extensions in the front of the `extensions` carry
-
# more weight.
-
2
def sort_matches(matches, basename)
-
aliases = find_aliases_for(basename.extname)
-
-
matches.sort_by do |match|
-
extnames = match.sub(basename.to_s, '').to_s.scan(/\.[^.]+/)
-
extnames.inject(0) do |sum, ext|
-
if i = extensions.index(ext)
-
sum + i + 1
-
elsif i = aliases.index(ext)
-
sum + i + 11
-
else
-
sum
-
end
-
end
-
end
-
end
-
-
2
def find_aliases_for(extension)
-
@aliases.inject([]) do |aliases, (key, value)|
-
aliases.push(key) if value == extension
-
aliases
-
end
-
end
-
end
-
end
-
2
module Hike
-
# `NormalizedArray` is an internal abstract wrapper class that calls
-
# a callback `normalize_element` anytime an element is added to the
-
# Array.
-
#
-
# `Extensions` and `Paths` are subclasses of `NormalizedArray`.
-
2
class NormalizedArray < Array
-
2
def initialize
-
4
super()
-
end
-
-
2
def []=(*args)
-
value = args.pop
-
-
if value.respond_to?(:to_ary)
-
value = normalize_elements(value)
-
else
-
value = normalize_element(value)
-
end
-
-
super(*args.concat([value]))
-
end
-
-
2
def <<(element)
-
super normalize_element(element)
-
end
-
-
2
def collect!
-
super do |element|
-
result = yield element
-
normalize_element(result)
-
end
-
end
-
-
2
alias_method :map!, :collect!
-
-
2
def insert(index, *elements)
-
super index, *normalize_elements(elements)
-
end
-
-
2
def push(*elements)
-
48
super(*normalize_elements(elements))
-
end
-
-
2
def replace(elements)
-
super normalize_elements(elements)
-
end
-
-
2
def unshift(*elements)
-
super(*normalize_elements(elements))
-
end
-
-
2
def normalize_elements(elements)
-
48
elements.map do |element|
-
48
normalize_element(element)
-
end
-
end
-
end
-
end
-
2
require 'pathname'
-
2
require 'hike/normalized_array'
-
-
2
module Hike
-
# `Paths` is an internal collection for tracking path strings.
-
2
class Paths < NormalizedArray
-
2
def initialize(root = ".")
-
2
@root = Pathname.new(root)
-
2
super()
-
end
-
-
# Relative paths added to this array are expanded relative to `@root`.
-
#
-
# paths = Paths.new("/usr/local")
-
# paths << "tmp"
-
# paths << "/tmp"
-
#
-
# paths
-
# # => ["/usr/local/tmp", "/tmp"]
-
#
-
2
def normalize_element(path)
-
26
path = Pathname.new(path)
-
26
path = @root.join(path) if path.relative?
-
26
path.expand_path.to_s
-
end
-
end
-
end
-
2
require 'pathname'
-
2
require 'hike/extensions'
-
2
require 'hike/index'
-
2
require 'hike/paths'
-
-
2
module Hike
-
# `Trail` is the public container class for holding paths and extensions.
-
2
class Trail
-
# `Trail#paths` is a mutable `Paths` collection.
-
#
-
# trail = Hike::Trail.new
-
# trail.paths.push "~/Projects/hike/lib", "~/Projects/hike/test"
-
#
-
# The order of the paths is significant. Paths in the beginning of
-
# the collection will be checked first. In the example above,
-
# `~/Projects/hike/lib/hike.rb` would shadow the existent of
-
# `~/Projects/hike/test/hike.rb`.
-
2
attr_reader :paths
-
-
# `Trail#extensions` is a mutable `Extensions` collection.
-
#
-
# trail = Hike::Trail.new
-
# trail.paths.push "~/Projects/hike/lib"
-
# trail.extensions.push ".rb"
-
#
-
# Extensions allow you to find files by just their name omitting
-
# their extension. Is similar to Ruby's require mechanism that
-
# allows you to require files with specifiying `foo.rb`.
-
2
attr_reader :extensions
-
-
# `Index#aliases` is a mutable `Hash` mapping an extension to
-
# an `Array` of aliases.
-
#
-
# trail = Hike::Trail.new
-
# trail.paths.push "~/Projects/hike/site"
-
# trail.aliases['.htm'] = 'html'
-
# trail.aliases['.xhtml'] = 'html'
-
# trail.aliases['.php'] = 'html'
-
#
-
# Aliases provide a fallback when the primary extension is not
-
# matched. In the example above, a lookup for "foo.html" will
-
# check for the existence of "foo.htm", "foo.xhtml", or "foo.php".
-
2
attr_reader :aliases
-
-
# A Trail accepts an optional root path that defaults to your
-
# current working directory. Any relative paths added to
-
# `Trail#paths` will expanded relative to the root.
-
2
def initialize(root = ".")
-
2
@root = Pathname.new(root).expand_path
-
2
@paths = Paths.new(@root)
-
2
@extensions = Extensions.new
-
2
@aliases = Hash.new { |h, k| h[k] = Extensions.new }
-
end
-
-
# `Trail#root` returns root path as a `String`. This attribute is immutable.
-
2
def root
-
@root.to_s
-
end
-
-
# Prepend `path` to `Paths` collection
-
2
def prepend_paths(*paths)
-
self.paths.unshift(*paths)
-
end
-
2
alias_method :prepend_path, :prepend_paths
-
-
# Append `path` to `Paths` collection
-
2
def append_paths(*paths)
-
26
self.paths.push(*paths)
-
end
-
2
alias_method :append_path, :append_paths
-
-
# Remove `path` from `Paths` collection
-
2
def remove_path(path)
-
self.paths.delete(path)
-
end
-
-
# Prepend `extension` to `Extensions` collection
-
2
def prepend_extensions(*extensions)
-
self.extensions.unshift(*extensions)
-
end
-
2
alias_method :prepend_extension, :prepend_extensions
-
-
# Append `extension` to `Extensions` collection
-
2
def append_extensions(*extensions)
-
22
self.extensions.push(*extensions)
-
end
-
2
alias_method :append_extension, :append_extensions
-
-
# Remove `extension` from `Extensions` collection
-
2
def remove_extension(extension)
-
self.extensions.delete(extension)
-
end
-
-
# Alias `new_extension` to `old_extension`
-
2
def alias_extension(new_extension, old_extension)
-
10
aliases[normalize_extension(new_extension)] = normalize_extension(old_extension)
-
end
-
-
# Remove the alias for `extension`
-
2
def unalias_extension(extension)
-
aliases.delete(normalize_extension(extension))
-
end
-
-
# `Trail#find` returns a the expand path for a logical path in the
-
# path collection.
-
#
-
# trail = Hike::Trail.new "~/Projects/hike"
-
# trail.extensions.push ".rb"
-
# trail.paths.push "lib", "test"
-
#
-
# trail.find "hike/trail"
-
# # => "~/Projects/hike/lib/hike/trail.rb"
-
#
-
# trail.find "test_trail"
-
# # => "~/Projects/hike/test/test_trail.rb"
-
#
-
# `find` accepts multiple fallback logical paths that returns the
-
# first match.
-
#
-
# trail.find "hike", "hike/index"
-
#
-
# is equivalent to
-
#
-
# trail.find("hike") || trail.find("hike/index")
-
#
-
# Though `find` always returns the first match, it is possible
-
# to iterate over all shadowed matches and fallbacks by supplying
-
# a block.
-
#
-
# trail.find("hike", "hike/index") { |path| warn path }
-
#
-
# This allows you to filter your matches by any condition.
-
#
-
# trail.find("application") do |path|
-
# return path if mime_type_for(path) == "text/css"
-
# end
-
#
-
2
def find(*args, &block)
-
index.find(*args, &block)
-
end
-
-
# `Trail#index` returns an `Index` object that has the same
-
# interface as `Trail`. An `Index` is a cached `Trail` object that
-
# does not update when the file system changes. If you are
-
# confident that you are not making changes the paths you are
-
# searching, `index` will avoid excess system calls.
-
#
-
# index = trail.index
-
# index.find "hike/trail"
-
# index.find "test_trail"
-
#
-
2
def index
-
Index.new(root, paths, extensions, aliases)
-
end
-
-
# `Trail#entries` is equivalent to `Dir#entries`. It is not
-
# recommend to use this method for general purposes. It exists for
-
# parity with `Index#entries`.
-
2
def entries(path)
-
pathname = Pathname.new(path)
-
if pathname.directory?
-
pathname.entries.reject { |entry| entry.to_s =~ /^\.|~$|^\#.*\#$/ }.sort
-
else
-
[]
-
end
-
end
-
-
# `Trail#stat` is equivalent to `File#stat`. It is not
-
# recommend to use this method for general purposes. It exists for
-
# parity with `Index#stat`.
-
2
def stat(path)
-
if File.exist?(path)
-
File.stat(path.to_s)
-
else
-
nil
-
end
-
end
-
-
2
private
-
2
def normalize_extension(extension)
-
20
if extension[/^\./]
-
20
extension
-
else
-
".#{extension}"
-
end
-
end
-
end
-
end
-
2
require 'i18n/version'
-
2
require 'i18n/exceptions'
-
2
require 'i18n/interpolate/ruby'
-
-
2
module I18n
-
2
autoload :Backend, 'i18n/backend'
-
2
autoload :Config, 'i18n/config'
-
2
autoload :Gettext, 'i18n/gettext'
-
2
autoload :Locale, 'i18n/locale'
-
2
autoload :Tests, 'i18n/tests'
-
-
2
RESERVED_KEYS = [:scope, :default, :separator, :resolve, :object, :fallback, :format, :cascade, :throw, :raise, :rescue_format]
-
2
RESERVED_KEYS_PATTERN = /%\{(#{RESERVED_KEYS.join("|")})\}/
-
-
extend(Module.new {
-
# Gets I18n configuration object.
-
2
def config
-
74
Thread.current[:i18n_config] ||= I18n::Config.new
-
end
-
-
# Sets I18n configuration object.
-
2
def config=(value)
-
26
Thread.current[:i18n_config] = value
-
end
-
-
# Write methods which delegates to the configuration object
-
2
%w(locale backend default_locale available_locales default_separator
-
exception_handler load_path enforce_available_locales).each do |method|
-
16
module_eval <<-DELEGATORS, __FILE__, __LINE__ + 1
-
def #{method}
-
config.#{method}
-
end
-
-
def #{method}=(value)
-
config.#{method} = (value)
-
end
-
DELEGATORS
-
end
-
-
# Tells the backend to reload translations. Used in situations like the
-
# Rails development environment. Backends can implement whatever strategy
-
# is useful.
-
2
def reload!
-
2
config.backend.reload!
-
end
-
-
# Translates, pluralizes and interpolates a given key using a given locale,
-
# scope, and default, as well as interpolation values.
-
#
-
# *LOOKUP*
-
#
-
# Translation data is organized as a nested hash using the upper-level keys
-
# as namespaces. <em>E.g.</em>, ActionView ships with the translation:
-
# <tt>:date => {:formats => {:short => "%b %d"}}</tt>.
-
#
-
# Translations can be looked up at any level of this hash using the key argument
-
# and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt>
-
# returns the whole translations hash <tt>{:formats => {:short => "%b %d"}}</tt>.
-
#
-
# Key can be either a single key or a dot-separated key (both Strings and Symbols
-
# work). <em>E.g.</em>, the short format can be looked up using both:
-
# I18n.t 'date.formats.short'
-
# I18n.t :'date.formats.short'
-
#
-
# Scope can be either a single key, a dot-separated key or an array of keys
-
# or dot-separated keys. Keys and scopes can be combined freely. So these
-
# examples will all look up the same short date format:
-
# I18n.t 'date.formats.short'
-
# I18n.t 'formats.short', :scope => 'date'
-
# I18n.t 'short', :scope => 'date.formats'
-
# I18n.t 'short', :scope => %w(date formats)
-
#
-
# *INTERPOLATION*
-
#
-
# Translations can contain interpolation variables which will be replaced by
-
# values passed to #translate as part of the options hash, with the keys matching
-
# the interpolation variable names.
-
#
-
# <em>E.g.</em>, with a translation <tt>:foo => "foo %{bar}"</tt> the option
-
# value for the key +bar+ will be interpolated into the translation:
-
# I18n.t :foo, :bar => 'baz' # => 'foo baz'
-
#
-
# *PLURALIZATION*
-
#
-
# Translation data can contain pluralized translations. Pluralized translations
-
# are arrays of singluar/plural versions of translations like <tt>['Foo', 'Foos']</tt>.
-
#
-
# Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English
-
# pluralization rules. Other algorithms can be supported by custom backends.
-
#
-
# This returns the singular version of a pluralized translation:
-
# I18n.t :foo, :count => 1 # => 'Foo'
-
#
-
# These both return the plural version of a pluralized translation:
-
# I18n.t :foo, :count => 0 # => 'Foos'
-
# I18n.t :foo, :count => 2 # => 'Foos'
-
#
-
# The <tt>:count</tt> option can be used both for pluralization and interpolation.
-
# <em>E.g.</em>, with the translation
-
# <tt>:foo => ['%{count} foo', '%{count} foos']</tt>, count will
-
# be interpolated to the pluralized translation:
-
# I18n.t :foo, :count => 1 # => '1 foo'
-
#
-
# *DEFAULTS*
-
#
-
# This returns the translation for <tt>:foo</tt> or <tt>default</tt> if no translation was found:
-
# I18n.t :foo, :default => 'default'
-
#
-
# This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no
-
# translation for <tt>:foo</tt> was found:
-
# I18n.t :foo, :default => :bar
-
#
-
# Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt>
-
# or <tt>default</tt> if no translations for <tt>:foo</tt> and <tt>:bar</tt> were found.
-
# I18n.t :foo, :default => [:bar, 'default']
-
#
-
# *BULK LOOKUP*
-
#
-
# This returns an array with the translations for <tt>:foo</tt> and <tt>:bar</tt>.
-
# I18n.t [:foo, :bar]
-
#
-
# Can be used with dot-separated nested keys:
-
# I18n.t [:'baz.foo', :'baz.bar']
-
#
-
# Which is the same as using a scope option:
-
# I18n.t [:foo, :bar], :scope => :baz
-
#
-
# *LAMBDAS*
-
#
-
# Both translations and defaults can be given as Ruby lambdas. Lambdas will be
-
# called and passed the key and options.
-
#
-
# E.g. assuming the key <tt>:salutation</tt> resolves to:
-
# lambda { |key, options| options[:gender] == 'm' ? "Mr. %{options[:name]}" : "Mrs. %{options[:name]}" }
-
#
-
# Then <tt>I18n.t(:salutation, :gender => 'w', :name => 'Smith') will result in "Mrs. Smith".
-
#
-
# It is recommended to use/implement lambdas in an "idempotent" way. E.g. when
-
# a cache layer is put in front of I18n.translate it will generate a cache key
-
# from the argument values passed to #translate. Therefor your lambdas should
-
# always return the same translations/values per unique combination of argument
-
# values.
-
2
def translate(*args)
-
options = args.last.is_a?(Hash) ? args.pop.dup : {}
-
key = args.shift
-
backend = config.backend
-
locale = options.delete(:locale) || config.locale
-
handling = options.delete(:throw) && :throw || options.delete(:raise) && :raise # TODO deprecate :raise
-
-
enforce_available_locales!(locale)
-
raise I18n::ArgumentError if key.is_a?(String) && key.empty?
-
-
result = catch(:exception) do
-
if key.is_a?(Array)
-
key.map { |k| backend.translate(locale, k, options) }
-
else
-
backend.translate(locale, key, options)
-
end
-
end
-
result.is_a?(MissingTranslation) ? handle_exception(handling, result, locale, key, options) : result
-
end
-
2
alias :t :translate
-
-
# Wrapper for <tt>translate</tt> that adds <tt>:raise => true</tt>. With
-
# this option, if no translation is found, it will raise <tt>I18n::MissingTranslationData</tt>
-
2
def translate!(key, options={})
-
translate(key, options.merge(:raise => true))
-
end
-
2
alias :t! :translate!
-
-
# Returns true if a translation exists for a given key, otherwise returns false.
-
2
def exists?(key, locale = config.locale)
-
raise I18n::ArgumentError if key.is_a?(String) && key.empty?
-
config.backend.exists?(locale, key)
-
end
-
-
# Transliterates UTF-8 characters to ASCII. By default this method will
-
# transliterate only Latin strings to an ASCII approximation:
-
#
-
# I18n.transliterate("Ærøskøbing")
-
# # => "AEroskobing"
-
#
-
# I18n.transliterate("日本語")
-
# # => "???"
-
#
-
# It's also possible to add support for per-locale transliterations. I18n
-
# expects transliteration rules to be stored at
-
# <tt>i18n.transliterate.rule</tt>.
-
#
-
# Transliteration rules can either be a Hash or a Proc. Procs must accept a
-
# single string argument. Hash rules inherit the default transliteration
-
# rules, while Procs do not.
-
#
-
# *Examples*
-
#
-
# Setting a Hash in <locale>.yml:
-
#
-
# i18n:
-
# transliterate:
-
# rule:
-
# ü: "ue"
-
# ö: "oe"
-
#
-
# Setting a Hash using Ruby:
-
#
-
# store_translations(:de, :i18n => {
-
# :transliterate => {
-
# :rule => {
-
# "ü" => "ue",
-
# "ö" => "oe"
-
# }
-
# }
-
# )
-
#
-
# Setting a Proc:
-
#
-
# translit = lambda {|string| MyTransliterator.transliterate(string) }
-
# store_translations(:xx, :i18n => {:transliterate => {:rule => translit})
-
#
-
# Transliterating strings:
-
#
-
# I18n.locale = :en
-
# I18n.transliterate("Jürgen") # => "Jurgen"
-
# I18n.locale = :de
-
# I18n.transliterate("Jürgen") # => "Juergen"
-
# I18n.transliterate("Jürgen", :locale => :en) # => "Jurgen"
-
# I18n.transliterate("Jürgen", :locale => :de) # => "Juergen"
-
2
def transliterate(*args)
-
options = args.pop.dup if args.last.is_a?(Hash)
-
key = args.shift
-
locale = options && options.delete(:locale) || config.locale
-
handling = options && (options.delete(:throw) && :throw || options.delete(:raise) && :raise)
-
replacement = options && options.delete(:replacement)
-
enforce_available_locales!(locale)
-
config.backend.transliterate(locale, key, replacement)
-
rescue I18n::ArgumentError => exception
-
handle_exception(handling, exception, locale, key, options || {})
-
end
-
-
# Localizes certain objects, such as dates and numbers to local formatting.
-
2
def localize(object, options = nil)
-
options = options ? options.dup : {}
-
locale = options.delete(:locale) || config.locale
-
format = options.delete(:format) || :default
-
enforce_available_locales!(locale)
-
config.backend.localize(locale, object, format, options)
-
end
-
2
alias :l :localize
-
-
# Executes block with given I18n.locale set.
-
2
def with_locale(tmp_locale = nil)
-
if tmp_locale
-
current_locale = self.locale
-
self.locale = tmp_locale
-
end
-
yield
-
ensure
-
self.locale = current_locale if tmp_locale
-
end
-
-
# Merges the given locale, key and scope into a single array of keys.
-
# Splits keys that contain dots into multiple keys. Makes sure all
-
# keys are Symbols.
-
2
def normalize_keys(locale, key, scope, separator = nil)
-
separator ||= I18n.default_separator
-
-
keys = []
-
keys.concat normalize_key(locale, separator)
-
keys.concat normalize_key(scope, separator)
-
keys.concat normalize_key(key, separator)
-
keys
-
end
-
-
# Returns true when the passed locale is in I18.available_locales.
-
# Returns false otherwise.
-
# Compare with Strings as `locale` may be coming from user input
-
2
def locale_available?(locale)
-
I18n.available_locales.map(&:to_s).include?(locale.to_s)
-
end
-
-
# Raises an InvalidLocale exception when the passed locale is not
-
# included in I18n.available_locales.
-
# Returns false otherwise
-
2
def enforce_available_locales!(locale)
-
handle_enforce_available_locales_deprecation
-
-
if config.enforce_available_locales
-
raise I18n::InvalidLocale.new(locale) if !locale_available?(locale)
-
end
-
end
-
-
# making these private until Ruby 1.9.2 can send to protected methods again
-
# see http://redmine.ruby-lang.org/repositories/revision/ruby-19?rev=24280
-
2
private
-
-
# Any exceptions thrown in translate will be sent to the @@exception_handler
-
# which can be a Symbol, a Proc or any other Object unless they're forced to
-
# be raised or thrown (MissingTranslation).
-
#
-
# If exception_handler is a Symbol then it will simply be sent to I18n as
-
# a method call. A Proc will simply be called. In any other case the
-
# method #call will be called on the exception_handler object.
-
#
-
# Examples:
-
#
-
# I18n.exception_handler = :default_exception_handler # this is the default
-
# I18n.default_exception_handler(exception, locale, key, options) # will be called like this
-
#
-
# I18n.exception_handler = lambda { |*args| ... } # a lambda
-
# I18n.exception_handler.call(exception, locale, key, options) # will be called like this
-
#
-
# I18n.exception_handler = I18nExceptionHandler.new # an object
-
# I18n.exception_handler.call(exception, locale, key, options) # will be called like this
-
2
def handle_exception(handling, exception, locale, key, options)
-
case handling
-
when :raise
-
raise(exception.respond_to?(:to_exception) ? exception.to_exception : exception)
-
when :throw
-
throw :exception, exception
-
else
-
case handler = options[:exception_handler] || config.exception_handler
-
when Symbol
-
send(handler, exception, locale, key, options)
-
else
-
handler.call(exception, locale, key, options)
-
end
-
end
-
end
-
-
2
def normalize_key(key, separator)
-
normalized_key_cache[separator][key] ||=
-
case key
-
when Array
-
key.map { |k| normalize_key(k, separator) }.flatten
-
else
-
keys = key.to_s.split(separator)
-
keys.delete('')
-
keys.map! { |k| k.to_sym }
-
keys
-
end
-
end
-
-
2
def normalized_key_cache
-
@normalized_key_cache ||= Hash.new { |h,k| h[k] = {} }
-
end
-
-
# DEPRECATED. Use I18n.normalize_keys instead.
-
2
def normalize_translation_keys(locale, key, scope, separator = nil)
-
puts "I18n.normalize_translation_keys is deprecated. Please use the class I18n.normalize_keys instead."
-
normalize_keys(locale, key, scope, separator)
-
end
-
-
# DEPRECATED. Please use the I18n::ExceptionHandler class instead.
-
2
def default_exception_handler(exception, locale, key, options)
-
puts "I18n.default_exception_handler is deprecated. Please use the class I18n::ExceptionHandler instead " +
-
"(an instance of which is set to I18n.exception_handler by default)."
-
exception.is_a?(MissingTranslation) ? exception.message : raise(exception)
-
end
-
-
2
def handle_enforce_available_locales_deprecation
-
if config.enforce_available_locales.nil? && !@unenforced_available_locales_deprecation
-
$stderr.puts "[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message."
-
@unenforced_available_locales_deprecation = true
-
end
-
end
-
2
})
-
end
-
2
module I18n
-
2
module Backend
-
2
autoload :Base, 'i18n/backend/base'
-
2
autoload :InterpolationCompiler, 'i18n/backend/interpolation_compiler'
-
2
autoload :Cache, 'i18n/backend/cache'
-
2
autoload :Cascade, 'i18n/backend/cascade'
-
2
autoload :Chain, 'i18n/backend/chain'
-
2
autoload :Fallbacks, 'i18n/backend/fallbacks'
-
2
autoload :Flatten, 'i18n/backend/flatten'
-
2
autoload :Gettext, 'i18n/backend/gettext'
-
2
autoload :KeyValue, 'i18n/backend/key_value'
-
2
autoload :Memoize, 'i18n/backend/memoize'
-
2
autoload :Metadata, 'i18n/backend/metadata'
-
2
autoload :Pluralization, 'i18n/backend/pluralization'
-
2
autoload :Simple, 'i18n/backend/simple'
-
2
autoload :Transliterator, 'i18n/backend/transliterator'
-
end
-
end
-
2
require 'yaml'
-
2
require 'i18n/core_ext/hash'
-
2
require 'i18n/core_ext/kernel/surpress_warnings'
-
-
2
module I18n
-
2
module Backend
-
2
module Base
-
2
include I18n::Backend::Transliterator
-
-
# Accepts a list of paths to translation files. Loads translations from
-
# plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml
-
# for details.
-
2
def load_translations(*filenames)
-
filenames = I18n.load_path if filenames.empty?
-
filenames.flatten.each { |filename| load_file(filename) }
-
end
-
-
# This method receives a locale, a data hash and options for storing translations.
-
# Should be implemented
-
2
def store_translations(locale, data, options = {})
-
raise NotImplementedError
-
end
-
-
2
def translate(locale, key, options = {})
-
raise InvalidLocale.new(locale) unless locale
-
entry = key && lookup(locale, key, options[:scope], options)
-
-
if options.empty?
-
entry = resolve(locale, key, entry, options)
-
else
-
count, default = options.values_at(:count, :default)
-
values = options.except(*RESERVED_KEYS)
-
entry = entry.nil? && default ?
-
default(locale, key, default, options) : resolve(locale, key, entry, options)
-
end
-
-
throw(:exception, I18n::MissingTranslation.new(locale, key, options)) if entry.nil?
-
entry = entry.dup if entry.is_a?(String)
-
-
entry = pluralize(locale, entry, count) if count
-
entry = interpolate(locale, entry, values) if values
-
entry
-
end
-
-
2
def exists?(locale, key)
-
lookup(locale, key) != nil
-
end
-
-
# Acts the same as +strftime+, but uses a localized version of the
-
# format string. Takes a key from the date/time formats translations as
-
# a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>).
-
2
def localize(locale, object, format = :default, options = {})
-
raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime)
-
-
if Symbol === format
-
key = format
-
type = object.respond_to?(:sec) ? 'time' : 'date'
-
options = options.merge(:raise => true, :object => object, :locale => locale)
-
format = I18n.t(:"#{type}.formats.#{key}", options)
-
end
-
-
# format = resolve(locale, object, format, options)
-
format = format.to_s.gsub(/%[aAbBpP]/) do |match|
-
case match
-
when '%a' then I18n.t(:"date.abbr_day_names", :locale => locale, :format => format)[object.wday]
-
when '%A' then I18n.t(:"date.day_names", :locale => locale, :format => format)[object.wday]
-
when '%b' then I18n.t(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon]
-
when '%B' then I18n.t(:"date.month_names", :locale => locale, :format => format)[object.mon]
-
when '%p' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format).upcase if object.respond_to? :hour
-
when '%P' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format).downcase if object.respond_to? :hour
-
end
-
end
-
-
object.strftime(format)
-
end
-
-
# Returns an array of locales for which translations are available
-
# ignoring the reserved translation meta data key :i18n.
-
2
def available_locales
-
raise NotImplementedError
-
end
-
-
2
def reload!
-
2
@skip_syntax_deprecation = false
-
end
-
-
2
protected
-
-
# The method which actually looks up for the translation in the store.
-
2
def lookup(locale, key, scope = [], options = {})
-
raise NotImplementedError
-
end
-
-
# Evaluates defaults.
-
# If given subject is an Array, it walks the array and returns the
-
# first translation that can be resolved. Otherwise it tries to resolve
-
# the translation directly.
-
2
def default(locale, object, subject, options = {})
-
options = options.dup.reject { |key, value| key == :default }
-
case subject
-
when Array
-
subject.each do |item|
-
result = resolve(locale, object, item, options) and return result
-
end and nil
-
else
-
resolve(locale, object, subject, options)
-
end
-
end
-
-
# Resolves a translation.
-
# If the given subject is a Symbol, it will be translated with the
-
# given options. If it is a Proc then it will be evaluated. All other
-
# subjects will be returned directly.
-
2
def resolve(locale, object, subject, options = {})
-
return subject if options[:resolve] == false
-
result = catch(:exception) do
-
case subject
-
when Symbol
-
I18n.translate(subject, options.merge(:locale => locale, :throw => true))
-
when Proc
-
date_or_time = options.delete(:object) || object
-
resolve(locale, object, subject.call(date_or_time, options))
-
else
-
subject
-
end
-
end
-
result unless result.is_a?(MissingTranslation)
-
end
-
-
# Picks a translation from a pluralized mnemonic subkey according to English
-
# pluralization rules :
-
# - It will pick the :one subkey if count is equal to 1.
-
# - It will pick the :other subkey otherwise.
-
# - It will pick the :zero subkey in the special case where count is
-
# equal to 0 and there is a :zero subkey present. This behaviour is
-
# not stand with regards to the CLDR pluralization rules.
-
# Other backends can implement more flexible or complex pluralization rules.
-
2
def pluralize(locale, entry, count)
-
return entry unless entry.is_a?(Hash) && count
-
-
key = :zero if count == 0 && entry.has_key?(:zero)
-
key ||= count == 1 ? :one : :other
-
raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key)
-
entry[key]
-
end
-
-
# Interpolates values into a given string.
-
#
-
# interpolate "file %{file} opened by %%{user}", :file => 'test.txt', :user => 'Mr. X'
-
# # => "file test.txt opened by %{user}"
-
2
def interpolate(locale, string, values = {})
-
if string.is_a?(::String) && !values.empty?
-
I18n.interpolate(string, values)
-
else
-
string
-
end
-
end
-
-
# Loads a single translations file by delegating to #load_rb or
-
# #load_yml depending on the file extension and directly merges the
-
# data to the existing translations. Raises I18n::UnknownFileType
-
# for all other file extensions.
-
2
def load_file(filename)
-
type = File.extname(filename).tr('.', '').downcase
-
raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}", true)
-
data = send(:"load_#{type}", filename)
-
unless data.is_a?(Hash)
-
raise InvalidLocaleData.new(filename, 'expects it to return a hash, but does not')
-
end
-
data.each { |locale, d| store_translations(locale, d || {}) }
-
end
-
-
# Loads a plain Ruby translations file. eval'ing the file must yield
-
# a Hash containing translation data with locales as toplevel keys.
-
2
def load_rb(filename)
-
eval(IO.read(filename), binding, filename)
-
end
-
-
# Loads a YAML translations file. The data must have locales as
-
# toplevel keys.
-
2
def load_yml(filename)
-
begin
-
YAML.load_file(filename)
-
rescue TypeError, ScriptError, StandardError => e
-
raise InvalidLocaleData.new(filename, e.inspect)
-
end
-
end
-
end
-
end
-
end
-
2
module I18n
-
2
module Backend
-
# A simple backend that reads translations from YAML files and stores them in
-
# an in-memory hash. Relies on the Base backend.
-
#
-
# The implementation is provided by a Implementation module allowing to easily
-
# extend Simple backend's behavior by including modules. E.g.:
-
#
-
# module I18n::Backend::Pluralization
-
# def pluralize(*args)
-
# # extended pluralization logic
-
# super
-
# end
-
# end
-
#
-
# I18n::Backend::Simple.include(I18n::Backend::Pluralization)
-
2
class Simple
-
6
(class << self; self; end).class_eval { public :include }
-
-
2
module Implementation
-
2
include Base
-
-
2
def initialized?
-
@initialized ||= false
-
end
-
-
# Stores translations for the given locale in memory.
-
# This uses a deep merge for the translations hash, so existing
-
# translations will be overwritten by new ones only at the deepest
-
# level of the hash.
-
2
def store_translations(locale, data, options = {})
-
locale = locale.to_sym
-
translations[locale] ||= {}
-
data = data.deep_symbolize_keys
-
translations[locale].deep_merge!(data)
-
end
-
-
# Get available locales from the translations hash
-
2
def available_locales
-
init_translations unless initialized?
-
translations.inject([]) do |locales, (locale, data)|
-
locales << locale unless (data.keys - [:i18n]).empty?
-
locales
-
end
-
end
-
-
# Clean up translations hash and set initialized to false on reload!
-
2
def reload!
-
2
@initialized = false
-
2
@translations = nil
-
2
super
-
end
-
-
2
protected
-
-
2
def init_translations
-
load_translations
-
@initialized = true
-
end
-
-
2
def translations
-
@translations ||= {}
-
end
-
-
# Looks up a translation from the translations hash. Returns nil if
-
# eiher key is nil, or locale, scope or key do not exist as a key in the
-
# nested translations hash. Splits keys or scopes containing dots
-
# into multiple keys, i.e. <tt>currency.format</tt> is regarded the same as
-
# <tt>%w(currency format)</tt>.
-
2
def lookup(locale, key, scope = [], options = {})
-
init_translations unless initialized?
-
keys = I18n.normalize_keys(locale, key, scope, options[:separator])
-
-
keys.inject(translations) do |result, _key|
-
_key = _key.to_sym
-
return nil unless result.is_a?(Hash) && result.has_key?(_key)
-
result = result[_key]
-
result = resolve(locale, _key, result, options.merge(:scope => nil)) if result.is_a?(Symbol)
-
result
-
end
-
end
-
end
-
-
2
include Implementation
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module I18n
-
2
module Backend
-
2
module Transliterator
-
2
DEFAULT_REPLACEMENT_CHAR = "?"
-
-
# Given a locale and a UTF-8 string, return the locale's ASCII
-
# approximation for the string.
-
2
def transliterate(locale, string, replacement = nil)
-
@transliterators ||= {}
-
@transliterators[locale] ||= Transliterator.get I18n.t(:'i18n.transliterate.rule',
-
:locale => locale, :resolve => false, :default => {})
-
@transliterators[locale].transliterate(string, replacement)
-
end
-
-
# Get a transliterator instance.
-
2
def self.get(rule = nil)
-
if !rule || rule.kind_of?(Hash)
-
HashTransliterator.new(rule)
-
elsif rule.kind_of? Proc
-
ProcTransliterator.new(rule)
-
else
-
raise I18n::ArgumentError, "Transliteration rule must be a proc or a hash."
-
end
-
end
-
-
# A transliterator which accepts a Proc as its transliteration rule.
-
2
class ProcTransliterator
-
2
def initialize(rule)
-
@rule = rule
-
end
-
-
2
def transliterate(string, replacement = nil)
-
@rule.call(string)
-
end
-
end
-
-
# A transliterator which accepts a Hash of characters as its translation
-
# rule.
-
2
class HashTransliterator
-
2
DEFAULT_APPROXIMATIONS = {
-
"À"=>"A", "Á"=>"A", "Â"=>"A", "Ã"=>"A", "Ä"=>"A", "Å"=>"A", "Æ"=>"AE",
-
"Ç"=>"C", "È"=>"E", "É"=>"E", "Ê"=>"E", "Ë"=>"E", "Ì"=>"I", "Í"=>"I",
-
"Î"=>"I", "Ï"=>"I", "Ð"=>"D", "Ñ"=>"N", "Ò"=>"O", "Ó"=>"O", "Ô"=>"O",
-
"Õ"=>"O", "Ö"=>"O", "×"=>"x", "Ø"=>"O", "Ù"=>"U", "Ú"=>"U", "Û"=>"U",
-
"Ü"=>"U", "Ý"=>"Y", "Þ"=>"Th", "ß"=>"ss", "à"=>"a", "á"=>"a", "â"=>"a",
-
"ã"=>"a", "ä"=>"a", "å"=>"a", "æ"=>"ae", "ç"=>"c", "è"=>"e", "é"=>"e",
-
"ê"=>"e", "ë"=>"e", "ì"=>"i", "í"=>"i", "î"=>"i", "ï"=>"i", "ð"=>"d",
-
"ñ"=>"n", "ò"=>"o", "ó"=>"o", "ô"=>"o", "õ"=>"o", "ö"=>"o", "ø"=>"o",
-
"ù"=>"u", "ú"=>"u", "û"=>"u", "ü"=>"u", "ý"=>"y", "þ"=>"th", "ÿ"=>"y",
-
"Ā"=>"A", "ā"=>"a", "Ă"=>"A", "ă"=>"a", "Ą"=>"A", "ą"=>"a", "Ć"=>"C",
-
"ć"=>"c", "Ĉ"=>"C", "ĉ"=>"c", "Ċ"=>"C", "ċ"=>"c", "Č"=>"C", "č"=>"c",
-
"Ď"=>"D", "ď"=>"d", "Đ"=>"D", "đ"=>"d", "Ē"=>"E", "ē"=>"e", "Ĕ"=>"E",
-
"ĕ"=>"e", "Ė"=>"E", "ė"=>"e", "Ę"=>"E", "ę"=>"e", "Ě"=>"E", "ě"=>"e",
-
"Ĝ"=>"G", "ĝ"=>"g", "Ğ"=>"G", "ğ"=>"g", "Ġ"=>"G", "ġ"=>"g", "Ģ"=>"G",
-
"ģ"=>"g", "Ĥ"=>"H", "ĥ"=>"h", "Ħ"=>"H", "ħ"=>"h", "Ĩ"=>"I", "ĩ"=>"i",
-
"Ī"=>"I", "ī"=>"i", "Ĭ"=>"I", "ĭ"=>"i", "Į"=>"I", "į"=>"i", "İ"=>"I",
-
"ı"=>"i", "IJ"=>"IJ", "ij"=>"ij", "Ĵ"=>"J", "ĵ"=>"j", "Ķ"=>"K", "ķ"=>"k",
-
"ĸ"=>"k", "Ĺ"=>"L", "ĺ"=>"l", "Ļ"=>"L", "ļ"=>"l", "Ľ"=>"L", "ľ"=>"l",
-
"Ŀ"=>"L", "ŀ"=>"l", "Ł"=>"L", "ł"=>"l", "Ń"=>"N", "ń"=>"n", "Ņ"=>"N",
-
"ņ"=>"n", "Ň"=>"N", "ň"=>"n", "ʼn"=>"'n", "Ŋ"=>"NG", "ŋ"=>"ng",
-
"Ō"=>"O", "ō"=>"o", "Ŏ"=>"O", "ŏ"=>"o", "Ő"=>"O", "ő"=>"o", "Œ"=>"OE",
-
"œ"=>"oe", "Ŕ"=>"R", "ŕ"=>"r", "Ŗ"=>"R", "ŗ"=>"r", "Ř"=>"R", "ř"=>"r",
-
"Ś"=>"S", "ś"=>"s", "Ŝ"=>"S", "ŝ"=>"s", "Ş"=>"S", "ş"=>"s", "Š"=>"S",
-
"š"=>"s", "Ţ"=>"T", "ţ"=>"t", "Ť"=>"T", "ť"=>"t", "Ŧ"=>"T", "ŧ"=>"t",
-
"Ũ"=>"U", "ũ"=>"u", "Ū"=>"U", "ū"=>"u", "Ŭ"=>"U", "ŭ"=>"u", "Ů"=>"U",
-
"ů"=>"u", "Ű"=>"U", "ű"=>"u", "Ų"=>"U", "ų"=>"u", "Ŵ"=>"W", "ŵ"=>"w",
-
"Ŷ"=>"Y", "ŷ"=>"y", "Ÿ"=>"Y", "Ź"=>"Z", "ź"=>"z", "Ż"=>"Z", "ż"=>"z",
-
"Ž"=>"Z", "ž"=>"z"
-
}.freeze
-
-
2
def initialize(rule = nil)
-
@rule = rule
-
add DEFAULT_APPROXIMATIONS.dup
-
add rule if rule
-
end
-
-
2
def transliterate(string, replacement = nil)
-
string.gsub(/[^\x00-\x7f]/u) do |char|
-
approximations[char] || replacement || DEFAULT_REPLACEMENT_CHAR
-
end
-
end
-
-
2
private
-
-
2
def approximations
-
@approximations ||= {}
-
end
-
-
# Add transliteration rules to the approximations hash.
-
2
def add(hash)
-
hash.each do |key, value|
-
approximations[key.to_s] = value.to_s
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module I18n
-
2
class Config
-
# The only configuration value that is not global and scoped to thread is :locale.
-
# It defaults to the default_locale.
-
2
def locale
-
18
@locale ||= default_locale
-
end
-
-
# Sets the current locale pseudo-globally, i.e. in the Thread.current hash.
-
2
def locale=(locale)
-
I18n.enforce_available_locales!(locale)
-
@locale = locale.to_sym rescue nil
-
end
-
-
# Returns the current backend. Defaults to +Backend::Simple+.
-
2
def backend
-
2
@@backend ||= Backend::Simple.new
-
end
-
-
# Sets the current backend. Used to set a custom backend.
-
2
def backend=(backend)
-
@@backend = backend
-
end
-
-
# Returns the current default locale. Defaults to :'en'
-
2
def default_locale
-
16
@@default_locale ||= :en
-
end
-
-
# Sets the current default locale. Used to set a custom default locale.
-
2
def default_locale=(locale)
-
I18n.enforce_available_locales!(locale)
-
@@default_locale = locale.to_sym rescue nil
-
end
-
-
# Returns an array of locales for which translations are available.
-
# Unless you explicitely set these through I18n.available_locales=
-
# the call will be delegated to the backend.
-
2
def available_locales
-
@@available_locales ||= nil
-
@@available_locales || backend.available_locales
-
end
-
-
# Sets the available locales.
-
2
def available_locales=(locales)
-
@@available_locales = Array(locales).map { |locale| locale.to_sym }
-
@@available_locales = nil if @@available_locales.empty?
-
end
-
-
# Returns the current default scope separator. Defaults to '.'
-
2
def default_separator
-
@@default_separator ||= '.'
-
end
-
-
# Sets the current default scope separator.
-
2
def default_separator=(separator)
-
@@default_separator = separator
-
end
-
-
# Return the current exception handler. Defaults to :default_exception_handler.
-
2
def exception_handler
-
@@exception_handler ||= ExceptionHandler.new
-
end
-
-
# Sets the exception handler.
-
2
def exception_handler=(exception_handler)
-
@@exception_handler = exception_handler
-
end
-
-
# Returns the current handler for situations when interpolation argument
-
# is missing. MissingInterpolationArgument will be raised by default.
-
2
def missing_interpolation_argument_handler
-
@@missing_interpolation_argument_handler ||= lambda do |missing_key, provided_hash, string|
-
raise MissingInterpolationArgument.new(missing_key, provided_hash, string)
-
end
-
end
-
-
# Sets the missing interpolation argument handler. It can be any
-
# object that responds to #call. The arguments that will be passed to #call
-
# are the same as for MissingInterpolationArgument initializer. Use +Proc.new+
-
# if you don't care about arity.
-
#
-
# == Example:
-
# You can supress raising an exception and return string instead:
-
#
-
# I18n.config.missing_interpolation_argument_handler = Proc.new do |key|
-
# "#{key} is missing"
-
# end
-
2
def missing_interpolation_argument_handler=(exception_handler)
-
@@missing_interpolation_argument_handler = exception_handler
-
end
-
-
# Allow clients to register paths providing translation data sources. The
-
# backend defines acceptable sources.
-
#
-
# E.g. the provided SimpleBackend accepts a list of paths to translation
-
# files which are either named *.rb and contain plain Ruby Hashes or are
-
# named *.yml and contain YAML data. So for the SimpleBackend clients may
-
# register translation files like this:
-
# I18n.load_path << 'path/to/locale/en.yml'
-
2
def load_path
-
12
@@load_path ||= []
-
end
-
-
# Sets the load path instance. Custom implementations are expected to
-
# behave like a Ruby Array.
-
2
def load_path=(load_path)
-
2
@@load_path = load_path
-
end
-
-
# [Deprecated] this will default to true in the future
-
# Defaults to nil so that it triggers the deprecation warning
-
2
def enforce_available_locales
-
defined?(@@enforce_available_locales) ? @@enforce_available_locales : nil
-
end
-
-
2
def enforce_available_locales=(enforce_available_locales)
-
@@enforce_available_locales = enforce_available_locales
-
end
-
end
-
end
-
2
class Hash
-
def slice(*keep_keys)
-
h = {}
-
keep_keys.each { |key| h[key] = fetch(key) }
-
h
-
2
end unless Hash.method_defined?(:slice)
-
-
def except(*less_keys)
-
slice(*keys - less_keys)
-
2
end unless Hash.method_defined?(:except)
-
-
def deep_symbolize_keys
-
inject({}) { |result, (key, value)|
-
value = value.deep_symbolize_keys if value.is_a?(Hash)
-
result[(key.to_sym rescue key) || key] = value
-
result
-
}
-
2
end unless Hash.method_defined?(:deep_symbolize_keys)
-
-
# deep_merge_hash! by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809
-
2
MERGER = proc do |key, v1, v2|
-
Hash === v1 && Hash === v2 ? v1.merge(v2, &MERGER) : v2
-
end
-
-
def deep_merge!(data)
-
merge!(data, &MERGER)
-
2
end unless Hash.method_defined?(:deep_merge!)
-
end
-
-
2
module Kernel
-
2
def suppress_warnings
-
original_verbosity = $VERBOSE
-
$VERBOSE = nil
-
result = yield
-
$VERBOSE = original_verbosity
-
result
-
end
-
end
-
# This backports the Ruby 1.9 String interpolation syntax to Ruby 1.8.
-
#
-
# This backport has been shipped with I18n for a number of versions. Meanwhile
-
# Rails has started to rely on it and we are going to move it to ActiveSupport.
-
# See https://rails.lighthouseapp.com/projects/8994/tickets/6013-move-19-string-interpolation-syntax-backport-from-i18n-to-activesupport
-
#
-
# Once the above patch has been applied to Rails the following code will be
-
# removed from I18n.
-
-
=begin
-
heavily based on Masao Mutoh's gettext String interpolation extension
-
http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb
-
Copyright (C) 2005-2009 Masao Mutoh
-
You may redistribute it and/or modify it under the same license terms as Ruby.
-
=end
-
-
2
begin
-
2
raise ArgumentError if ("a %{x}" % {:x=>'b'}) != 'a b'
-
rescue ArgumentError
-
# KeyError is raised by String#% when the string contains a named placeholder
-
# that is not contained in the given arguments hash. Ruby 1.9 includes and
-
# raises this exception natively. We define it to mimic Ruby 1.9's behaviour
-
# in Ruby 1.8.x
-
class KeyError < IndexError
-
def initialize(message = nil)
-
super(message || "key not found")
-
end
-
end unless defined?(KeyError)
-
-
# Extension for String class. This feature is included in Ruby 1.9 or later but not occur TypeError.
-
#
-
# String#% method which accept "named argument". The translator can know
-
# the meaning of the msgids using "named argument" instead of %s/%d style.
-
class String
-
# For older ruby versions, such as ruby-1.8.5
-
alias :bytesize :size unless instance_methods.find {|m| m.to_s == 'bytesize'}
-
alias :interpolate_without_ruby_19_syntax :% # :nodoc:
-
-
INTERPOLATION_PATTERN = Regexp.union(
-
/%\{(\w+)\}/, # matches placeholders like "%{foo}"
-
/%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # matches placeholders like "%<foo>.d"
-
)
-
-
INTERPOLATION_PATTERN_WITH_ESCAPE = Regexp.union(
-
/%%/,
-
INTERPOLATION_PATTERN
-
)
-
-
# % uses self (i.e. the String) as a format specification and returns the
-
# result of applying it to the given arguments. In other words it interpolates
-
# the given arguments to the string according to the formats the string
-
# defines.
-
#
-
# There are three ways to use it:
-
#
-
# * Using a single argument or Array of arguments.
-
#
-
# This is the default behaviour of the String class. See Kernel#sprintf for
-
# more details about the format string.
-
#
-
# Example:
-
#
-
# "%d %s" % [1, "message"]
-
# # => "1 message"
-
#
-
# * Using a Hash as an argument and unformatted, named placeholders.
-
#
-
# When you pass a Hash as an argument and specify placeholders with %{foo}
-
# it will interpret the hash values as named arguments.
-
#
-
# Example:
-
#
-
# "%{firstname}, %{lastname}" % {:firstname => "Masao", :lastname => "Mutoh"}
-
# # => "Masao Mutoh"
-
#
-
# * Using a Hash as an argument and formatted, named placeholders.
-
#
-
# When you pass a Hash as an argument and specify placeholders with %<foo>d
-
# it will interpret the hash values as named arguments and format the value
-
# according to the formatting instruction appended to the closing >.
-
#
-
# Example:
-
#
-
# "%<integer>d, %<float>.1f" % { :integer => 10, :float => 43.4 }
-
# # => "10, 43.3"
-
def %(args)
-
if args.kind_of?(Hash)
-
dup.gsub(INTERPOLATION_PATTERN_WITH_ESCAPE) do |match|
-
if match == '%%'
-
'%'
-
else
-
key = ($1 || $2).to_sym
-
raise KeyError unless args.has_key?(key)
-
$3 ? sprintf("%#{$3}", args[key]) : args[key]
-
end
-
end
-
elsif self =~ INTERPOLATION_PATTERN
-
raise ArgumentError.new('one hash required')
-
else
-
result = gsub(/%([{<])/, '%%\1')
-
result.send :'interpolate_without_ruby_19_syntax', args
-
end
-
end
-
end
-
end
-
2
require 'cgi'
-
-
2
module I18n
-
# Handles exceptions raised in the backend. All exceptions except for
-
# MissingTranslationData exceptions are re-thrown. When a MissingTranslationData
-
# was caught the handler returns an error message string containing the key/scope.
-
# Note that the exception handler is not called when the option :throw was given.
-
2
class ExceptionHandler
-
include Module.new {
-
2
def call(exception, locale, key, options)
-
if exception.is_a?(MissingTranslation)
-
#
-
# TODO: this block is to be replaced by `exception.message` when
-
# rescue_format is removed
-
if options[:rescue_format] == :html
-
if @rescue_format_deprecation
-
$stderr.puts "[DEPRECATED] I18n's :recue_format option will be removed from a future release. All exception messages will be plain text. If you need the exception handler to return an html format please set or pass a custom exception handler."
-
@rescue_format_deprecation = true
-
end
-
exception.html_message
-
else
-
exception.message
-
end
-
-
elsif exception.is_a?(Exception)
-
raise exception
-
else
-
throw :exception, exception
-
end
-
end
-
2
}
-
end
-
-
2
class ArgumentError < ::ArgumentError; end
-
-
2
class InvalidLocale < ArgumentError
-
2
attr_reader :locale
-
2
def initialize(locale)
-
@locale = locale
-
super "#{locale.inspect} is not a valid locale"
-
end
-
end
-
-
2
class InvalidLocaleData < ArgumentError
-
2
attr_reader :filename
-
2
def initialize(filename, exception_message)
-
@filename, @exception_message = filename, exception_message
-
super "can not load translations from #{filename}: #{exception_message}"
-
end
-
end
-
-
2
class MissingTranslation
-
2
module Base
-
2
attr_reader :locale, :key, :options
-
-
2
def initialize(locale, key, options = nil)
-
@key, @locale, @options = key, locale, options.dup || {}
-
options.each { |k, v| self.options[k] = v.inspect if v.is_a?(Proc) }
-
end
-
-
2
def html_message
-
key = CGI.escapeHTML titleize(keys.last)
-
path = CGI.escapeHTML keys.join('.')
-
%(<span class="translation_missing" title="translation missing: #{path}">#{key}</span>)
-
end
-
-
2
def keys
-
@keys ||= I18n.normalize_keys(locale, key, options[:scope]).tap do |keys|
-
keys << 'no key' if keys.size < 2
-
end
-
end
-
-
2
def message
-
"translation missing: #{keys.join('.')}"
-
end
-
2
alias :to_s :message
-
-
2
def to_exception
-
MissingTranslationData.new(locale, key, options)
-
end
-
-
2
protected
-
-
# TODO : remove when #html_message is removed
-
2
def titleize(key)
-
key.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize }
-
end
-
end
-
-
2
include Base
-
end
-
-
2
class MissingTranslationData < ArgumentError
-
2
include MissingTranslation::Base
-
end
-
-
2
class InvalidPluralizationData < ArgumentError
-
2
attr_reader :entry, :count
-
2
def initialize(entry, count)
-
@entry, @count = entry, count
-
super "translation data #{entry.inspect} can not be used with :count => #{count}"
-
end
-
end
-
-
2
class MissingInterpolationArgument < ArgumentError
-
2
attr_reader :key, :values, :string
-
2
def initialize(key, values, string)
-
@key, @values, @string = key, values, string
-
super "missing interpolation argument #{key.inspect} in #{string.inspect} (#{values.inspect} given)"
-
end
-
end
-
-
2
class ReservedInterpolationKey < ArgumentError
-
2
attr_reader :key, :string
-
2
def initialize(key, string)
-
@key, @string = key, string
-
super "reserved key #{key.inspect} used in #{string.inspect}"
-
end
-
end
-
-
2
class UnknownFileType < ArgumentError
-
2
attr_reader :type, :filename
-
2
def initialize(type, filename)
-
@type, @filename = type, filename
-
super "can not load translations from #{filename}, the file type #{type} is not known"
-
end
-
end
-
end
-
# heavily based on Masao Mutoh's gettext String interpolation extension
-
# http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb
-
-
2
module I18n
-
2
INTERPOLATION_PATTERN = Regexp.union(
-
/%%/,
-
/%\{(\w+)\}/, # matches placeholders like "%{foo}"
-
/%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # matches placeholders like "%<foo>.d"
-
)
-
-
2
class << self
-
# Return String or raises MissingInterpolationArgument exception.
-
# Missing argument's logic is handled by I18n.config.missing_interpolation_argument_handler.
-
2
def interpolate(string, values)
-
raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ RESERVED_KEYS_PATTERN
-
raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash)
-
interpolate_hash(string, values)
-
end
-
-
2
def interpolate_hash(string, values)
-
string.gsub(INTERPOLATION_PATTERN) do |match|
-
if match == '%%'
-
'%'
-
else
-
key = ($1 || $2).to_sym
-
value = if values.key?(key)
-
values[key]
-
else
-
config.missing_interpolation_argument_handler.call(key, values, string)
-
end
-
value = value.call(values) if value.respond_to?(:call)
-
$3 ? sprintf("%#{$3}", value) : value
-
end
-
end
-
end
-
end
-
end
-
2
module I18n
-
2
VERSION = "0.6.9"
-
end
-
2
require 'journey/router'
-
2
require 'journey/gtg/builder'
-
2
require 'journey/gtg/simulator'
-
2
require 'journey/nfa/builder'
-
2
require 'journey/nfa/simulator'
-
# :stopdoc:
-
2
if RUBY_VERSION < '1.9'
-
class Hash
-
def keep_if
-
each do |k,v|
-
delete(k) unless yield(k,v)
-
end
-
end
-
end
-
end
-
# :startdoc:
-
2
module Journey
-
###
-
# The Formatter class is used for formatting URLs. For example, parameters
-
# passed to +url_for+ in rails will eventually call Formatter#generate
-
2
class Formatter
-
2
attr_reader :routes
-
-
2
def initialize routes
-
2
@routes = routes
-
2
@cache = nil
-
end
-
-
2
def generate key, name, options, recall = {}, parameterize = nil
-
29
constraints = recall.merge options
-
-
29
match_route(name, constraints) do |route|
-
29
data = constraints.dup
-
-
29
keys_to_keep = route.parts.reverse.drop_while { |part|
-
37
!options.key?(part) || (options[part] || recall[part]).nil?
-
} | route.required_parts
-
-
29
(data.keys - keys_to_keep).each do |bad_key|
-
75
data.delete bad_key
-
end
-
-
29
parameterized_parts = data.dup
-
-
29
if parameterize
-
29
parameterized_parts.each do |k,v|
-
9
parameterized_parts[k] = parameterize.call(k, v)
-
end
-
end
-
-
38
parameterized_parts.keep_if { |_,v| v }
-
-
29
next if !name && route.requirements.empty? && route.parts.empty?
-
-
28
next unless verify_required_parts!(route, parameterized_parts)
-
-
27
z = Hash[options.to_a - data.to_a - route.defaults.to_a]
-
-
27
return [route.format(parameterized_parts), z]
-
end
-
-
2
raise Router::RoutingError
-
end
-
-
2
def clear
-
2
@cache = nil
-
end
-
-
2
private
-
2
def named_routes
-
39
routes.named_routes
-
end
-
-
2
def match_route name, options
-
29
if named_routes.key? name
-
10
yield named_routes[name]
-
else
-
#routes = possibles(@cache, options.to_a)
-
19
routes = non_recursive(cache, options.to_a)
-
-
19
hash = routes.group_by { |_, r|
-
38
r.score options
-
}
-
-
19
hash.keys.sort.reverse_each do |score|
-
20
next if score < 0
-
-
38
hash[score].sort_by { |i,_| i }.each do |_,route|
-
19
yield route
-
end
-
end
-
end
-
end
-
-
2
def non_recursive cache, options
-
19
routes = []
-
19
stack = [cache]
-
-
19
while stack.any?
-
59
c = stack.shift
-
59
routes.concat c[:___routes] if c.key? :___routes
-
-
59
options.each do |pair|
-
182
stack << c[pair] if c.key? pair
-
end
-
end
-
-
19
routes
-
end
-
-
2
def possibles cache, options, depth = 0
-
cache.fetch(:___routes) { [] } + options.find_all { |pair|
-
cache.key? pair
-
}.map { |pair|
-
possibles(cache[pair], options, depth + 1)
-
}.flatten(1)
-
end
-
-
2
def verify_required_parts! route, parts
-
28
tests = route.path.requirements
-
28
route.required_parts.all? { |key|
-
9
if tests.key? key
-
/\A#{tests[key]}\Z/ === parts[key]
-
else
-
10
parts.fetch(key) { false }
-
end
-
}
-
end
-
-
2
def build_cache
-
1
kash = {}
-
1
routes.each_with_index do |route, i|
-
82
money = kash
-
82
route.required_defaults.each do |tuple|
-
162
hash = (money[tuple] ||= {})
-
162
money = hash
-
end
-
82
(money[:___routes] ||= []) << [i, route]
-
end
-
1
kash
-
end
-
-
2
def cache
-
19
@cache ||= build_cache
-
end
-
end
-
end
-
2
require 'journey/gtg/transition_table'
-
-
2
module Journey
-
2
module GTG
-
2
class Builder
-
2
DUMMY = Nodes::Dummy.new # :nodoc:
-
-
2
attr_reader :root, :ast, :endpoints
-
-
2
def initialize root
-
164
@root = root
-
164
@ast = Nodes::Cat.new root, DUMMY
-
164
@followpos = nil
-
end
-
-
2
def transition_table
-
dtrans = TransitionTable.new
-
marked = {}
-
state_id = Hash.new { |h,k| h[k] = h.length }
-
-
start = firstpos(root)
-
dstates = [start]
-
until dstates.empty?
-
s = dstates.shift
-
next if marked[s]
-
marked[s] = true # mark s
-
-
s.group_by { |state| symbol(state) }.each do |sym, ps|
-
u = ps.map { |l| followpos(l) }.flatten
-
next if u.empty?
-
-
if u.uniq == [DUMMY]
-
from = state_id[s]
-
to = state_id[Object.new]
-
dtrans[from, to] = sym
-
-
dtrans.add_accepting to
-
ps.each { |state| dtrans.add_memo to, state.memo }
-
else
-
dtrans[state_id[s], state_id[u]] = sym
-
-
if u.include? DUMMY
-
to = state_id[u]
-
-
accepting = ps.find_all { |l| followpos(l).include? DUMMY }
-
-
accepting.each { |accepting_state|
-
dtrans.add_memo to, accepting_state.memo
-
}
-
-
dtrans.add_accepting state_id[u]
-
end
-
end
-
-
dstates << u
-
end
-
end
-
-
dtrans
-
end
-
-
2
def nullable? node
-
3226
case node
-
when Nodes::Group
-
160
true
-
when Nodes::Star
-
true
-
when Nodes::Or
-
node.children.any? { |c| nullable?(c) }
-
when Nodes::Cat
-
nullable?(node.left) && nullable?(node.right)
-
when Nodes::Terminal
-
3066
!node.left
-
when Nodes::Unary
-
nullable? node.left
-
else
-
raise ArgumentError, 'unknown nullable: %s' % node.class.name
-
end
-
end
-
-
2
def firstpos node
-
1396
case node
-
when Nodes::Star
-
firstpos(node.left)
-
when Nodes::Cat
-
160
if nullable? node.left
-
firstpos(node.left) | firstpos(node.right)
-
else
-
160
firstpos(node.left)
-
end
-
when Nodes::Or
-
node.children.map { |c| firstpos(c) }.flatten.uniq
-
when Nodes::Unary
-
160
firstpos(node.left)
-
when Nodes::Terminal
-
1076
nullable?(node) ? [] : [node]
-
else
-
raise ArgumentError, 'unknown firstpos: %s' % node.class.name
-
end
-
end
-
-
2
def lastpos node
-
2150
case node
-
when Nodes::Star
-
firstpos(node.left)
-
when Nodes::Or
-
node.children.map { |c| lastpos(c) }.flatten.uniq
-
when Nodes::Cat
-
914
if nullable? node.right
-
160
lastpos(node.left) | lastpos(node.right)
-
else
-
754
lastpos(node.right)
-
end
-
when Nodes::Terminal
-
1076
nullable?(node) ? [] : [node]
-
when Nodes::Unary
-
160
lastpos(node.left)
-
else
-
raise ArgumentError, 'unknown lastpos: %s' % node.class.name
-
end
-
end
-
-
2
def followpos node
-
458
followpos_table[node]
-
end
-
-
2
private
-
2
def followpos_table
-
458
@followpos ||= build_followpos
-
end
-
-
2
def build_followpos
-
1078
table = Hash.new { |h,k| h[k] = [] }
-
162
@ast.each do |n|
-
2154
case n
-
when Nodes::Cat
-
916
lastpos(n.left).each do |i|
-
1076
table[i] += firstpos(n.right)
-
end
-
when Nodes::Star
-
lastpos(n).each do |i|
-
table[i] += firstpos(n)
-
end
-
end
-
end
-
162
table
-
end
-
-
2
def symbol edge
-
case edge
-
when Journey::Nodes::Symbol
-
edge.regexp
-
else
-
edge.left
-
end
-
end
-
end
-
end
-
end
-
2
require 'strscan'
-
-
2
module Journey
-
2
module GTG
-
2
class MatchData
-
2
attr_reader :memos
-
-
2
def initialize memos
-
@memos = memos
-
end
-
end
-
-
2
class Simulator
-
2
attr_reader :tt
-
-
2
def initialize transition_table
-
@tt = transition_table
-
end
-
-
2
def simulate string
-
input = StringScanner.new string
-
state = [0]
-
while sym = input.scan(/[\/\.\?]|[^\/\.\?]+/)
-
state = tt.move(state, sym)
-
end
-
-
acceptance_states = state.find_all { |s|
-
tt.accepting? s
-
}
-
-
return if acceptance_states.empty?
-
-
memos = acceptance_states.map { |x| tt.memo x }.flatten.compact
-
-
MatchData.new memos
-
end
-
-
2
alias :=~ :simulate
-
2
alias :match :simulate
-
end
-
end
-
end
-
-
2
require 'journey/nfa/dot'
-
-
2
module Journey
-
2
module GTG
-
2
class TransitionTable
-
2
include Journey::NFA::Dot
-
-
2
attr_reader :memos
-
-
2
def initialize
-
@regexp_states = Hash.new { |h,k| h[k] = {} }
-
@string_states = Hash.new { |h,k| h[k] = {} }
-
@accepting = {}
-
@memos = Hash.new { |h,k| h[k] = [] }
-
end
-
-
2
def add_accepting state
-
@accepting[state] = true
-
end
-
-
2
def accepting_states
-
@accepting.keys
-
end
-
-
2
def accepting? state
-
@accepting[state]
-
end
-
-
2
def add_memo idx, memo
-
@memos[idx] << memo
-
end
-
-
2
def memo idx
-
@memos[idx]
-
end
-
-
2
def eclosure t
-
Array(t)
-
end
-
-
2
def move t, a
-
move_string(t, a).concat move_regexp(t, a)
-
end
-
-
2
def to_json
-
require 'json'
-
-
simple_regexp = Hash.new { |h,k| h[k] = {} }
-
-
@regexp_states.each do |from, hash|
-
hash.each do |re, to|
-
simple_regexp[from][re.source] = to
-
end
-
end
-
-
JSON.dump({
-
:regexp_states => simple_regexp,
-
:string_states => @string_states,
-
:accepting => @accepting
-
})
-
end
-
-
2
def to_svg
-
svg = IO.popen("dot -Tsvg", 'w+') { |f|
-
f.write to_dot
-
f.close_write
-
f.readlines
-
}
-
3.times { svg.shift }
-
svg.join.sub(/width="[^"]*"/, '').sub(/height="[^"]*"/, '')
-
end
-
-
2
def visualizer paths, title = 'FSM'
-
viz_dir = File.join File.dirname(__FILE__), '..', 'visualizer'
-
fsm_js = File.read File.join(viz_dir, 'fsm.js')
-
fsm_css = File.read File.join(viz_dir, 'fsm.css')
-
erb = File.read File.join(viz_dir, 'index.html.erb')
-
states = "function tt() { return #{to_json}; }"
-
-
fun_routes = paths.shuffle.first(3).map do |ast|
-
ast.map { |n|
-
case n
-
when Nodes::Symbol
-
case n.left
-
when ':id' then rand(100).to_s
-
when ':format' then %w{ xml json }.shuffle.first
-
else
-
'omg'
-
end
-
when Nodes::Terminal then n.symbol
-
else
-
nil
-
end
-
}.compact.join
-
end
-
-
stylesheets = [fsm_css]
-
svg = to_svg
-
javascripts = [states, fsm_js]
-
-
# Annoying hack for 1.9 warnings
-
fun_routes = fun_routes
-
stylesheets = stylesheets
-
svg = svg
-
javascripts = javascripts
-
-
require 'erb'
-
template = ERB.new erb
-
template.result(binding)
-
end
-
-
2
def []= from, to, sym
-
case sym
-
when String
-
@string_states[from][sym] = to
-
when Regexp
-
@regexp_states[from][sym] = to
-
else
-
raise ArgumentError, 'unknown symbol: %s' % sym.class
-
end
-
end
-
-
2
def states
-
ss = @string_states.keys + @string_states.values.map(&:values).flatten
-
rs = @regexp_states.keys + @regexp_states.values.map(&:values).flatten
-
(ss + rs).uniq
-
end
-
-
2
def transitions
-
@string_states.map { |from, hash|
-
hash.map { |s, to| [from, s, to] }
-
}.flatten(1) + @regexp_states.map { |from, hash|
-
hash.map { |s, to| [from, s, to] }
-
}.flatten(1)
-
end
-
-
2
private
-
2
def move_regexp t, a
-
return [] if t.empty?
-
-
t.map { |s|
-
@regexp_states[s].map { |re,v| re === a ? v : nil }
-
}.flatten.compact.uniq
-
end
-
-
2
def move_string t, a
-
return [] if t.empty?
-
-
t.map { |s| @string_states[s][a] }.compact
-
end
-
end
-
end
-
end
-
2
require 'journey/nfa/transition_table'
-
2
require 'journey/gtg/transition_table'
-
-
2
module Journey
-
2
module NFA
-
2
class Visitor < Visitors::Visitor
-
2
def initialize tt
-
@tt = tt
-
@i = -1
-
end
-
-
2
def visit_CAT node
-
left = visit node.left
-
right = visit node.right
-
-
@tt.merge left.last, right.first
-
-
[left.first, right.last]
-
end
-
-
2
def visit_GROUP node
-
from = @i += 1
-
left = visit node.left
-
to = @i += 1
-
-
@tt.accepting = to
-
-
@tt[from, left.first] = nil
-
@tt[left.last, to] = nil
-
@tt[from, to] = nil
-
-
[from, to]
-
end
-
-
2
def visit_OR node
-
from = @i += 1
-
children = node.children.map { |c| visit c }
-
to = @i += 1
-
-
children.each do |child|
-
@tt[from, child.first] = nil
-
@tt[child.last, to] = nil
-
end
-
-
@tt.accepting = to
-
-
[from, to]
-
end
-
-
2
def terminal node
-
from_i = @i += 1 # new state
-
to_i = @i += 1 # new state
-
-
@tt[from_i, to_i] = node
-
@tt.accepting = to_i
-
@tt.add_memo to_i, node.memo
-
-
[from_i, to_i]
-
end
-
end
-
-
2
class Builder
-
2
def initialize ast
-
@ast = ast
-
end
-
-
2
def transition_table
-
tt = TransitionTable.new
-
Visitor.new(tt).accept @ast
-
tt
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
2
module Journey
-
2
module NFA
-
2
module Dot
-
2
def to_dot
-
edges = transitions.map { |from, sym, to|
-
" #{from} -> #{to} [label=\"#{sym || 'ε'}\"];"
-
}
-
-
#memo_nodes = memos.values.flatten.map { |n|
-
# label = n
-
# if Journey::Route === n
-
# label = "#{n.verb.source} #{n.path.spec}"
-
# end
-
# " #{n.object_id} [label=\"#{label}\", shape=box];"
-
#}
-
#memo_edges = memos.map { |k, memos|
-
# (memos || []).map { |v| " #{k} -> #{v.object_id};" }
-
#}.flatten.uniq
-
-
<<-eodot
-
digraph nfa {
-
rankdir=LR;
-
node [shape = doublecircle];
-
#{accepting_states.join ' '};
-
node [shape = circle];
-
#{edges.join "\n"}
-
}
-
eodot
-
end
-
end
-
end
-
end
-
2
require 'strscan'
-
-
2
module Journey
-
2
module NFA
-
2
class MatchData
-
2
attr_reader :memos
-
-
2
def initialize memos
-
@memos = memos
-
end
-
end
-
-
2
class Simulator
-
2
attr_reader :tt
-
-
2
def initialize transition_table
-
@tt = transition_table
-
end
-
-
2
def simulate string
-
input = StringScanner.new string
-
state = tt.eclosure 0
-
until input.eos?
-
sym = input.scan(/[\/\.\?]|[^\/\.\?]+/)
-
-
# FIXME: tt.eclosure is not needed for the GTG
-
state = tt.eclosure tt.move(state, sym)
-
end
-
-
acceptance_states = state.find_all { |s|
-
tt.accepting? tt.eclosure(s).sort.last
-
}
-
-
return if acceptance_states.empty?
-
-
memos = acceptance_states.map { |x| tt.memo x }.flatten.compact
-
-
MatchData.new memos
-
end
-
-
2
alias :=~ :simulate
-
2
alias :match :simulate
-
end
-
end
-
end
-
2
require 'journey/nfa/dot'
-
-
2
module Journey
-
2
module NFA
-
2
class TransitionTable
-
2
include Journey::NFA::Dot
-
-
2
attr_accessor :accepting
-
2
attr_reader :memos
-
-
2
def initialize
-
@table = Hash.new { |h,f| h[f] = {} }
-
@memos = {}
-
@accepting = nil
-
@inverted = nil
-
end
-
-
2
def accepting? state
-
accepting == state
-
end
-
-
2
def accepting_states
-
[accepting]
-
end
-
-
2
def add_memo idx, memo
-
@memos[idx] = memo
-
end
-
-
2
def memo idx
-
@memos[idx]
-
end
-
-
2
def []= i, f, s
-
@table[f][i] = s
-
end
-
-
2
def merge left, right
-
@memos[right] = @memos.delete left
-
@table[right] = @table.delete(left)
-
end
-
-
2
def states
-
(@table.keys + @table.values.map(&:keys).flatten).uniq
-
end
-
-
###
-
# Returns a generalized transition graph with reduced states. The states
-
# are reduced like a DFA, but the table must be simulated like an NFA.
-
#
-
# Edges of the GTG are regular expressions
-
2
def generalized_table
-
gt = GTG::TransitionTable.new
-
marked = {}
-
state_id = Hash.new { |h,k| h[k] = h.length }
-
alphabet = self.alphabet
-
-
stack = [eclosure(0)]
-
-
until stack.empty?
-
state = stack.pop
-
next if marked[state] || state.empty?
-
-
marked[state] = true
-
-
alphabet.each do |alpha|
-
next_state = eclosure(following_states(state, alpha))
-
next if next_state.empty?
-
-
gt[state_id[state], state_id[next_state]] = alpha
-
stack << next_state
-
end
-
end
-
-
final_groups = state_id.keys.find_all { |s|
-
s.sort.last == accepting
-
}
-
-
final_groups.each do |states|
-
id = state_id[states]
-
-
gt.add_accepting id
-
save = states.find { |s|
-
@memos.key?(s) && eclosure(s).sort.last == accepting
-
}
-
-
gt.add_memo id, memo(save)
-
end
-
-
gt
-
end
-
-
###
-
# Returns set of NFA states to which there is a transition on ast symbol
-
# +a+ from some state +s+ in +t+.
-
2
def following_states t, a
-
Array(t).map { |s| inverted[s][a] }.flatten.uniq
-
end
-
-
###
-
# Returns set of NFA states to which there is a transition on ast symbol
-
# +a+ from some state +s+ in +t+.
-
2
def move t, a
-
Array(t).map { |s|
-
inverted[s].keys.compact.find_all { |sym|
-
sym === a
-
}.map { |sym| inverted[s][sym] }
-
}.flatten.uniq
-
end
-
-
2
def alphabet
-
inverted.values.map(&:keys).flatten.compact.uniq.sort_by { |x| x.to_s }
-
end
-
-
###
-
# Returns a set of NFA states reachable from some NFA state +s+ in set
-
# +t+ on nil-transitions alone.
-
2
def eclosure t
-
stack = Array(t)
-
seen = {}
-
children = []
-
-
until stack.empty?
-
s = stack.pop
-
next if seen[s]
-
-
seen[s] = true
-
children << s
-
-
stack.concat inverted[s][nil]
-
end
-
-
children.uniq
-
end
-
-
2
def transitions
-
@table.map { |to, hash|
-
hash.map { |from, sym| [from, sym, to] }
-
}.flatten(1)
-
end
-
-
2
private
-
2
def inverted
-
return @inverted if @inverted
-
-
@inverted = Hash.new { |h,from|
-
h[from] = Hash.new { |j,s| j[s] = [] }
-
}
-
-
@table.each { |to, hash|
-
hash.each { |from, sym|
-
if sym
-
sym = Nodes::Symbol === sym ? sym.regexp : sym.left
-
end
-
-
@inverted[from][sym] << to
-
}
-
}
-
-
@inverted
-
end
-
end
-
end
-
end
-
2
require 'journey/visitors'
-
-
2
module Journey
-
2
module Nodes
-
2
class Node # :nodoc:
-
2
include Enumerable
-
-
2
attr_accessor :left, :memo
-
-
2
def initialize left
-
1998
@left = left
-
1998
@memo = nil
-
end
-
-
2
def each(&block)
-
677
Visitors::Each.new(block).accept(self)
-
end
-
-
2
def to_s
-
Visitors::String.new.accept(self)
-
end
-
-
2
def to_dot
-
Visitors::Dot.new.accept(self)
-
end
-
-
2
def to_sym
-
8
name.to_sym
-
end
-
-
2
def name
-
259
left.tr ':', ''
-
end
-
-
2
def type
-
raise NotImplementedError
-
end
-
-
220
def symbol?; false; end
-
1696
def literal?; false; end
-
end
-
-
2
class Terminal < Node
-
2
alias :symbol :left
-
end
-
-
2
class Literal < Terminal
-
220
def literal?; true; end
-
1088
def type; :LITERAL; end
-
end
-
-
2
class Dummy < Literal
-
2
def initialize x = Object.new
-
2
super
-
end
-
-
162
def literal?; false; end
-
end
-
-
2
%w{ Symbol Slash Dot }.each do |t|
-
class_eval %{
-
class #{t} < Terminal
-
def type; :#{t.upcase}; end
-
end
-
6
}
-
end
-
-
2
class Symbol < Terminal
-
2
attr_accessor :regexp
-
2
alias :symbol :regexp
-
-
2
DEFAULT_EXP = /[^\.\/\?]+/
-
2
def initialize left
-
240
super
-
240
@regexp = DEFAULT_EXP
-
end
-
-
2
def default_regexp?
-
regexp == DEFAULT_EXP
-
end
-
-
2
def symbol?; true; end
-
end
-
-
2
class Unary < Node
-
2
def children; [value] end
-
end
-
-
2
class Group < Unary
-
691
def type; :GROUP; end
-
end
-
-
2
class Star < Unary
-
2
def type; :STAR; end
-
end
-
-
2
class Binary < Node
-
2
attr_accessor :right
-
-
2
def initialize left, right
-
918
super(left)
-
918
@right = right
-
end
-
-
2
def children; [left, right] end
-
end
-
-
2
class Cat < Binary
-
3331
def type; :CAT; end
-
end
-
-
2
class Or < Node
-
2
attr_reader :children
-
-
2
def initialize children
-
@children = children
-
end
-
-
2
def type; :OR; end
-
end
-
end
-
end
-
#
-
# DO NOT MODIFY!!!!
-
# This file is automatically generated by Racc 1.4.6
-
# from Racc grammer file "".
-
#
-
-
2
require 'racc/parser.rb'
-
-
-
2
require 'journey/parser_extras'
-
2
module Journey
-
2
class Parser < Racc::Parser
-
##### State transition tables begin ###
-
-
2
racc_action_table = [
-
17, 22, 13, 15, 14, 7, 15, 16, 8, 19,
-
13, 15, 14, 7, 24, 16, 8, 19, 13, 15,
-
14, 7, nil, 16, 8, 13, 15, 14, 7, nil,
-
16, 8, 13, 15, 14, 7, nil, 16, 8 ]
-
-
2
racc_action_check = [
-
1, 17, 1, 1, 1, 1, 8, 1, 1, 1,
-
20, 20, 20, 20, 20, 20, 20, 20, 7, 7,
-
7, 7, nil, 7, 7, 19, 19, 19, 19, nil,
-
19, 19, 0, 0, 0, 0, nil, 0, 0 ]
-
-
2
racc_action_pointer = [
-
30, 0, nil, nil, nil, nil, nil, 16, 3, nil,
-
nil, nil, nil, nil, nil, nil, nil, 1, nil, 23,
-
8, nil, nil, nil, nil ]
-
-
2
racc_action_default = [
-
-18, -18, -2, -3, -4, -5, -6, -18, -18, -10,
-
-11, -12, -13, -14, -15, -16, -17, -18, -1, -18,
-
-18, -9, 25, -8, -7 ]
-
-
2
racc_goto_table = [
-
18, 1, 21, nil, nil, nil, nil, nil, 20, nil,
-
nil, nil, nil, nil, nil, nil, nil, nil, 23, 18 ]
-
-
2
racc_goto_check = [
-
2, 1, 7, nil, nil, nil, nil, nil, 1, nil,
-
nil, nil, nil, nil, nil, nil, nil, nil, 2, 2 ]
-
-
2
racc_goto_pointer = [
-
nil, 1, -1, nil, nil, nil, nil, -6, nil, nil,
-
nil ]
-
-
2
racc_goto_default = [
-
nil, nil, 2, 3, 4, 5, 6, 10, 9, 11,
-
12 ]
-
-
2
racc_reduce_table = [
-
0, 0, :racc_error,
-
2, 11, :_reduce_1,
-
1, 11, :_reduce_2,
-
1, 11, :_reduce_none,
-
1, 12, :_reduce_none,
-
1, 12, :_reduce_none,
-
1, 12, :_reduce_none,
-
3, 15, :_reduce_7,
-
3, 13, :_reduce_8,
-
2, 16, :_reduce_9,
-
1, 14, :_reduce_none,
-
1, 14, :_reduce_none,
-
1, 14, :_reduce_none,
-
1, 14, :_reduce_none,
-
1, 19, :_reduce_14,
-
1, 18, :_reduce_15,
-
1, 17, :_reduce_16,
-
1, 20, :_reduce_17 ]
-
-
2
racc_reduce_n = 18
-
-
2
racc_shift_n = 25
-
-
2
racc_token_table = {
-
false => 0,
-
:error => 1,
-
:SLASH => 2,
-
:LITERAL => 3,
-
:SYMBOL => 4,
-
:LPAREN => 5,
-
:RPAREN => 6,
-
:DOT => 7,
-
:STAR => 8,
-
:OR => 9 }
-
-
2
racc_nt_base = 10
-
-
2
racc_use_result_var = true
-
-
2
Racc_arg = [
-
racc_action_table,
-
racc_action_check,
-
racc_action_default,
-
racc_action_pointer,
-
racc_goto_table,
-
racc_goto_check,
-
racc_goto_default,
-
racc_goto_pointer,
-
racc_nt_base,
-
racc_reduce_table,
-
racc_token_table,
-
racc_shift_n,
-
racc_reduce_n,
-
racc_use_result_var ]
-
-
2
Racc_token_to_s_table = [
-
"$end",
-
"error",
-
"SLASH",
-
"LITERAL",
-
"SYMBOL",
-
"LPAREN",
-
"RPAREN",
-
"DOT",
-
"STAR",
-
"OR",
-
"$start",
-
"expressions",
-
"expression",
-
"or",
-
"terminal",
-
"group",
-
"star",
-
"literal",
-
"symbol",
-
"slash",
-
"dot" ]
-
-
2
Racc_debug_parser = false
-
-
##### State transition tables end #####
-
-
# reduce 0 omitted
-
-
2
def _reduce_1(val, _values, result)
-
754
result = Cat.new(val.first, val.last)
-
754
result
-
end
-
-
2
def _reduce_2(val, _values, result)
-
324
result = val.first
-
324
result
-
end
-
-
# reduce 3 omitted
-
-
# reduce 4 omitted
-
-
# reduce 5 omitted
-
-
# reduce 6 omitted
-
-
2
def _reduce_7(val, _values, result)
-
160
result = Group.new(val[1])
-
160
result
-
end
-
-
2
def _reduce_8(val, _values, result)
-
result = Or.new([val.first, val.last])
-
result
-
end
-
-
2
def _reduce_9(val, _values, result)
-
result = Star.new(Symbol.new(val.last.left))
-
result
-
end
-
-
# reduce 10 omitted
-
-
# reduce 11 omitted
-
-
# reduce 12 omitted
-
-
# reduce 13 omitted
-
-
2
def _reduce_14(val, _values, result)
-
300
result = Slash.new('/')
-
300
result
-
end
-
-
2
def _reduce_15(val, _values, result)
-
240
result = Symbol.new(val.first)
-
240
result
-
end
-
-
2
def _reduce_16(val, _values, result)
-
218
result = Literal.new(val.first)
-
218
result
-
end
-
-
2
def _reduce_17(val, _values, result)
-
160
result = Dot.new(val.first)
-
160
result
-
end
-
-
2
def _reduce_none(val, _values, result)
-
val[0]
-
end
-
-
end # class Parser
-
end # module Journey
-
2
require 'journey/scanner'
-
2
require 'journey/nodes/node'
-
-
2
module Journey
-
2
class Parser < Racc::Parser
-
2
include Journey::Nodes
-
-
2
def initialize
-
164
@scanner = Scanner.new
-
end
-
-
2
def parse string
-
164
@scanner.scan_setup string
-
164
do_parse
-
end
-
-
2
def next_token
-
1402
@scanner.next_token
-
end
-
end
-
end
-
2
module Journey
-
2
module Path
-
2
class Pattern
-
2
attr_reader :spec, :requirements, :anchored
-
-
2
def initialize strexp
-
164
parser = Journey::Parser.new
-
-
164
@anchored = true
-
-
164
case strexp
-
when String
-
@spec = parser.parse strexp
-
@requirements = {}
-
@separators = "/.?"
-
when Router::Strexp
-
164
@spec = parser.parse strexp.path
-
164
@requirements = strexp.requirements
-
164
@separators = strexp.separators.join
-
164
@anchored = strexp.anchor
-
else
-
raise "wtf bro: #{strexp}"
-
end
-
-
164
@names = nil
-
164
@optional_names = nil
-
164
@required_names = nil
-
164
@re = nil
-
164
@offsets = nil
-
end
-
-
2
def ast
-
@spec.grep(Nodes::Symbol).each do |node|
-
re = @requirements[node.to_sym]
-
node.regexp = re if re
-
end
-
-
@spec.grep(Nodes::Star).each do |node|
-
node = node.left
-
node.regexp = @requirements[node.to_sym] || /(.+)/
-
end
-
-
@spec
-
end
-
-
2
def names
-
588
@names ||= spec.grep(Nodes::Symbol).map { |n| n.name }
-
end
-
-
2
def required_names
-
49
@required_names ||= names - optional_names
-
end
-
-
2
def optional_names
-
@optional_names ||= spec.grep(Nodes::Group).map { |group|
-
11
group.grep(Nodes::Symbol)
-
23
}.flatten.map { |n| n.name }.uniq
-
end
-
-
2
class RegexpOffsets < Journey::Visitors::Visitor # :nodoc:
-
2
attr_reader :offsets
-
-
2
def initialize matchers
-
@matchers = matchers
-
@capture_count = [0]
-
end
-
-
2
def visit node
-
super
-
@capture_count
-
end
-
-
2
def visit_SYMBOL node
-
node = node.to_sym
-
-
if @matchers.key? node
-
re = /#{@matchers[node]}|/
-
@capture_count.push((re.match('').length - 1) + (@capture_count.last || 0))
-
else
-
@capture_count << (@capture_count.last || 0)
-
end
-
end
-
end
-
-
2
class AnchoredRegexp < Journey::Visitors::Visitor # :nodoc:
-
2
def initialize separator, matchers
-
@separator = separator
-
@matchers = matchers
-
@separator_re = "([^#{separator}]+)"
-
super()
-
end
-
-
2
def accept node
-
%r{\A#{visit node}\Z}
-
end
-
-
2
def visit_CAT node
-
[visit(node.left), visit(node.right)].join
-
end
-
-
2
def visit_SYMBOL node
-
node = node.to_sym
-
-
return @separator_re unless @matchers.key? node
-
-
re = @matchers[node]
-
"(#{re})"
-
end
-
-
2
def visit_GROUP node
-
"(?:#{visit node.left})?"
-
end
-
-
2
def visit_LITERAL node
-
Regexp.escape node.left
-
end
-
2
alias :visit_DOT :visit_LITERAL
-
-
2
def visit_SLASH node
-
node.left
-
end
-
-
2
def visit_STAR node
-
re = @matchers[node.left.to_sym] || '.+'
-
"(#{re})"
-
end
-
end
-
-
2
class UnanchoredRegexp < AnchoredRegexp # :nodoc:
-
2
def accept node
-
%r{\A#{visit node}}
-
end
-
end
-
-
2
class MatchData
-
2
attr_reader :names
-
-
2
def initialize names, offsets, match
-
@names = names
-
@offsets = offsets
-
@match = match
-
end
-
-
2
def captures
-
(length - 1).times.map { |i| self[i + 1] }
-
end
-
-
2
def [] x
-
idx = @offsets[x - 1] + x
-
@match[idx]
-
end
-
-
2
def length
-
@offsets.length
-
end
-
-
2
def post_match
-
@match.post_match
-
end
-
-
2
def to_s
-
@match.to_s
-
end
-
end
-
-
2
def match other
-
return unless match = to_regexp.match(other)
-
MatchData.new names, offsets, match
-
end
-
2
alias :=~ :match
-
-
2
def source
-
to_regexp.source
-
end
-
-
2
def to_regexp
-
@re ||= regexp_visitor.new(@separators, @requirements).accept spec
-
end
-
-
2
private
-
2
def regexp_visitor
-
@anchored ? AnchoredRegexp : UnanchoredRegexp
-
end
-
-
2
def offsets
-
return @offsets if @offsets
-
-
viz = RegexpOffsets.new @requirements
-
@offsets = viz.accept spec
-
end
-
end
-
end
-
end
-
2
module Journey
-
2
class Route
-
2
attr_reader :app, :path, :verb, :defaults, :ip, :name
-
-
2
attr_reader :constraints
-
2
alias :conditions :constraints
-
-
2
attr_accessor :precedence
-
-
##
-
# +path+ is a path constraint.
-
# +constraints+ is a hash of constraints to be applied to this route.
-
2
def initialize name, app, path, constraints, defaults = {}
-
164
constraints = constraints.dup
-
164
@name = name
-
164
@app = app
-
164
@path = path
-
164
@verb = constraints[:request_method] || //
-
164
@ip = constraints.delete(:ip) || //
-
-
164
@constraints = constraints
-
316
@constraints.keep_if { |_,v| Regexp === v || String === v }
-
164
@defaults = defaults
-
164
@required_defaults = nil
-
164
@required_parts = nil
-
164
@parts = nil
-
164
@decorated_ast = nil
-
164
@precedence = 0
-
end
-
-
2
def ast
-
return @decorated_ast if @decorated_ast
-
-
@decorated_ast = path.ast
-
@decorated_ast.grep(Nodes::Terminal).each { |n| n.memo = self }
-
@decorated_ast
-
end
-
-
2
def requirements # :nodoc:
-
# needed for rails `rake routes`
-
19
path.requirements.merge(@defaults).delete_if { |_,v|
-
36
/.+?/ == v
-
}
-
end
-
-
2
def segments
-
135
@path.names
-
end
-
-
2
def required_keys
-
path.required_names.map { |x| x.to_sym } + required_defaults.keys
-
end
-
-
2
def score constraints
-
38
required_keys = path.required_names
-
156
supplied_keys = constraints.map { |k,v| v && k.to_s }.compact
-
-
38
return -1 unless (required_keys - supplied_keys).empty?
-
-
37
score = (supplied_keys & path.names).length
-
37
score + (required_defaults.length * 2)
-
end
-
-
2
def parts
-
519
@parts ||= segments.map { |n| n.to_sym }
-
end
-
2
alias :segment_keys :parts
-
-
2
def format path_options
-
27
(defaults.keys - required_parts).each do |key|
-
54
path_options.delete key if defaults[key].to_s == path_options[key].to_s
-
end
-
-
27
formatter = Visitors::Formatter.new(path_options)
-
-
27
formatted_path = formatter.accept(path.spec)
-
27
formatted_path.gsub(/\/\x00/, '')
-
end
-
-
2
def optional_parts
-
path.optional_names.map { |n| n.to_sym }
-
end
-
-
2
def required_parts
-
88
@required_parts ||= path.required_names.map { |n| n.to_sym }
-
end
-
-
2
def required_defaults
-
@required_defaults ||= begin
-
82
matches = parts
-
244
@defaults.dup.delete_if { |k,_| matches.include? k }
-
119
end
-
end
-
end
-
end
-
2
require 'journey/core-ext/hash'
-
2
require 'journey/router/utils'
-
2
require 'journey/router/strexp'
-
2
require 'journey/routes'
-
2
require 'journey/formatter'
-
-
2
before = $-w
-
2
$-w = false
-
2
require 'journey/parser'
-
2
$-w = before
-
-
2
require 'journey/route'
-
2
require 'journey/path/pattern'
-
-
2
module Journey
-
2
class Router
-
2
class RoutingError < ::StandardError
-
end
-
-
2
VERSION = '1.0.4'
-
-
2
class NullReq # :nodoc:
-
2
attr_reader :env
-
2
def initialize env
-
@env = env
-
end
-
-
2
def request_method
-
env['REQUEST_METHOD']
-
end
-
-
2
def path_info
-
env['PATH_INFO']
-
end
-
-
2
def ip
-
env['REMOTE_ADDR']
-
end
-
-
2
def [](k); env[k]; end
-
end
-
-
2
attr_reader :request_class, :formatter
-
2
attr_accessor :routes
-
-
2
def initialize routes, options
-
2
@options = options
-
2
@params_key = options[:parameters_key]
-
2
@request_class = options[:request_class] || NullReq
-
2
@routes = routes
-
end
-
-
2
def call env
-
env['PATH_INFO'] = Utils.normalize_path env['PATH_INFO']
-
-
find_routes(env).each do |match, parameters, route|
-
script_name, path_info, set_params = env.values_at('SCRIPT_NAME',
-
'PATH_INFO',
-
@params_key)
-
-
unless route.path.anchored
-
env['SCRIPT_NAME'] = (script_name.to_s + match.to_s).chomp('/')
-
env['PATH_INFO'] = Utils.normalize_path(match.post_match)
-
end
-
-
env[@params_key] = (set_params || {}).merge parameters
-
-
status, headers, body = route.app.call(env)
-
-
if 'pass' == headers['X-Cascade']
-
env['SCRIPT_NAME'] = script_name
-
env['PATH_INFO'] = path_info
-
env[@params_key] = set_params
-
next
-
end
-
-
return [status, headers, body]
-
end
-
-
return [404, {'X-Cascade' => 'pass'}, ['Not Found']]
-
end
-
-
2
def recognize req
-
find_routes(req.env).each do |match, parameters, route|
-
unless route.path.anchored
-
req.env['SCRIPT_NAME'] = match.to_s
-
req.env['PATH_INFO'] = match.post_match.sub(/^([^\/])/, '/\1')
-
end
-
-
yield(route, nil, parameters)
-
end
-
end
-
-
2
def visualizer
-
tt = GTG::Builder.new(ast).transition_table
-
groups = partitioned_routes.first.map(&:ast).group_by { |a| a.to_s }
-
asts = groups.values.map { |v| v.first }
-
tt.visualizer asts
-
end
-
-
2
private
-
-
2
def partitioned_routes
-
routes.partitioned_routes
-
end
-
-
2
def ast
-
routes.ast
-
end
-
-
2
def simulator
-
routes.simulator
-
end
-
-
2
def custom_routes
-
partitioned_routes.last
-
end
-
-
2
def filter_routes path
-
return [] unless ast
-
data = simulator.match(path)
-
data ? data.memos : []
-
end
-
-
2
def find_routes env
-
req = request_class.new env
-
-
routes = filter_routes(req.path_info) + custom_routes.find_all { |r|
-
r.path.match(req.path_info)
-
}
-
-
routes.sort_by(&:precedence).find_all { |r|
-
r.constraints.all? { |k,v| v === req.send(k) } &&
-
r.verb === req.request_method
-
}.reject { |r| req.ip && !(r.ip === req.ip) }.map { |r|
-
match_data = r.path.match(req.path_info)
-
match_names = match_data.names.map { |n| n.to_sym }
-
match_values = match_data.captures.map { |v| v && Utils.unescape_uri(v) }
-
info = Hash[match_names.zip(match_values).find_all { |_,y| y }]
-
-
[match_data, r.defaults.merge(info), r]
-
}
-
end
-
end
-
end
-
2
module Journey
-
2
class Router
-
2
class Strexp
-
2
class << self
-
2
alias :compile :new
-
end
-
-
2
attr_reader :path, :requirements, :separators, :anchor
-
-
2
def initialize path, requirements, separators, anchor = true
-
164
@path = path
-
164
@requirements = requirements
-
164
@separators = separators
-
164
@anchor = anchor
-
end
-
-
2
def names
-
@path.scan(/:\w+/).map { |s| s.tr(':', '') }
-
end
-
end
-
end
-
end
-
2
require 'uri'
-
-
2
module Journey
-
2
class Router
-
2
class Utils
-
# Normalizes URI path.
-
#
-
# Strips off trailing slash and ensures there is a leading slash.
-
#
-
# normalize_path("/foo") # => "/foo"
-
# normalize_path("/foo/") # => "/foo"
-
# normalize_path("foo") # => "/foo"
-
# normalize_path("") # => "/"
-
2
def self.normalize_path(path)
-
282
path = "/#{path}"
-
282
path.squeeze!('/')
-
282
path.sub!(%r{/+\Z}, '')
-
282
path = '/' if path == ''
-
282
path
-
end
-
-
# URI path and fragment escaping
-
# http://tools.ietf.org/html/rfc3986
-
2
module UriEscape
-
# Symbol captures can generate multiple path segments, so include /.
-
2
reserved_segment = '/'
-
2
reserved_fragment = '/?'
-
2
reserved_pchar = ':@&=+$,;%'
-
-
2
safe_pchar = "#{URI::REGEXP::PATTERN::UNRESERVED}#{reserved_pchar}"
-
2
safe_segment = "#{safe_pchar}#{reserved_segment}"
-
2
safe_fragment = "#{safe_pchar}#{reserved_fragment}"
-
2
if RUBY_VERSION >= '1.9'
-
2
UNSAFE_SEGMENT = Regexp.new("[^#{safe_segment}]", false).freeze
-
2
UNSAFE_FRAGMENT = Regexp.new("[^#{safe_fragment}]", false).freeze
-
else
-
UNSAFE_SEGMENT = Regexp.new("[^#{safe_segment}]", false, 'N').freeze
-
UNSAFE_FRAGMENT = Regexp.new("[^#{safe_fragment}]", false, 'N').freeze
-
end
-
end
-
-
2
Parser = URI.const_defined?(:Parser) ? URI::Parser.new : URI
-
-
2
def self.escape_path(path)
-
8
Parser.escape(path.to_s, UriEscape::UNSAFE_SEGMENT)
-
end
-
-
2
def self.escape_fragment(fragment)
-
Parser.escape(fragment.to_s, UriEscape::UNSAFE_FRAGMENT)
-
end
-
-
2
def self.unescape_uri(uri)
-
Parser.unescape(uri)
-
end
-
end
-
end
-
end
-
2
module Journey
-
###
-
# The Routing table. Contains all routes for a system. Routes can be
-
# added to the table by calling Routes#add_route
-
2
class Routes
-
2
include Enumerable
-
-
2
attr_reader :routes, :named_routes
-
-
2
def initialize
-
2
@routes = []
-
2
@named_routes = {}
-
2
@ast = nil
-
2
@partitioned_routes = nil
-
2
@simulator = nil
-
end
-
-
2
def length
-
@routes.length
-
end
-
2
alias :size :length
-
-
2
def last
-
@routes.last
-
end
-
-
2
def each(&block)
-
151
routes.each(&block)
-
end
-
-
2
def clear
-
2
routes.clear
-
end
-
-
2
def partitioned_routes
-
@partitioned_routes ||= routes.partition { |r|
-
r.path.anchored && r.ast.grep(Nodes::Symbol).all? { |n| n.default_regexp? }
-
}
-
end
-
-
2
def ast
-
return @ast if @ast
-
return if partitioned_routes.first.empty?
-
-
asts = partitioned_routes.first.map { |r| r.ast }
-
@ast = Nodes::Or.new(asts)
-
end
-
-
2
def simulator
-
return @simulator if @simulator
-
-
gtg = GTG::Builder.new(ast).transition_table
-
@simulator = GTG::Simulator.new gtg
-
end
-
-
###
-
# Add a route to the routing table.
-
2
def add_route app, path, conditions, defaults, name = nil
-
164
route = Route.new(name, app, path, conditions, defaults)
-
-
164
route.precedence = routes.length
-
164
routes << route
-
164
named_routes[name] = route if name
-
164
clear_cache!
-
164
route
-
end
-
-
2
private
-
2
def clear_cache!
-
164
@ast = nil
-
164
@partitioned_routes = nil
-
164
@simulator = nil
-
end
-
end
-
end
-
2
require 'strscan'
-
-
2
module Journey
-
2
class Scanner
-
2
def initialize
-
164
@ss = nil
-
end
-
-
2
def scan_setup str
-
164
@ss = StringScanner.new str
-
end
-
-
2
def eos?
-
@ss.eos?
-
end
-
-
2
def pos
-
@ss.pos
-
end
-
-
2
def pre_match
-
@ss.pre_match
-
end
-
-
2
def next_token
-
1402
return if @ss.eos?
-
-
1238
until token = scan || @ss.eos?; end
-
1238
token
-
end
-
-
2
private
-
2
def scan
-
case
-
# /
-
when text = @ss.scan(/\//)
-
300
[:SLASH, text]
-
when text = @ss.scan(/\*/)
-
[:STAR, text]
-
when text = @ss.scan(/\(/)
-
160
[:LPAREN, text]
-
when text = @ss.scan(/\)/)
-
160
[:RPAREN, text]
-
when text = @ss.scan(/\|/)
-
[:OR, text]
-
when text = @ss.scan(/\./)
-
160
[:DOT, text]
-
when text = @ss.scan(/:\w+/)
-
240
[:SYMBOL, text]
-
when text = @ss.scan(/[\w%\-~]+/)
-
218
[:LITERAL, text]
-
# any char
-
when text = @ss.scan(/./)
-
[:LITERAL, text]
-
1238
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module Journey
-
2
module Visitors
-
2
class Visitor # :nodoc:
-
2
DISPATCH_CACHE = Hash.new { |h,k|
-
12
h[k] = "visit_#{k}"
-
}
-
-
2
def accept node
-
704
visit node
-
end
-
-
2
private
-
2
def visit node
-
8024
send DISPATCH_CACHE[node.type], node
-
end
-
-
2
def binary node
-
3243
visit node.left
-
3243
visit node.right
-
end
-
3331
def visit_CAT(n); binary(n); end
-
-
2
def nary node
-
node.children.each { |c| visit c }
-
end
-
2
def visit_OR(n); nary(n); end
-
-
2
def unary node
-
662
visit node.left
-
end
-
664
def visit_GROUP(n); unary(n); end
-
2
def visit_STAR(n); unary(n); end
-
-
2
def terminal node; end
-
2
%w{ LITERAL SYMBOL SLASH DOT }.each do |t|
-
8
class_eval %{ def visit_#{t}(n); terminal(n); end }, __FILE__, __LINE__
-
end
-
end
-
-
##
-
# Loop through the requirements AST
-
2
class Each < Visitor # :nodoc:
-
2
attr_reader :block
-
-
2
def initialize block
-
677
@block = block
-
end
-
-
2
def visit node
-
7825
super
-
7825
block.call node
-
end
-
end
-
-
2
class String < Visitor
-
2
private
-
-
2
def binary node
-
[visit(node.left), visit(node.right)].join
-
end
-
-
2
def nary node
-
node.children.map { |c| visit c }.join '|'
-
end
-
-
2
def terminal node
-
node.left
-
end
-
-
2
def visit_STAR node
-
"*" + super
-
end
-
-
2
def visit_GROUP node
-
"(#{visit node.left})"
-
end
-
end
-
-
###
-
# Used for formatting urls (url_for)
-
2
class Formatter < Visitor
-
2
attr_reader :options, :consumed
-
-
2
def initialize options
-
27
@options = options
-
27
@consumed = {}
-
end
-
-
2
private
-
2
def visit_GROUP node
-
27
if consumed == options
-
nil
-
else
-
route = visit node.left
-
route.include?("\0") ? nil : route
-
end
-
end
-
-
2
def terminal node
-
78
node.left
-
end
-
-
2
def binary node
-
86
[visit(node.left), visit(node.right)].join
-
end
-
-
2
def nary node
-
node.children.map { |c| visit c }.join
-
end
-
-
2
def visit_SYMBOL node
-
8
key = node.to_sym
-
-
8
if value = options[key]
-
8
consumed[key] = value
-
8
Router::Utils.escape_path(value)
-
else
-
"\0"
-
end
-
end
-
end
-
-
2
class Dot < Visitor
-
2
def initialize
-
@nodes = []
-
@edges = []
-
end
-
-
2
def accept node
-
super
-
<<-eodot
-
digraph parse_tree {
-
size="8,5"
-
node [shape = none];
-
edge [dir = none];
-
#{@nodes.join "\n"}
-
#{@edges.join("\n")}
-
}
-
eodot
-
end
-
-
2
private
-
2
def binary node
-
node.children.each do |c|
-
@edges << "#{node.object_id} -> #{c.object_id};"
-
end
-
super
-
end
-
-
2
def nary node
-
node.children.each do |c|
-
@edges << "#{node.object_id} -> #{c.object_id};"
-
end
-
super
-
end
-
-
2
def unary node
-
@edges << "#{node.object_id} -> #{node.left.object_id};"
-
super
-
end
-
-
2
def visit_GROUP node
-
@nodes << "#{node.object_id} [label=\"()\"];"
-
super
-
end
-
-
2
def visit_CAT node
-
@nodes << "#{node.object_id} [label=\"○\"];"
-
super
-
end
-
-
2
def visit_STAR node
-
@nodes << "#{node.object_id} [label=\"*\"];"
-
super
-
end
-
-
2
def visit_OR node
-
@nodes << "#{node.object_id} [label=\"|\"];"
-
super
-
end
-
-
2
def terminal node
-
value = node.left
-
-
@nodes << "#{node.object_id} [label=\"#{value}\"];"
-
end
-
end
-
end
-
end
-
2
require 'jquery/rails'
-
2
module ActionDispatch
-
2
module Assertions
-
2
module SelectorAssertions
-
# Selects content from a JQuery response. Patterned loosely on
-
# assert_select_rjs.
-
#
-
# === Narrowing down
-
#
-
# With no arguments, asserts that one or more method calls are made.
-
#
-
# Use the +method+ argument to narrow down the assertion to only
-
# statements that call that specific method.
-
#
-
# Use the +opt+ argument to narrow down the assertion to only statements
-
# that pass +opt+ as the first argument.
-
#
-
# Use the +id+ argument to narrow down the assertion to only statements
-
# that invoke methods on the result of using that identifier as a
-
# selector.
-
#
-
# === Using blocks
-
#
-
# Without a block, +assert_select_jquery_ merely asserts that the
-
# response contains one or more statements that match the conditions
-
# specified above
-
#
-
# With a block +assert_select_jquery_ also asserts that the method call
-
# passes a javascript escaped string containing HTML. All such HTML
-
# fragments are selected and passed to the block. Nested assertions are
-
# supported.
-
#
-
# === Examples
-
#
-
# # asserts that the #notice element is hidden
-
# assert_select :hide, '#notice'
-
#
-
# # asserts that the #cart element is shown with a blind parameter
-
# assert_select :show, :blind, '#cart'
-
#
-
# # asserts that #cart content contains a #current_item
-
# assert_select :html, '#cart' do
-
# assert_select '#current_item'
-
# end
-
-
2
PATTERN_HTML = "\"((\\\\\"|[^\"])*)\""
-
2
PATTERN_UNICODE_ESCAPED_CHAR = /\\u([0-9a-zA-Z]{4})/
-
-
2
def assert_select_jquery(*args, &block)
-
jquery_method = args.first.is_a?(Symbol) ? args.shift : nil
-
jquery_opt = args.first.is_a?(Symbol) ? args.shift : nil
-
id = args.first.is_a?(String) ? args.shift : nil
-
-
pattern = "\\.#{jquery_method || '\\w+'}\\("
-
pattern = "#{pattern}['\"]#{jquery_opt}['\"],?\\s*" if jquery_opt
-
pattern = "#{pattern}#{PATTERN_HTML}"
-
pattern = "(?:jQuery|\\$)\\(['\"]#{id}['\"]\\)#{pattern}" if id
-
-
fragments = []
-
response.body.scan(Regexp.new(pattern)).each do |match|
-
doc = HTML::Document.new(unescape_js(match.first))
-
doc.root.children.each do |child|
-
fragments.push child if child.tag?
-
end
-
end
-
-
if fragments.empty?
-
opts = [jquery_method, jquery_opt, id].compact
-
flunk "No JQuery call matches #{opts.inspect}"
-
end
-
-
if block
-
begin
-
in_scope, @selected = @selected, fragments
-
yield
-
ensure
-
@selected = in_scope
-
end
-
end
-
end
-
-
2
private
-
-
# Unescapes a JS string.
-
2
def unescape_js(js_string)
-
# js encodes double quotes and line breaks.
-
unescaped= js_string.gsub('\"', '"')
-
unescaped.gsub!('\\\'', "'")
-
unescaped.gsub!(/\\\//, '/')
-
unescaped.gsub!('\n', "\n")
-
unescaped.gsub!('\076', '>')
-
unescaped.gsub!('\074', '<')
-
# js encodes non-ascii characters.
-
unescaped.gsub!(PATTERN_UNICODE_ESCAPED_CHAR) {|u| [$1.hex].pack('U*')}
-
unescaped
-
end
-
-
end
-
end
-
end
-
2
require 'jquery/assert_select' if ::Rails.env.test?
-
2
require 'jquery/rails/engine' if ::Rails.version >= '3.1'
-
2
require 'jquery/rails/railtie'
-
2
require 'jquery/rails/version'
-
-
2
module Jquery
-
2
module Rails
-
2
PROTOTYPE_JS = %w{prototype effects dragdrop controls}
-
end
-
end
-
2
module Jquery
-
2
module Rails
-
2
class Engine < ::Rails::Engine
-
end
-
end
-
end
-
# Used to ensure that Rails 3.0.x, as well as Rails >= 3.1 with asset pipeline disabled
-
# get the minified version of the scripts included into the layout in production.
-
2
module Jquery
-
2
module Rails
-
2
class Railtie < ::Rails::Railtie
-
2
config.before_configuration do
-
2
if config.action_view.javascript_expansions
-
2
jq_defaults = ::Rails.env.production? || ::Rails.env.test? ? %w(jquery.min) : %w(jquery)
-
-
# Merge the jQuery scripts, remove the Prototype defaults and finally add 'jquery_ujs'
-
# at the end, because load order is important
-
2
config.action_view.javascript_expansions[:defaults] -= PROTOTYPE_JS + ['rails']
-
2
config.action_view.javascript_expansions[:defaults] |= jq_defaults + ['jquery_ujs']
-
end
-
end
-
end
-
end
-
end
-
2
module Jquery
-
2
module Rails
-
2
VERSION = "3.0.4"
-
2
JQUERY_VERSION = "1.10.2"
-
2
JQUERY_UJS_VERSION = "e9e8b8fd3abb1571781bca7640e5c0c4d9cea2e3"
-
end
-
end
-
2
require 'json/common'
-
-
##
-
# = JavaScript Object Notation (JSON)
-
#
-
# JSON is a lightweight data-interchange format. It is easy for us
-
# humans to read and write. Plus, equally simple for machines to generate or parse.
-
# JSON is completely language agnostic, making it the ideal interchange format.
-
#
-
# Built on two universally available structures:
-
# 1. A collection of name/value pairs. Often referred to as an _object_, hash table, record, struct, keyed list, or associative array.
-
# 2. An ordered list of values. More commonly called an _array_, vector, sequence or list.
-
#
-
# To read more about JSON visit: http://json.org
-
#
-
# == Parsing JSON
-
#
-
# To parse a JSON string received by another application or generated within
-
# your existing application:
-
#
-
# require 'json'
-
#
-
# my_hash = JSON.parse('{"hello": "goodbye"}')
-
# puts my_hash["hello"] => "goodbye"
-
#
-
# Notice the extra quotes <tt>''</tt> around the hash notation. Ruby expects
-
# the argument to be a string and can't convert objects like a hash or array.
-
#
-
# Ruby converts your string into a hash
-
#
-
# == Generating JSON
-
#
-
# Creating a JSON string for communication or serialization is
-
# just as simple.
-
#
-
# require 'json'
-
#
-
# my_hash = {:hello => "goodbye"}
-
# puts JSON.generate(my_hash) => "{\"hello\":\"goodbye\"}"
-
#
-
# Or an alternative way:
-
#
-
# require 'json'
-
# puts {:hello => "goodbye"}.to_json => "{\"hello\":\"goodbye\"}"
-
#
-
# <tt>JSON.generate</tt> only allows objects or arrays to be converted
-
# to JSON syntax. <tt>to_json</tt>, however, accepts many Ruby classes
-
# even though it acts only as a method for serialization:
-
#
-
# require 'json'
-
#
-
# 1.to_json => "1"
-
#
-
2
module JSON
-
2
require 'json/version'
-
-
2
begin
-
2
require 'json/ext'
-
rescue LoadError
-
require 'json/pure'
-
end
-
end
-
2
require 'json/version'
-
2
require 'json/generic_object'
-
-
2
module JSON
-
2
class << self
-
# If _object_ is string-like, parse the string and return the parsed result
-
# as a Ruby data structure. Otherwise generate a JSON text from the Ruby
-
# data structure object and return it.
-
#
-
# The _opts_ argument is passed through to generate/parse respectively. See
-
# generate and parse for their documentation.
-
2
def [](object, opts = {})
-
if object.respond_to? :to_str
-
JSON.parse(object.to_str, opts)
-
else
-
JSON.generate(object, opts)
-
end
-
end
-
-
# Returns the JSON parser class that is used by JSON. This is either
-
# JSON::Ext::Parser or JSON::Pure::Parser.
-
2
attr_reader :parser
-
-
# Set the JSON parser class _parser_ to be used by JSON.
-
2
def parser=(parser) # :nodoc:
-
2
@parser = parser
-
2
remove_const :Parser if JSON.const_defined_in?(self, :Parser)
-
2
const_set :Parser, parser
-
end
-
-
# Return the constant located at _path_. The format of _path_ has to be
-
# either ::A::B::C or A::B::C. In any case, A has to be located at the top
-
# level (absolute namespace path?). If there doesn't exist a constant at
-
# the given path, an ArgumentError is raised.
-
2
def deep_const_get(path) # :nodoc:
-
20
path.to_s.split(/::/).inject(Object) do |p, c|
-
case
-
when c.empty? then p
-
20
when JSON.const_defined_in?(p, c) then p.const_get(c)
-
else
-
begin
-
p.const_missing(c)
-
rescue NameError => e
-
raise ArgumentError, "can't get const #{path}: #{e}"
-
end
-
20
end
-
end
-
end
-
-
# Set the module _generator_ to be used by JSON.
-
2
def generator=(generator) # :nodoc:
-
2
old, $VERBOSE = $VERBOSE, nil
-
2
@generator = generator
-
2
generator_methods = generator::GeneratorMethods
-
2
for const in generator_methods.constants
-
20
klass = deep_const_get(const)
-
20
modul = generator_methods.const_get(const)
-
20
klass.class_eval do
-
20
instance_methods(false).each do |m|
-
906
m.to_s == 'to_json' and remove_method m
-
end
-
20
include modul
-
end
-
end
-
2
self.state = generator::State
-
2
const_set :State, self.state
-
2
const_set :SAFE_STATE_PROTOTYPE, State.new
-
2
const_set :FAST_STATE_PROTOTYPE, State.new(
-
:indent => '',
-
:space => '',
-
:object_nl => "",
-
:array_nl => "",
-
:max_nesting => false
-
)
-
2
const_set :PRETTY_STATE_PROTOTYPE, State.new(
-
:indent => ' ',
-
:space => ' ',
-
:object_nl => "\n",
-
:array_nl => "\n"
-
)
-
ensure
-
2
$VERBOSE = old
-
end
-
-
# Returns the JSON generator module that is used by JSON. This is
-
# either JSON::Ext::Generator or JSON::Pure::Generator.
-
2
attr_reader :generator
-
-
# Returns the JSON generator state class that is used by JSON. This is
-
# either JSON::Ext::Generator::State or JSON::Pure::Generator::State.
-
2
attr_accessor :state
-
-
# This is create identifier, which is used to decide if the _json_create_
-
# hook of a class should be called. It defaults to 'json_class'.
-
2
attr_accessor :create_id
-
end
-
2
self.create_id = 'json_class'
-
-
2
NaN = 0.0/0
-
-
2
Infinity = 1.0/0
-
-
2
MinusInfinity = -Infinity
-
-
# The base exception for JSON errors.
-
2
class JSONError < StandardError
-
2
def self.wrap(exception)
-
obj = new("Wrapped(#{exception.class}): #{exception.message.inspect}")
-
obj.set_backtrace exception.backtrace
-
obj
-
end
-
end
-
-
# This exception is raised if a parser error occurs.
-
2
class ParserError < JSONError; end
-
-
# This exception is raised if the nesting of parsed data structures is too
-
# deep.
-
2
class NestingError < ParserError; end
-
-
# :stopdoc:
-
2
class CircularDatastructure < NestingError; end
-
# :startdoc:
-
-
# This exception is raised if a generator or unparser error occurs.
-
2
class GeneratorError < JSONError; end
-
# For backwards compatibility
-
2
UnparserError = GeneratorError
-
-
# This exception is raised if the required unicode support is missing on the
-
# system. Usually this means that the iconv library is not installed.
-
2
class MissingUnicodeSupport < JSONError; end
-
-
2
module_function
-
-
# Parse the JSON document _source_ into a Ruby data structure and return it.
-
#
-
# _opts_ can have the following
-
# keys:
-
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
-
# structures. Disable depth checking with :max_nesting => false. It defaults
-
# to 100.
-
# * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
-
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
-
# to false.
-
# * *symbolize_names*: If set to true, returns symbols for the names
-
# (keys) in a JSON object. Otherwise strings are returned. Strings are
-
# the default.
-
# * *create_additions*: If set to false, the Parser doesn't create
-
# additions even if a matching class and create_id was found. This option
-
# defaults to true.
-
# * *object_class*: Defaults to Hash
-
# * *array_class*: Defaults to Array
-
2
def parse(source, opts = {})
-
Parser.new(source, opts).parse
-
end
-
-
# Parse the JSON document _source_ into a Ruby data structure and return it.
-
# The bang version of the parse method defaults to the more dangerous values
-
# for the _opts_ hash, so be sure only to parse trusted _source_ documents.
-
#
-
# _opts_ can have the following keys:
-
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
-
# structures. Enable depth checking with :max_nesting => anInteger. The parse!
-
# methods defaults to not doing max depth checking: This can be dangerous
-
# if someone wants to fill up your stack.
-
# * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
-
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
-
# to true.
-
# * *create_additions*: If set to false, the Parser doesn't create
-
# additions even if a matching class and create_id was found. This option
-
# defaults to true.
-
2
def parse!(source, opts = {})
-
opts = {
-
:max_nesting => false,
-
:allow_nan => true
-
}.update(opts)
-
Parser.new(source, opts).parse
-
end
-
-
# Generate a JSON document from the Ruby data structure _obj_ and return
-
# it. _state_ is * a JSON::State object,
-
# * or a Hash like object (responding to to_hash),
-
# * an object convertible into a hash by a to_h method,
-
# that is used as or to configure a State object.
-
#
-
# It defaults to a state object, that creates the shortest possible JSON text
-
# in one line, checks for circular data structures and doesn't allow NaN,
-
# Infinity, and -Infinity.
-
#
-
# A _state_ hash can have the following keys:
-
# * *indent*: a string used to indent levels (default: ''),
-
# * *space*: a string that is put after, a : or , delimiter (default: ''),
-
# * *space_before*: a string that is put before a : pair delimiter (default: ''),
-
# * *object_nl*: a string that is put at the end of a JSON object (default: ''),
-
# * *array_nl*: a string that is put at the end of a JSON array (default: ''),
-
# * *allow_nan*: true if NaN, Infinity, and -Infinity should be
-
# generated, otherwise an exception is thrown if these values are
-
# encountered. This options defaults to false.
-
# * *max_nesting*: The maximum depth of nesting allowed in the data
-
# structures from which JSON is to be generated. Disable depth checking
-
# with :max_nesting => false, it defaults to 100.
-
#
-
# See also the fast_generate for the fastest creation method with the least
-
# amount of sanity checks, and the pretty_generate method for some
-
# defaults for pretty output.
-
2
def generate(obj, opts = nil)
-
if State === opts
-
state, opts = opts, nil
-
else
-
state = SAFE_STATE_PROTOTYPE.dup
-
end
-
if opts
-
if opts.respond_to? :to_hash
-
opts = opts.to_hash
-
elsif opts.respond_to? :to_h
-
opts = opts.to_h
-
else
-
raise TypeError, "can't convert #{opts.class} into Hash"
-
end
-
state = state.configure(opts)
-
end
-
state.generate(obj)
-
end
-
-
# :stopdoc:
-
# I want to deprecate these later, so I'll first be silent about them, and
-
# later delete them.
-
2
alias unparse generate
-
2
module_function :unparse
-
# :startdoc:
-
-
# Generate a JSON document from the Ruby data structure _obj_ and return it.
-
# This method disables the checks for circles in Ruby objects.
-
#
-
# *WARNING*: Be careful not to pass any Ruby data structures with circles as
-
# _obj_ argument because this will cause JSON to go into an infinite loop.
-
2
def fast_generate(obj, opts = nil)
-
if State === opts
-
state, opts = opts, nil
-
else
-
state = FAST_STATE_PROTOTYPE.dup
-
end
-
if opts
-
if opts.respond_to? :to_hash
-
opts = opts.to_hash
-
elsif opts.respond_to? :to_h
-
opts = opts.to_h
-
else
-
raise TypeError, "can't convert #{opts.class} into Hash"
-
end
-
state.configure(opts)
-
end
-
state.generate(obj)
-
end
-
-
# :stopdoc:
-
# I want to deprecate these later, so I'll first be silent about them, and later delete them.
-
2
alias fast_unparse fast_generate
-
2
module_function :fast_unparse
-
# :startdoc:
-
-
# Generate a JSON document from the Ruby data structure _obj_ and return it.
-
# The returned document is a prettier form of the document returned by
-
# #unparse.
-
#
-
# The _opts_ argument can be used to configure the generator. See the
-
# generate method for a more detailed explanation.
-
2
def pretty_generate(obj, opts = nil)
-
if State === opts
-
state, opts = opts, nil
-
else
-
state = PRETTY_STATE_PROTOTYPE.dup
-
end
-
if opts
-
if opts.respond_to? :to_hash
-
opts = opts.to_hash
-
elsif opts.respond_to? :to_h
-
opts = opts.to_h
-
else
-
raise TypeError, "can't convert #{opts.class} into Hash"
-
end
-
state.configure(opts)
-
end
-
state.generate(obj)
-
end
-
-
# :stopdoc:
-
# I want to deprecate these later, so I'll first be silent about them, and later delete them.
-
2
alias pretty_unparse pretty_generate
-
2
module_function :pretty_unparse
-
# :startdoc:
-
-
2
class << self
-
# The global default options for the JSON.load method:
-
# :max_nesting: false
-
# :allow_nan: true
-
# :quirks_mode: true
-
2
attr_accessor :load_default_options
-
end
-
2
self.load_default_options = {
-
:max_nesting => false,
-
:allow_nan => true,
-
:quirks_mode => true,
-
:create_additions => true,
-
}
-
-
# Load a ruby data structure from a JSON _source_ and return it. A source can
-
# either be a string-like object, an IO-like object, or an object responding
-
# to the read method. If _proc_ was given, it will be called with any nested
-
# Ruby object as an argument recursively in depth first order. To modify the
-
# default options pass in the optional _options_ argument as well.
-
#
-
# BEWARE: This method is meant to serialise data from trusted user input,
-
# like from your own database server or clients under your control, it could
-
# be dangerous to allow untrusted users to pass JSON sources into it. The
-
# default options for the parser can be changed via the load_default_options
-
# method.
-
#
-
# This method is part of the implementation of the load/dump interface of
-
# Marshal and YAML.
-
2
def load(source, proc = nil, options = {})
-
opts = load_default_options.merge options
-
if source.respond_to? :to_str
-
source = source.to_str
-
elsif source.respond_to? :to_io
-
source = source.to_io.read
-
elsif source.respond_to?(:read)
-
source = source.read
-
end
-
if opts[:quirks_mode] && (source.nil? || source.empty?)
-
source = 'null'
-
end
-
result = parse(source, opts)
-
recurse_proc(result, &proc) if proc
-
result
-
end
-
-
# Recursively calls passed _Proc_ if the parsed data structure is an _Array_ or _Hash_
-
2
def recurse_proc(result, &proc)
-
case result
-
when Array
-
result.each { |x| recurse_proc x, &proc }
-
proc.call result
-
when Hash
-
result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
-
proc.call result
-
else
-
proc.call result
-
end
-
end
-
-
2
alias restore load
-
2
module_function :restore
-
-
2
class << self
-
# The global default options for the JSON.dump method:
-
# :max_nesting: false
-
# :allow_nan: true
-
# :quirks_mode: true
-
2
attr_accessor :dump_default_options
-
end
-
2
self.dump_default_options = {
-
:max_nesting => false,
-
:allow_nan => true,
-
:quirks_mode => true,
-
}
-
-
# Dumps _obj_ as a JSON string, i.e. calls generate on the object and returns
-
# the result.
-
#
-
# If anIO (an IO-like object or an object that responds to the write method)
-
# was given, the resulting JSON is written to it.
-
#
-
# If the number of nested arrays or objects exceeds _limit_, an ArgumentError
-
# exception is raised. This argument is similar (but not exactly the
-
# same!) to the _limit_ argument in Marshal.dump.
-
#
-
# The default options for the generator can be changed via the
-
# dump_default_options method.
-
#
-
# This method is part of the implementation of the load/dump interface of
-
# Marshal and YAML.
-
2
def dump(obj, anIO = nil, limit = nil)
-
if anIO and limit.nil?
-
anIO = anIO.to_io if anIO.respond_to?(:to_io)
-
unless anIO.respond_to?(:write)
-
limit = anIO
-
anIO = nil
-
end
-
end
-
opts = JSON.dump_default_options
-
limit and opts.update(:max_nesting => limit)
-
result = generate(obj, opts)
-
if anIO
-
anIO.write result
-
anIO
-
else
-
result
-
end
-
rescue JSON::NestingError
-
raise ArgumentError, "exceed depth limit"
-
end
-
-
# Swap consecutive bytes of _string_ in place.
-
2
def self.swap!(string) # :nodoc:
-
0.upto(string.size / 2) do |i|
-
break unless string[2 * i + 1]
-
string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i]
-
end
-
string
-
end
-
-
# Shortuct for iconv.
-
2
if ::String.method_defined?(:encode)
-
# Encodes string using Ruby's _String.encode_
-
2
def self.iconv(to, from, string)
-
string.encode(to, from)
-
end
-
else
-
require 'iconv'
-
# Encodes string using _iconv_ library
-
def self.iconv(to, from, string)
-
Iconv.conv(to, from, string)
-
end
-
end
-
-
2
if ::Object.method(:const_defined?).arity == 1
-
def self.const_defined_in?(modul, constant)
-
modul.const_defined?(constant)
-
end
-
else
-
2
def self.const_defined_in?(modul, constant)
-
22
modul.const_defined?(constant, false)
-
end
-
end
-
end
-
-
2
module ::Kernel
-
2
private
-
-
# Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in
-
# one line.
-
2
def j(*objs)
-
objs.each do |obj|
-
puts JSON::generate(obj, :allow_nan => true, :max_nesting => false)
-
end
-
nil
-
end
-
-
# Ouputs _objs_ to STDOUT as JSON strings in a pretty format, with
-
# indentation and over many lines.
-
2
def jj(*objs)
-
objs.each do |obj|
-
puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
-
end
-
nil
-
end
-
-
# If _object_ is string-like, parse the string and return the parsed result as
-
# a Ruby data structure. Otherwise, generate a JSON text from the Ruby data
-
# structure object and return it.
-
#
-
# The _opts_ argument is passed through to generate/parse respectively. See
-
# generate and parse for their documentation.
-
2
def JSON(object, *args)
-
if object.respond_to? :to_str
-
JSON.parse(object.to_str, args.first)
-
else
-
JSON.generate(object, args.first)
-
end
-
end
-
end
-
-
# Extends any Class to include _json_creatable?_ method.
-
2
class ::Class
-
# Returns true if this class can be used to create an instance
-
# from a serialised JSON string. The class has to implement a class
-
# method _json_create_ that expects a hash as first parameter. The hash
-
# should include the required data.
-
2
def json_creatable?
-
respond_to?(:json_create)
-
end
-
end
-
2
if ENV['SIMPLECOV_COVERAGE'].to_i == 1
-
require 'simplecov'
-
SimpleCov.start do
-
add_filter "/tests/"
-
end
-
end
-
2
require 'json/common'
-
-
2
module JSON
-
# This module holds all the modules/classes that implement JSON's
-
# functionality as C extensions.
-
2
module Ext
-
2
require 'json/ext/parser'
-
2
require 'json/ext/generator'
-
2
$DEBUG and warn "Using Ext extension for JSON."
-
2
JSON.parser = Parser
-
2
JSON.generator = Generator
-
end
-
-
2
JSON_LOADED = true unless defined?(::JSON::JSON_LOADED)
-
end
-
2
require 'ostruct'
-
-
2
module JSON
-
2
class GenericObject < OpenStruct
-
2
class << self
-
2
alias [] new
-
-
2
def json_creatable?
-
@json_creatable
-
end
-
-
2
attr_writer :json_creatable
-
-
2
def json_create(data)
-
data = data.dup
-
data.delete JSON.create_id
-
self[data]
-
end
-
-
2
def from_hash(object)
-
case
-
when object.respond_to?(:to_hash)
-
result = new
-
object.to_hash.each do |key, value|
-
result[key] = from_hash(value)
-
end
-
result
-
when object.respond_to?(:to_ary)
-
object.to_ary.map { |a| from_hash(a) }
-
else
-
object
-
end
-
end
-
-
2
def load(source, proc = nil, opts = {})
-
result = ::JSON.load(source, proc, opts.merge(:object_class => self))
-
result.nil? ? new : result
-
end
-
-
2
def dump(obj, *args)
-
::JSON.dump(obj, *args)
-
end
-
end
-
2
self.json_creatable = false
-
-
2
def to_hash
-
table
-
end
-
-
2
def [](name)
-
table[name.to_sym]
-
end
-
-
2
def []=(name, value)
-
__send__ "#{name}=", value
-
end
-
-
2
def |(other)
-
self.class[other.to_hash.merge(to_hash)]
-
end
-
-
2
def as_json(*)
-
{ JSON.create_id => self.class.name }.merge to_hash
-
end
-
-
2
def to_json(*a)
-
as_json.to_json(*a)
-
end
-
end
-
end
-
2
module JSON
-
# JSON version
-
2
VERSION = '1.8.1'
-
8
VERSION_ARRAY = VERSION.split(/\./).map { |x| x.to_i } # :nodoc:
-
2
VERSION_MAJOR = VERSION_ARRAY[0] # :nodoc:
-
2
VERSION_MINOR = VERSION_ARRAY[1] # :nodoc:
-
2
VERSION_BUILD = VERSION_ARRAY[2] # :nodoc:
-
end
-
-
2
require 'less/defaults'
-
2
require 'less/errors'
-
2
require 'less/loader'
-
2
require 'less/parser'
-
2
require 'less/version'
-
2
require 'less/java_script'
-
-
2
module Less
-
2
extend Less::Defaults
-
-
# NOTE: keep the @loader as less-rails depends on
-
# it as it overrides some less/tree.js functions!
-
2
@loader = Less::Loader.new
-
2
@less = @loader.require('less/index')
-
-
2
def self.[](name)
-
@less[name]
-
end
-
-
# exposes less.Parser
-
2
def self.Parser
-
self['Parser']
-
end
-
-
# exposes less.tree e.g. for attaching custom functions
-
# Less.tree.functions['foo'] = lambda { |*args| 'bar' }
-
2
def self.tree
-
self['tree']
-
end
-
-
end
-
2
module Less
-
2
module Defaults
-
-
2
def defaults
-
@defaults ||= { :paths => [], :relativeUrls => true }
-
end
-
-
2
def paths
-
defaults[:paths]
-
end
-
-
end
-
end
-
2
module Less
-
-
2
class Error < ::StandardError
-
-
2
def initialize(cause, value = nil)
-
@value = value
-
message = nil
-
if @value # 2 args passed
-
message = @value['message']
-
else # allow passing only value as first arg cause :
-
if cause.respond_to?(:'[]') && message = cause['message']
-
@value = cause
-
end
-
end
-
-
if cause.is_a?(::Exception)
-
@cause = cause
-
super(message || cause.message)
-
else
-
super(message || cause)
-
end
-
end
-
-
2
def cause
-
@cause
-
end
-
-
2
def backtrace
-
@cause ? @cause.backtrace : super
-
end
-
-
# function LessError(e, env) { ... }
-
2
%w{ type filename stack extract }.each do |key|
-
8
class_eval "def #{key}; @value && @value['#{key}']; end"
-
end
-
2
%w{ index line column }.each do |key|
-
6
class_eval "def #{key}; @value && @value['#{key}'].to_i; end"
-
end
-
-
end
-
-
2
class ParseError < Error; end
-
-
end
-
2
module Less
-
2
module JavaScript
-
-
2
def self.default_context_wrapper
-
2
if defined?(JRUBY_VERSION)
-
require 'less/java_script/rhino_context'
-
RhinoContext
-
else
-
2
require 'less/java_script/v8_context'
-
2
V8Context
-
end
-
end
-
-
2
@@context_wrapper = nil
-
-
2
def self.context_wrapper
-
2
@@context_wrapper ||= default_context_wrapper
-
end
-
-
2
def self.context_wrapper=(klass)
-
@@context_wrapper = klass
-
end
-
-
# execute a block as JS
-
2
def self.exec(&block)
-
context_wrapper.instance.exec(&block)
-
end
-
-
2
def self.eval(source)
-
context_wrapper.instance.eval(source)
-
end
-
-
end
-
end
-
2
begin
-
2
require 'v8' unless defined?(V8)
-
rescue LoadError => e
-
warn "[WARNING] Please install gem 'therubyracer' to use Less."
-
raise e
-
end
-
-
2
require 'pathname'
-
-
2
module Less
-
2
module JavaScript
-
2
class V8Context
-
-
2
def self.instance
-
2
return new
-
end
-
-
2
def initialize(globals = nil)
-
2
lock do
-
2
@v8_context = V8::Context.new
-
2
globals.each { |key, val| @v8_context[key] = val } if globals
-
end
-
end
-
-
2
def unwrap
-
2
@v8_context
-
end
-
-
2
def exec(&block)
-
lock(&block)
-
end
-
-
2
def eval(source, options = nil) # passing options not supported
-
source = source.encode('UTF-8') if source.respond_to?(:encode)
-
-
lock do
-
@v8_context.eval("(#{source})")
-
end
-
end
-
-
2
def call(properties, *args)
-
args.last.is_a?(::Hash) ? args.pop : nil # extract_options!
-
-
lock do
-
@v8_context.eval(properties).call(*args)
-
end
-
end
-
-
2
def method_missing(symbol, *args)
-
if @v8_context.respond_to?(symbol)
-
@v8_context.send(symbol, *args)
-
else
-
super
-
end
-
end
-
-
2
private
-
-
2
def lock(&block)
-
2
do_lock(&block)
-
rescue V8::JSError => e
-
if e.in_javascript?
-
js_value = e.value.respond_to?(:'[]')
-
name = js_value && e.value["name"]
-
constructor = js_value && e.value['constructor']
-
if name == "SyntaxError" ||
-
( constructor && constructor.name == "LessError" )
-
raise Less::ParseError.new(e, js_value ? e.value : nil)
-
end
-
# NOTE: less/parser.js :
-
#
-
# error = new(LessError)({
-
# index: i,
-
# type: 'Parse',
-
# message: "missing closing `}`",
-
# filename: env.filename
-
# }, env);
-
#
-
# comes back as value: RuntimeError !
-
elsif e.value.to_s =~ /missing closing `\}`/
-
raise Less::ParseError.new(e.value.to_s)
-
end
-
raise Less::Error.new(e)
-
end
-
-
2
def do_lock
-
2
result, exception = nil, nil
-
2
V8::C::Locker() do
-
2
begin
-
2
result = yield
-
rescue Exception => e
-
exception = e
-
end
-
end
-
-
2
if exception
-
raise exception
-
else
-
2
result
-
end
-
end
-
-
end
-
end
-
end
-
2
require 'pathname'
-
2
require 'commonjs'
-
2
require 'net/http'
-
2
require 'uri'
-
2
require 'base64'
-
-
2
module Less
-
2
class Loader
-
-
2
attr_reader :environment
-
-
2
def initialize
-
2
context_wrapper = Less::JavaScript.context_wrapper.instance
-
2
@context = context_wrapper.unwrap
-
2
@context['process'] = Process.new
-
2
@context['console'] = Console.new
-
2
path = Pathname(__FILE__).dirname.join('js', 'lib')
-
2
@environment = CommonJS::Environment.new(@context, :path => path.to_s)
-
2
@environment.native('path', Path)
-
2
@environment.native('util', Util)
-
2
@environment.native('fs', FS)
-
2
@environment.native('url', Url)
-
2
@environment.native('http', Http)
-
end
-
-
2
def require(module_id)
-
32
@environment.require(module_id)
-
end
-
-
# JS exports (required by less.js) :
-
-
2
class Process # :nodoc:
-
2
def exit(*args)
-
warn("JS process.exit(#{args.first}) called from: \n#{caller.join("\n")}")
-
end
-
end
-
-
2
class Console # :nodoc:
-
2
def log(*msgs)
-
puts msgs.join(', ')
-
end
-
-
2
def warn(*msgs)
-
$stderr.puts msgs.join(', ')
-
end
-
end
-
-
# stubbed JS modules (required by less.js) :
-
-
2
module Path # :nodoc:
-
2
def self.join(*components)
-
# node.js expands path on join
-
File.expand_path(File.join(*components))
-
end
-
-
2
def self.dirname(path)
-
File.dirname(path)
-
end
-
-
2
def self.basename(path)
-
File.basename(path)
-
end
-
-
2
def self.extname(path)
-
File.extname(path)
-
end
-
-
2
def self.resolve(path)
-
File.basename(path)
-
end
-
-
end
-
-
2
module Util # :nodoc:
-
-
2
def self.error(*errors)
-
raise errors.join(' ')
-
end
-
-
2
def self.puts(*args)
-
args.each { |arg| STDOUT.puts(arg) }
-
end
-
-
end
-
-
2
module FS # :nodoc:
-
-
2
def self.statSync(path)
-
File.stat(path)
-
end
-
-
2
def self.readFile(path, encoding, callback)
-
callback.call(nil, File.read(path))
-
end
-
-
2
def self.readFileSync(path, encoding)
-
Buffer.new(path)
-
end
-
-
2
class Buffer
-
2
attr_accessor :data
-
-
2
def initialize(path)
-
@data = File.read(path)
-
end
-
-
2
def length
-
@data.length
-
end
-
-
2
def toString(*args)
-
if args.last == "base64"
-
Base64.strict_encode64(@data)
-
else
-
@data
-
end
-
end
-
end
-
-
end
-
-
2
module Url # :nodoc:
-
-
2
def self.resolve(*args)
-
URI.join(*args)
-
end
-
-
2
def self.parse(url_string)
-
u = URI.parse(url_string)
-
result = {}
-
result['protocol'] = u.scheme + ':' if u.scheme
-
result['hostname'] = u.host if u.host
-
result['pathname'] = u.path if u.path
-
result['port'] = u.port if u.port
-
result['query'] = u.query if u.query
-
result['search'] = '?' + u.query if u.query
-
result['hash'] = '#' + u.fragment if u.fragment
-
result
-
end
-
-
end
-
-
2
module Http # :nodoc:
-
-
2
def self.get(options, callback)
-
err = nil
-
begin
-
#less always sends options as an object, so no need to check for string
-
uri_hash = {}
-
uri_hash[:host] = options['hostname'] ? options['hostname'] : options['host']
-
path_components = options['path'] ? options['path'].split('?', 2) : [''] #have to do this because node expects path and query to be combined
-
if path_components.length > 1
-
uri_hash[:path] = path_components[0]
-
uri_hash[:query] = path_components[0]
-
else
-
uri_hash[:path] = path_components[0]
-
end
-
uri_hash[:port] = options['port'] ? options['port'] : Net::HTTP.http_default_port
-
uri_hash[:scheme] = uri_hash[:port] == Net::HTTP.https_default_port ? 'https' : 'http' #have to check this way because of node's http.get
-
case uri_hash[:scheme]
-
when 'http'
-
uri = URI::HTTP.build(uri_hash)
-
when 'https'
-
uri = URI::HTTPS.build(uri_hash)
-
else
-
raise Exception, 'Less import only supports http and https'
-
end
-
http = Net::HTTP.new uri.host, uri.port
-
if uri.scheme == 'https'
-
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
-
http.use_ssl = true
-
end
-
response = nil
-
http.start do |req|
-
response = req.get(uri.to_s)
-
end
-
callback.call ServerResponse.new(response.read_body, response.code.to_i)
-
rescue => e
-
err = e.message
-
ensure
-
ret = HttpGetResult.new(err)
-
end
-
ret
-
end
-
-
2
class HttpGetResult
-
2
attr_accessor :err
-
-
2
def initialize(err)
-
@err = err
-
end
-
-
2
def on(event, callback)
-
case event
-
when 'error'
-
callback.call(@err) if @err #only call when error exists
-
else
-
callback.call()
-
end
-
end
-
end
-
-
2
class ServerResponse
-
2
attr_accessor :statusCode
-
2
attr_accessor :data #faked because ServerResponse acutally implements WriteableStream
-
-
2
def initialize(data, status_code)
-
@data = data
-
@statusCode = status_code
-
end
-
-
2
def on(event, callback)
-
case event
-
when 'data'
-
callback.call(@data)
-
else
-
callback.call()
-
end
-
end
-
end
-
-
end
-
-
end
-
end
-
2
require 'pathname'
-
-
2
module Less
-
-
# Convert lesscss source into an abstract syntax Tree
-
2
class Parser
-
-
# Construct and configure new Less::Parser
-
#
-
# @param [Hash] options configuration options
-
# @option options [Array] :paths a list of directories to search when handling \@import statements
-
# @option options [String] :filename to associate with resulting parse trees (useful for generating errors)
-
# @option options [TrueClass, FalseClass] :compress
-
# @option options [TrueClass, FalseClass] :strictImports
-
# @option options [TrueClass, FalseClass] :relativeUrls
-
# @option options [String] :dumpLineNumbers one of 'mediaquery', 'comments', or 'all'
-
2
def initialize(options = {})
-
# LeSS supported _env_ options :
-
#
-
# - paths (unmodified) - paths to search for imports on
-
# - optimization - optimization level (for the chunker)
-
# - mime (browser only) mime type for sheet import
-
# - contents (browser only)
-
# - strictImports
-
# - dumpLineNumbers - whether to dump line numbers
-
# - compress - whether to compress
-
# - processImports - whether to process imports. if false then imports will not be imported
-
# - relativeUrls (true/false) whether to adjust URL's to be relative
-
# - errback (error callback function)
-
# - rootpath string
-
# - entryPath string
-
# - files (internal) - list of files that have been imported, used for import-once
-
# - currentFileInfo (internal) - information about the current file -
-
# for error reporting and importing and making urls relative etc :
-
# this.currentFileInfo = {
-
# filename: filename,
-
# relativeUrls: this.relativeUrls,
-
# rootpath: options.rootpath || "",
-
# currentDirectory: entryPath,
-
# entryPath: entryPath,
-
# rootFilename: filename
-
# };
-
#
-
env = {}
-
Less.defaults.merge(options).each do |key, val|
-
env[key.to_s] =
-
case val
-
when Symbol, Pathname then val.to_s
-
when Array
-
val.map!(&:to_s) if key.to_sym == :paths # might contain Pathname-s
-
val # keep the original passed Array
-
else val # true/false/String/Method
-
end
-
end
-
@parser = Less::JavaScript.exec { Less['Parser'].new(env) }
-
end
-
-
# Convert `less` source into a abstract syntaxt tree
-
# @param [String] less the source to parse
-
# @return [Less::Tree] the parsed tree
-
2
def parse(less)
-
error, tree = nil, nil
-
Less::JavaScript.exec do
-
@parser.parse(less, lambda { |*args| # (error, tree)
-
# v8 >= 0.10 passes this as first arg :
-
if args.size > 2
-
error, tree = args[-2], args[-1]
-
elsif args.last.respond_to?(:message) && args.last.message
-
# might get invoked as callback(error)
-
error = args.last
-
else
-
error, tree = *args
-
end
-
fail error.message unless error.nil?
-
})
-
end
-
Tree.new(tree) if tree
-
end
-
-
2
def imports
-
Less::JavaScript.exec { @parser.imports.files.map { |file, _| file } }
-
end
-
-
2
private
-
-
# Abstract LessCSS syntax tree Less. Mainly used to emit CSS
-
2
class Tree
-
-
# Create a tree from a native javascript object.
-
# @param [V8::Object] tree the native less.js tree
-
2
def initialize(tree)
-
@tree = tree
-
end
-
-
# Serialize this tree into CSS.
-
# By default this will be in pretty-printed form.
-
# @param [Hash] opts modifications to the output
-
# @option opts [Boolean] :compress minify output instead of pretty-printing
-
2
def to_css(options = {})
-
Less::JavaScript.exec { @tree.toCSS(options) }
-
end
-
-
end
-
-
end
-
-
end
-
2
module Less
-
2
VERSION = '2.4.0'
-
end
-
2
require 'less/rails'
-
2
module Less
-
2
module Rails
-
end
-
end
-
-
2
require 'less'
-
2
require 'rails'
-
2
require 'tilt'
-
2
require 'sprockets'
-
2
begin
-
2
require 'sprockets/railtie'
-
rescue LoadError
-
require 'sprockets/rails/railtie'
-
end
-
-
2
require 'less/rails/version'
-
2
require 'less/rails/helpers'
-
2
require 'less/rails/template_handlers'
-
2
require 'less/rails/import_processor'
-
2
require 'less/rails/railtie'
-
2
module Less
-
-
2
def self.less
-
@less
-
end
-
-
2
def self.register_rails_helper(name, &block)
-
30
tree = @loader.require('less/tree')
-
30
tree.functions[name] = lambda do |*args|
-
# args: (this, node) v8 >= 0.10, otherwise (node)
-
raise ArgumentError, "missing node" if args.empty?
-
tree[:Anonymous].new block.call(tree, args.last)
-
end
-
end
-
-
2
module Rails
-
2
module Helpers
-
-
2
extend ActiveSupport::Concern
-
-
2
included do
-
2
Less.register_rails_helper('asset-path') { |tree, cxt| asset_path unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('asset-url') { |tree, cxt| asset_url unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('image-path') { |tree, cxt| image_path unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('image-url') { |tree, cxt| image_url unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('video-path') { |tree, cxt| video_path unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('video-url') { |tree, cxt| video_url unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('audio-path') { |tree, cxt| audio_path unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('audio-url') { |tree, cxt| audio_url unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('javascript-path') { |tree, cxt| javascript_path unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('javascript-url') { |tree, cxt| javascript_url unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('stylesheet-path') { |tree, cxt| stylesheet_path unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('stylesheet-url') { |tree, cxt| stylesheet_url unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('font-path') { |tree, cxt| font_path unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('font-url') { |tree, cxt| font_url unquote(cxt.toCSS()) }
-
2
Less.register_rails_helper('asset-data-url') { |tree, cxt| asset_data_url unquote(cxt.toCSS()) }
-
end
-
-
2
module ClassMethods
-
-
2
def asset_data_url(path)
-
"url(#{scope.asset_data_uri(path)})"
-
end
-
-
2
def asset_path(asset)
-
public_path(asset).inspect
-
end
-
-
2
def asset_url(asset)
-
"url(#{public_path(asset)})"
-
end
-
-
2
def image_path(img)
-
scope.image_path(img).inspect
-
end
-
-
2
def image_url(img)
-
"url(#{scope.image_path(img)})"
-
end
-
-
2
def video_path(video)
-
scope.video_path(video).inspect
-
end
-
-
2
def video_url(video)
-
"url(#{scope.video_path(video)})"
-
end
-
-
2
def audio_path(audio)
-
scope.audio_path(audio).inspect
-
end
-
-
2
def audio_url(audio)
-
"url(#{scope.audio_path(audio)})"
-
end
-
-
2
def javascript_path(javascript)
-
scope.javascript_path(javascript).inspect
-
end
-
-
2
def javascript_url(javascript)
-
"url(#{scope.javascript_path(javascript)})"
-
end
-
-
2
def stylesheet_path(stylesheet)
-
scope.stylesheet_path(stylesheet).inspect
-
end
-
-
2
def stylesheet_url(stylesheet)
-
"url(#{scope.stylesheet_path(stylesheet)})"
-
end
-
-
2
def font_path(font)
-
if scope.respond_to?(:font_path)
-
scope.font_path(font).inspect
-
else
-
asset_path(font)
-
end
-
end
-
-
2
def font_url(font)
-
if scope.respond_to?(:font_path)
-
"url(#{scope.font_path(font)})"
-
else
-
asset_url(font)
-
end
-
end
-
-
2
private
-
-
2
def scope
-
Less.Parser['scope']
-
end
-
-
2
def public_path(asset)
-
if scope.respond_to?(:asset_paths)
-
scope.asset_paths.compute_public_path asset, ::Rails.application.config.assets.prefix
-
else
-
scope.path_to_asset(asset)
-
end
-
end
-
-
2
def context_asset_data_uri(path)
-
-
end
-
-
2
def unquote(str)
-
s = str.to_s.strip
-
s =~ /^['"](.*?)['"]$/ ? $1 : s
-
end
-
-
end
-
-
end
-
end
-
end
-
-
2
module Less
-
2
module Rails
-
2
class ImportProcessor < Tilt::Template
-
-
2
IMPORT_SCANNER = /@import\s*['"]([^'"]+)['"]\s*;/.freeze
-
2
PATHNAME_FINDER = Proc.new { |scope, path|
-
begin
-
scope.resolve(path)
-
rescue Sprockets::FileNotFound
-
nil
-
end
-
}
-
-
2
def prepare
-
end
-
-
2
def evaluate(scope, locals, &block)
-
depend_on scope, data
-
data
-
end
-
-
2
def depend_on(scope, data, base=File.dirname(scope.logical_path))
-
import_paths = data.scan(IMPORT_SCANNER).flatten.compact.uniq
-
import_paths.each do |path|
-
pathname = PATHNAME_FINDER.call(scope,path) || PATHNAME_FINDER.call(scope, File.join(base, path))
-
scope.depend_on(pathname) if pathname && pathname.to_s.ends_with?('.less')
-
depend_on scope, File.read(pathname), File.dirname(path) if pathname
-
end
-
data
-
end
-
-
end
-
end
-
end
-
2
module Less
-
2
module Rails
-
2
class Railtie < ::Rails::Railtie
-
-
2
module LessContext
-
2
attr_accessor :less_config
-
end
-
-
2
config.less = ActiveSupport::OrderedOptions.new
-
2
config.less.paths = []
-
2
config.less.compress = false
-
2
config.app_generators.stylesheet_engine :less
-
-
2
config.before_initialize do |app|
-
2
require 'less'
-
2
require 'less-rails'
-
2
Sprockets::Engines #force autoloading
-
2
Sprockets.register_engine '.less', LessTemplate
-
end
-
-
2
initializer 'less-rails.before.load_config_initializers', :before => :load_config_initializers, :group => :all do |app|
-
2
(Sprockets.respond_to?('register_preprocessor') ? Sprockets : app.assets).register_preprocessor 'text/css', ImportProcessor
-
2
app.assets.context_class.extend(LessContext)
-
2
app.assets.context_class.less_config = app.config.less
-
end
-
-
2
initializer 'less-rails.after.append_assets_path', :after => :append_assets_path, :group => :all do |app|
-
28
assets_stylesheet_paths = app.config.assets.paths.select { |p| p && p.to_s.ends_with?('stylesheets') }
-
2
app.config.less.paths.unshift(*assets_stylesheet_paths)
-
end
-
-
2
initializer 'less-rails.setup_compression', :group => :all do |app|
-
2
config.less.compress = app.config.assets.compress
-
end
-
-
end
-
end
-
end
-
-
2
module Less
-
2
module Rails
-
2
class LessTemplate < Tilt::LessTemplate
-
-
2
self.default_mime_type = 'text/css'
-
-
2
include Helpers
-
-
2
TO_CSS_KEYS = [:compress, :optimization, :silent, :color]
-
-
2
def prepare
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= begin
-
Less.Parser['scope'] = scope
-
parser = ::Less::Parser.new config_to_less_parser_options(scope)
-
engine = parser.parse(data)
-
engine.to_css config_to_css_options(scope)
-
end
-
end
-
-
2
protected
-
-
2
def config_to_less_parser_options(scope)
-
paths = config_paths(scope) + scope.environment.paths
-
local_path = scope.pathname.dirname
-
paths += [local_path] unless paths.include? local_path
-
{:filename => eval_file, :line => line, :paths => paths, :dumpLineNumbers => config_from_rails(scope).line_numbers}
-
end
-
-
2
def config_to_css_options(scope)
-
Hash[config_from_rails(scope).each.to_a].slice *TO_CSS_KEYS
-
end
-
-
2
def config_paths(scope)
-
config_from_rails(scope)[:paths]
-
end
-
-
2
def config_from_rails(scope)
-
scope.environment.context_class.less_config
-
end
-
-
end
-
end
-
end
-
2
module Less
-
2
module Rails
-
2
VERSION = "2.4.2"
-
end
-
end
-
# encoding: utf-8
-
# This file loads up the parsers for mail to use. It also will attempt to compile parsers
-
# if they don't exist.
-
#
-
# It also only uses the compiler if we are running the SPEC suite
-
2
module Mail # :doc:
-
2
require 'treetop/runtime'
-
-
2
def self.compile_parser(parser)
-
require 'treetop/compiler'
-
Treetop.load(File.join(File.dirname(__FILE__)) + "/mail/parsers/#{parser}")
-
end
-
-
2
parsers = %w[ rfc2822_obsolete rfc2822 address_lists phrase_lists
-
date_time received message_ids envelope_from rfc2045
-
mime_version content_type content_disposition
-
content_transfer_encoding content_location ]
-
-
2
if defined?(MAIL_SPEC_SUITE_RUNNING)
-
parsers.each do |parser|
-
compile_parser(parser)
-
end
-
-
else
-
2
parsers.each do |parser|
-
28
begin
-
28
require "mail/parsers/#{parser}"
-
rescue LoadError
-
compile_parser(parser)
-
end
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
2
module Mail # :doc:
-
-
2
require 'date'
-
2
require 'shellwords'
-
-
2
require 'uri'
-
2
require 'net/smtp'
-
2
require 'mime/types'
-
-
2
if RUBY_VERSION <= '1.8.6'
-
begin
-
require 'tlsmail'
-
rescue LoadError
-
raise "You need to install tlsmail if you are using ruby <= 1.8.6"
-
end
-
end
-
-
2
if RUBY_VERSION >= "1.9.0"
-
2
require 'mail/version_specific/ruby_1_9'
-
2
RubyVer = Ruby19
-
else
-
require 'mail/version_specific/ruby_1_8'
-
RubyVer = Ruby18
-
end
-
-
2
require 'mail/version'
-
-
2
require 'mail/core_extensions/nil'
-
2
require 'mail/core_extensions/object'
-
2
require 'mail/core_extensions/string'
-
2
require 'mail/core_extensions/smtp' if RUBY_VERSION < '1.9.3'
-
2
require 'mail/indifferent_hash'
-
-
# Only load our multibyte extensions if AS is not already loaded
-
2
if defined?(ActiveSupport)
-
2
require 'active_support/inflector'
-
else
-
require 'mail/core_extensions/string/access'
-
require 'mail/core_extensions/string/multibyte'
-
require 'mail/multibyte'
-
end
-
-
2
require 'mail/patterns'
-
2
require 'mail/utilities'
-
2
require 'mail/configuration'
-
-
2
@@autoloads = {}
-
2
def self.register_autoload(name, path)
-
106
@@autoloads[name] = path
-
106
autoload(name, path)
-
end
-
-
# This runs through the autoload list and explictly requires them for you.
-
# Useful when running mail in a threaded process.
-
#
-
# Usage:
-
#
-
# require 'mail'
-
# Mail.eager_autoload!
-
2
def self.eager_autoload!
-
@@autoloads.each { |_,path| require(path) }
-
end
-
-
# Autoload mail send and receive classes.
-
2
require 'mail/network'
-
-
2
require 'mail/message'
-
2
require 'mail/part'
-
2
require 'mail/header'
-
2
require 'mail/parts_list'
-
2
require 'mail/attachments_list'
-
2
require 'mail/body'
-
2
require 'mail/field'
-
2
require 'mail/field_list'
-
-
2
require 'mail/envelope'
-
-
2
require 'load_parsers'
-
-
# Autoload header field elements and transfer encodings.
-
2
require 'mail/elements'
-
2
require 'mail/encodings'
-
2
require 'mail/encodings/base64'
-
2
require 'mail/encodings/quoted_printable'
-
-
2
require 'mail/matchers/has_sent_mail'
-
-
# Finally... require all the Mail.methods
-
2
require 'mail/mail'
-
end
-
2
module Mail
-
2
class AttachmentsList < Array
-
-
2
def initialize(parts_list)
-
8
@parts_list = parts_list
-
8
@content_disposition_type = 'attachment'
-
8
parts_list.map { |p|
-
if p.content_type == "message/rfc822"
-
Mail.new(p.body).attachments
-
elsif p.parts.empty?
-
p if p.attachment?
-
else
-
p.attachments
-
end
-
}.flatten.compact.each { |a| self << a }
-
8
self
-
end
-
-
2
def inline
-
@content_disposition_type = 'inline'
-
self
-
end
-
-
# Returns the attachment by filename or at index.
-
#
-
# mail.attachments['test.png'] = File.read('test.png')
-
# mail.attachments['test.jpg'] = File.read('test.jpg')
-
#
-
# mail.attachments['test.png'].filename #=> 'test.png'
-
# mail.attachments[1].filename #=> 'test.jpg'
-
2
def [](index_value)
-
if index_value.is_a?(Fixnum)
-
self.fetch(index_value)
-
else
-
self.select { |a| a.filename == index_value }.first
-
end
-
end
-
-
2
def []=(name, value)
-
encoded_name = Mail::Encodings.decode_encode name, :encode
-
default_values = { :content_type => "#{set_mime_type(name)}; filename=\"#{encoded_name}\"",
-
:content_transfer_encoding => "#{guess_encoding}",
-
:content_disposition => "#{@content_disposition_type}; filename=\"#{encoded_name}\"" }
-
-
if value.is_a?(Hash)
-
-
default_values[:body] = value.delete(:content) if value[:content]
-
-
default_values[:body] = value.delete(:data) if value[:data]
-
-
encoding = value.delete(:transfer_encoding) || value.delete(:encoding)
-
if encoding
-
if Mail::Encodings.defined? encoding
-
default_values[:content_transfer_encoding] = encoding
-
else
-
raise "Do not know how to handle Content Transfer Encoding #{encoding}, please choose either quoted-printable or base64"
-
end
-
end
-
-
if value[:mime_type]
-
default_values[:content_type] = value.delete(:mime_type)
-
@mime_type = MIME::Types[default_values[:content_type]].first
-
default_values[:content_transfer_encoding] ||= guess_encoding
-
end
-
-
hash = default_values.merge(value)
-
else
-
default_values[:body] = value
-
hash = default_values
-
end
-
-
if hash[:body].respond_to? :force_encoding and hash[:body].respond_to? :valid_encoding?
-
if not hash[:body].valid_encoding? and default_values[:content_transfer_encoding].downcase == "binary"
-
hash[:body].force_encoding("BINARY")
-
end
-
end
-
-
attachment = Part.new(hash)
-
attachment.add_content_id(hash[:content_id])
-
-
@parts_list << attachment
-
end
-
-
# Uses the mime type to try and guess the encoding, if it is a binary type, or unknown, then we
-
# set it to binary, otherwise as set to plain text
-
2
def guess_encoding
-
if @mime_type && !@mime_type.binary?
-
"7bit"
-
else
-
"binary"
-
end
-
end
-
-
2
def set_mime_type(filename)
-
# Have to do this because MIME::Types is not Ruby 1.9 safe yet
-
if RUBY_VERSION >= '1.9'
-
filename = filename.encode(Encoding::UTF_8) if filename.respond_to?(:encode)
-
end
-
-
@mime_type = MIME::Types.type_for(filename).first
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
-
# = Body
-
#
-
# The body is where the text of the email is stored. Mail treats the body
-
# as a single object. The body itself has no information about boundaries
-
# used in the MIME standard, it just looks at its content as either a single
-
# block of text, or (if it is a multipart message) as an array of blocks of text.
-
#
-
# A body has to be told to split itself up into a multipart message by calling
-
# #split with the correct boundary. This is because the body object has no way
-
# of knowing what the correct boundary is for itself (there could be many
-
# boundaries in a body in the case of a nested MIME text).
-
#
-
# Once split is called, Mail::Body will slice itself up on this boundary,
-
# assigning anything that appears before the first part to the preamble, and
-
# anything that appears after the closing boundary to the epilogue, then
-
# each part gets initialized into a Mail::Part object.
-
#
-
# The boundary that is used to split up the Body is also stored in the Body
-
# object for use on encoding itself back out to a string. You can
-
# overwrite this if it needs to be changed.
-
#
-
# On encoding, the body will return the preamble, then each part joined by
-
# the boundary, followed by a closing boundary string and then the epilogue.
-
2
class Body
-
-
2
def initialize(string = '')
-
8
@boundary = nil
-
8
@preamble = nil
-
8
@epilogue = nil
-
8
@charset = nil
-
8
@part_sort_order = [ "text/plain", "text/enriched", "text/html" ]
-
8
@parts = Mail::PartsList.new
-
8
if string.blank?
-
4
@raw_source = ''
-
else
-
# Do join first incase we have been given an Array in Ruby 1.9
-
4
if string.respond_to?(:join)
-
@raw_source = string.join('')
-
elsif string.respond_to?(:to_s)
-
4
@raw_source = string.to_s
-
else
-
raise "You can only assign a string or an object that responds_to? :join or :to_s to a body."
-
end
-
end
-
8
@encoding = (only_us_ascii? ? '7bit' : '8bit')
-
8
set_charset
-
end
-
-
# Matches this body with another body. Also matches the decoded value of this
-
# body with a string.
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body == body #=> true
-
#
-
# body = Mail::Body.new('The body')
-
# body == 'The body' #=> true
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body == "The body" #=> true
-
2
def ==(other)
-
if other.class == String
-
self.decoded == other
-
else
-
super
-
end
-
end
-
-
# Accepts a string and performs a regular expression against the decoded text
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body =~ /The/ #=> 0
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body =~ /The/ #=> 0
-
2
def =~(regexp)
-
self.decoded =~ regexp
-
end
-
-
# Accepts a string and performs a regular expression against the decoded text
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body.match(/The/) #=> #<MatchData "The">
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body.match(/The/) #=> #<MatchData "The">
-
2
def match(regexp)
-
self.decoded.match(regexp)
-
end
-
-
# Accepts anything that responds to #to_s and checks if it's a substring of the decoded text
-
#
-
# Examples:
-
#
-
# body = Mail::Body.new('The body')
-
# body.include?('The') #=> true
-
#
-
# body = Mail::Body.new("VGhlIGJvZHk=\n")
-
# body.encoding = 'base64'
-
# body.include?('The') #=> true
-
2
def include?(other)
-
self.decoded.include?(other.to_s)
-
end
-
-
# Allows you to set the sort order of the parts, overriding the default sort order.
-
# Defaults to 'text/plain', then 'text/enriched', then 'text/html' with any other content
-
# type coming after.
-
2
def set_sort_order(order)
-
@part_sort_order = order
-
end
-
-
# Allows you to sort the parts according to the default sort order, or the sort order you
-
# set with :set_sort_order.
-
#
-
# sort_parts! is also called from :encode, so there is no need for you to call this explicitly
-
2
def sort_parts!
-
@parts.each do |p|
-
p.body.set_sort_order(@part_sort_order)
-
@parts.sort!(@part_sort_order)
-
p.body.sort_parts!
-
end
-
end
-
-
# Returns the raw source that the body was initialized with, without
-
# any tampering
-
2
def raw_source
-
40
@raw_source
-
end
-
-
2
def get_best_encoding(target)
-
16
target_encoding = Mail::Encodings.get_encoding(target)
-
16
target_encoding.get_best_compatible(encoding, raw_source)
-
end
-
-
# Returns a body encoded using transfer_encoding. Multipart always uses an
-
# identiy encoding (i.e. no encoding).
-
# Calling this directly is not a good idea, but supported for compatibility
-
# TODO: Validate that preamble and epilogue are valid for requested encoding
-
2
def encoded(transfer_encoding = '8bit')
-
8
if multipart?
-
self.sort_parts!
-
encoded_parts = parts.map { |p| p.encoded }
-
([preamble] + encoded_parts).join(crlf_boundary) + end_boundary + epilogue.to_s
-
else
-
8
be = get_best_encoding(transfer_encoding)
-
8
dec = Mail::Encodings::get_encoding(encoding)
-
8
enc = Mail::Encodings::get_encoding(be)
-
8
if transfer_encoding == encoding and dec.nil?
-
# Cannot decode, so skip normalization
-
raw_source
-
else
-
# Decode then encode to normalize and allow transforming
-
# from base64 to Q-P and vice versa
-
8
decoded = dec.decode(raw_source)
-
8
if defined?(Encoding) && charset && charset != "US-ASCII"
-
decoded.encode!(charset)
-
decoded.force_encoding('BINARY') unless Encoding.find(charset).ascii_compatible?
-
end
-
8
enc.encode(decoded)
-
end
-
end
-
end
-
-
2
def decoded
-
if !Encodings.defined?(encoding)
-
raise UnknownEncodingType, "Don't know how to decode #{encoding}, please call #encoded and decode it yourself."
-
else
-
Encodings.get_encoding(encoding).decode(raw_source)
-
end
-
end
-
-
2
def to_s
-
decoded
-
end
-
-
2
def charset
-
16
@charset
-
end
-
-
2
def charset=( val )
-
@charset = val
-
end
-
-
2
def encoding(val = nil)
-
32
if val
-
self.encoding = val
-
else
-
32
@encoding
-
end
-
end
-
-
2
def encoding=( val )
-
@encoding = if val == "text" || val.blank?
-
(only_us_ascii? ? '7bit' : '8bit')
-
else
-
val
-
end
-
end
-
-
# Returns the preamble (any text that is before the first MIME boundary)
-
2
def preamble
-
@preamble
-
end
-
-
# Sets the preamble to a string (adds text before the first MIME boundary)
-
2
def preamble=( val )
-
@preamble = val
-
end
-
-
# Returns the epilogue (any text that is after the last MIME boundary)
-
2
def epilogue
-
@epilogue
-
end
-
-
# Sets the epilogue to a string (adds text after the last MIME boundary)
-
2
def epilogue=( val )
-
@epilogue = val
-
end
-
-
# Returns true if there are parts defined in the body
-
2
def multipart?
-
28
true unless parts.empty?
-
end
-
-
# Returns the boundary used by the body
-
2
def boundary
-
@boundary
-
end
-
-
# Allows you to change the boundary of this Body object
-
2
def boundary=( val )
-
@boundary = val
-
end
-
-
2
def parts
-
52
@parts
-
end
-
-
2
def <<( val )
-
if @parts
-
@parts << val
-
else
-
@parts = Mail::PartsList.new[val]
-
end
-
end
-
-
2
def split!(boundary)
-
self.boundary = boundary
-
parts = raw_source.split(/(?:\A|\r\n)--#{Regexp.escape(boundary)}(?=(?:--)?\s*$)/)
-
# Make the preamble equal to the preamble (if any)
-
self.preamble = parts[0].to_s.strip
-
# Make the epilogue equal to the epilogue (if any)
-
self.epilogue = parts[-1].to_s.sub('--', '').strip
-
parts[1...-1].to_a.each { |part| @parts << Mail::Part.new(part) }
-
self
-
end
-
-
2
def only_us_ascii?
-
16
!(raw_source =~ /[^\x01-\x7f]/)
-
end
-
-
2
def empty?
-
!!raw_source.to_s.empty?
-
end
-
-
2
private
-
-
2
def crlf_boundary
-
"\r\n--#{boundary}\r\n"
-
end
-
-
2
def end_boundary
-
"\r\n--#{boundary}--\r\n"
-
end
-
-
2
def set_charset
-
8
only_us_ascii? ? @charset = 'US-ASCII' : @charset = nil
-
end
-
end
-
end
-
2
module Mail
-
2
module CheckDeliveryParams
-
2
def check_delivery_params(mail)
-
4
if mail.smtp_envelope_from.blank?
-
raise ArgumentError.new('An SMTP From address is required to send a message. Set the message smtp_envelope_from, return_path, sender, or from address.')
-
end
-
-
4
if mail.smtp_envelope_to.blank?
-
raise ArgumentError.new('An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address.')
-
end
-
-
4
message = mail.encoded if mail.respond_to?(:encoded)
-
4
if message.blank?
-
raise ArgumentError.new('An encoded message is required to send an email')
-
end
-
-
4
[mail.smtp_envelope_from, mail.smtp_envelope_to, message]
-
end
-
end
-
end
-
# encoding: utf-8
-
#
-
# Thanks to Nicolas Fouché for this wrapper
-
#
-
2
require 'singleton'
-
-
2
module Mail
-
-
# The Configuration class is a Singleton used to hold the default
-
# configuration for all Mail objects.
-
#
-
# Each new mail object gets a copy of these values at initialization
-
# which can be overwritten on a per mail object basis.
-
2
class Configuration
-
2
include Singleton
-
-
2
def initialize
-
1
@delivery_method = nil
-
1
@retriever_method = nil
-
1
super
-
end
-
-
2
def delivery_method(method = nil, settings = {})
-
4
return @delivery_method if @delivery_method && method.nil?
-
1
@delivery_method = lookup_delivery_method(method).new(settings)
-
end
-
-
2
def lookup_delivery_method(method)
-
5
case method.is_a?(String) ? method.to_sym : method
-
when nil
-
1
Mail::SMTP
-
when :smtp
-
Mail::SMTP
-
when :sendmail
-
Mail::Sendmail
-
when :exim
-
Mail::Exim
-
when :file
-
Mail::FileDelivery
-
when :smtp_connection
-
Mail::SMTPConnection
-
when :test
-
Mail::TestMailer
-
else
-
4
method
-
end
-
end
-
-
2
def retriever_method(method = nil, settings = {})
-
return @retriever_method if @retriever_method && method.nil?
-
@retriever_method = lookup_retriever_method(method).new(settings)
-
end
-
-
2
def lookup_retriever_method(method)
-
case method
-
when nil
-
Mail::POP3
-
when :pop3
-
Mail::POP3
-
when :imap
-
Mail::IMAP
-
when :test
-
Mail::TestRetriever
-
else
-
method
-
end
-
end
-
-
2
def param_encode_language(value = nil)
-
value ? @encode_language = value : @encode_language ||= 'en'
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
-
# This is not loaded if ActiveSupport is already loaded
-
-
2
class NilClass #:nodoc:
-
2
unless nil.respond_to? :blank?
-
def blank?
-
true
-
end
-
end
-
-
2
def to_crlf
-
4
''
-
end
-
-
2
def to_lf
-
''
-
end
-
end
-
# encoding: utf-8
-
-
2
unless Object.method_defined? :blank?
-
class Object
-
def blank?
-
if respond_to?(:empty?)
-
empty?
-
else
-
!self
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
class String #:nodoc:
-
2
def to_crlf
-
196
to_str.gsub(/\n|\r\n|\r/) { "\r\n" }
-
end
-
-
2
def to_lf
-
192
to_str.gsub(/\n|\r\n|\r/) { "\n" }
-
end
-
-
326
unless String.instance_methods(false).map {|m| m.to_sym}.include?(:blank?)
-
def blank?
-
self !~ /\S/
-
end
-
end
-
-
2
unless method_defined?(:ascii_only?)
-
# Backport from Ruby 1.9 checks for non-us-ascii characters.
-
def ascii_only?
-
self !~ MATCH_NON_US_ASCII
-
end
-
-
MATCH_NON_US_ASCII = /[^\x00-\x7f]/
-
end
-
-
2
def not_ascii_only?
-
8
!ascii_only?
-
end
-
-
2
unless method_defined?(:bytesize)
-
alias :bytesize :length
-
end
-
end
-
2
module Mail
-
2
register_autoload :Address, 'mail/elements/address'
-
2
register_autoload :AddressList, 'mail/elements/address_list'
-
2
register_autoload :ContentDispositionElement, 'mail/elements/content_disposition_element'
-
2
register_autoload :ContentLocationElement, 'mail/elements/content_location_element'
-
2
register_autoload :ContentTransferEncodingElement, 'mail/elements/content_transfer_encoding_element'
-
2
register_autoload :ContentTypeElement, 'mail/elements/content_type_element'
-
2
register_autoload :DateTimeElement, 'mail/elements/date_time_element'
-
2
register_autoload :EnvelopeFromElement, 'mail/elements/envelope_from_element'
-
2
register_autoload :MessageIdsElement, 'mail/elements/message_ids_element'
-
2
register_autoload :MimeVersionElement, 'mail/elements/mime_version_element'
-
2
register_autoload :PhraseList, 'mail/elements/phrase_list'
-
2
register_autoload :ReceivedElement, 'mail/elements/received_element'
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
class Address
-
-
1
include Mail::Utilities
-
-
# Mail::Address handles all email addresses in Mail. It takes an email address string
-
# and parses it, breaking it down into its component parts and allowing you to get the
-
# address, comments, display name, name, local part, domain part and fully formatted
-
# address.
-
#
-
# Mail::Address requires a correctly formatted email address per RFC2822 or RFC822. It
-
# handles all obsolete versions including obsolete domain routing on the local part.
-
#
-
# a = Address.new('Mikel Lindsaar (My email address) <mikel@test.lindsaar.net>')
-
# a.format #=> 'Mikel Lindsaar <mikel@test.lindsaar.net> (My email address)'
-
# a.address #=> 'mikel@test.lindsaar.net'
-
# a.display_name #=> 'Mikel Lindsaar'
-
# a.local #=> 'mikel'
-
# a.domain #=> 'test.lindsaar.net'
-
# a.comments #=> ['My email address']
-
# a.to_s #=> 'Mikel Lindsaar <mikel@test.lindsaar.net> (My email address)'
-
1
def initialize(value = nil)
-
8
@output_type = :decode
-
8
@tree = nil
-
8
@raw_text = value
-
case
-
when value.nil?
-
@parsed = false
-
return
-
else
-
8
parse(value)
-
8
end
-
end
-
-
# Returns the raw imput of the passed in string, this is before it is passed
-
# by the parser.
-
1
def raw
-
@raw_text
-
end
-
-
# Returns a correctly formatted address for the email going out. If given
-
# an incorrectly formatted address as input, Mail::Address will do its best
-
# to format it correctly. This includes quoting display names as needed and
-
# putting the address in angle brackets etc.
-
#
-
# a = Address.new('Mikel Lindsaar (My email address) <mikel@test.lindsaar.net>')
-
# a.format #=> 'Mikel Lindsaar <mikel@test.lindsaar.net> (My email address)'
-
1
def format
-
32
parse unless @parsed
-
case
-
when tree.nil?
-
''
-
when display_name
-
[quote_phrase(display_name), "<#{address}>", format_comments].compact.join(" ")
-
when address
-
32
[address, format_comments].compact.join(" ")
-
else
-
tree.text_value
-
32
end
-
end
-
-
# Returns the address that is in the address itself. That is, the
-
# local@domain string, without any angle brackets or the like.
-
#
-
# a = Address.new('Mikel Lindsaar (My email address) <mikel@test.lindsaar.net>')
-
# a.address #=> 'mikel@test.lindsaar.net'
-
1
def address
-
104
parse unless @parsed
-
104
domain ? "#{local}@#{domain}" : local
-
end
-
-
# Provides a way to assign an address to an already made Mail::Address object.
-
#
-
# a = Address.new
-
# a.address = 'Mikel Lindsaar (My email address) <mikel@test.lindsaar.net>'
-
# a.address #=> 'mikel@test.lindsaar.net'
-
1
def address=(value)
-
parse(value)
-
end
-
-
# Returns the display name of the email address passed in.
-
#
-
# a = Address.new('Mikel Lindsaar (My email address) <mikel@test.lindsaar.net>')
-
# a.display_name #=> 'Mikel Lindsaar'
-
1
def display_name
-
32
parse unless @parsed
-
32
@display_name ||= get_display_name
-
32
Encodings.decode_encode(@display_name.to_s, @output_type) if @display_name
-
end
-
-
# Provides a way to assign a display name to an already made Mail::Address object.
-
#
-
# a = Address.new
-
# a.address = 'mikel@test.lindsaar.net'
-
# a.display_name = 'Mikel Lindsaar'
-
# a.format #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>'
-
1
def display_name=( str )
-
@display_name = str
-
end
-
-
# Returns the local part (the left hand side of the @ sign in the email address) of
-
# the address
-
#
-
# a = Address.new('Mikel Lindsaar (My email address) <mikel@test.lindsaar.net>')
-
# a.local #=> 'mikel'
-
1
def local
-
104
parse unless @parsed
-
104
"#{obs_domain_list}#{get_local.strip}" if get_local
-
end
-
-
# Returns the domain part (the right hand side of the @ sign in the email address) of
-
# the address
-
#
-
# a = Address.new('Mikel Lindsaar (My email address) <mikel@test.lindsaar.net>')
-
# a.domain #=> 'test.lindsaar.net'
-
1
def domain
-
208
parse unless @parsed
-
208
strip_all_comments(get_domain) if get_domain
-
end
-
-
# Returns an array of comments that are in the email, or an empty array if there
-
# are no comments
-
#
-
# a = Address.new('Mikel Lindsaar (My email address) <mikel@test.lindsaar.net>')
-
# a.comments #=> ['My email address']
-
1
def comments
-
272
parse unless @parsed
-
272
if get_comments.empty?
-
nil
-
else
-
get_comments.map { |c| c.squeeze(" ") }
-
end
-
end
-
-
# Sometimes an address will not have a display name, but might have the name
-
# as a comment field after the address. This returns that name if it exists.
-
#
-
# a = Address.new('mikel@test.lindsaar.net (Mikel Lindsaar)')
-
# a.name #=> 'Mikel Lindsaar'
-
1
def name
-
parse unless @parsed
-
get_name
-
end
-
-
# Returns the format of the address, or returns nothing
-
#
-
# a = Address.new('Mikel Lindsaar (My email address) <mikel@test.lindsaar.net>')
-
# a.format #=> 'Mikel Lindsaar <mikel@test.lindsaar.net> (My email address)'
-
1
def to_s
-
parse unless @parsed
-
format
-
end
-
-
# Shows the Address object basic details, including the Address
-
# a = Address.new('Mikel (My email) <mikel@test.lindsaar.net>')
-
# a.inspect #=> "#<Mail::Address:14184910 Address: |Mikel <mikel@test.lindsaar.net> (My email)| >"
-
1
def inspect
-
parse unless @parsed
-
"#<#{self.class}:#{self.object_id} Address: |#{to_s}| >"
-
end
-
-
1
def encoded
-
32
@output_type = :encode
-
32
format
-
end
-
-
1
def decoded
-
@output_type = :decode
-
format
-
end
-
-
1
private
-
-
1
def parse(value = nil)
-
8
@parsed = true
-
case
-
when value.nil?
-
nil
-
when value.class == String
-
self.tree = Mail::AddressList.new(value).address_nodes.first
-
else
-
8
self.tree = value
-
8
end
-
end
-
-
-
1
def get_domain
-
416
if tree.respond_to?(:angle_addr) && tree.angle_addr.respond_to?(:addr_spec) && tree.angle_addr.addr_spec.respond_to?(:domain)
-
@domain_text ||= tree.angle_addr.addr_spec.domain.text_value.strip
-
416
elsif tree.respond_to?(:domain)
-
416
@domain_text ||= tree.domain.text_value.strip
-
elsif tree.respond_to?(:addr_spec) && tree.addr_spec.respond_to?(:domain)
-
tree.addr_spec.domain.text_value.strip
-
else
-
nil
-
end
-
end
-
-
1
def strip_all_comments(string)
-
208
unless comments.blank?
-
comments.each do |comment|
-
string = string.gsub("(#{comment})", '')
-
end
-
end
-
208
string.strip
-
end
-
-
1
def strip_domain_comments(value)
-
unless comments.blank?
-
comments.each do |comment|
-
if get_domain && get_domain.include?("(#{comment})")
-
value = value.gsub("(#{comment})", '')
-
end
-
end
-
end
-
value.to_s.strip
-
end
-
-
1
def get_comments
-
272
if tree.respond_to?(:comments)
-
272
@comments = tree.comments.map { |c| unparen(c.text_value.to_str) }
-
else
-
@comments = []
-
end
-
end
-
-
1
def get_display_name
-
32
if tree.respond_to?(:display_name)
-
name = unquote(tree.display_name.text_value.strip)
-
str = strip_all_comments(name.to_s)
-
elsif comments
-
if domain
-
str = strip_domain_comments(format_comments)
-
else
-
str = nil
-
end
-
else
-
32
nil
-
end
-
-
32
if str.blank?
-
nil
-
else
-
str
-
end
-
end
-
-
1
def get_name
-
if display_name
-
str = display_name
-
else
-
if comments
-
comment_text = comments.join(' ').squeeze(" ")
-
str = "(#{comment_text})"
-
end
-
end
-
-
if str.blank?
-
nil
-
else
-
unparen(str)
-
end
-
end
-
-
# Provides access to the Treetop parse tree for this address
-
1
def tree
-
3216
@tree
-
end
-
-
1
def tree=(value)
-
8
@tree = value
-
end
-
-
1
def format_comments
-
32
if comments
-
comment_text = comments.map {|c| escape_paren(c) }.join(' ').squeeze(" ")
-
@format_comments ||= "(#{comment_text})"
-
else
-
nil
-
end
-
end
-
-
1
def obs_domain_list
-
104
if tree.respond_to?(:angle_addr)
-
obs = tree.angle_addr.elements.select { |e| e.respond_to?(:obs_domain_list) }
-
!obs.empty? ? obs.first.text_value : nil
-
else
-
nil
-
end
-
end
-
-
1
def get_local
-
case
-
when tree.respond_to?(:local_dot_atom_text)
-
tree.local_dot_atom_text.text_value
-
when tree.respond_to?(:angle_addr) && tree.angle_addr.respond_to?(:addr_spec) && tree.angle_addr.addr_spec.respond_to?(:local_part)
-
tree.angle_addr.addr_spec.local_part.text_value
-
when tree.respond_to?(:addr_spec) && tree.addr_spec.respond_to?(:local_part)
-
tree.addr_spec.local_part.text_value
-
when tree.respond_to?(:angle_addr) && tree.angle_addr.respond_to?(:addr_spec) && tree.angle_addr.addr_spec.respond_to?(:local_dot_atom_text)
-
# Ignore local dot atom text when in angle brackets
-
nil
-
when tree.respond_to?(:addr_spec) && tree.addr_spec.respond_to?(:local_dot_atom_text)
-
# Ignore local dot atom text when in angle brackets
-
nil
-
else
-
208
tree && tree.respond_to?(:local_part) ? tree.local_part.text_value : nil
-
208
end
-
end
-
-
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
class AddressList # :nodoc:
-
-
# Mail::AddressList is the class that parses To, From and other address fields from
-
# emails passed into Mail.
-
#
-
# AddressList provides a way to query the groups and mailbox lists of the passed in
-
# string.
-
#
-
# It can supply all addresses in an array, or return each address as an address object.
-
#
-
# Mail::AddressList requires a correctly formatted group or mailbox list per RFC2822 or
-
# RFC822. It also handles all obsolete versions in those RFCs.
-
#
-
# list = 'ada@test.lindsaar.net, My Group: mikel@test.lindsaar.net, Bob <bob@test.lindsaar.net>;'
-
# a = AddressList.new(list)
-
# a.addresses #=> [#<Mail::Address:14943130 Address: |ada@test.lindsaar.net...
-
# a.group_names #=> ["My Group"]
-
1
def initialize(string)
-
16
if string.blank?
-
@address_nodes = []
-
return self
-
end
-
16
parser = Mail::AddressListsParser.new
-
16
if tree = parser.parse(string)
-
16
@address_nodes = tree.addresses
-
else
-
raise Mail::Field::ParseError.new(AddressListsParser, string, parser.failure_reason)
-
end
-
end
-
-
# Returns a list of address objects from the parsed line
-
1
def addresses
-
@addresses ||= get_addresses.map do |address_tree|
-
8
Mail::Address.new(address_tree)
-
56
end
-
end
-
-
# Returns a list of all recipient syntax trees that are not part of a group
-
1
def individual_recipients # :nodoc:
-
8
@individual_recipients ||= @address_nodes - group_recipients
-
end
-
-
# Returns a list of all recipient syntax trees that are part of a group
-
1
def group_recipients # :nodoc:
-
56
@group_recipients ||= @address_nodes.select { |an| an.respond_to?(:group_name) }
-
end
-
-
# Returns the names as an array of strings of all groups
-
1
def group_names # :nodoc:
-
group_recipients.map { |g| g.group_name.text_value }
-
end
-
-
# Returns a list of address syntax trees
-
1
def address_nodes # :nodoc:
-
@address_nodes
-
end
-
-
1
private
-
-
1
def get_addresses
-
8
(individual_recipients + group_recipients.map { |g| get_group_addresses(g) }).flatten
-
end
-
-
1
def get_group_addresses(g)
-
if g.group_list.respond_to?(:addresses)
-
g.group_list.addresses
-
else
-
[]
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
class ContentTransferEncodingElement
-
-
1
include Mail::Utilities
-
-
1
def initialize( string )
-
8
parser = Mail::ContentTransferEncodingParser.new
-
case
-
when string.blank?
-
@encoding = ''
-
when tree = parser.parse(string.to_s.downcase)
-
8
@encoding = tree.encoding.text_value
-
else
-
raise Mail::Field::ParseError.new(ContentTransferEncodingElement, string, parser.failure_reason)
-
8
end
-
end
-
-
1
def encoding
-
16
@encoding
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
class ContentTypeElement # :nodoc:
-
-
1
include Mail::Utilities
-
-
1
def initialize( string )
-
8
parser = Mail::ContentTypeParser.new
-
8
if tree = parser.parse(cleaned(string))
-
8
@main_type = tree.main_type.text_value.downcase
-
8
@sub_type = tree.sub_type.text_value.downcase
-
8
@parameters = tree.parameters
-
else
-
raise Mail::Field::ParseError.new(ContentTypeElement, string, parser.failure_reason)
-
end
-
end
-
-
1
def main_type
-
8
@main_type
-
end
-
-
1
def sub_type
-
8
@sub_type
-
end
-
-
1
def parameters
-
8
@parameters
-
end
-
-
1
def cleaned(string)
-
8
string =~ /(.+);\s*$/ ? $1 : string
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
class MessageIdsElement
-
-
1
include Mail::Utilities
-
-
1
def initialize(string)
-
4
parser = Mail::MessageIdsParser.new
-
4
if tree = parser.parse(string)
-
8
@message_ids = tree.message_ids.map { |msg_id| clean_msg_id(msg_id.text_value) }
-
else
-
raise Mail::Field::ParseError.new(MessageIdsElement, string, parser.failure_reason)
-
end
-
end
-
-
1
def message_ids
-
@message_ids
-
end
-
-
1
def message_id
-
16
@message_ids.first
-
end
-
-
1
def clean_msg_id( val )
-
4
val =~ /.*<(.*)>.*/ ; $1
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
module Mail
-
1
class MimeVersionElement
-
-
1
include Mail::Utilities
-
-
1
def initialize( string )
-
4
parser = Mail::MimeVersionParser.new
-
4
if tree = parser.parse(string)
-
4
@major = tree.major.text_value
-
4
@minor = tree.minor.text_value
-
else
-
raise Mail::Field::ParseError.new(MimeVersionElement, string, parser.failure_reason)
-
end
-
end
-
-
1
def major
-
8
@major
-
end
-
-
1
def minor
-
8
@minor
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
2
module Mail
-
# Raised when attempting to decode an unknown encoding type
-
2
class UnknownEncodingType < StandardError #:nodoc:
-
end
-
-
2
module Encodings
-
-
2
include Mail::Patterns
-
2
extend Mail::Utilities
-
-
2
@transfer_encodings = {}
-
-
# Register transfer encoding
-
#
-
# Example
-
#
-
# Encodings.register "base64", Mail::Encodings::Base64
-
2
def Encodings.register(name, cls)
-
10
@transfer_encodings[get_name(name)] = cls
-
end
-
-
# Is the encoding we want defined?
-
#
-
# Example:
-
#
-
# Encodings.defined?(:base64) #=> true
-
2
def Encodings.defined?( str )
-
16
@transfer_encodings.include? get_name(str)
-
end
-
-
# Gets a defined encoding type, QuotedPrintable or Base64 for now.
-
#
-
# Each encoding needs to be defined as a Mail::Encodings::ClassName for
-
# this to work, allows us to add other encodings in the future.
-
#
-
# Example:
-
#
-
# Encodings.get_encoding(:base64) #=> Mail::Encodings::Base64
-
2
def Encodings.get_encoding( str )
-
52
@transfer_encodings[get_name(str)]
-
end
-
-
2
def Encodings.get_all
-
@transfer_encodings.values
-
end
-
-
2
def Encodings.get_name(enc)
-
94
enc = enc.to_s.gsub("-", "_").downcase
-
end
-
-
# Encodes a parameter value using URI Escaping, note the language field 'en' can
-
# be set using Mail::Configuration, like so:
-
#
-
# Mail.defaults do
-
# param_encode_language 'jp'
-
# end
-
#
-
# The character set used for encoding will either be the value of $KCODE for
-
# Ruby < 1.9 or the encoding on the string passed in.
-
#
-
# Example:
-
#
-
# Mail::Encodings.param_encode("This is fun") #=> "us-ascii'en'This%20is%20fun"
-
2
def Encodings.param_encode(str)
-
case
-
when str.ascii_only? && str =~ TOKEN_UNSAFE
-
%Q{"#{str}"}
-
when str.ascii_only?
-
str
-
else
-
RubyVer.param_encode(str)
-
end
-
end
-
-
# Decodes a parameter value using URI Escaping.
-
#
-
# Example:
-
#
-
# Mail::Encodings.param_decode("This%20is%20fun", 'us-ascii') #=> "This is fun"
-
#
-
# str = Mail::Encodings.param_decode("This%20is%20fun", 'iso-8559-1')
-
# str.encoding #=> 'ISO-8859-1' ## Only on Ruby 1.9
-
# str #=> "This is fun"
-
2
def Encodings.param_decode(str, encoding)
-
RubyVer.param_decode(str, encoding)
-
end
-
-
# Decodes or encodes a string as needed for either Base64 or QP encoding types in
-
# the =?<encoding>?[QB]?<string>?=" format.
-
#
-
# The output type needs to be :decode to decode the input string or :encode to
-
# encode the input string. The character set used for encoding will either be
-
# the value of $KCODE for Ruby < 1.9 or the encoding on the string passed in.
-
#
-
# On encoding, will only send out Base64 encoded strings.
-
2
def Encodings.decode_encode(str, output_type)
-
case
-
when output_type == :decode
-
12
Encodings.value_decode(str)
-
else
-
if str.ascii_only?
-
str
-
else
-
Encodings.b_value_encode(str, find_encoding(str))
-
end
-
12
end
-
end
-
-
# Decodes a given string as Base64 or Quoted Printable, depending on what
-
# type it is.
-
#
-
# String has to be of the format =?<encoding>?[QB]?<string>?=
-
2
def Encodings.value_decode(str)
-
# Optimization: If there's no encoded-words in the string, just return it
-
12
return str unless str =~ /\=\?[^?]+\?[QB]\?[^?]+?\?\=/xmi
-
-
lines = collapse_adjacent_encodings(str)
-
-
# Split on white-space boundaries with capture, so we capture the white-space as well
-
lines.map do |line|
-
line.split(/([ \t])/).map do |text|
-
if text.index('=?').nil?
-
text
-
else
-
# Search for occurences of quoted strings or plain strings
-
text.scan(/( # Group around entire regex to include it in matches
-
\=\?[^?]+\?([QB])\?[^?]+?\?\= # Quoted String with subgroup for encoding method
-
| # or
-
.+?(?=\=\?|$) # Plain String
-
)/xmi).map do |matches|
-
string, method = *matches
-
if method == 'b' || method == 'B'
-
b_value_decode(string)
-
elsif method == 'q' || method == 'Q'
-
q_value_decode(string)
-
else
-
string
-
end
-
end
-
end
-
end
-
end.flatten.join("")
-
end
-
-
# Takes an encoded string of the format =?<encoding>?[QB]?<string>?=
-
2
def Encodings.unquote_and_convert_to(str, to_encoding)
-
output = value_decode( str ).to_s # output is already converted to UTF-8
-
-
if 'utf8' == to_encoding.to_s.downcase.gsub("-", "")
-
output
-
elsif to_encoding
-
begin
-
if RUBY_VERSION >= '1.9'
-
output.encode(to_encoding)
-
else
-
require 'iconv'
-
Iconv.iconv(to_encoding, 'UTF-8', output).first
-
end
-
rescue Iconv::IllegalSequence, Iconv::InvalidEncoding, Errno::EINVAL
-
# the 'from' parameter specifies a charset other than what the text
-
# actually is...not much we can do in this case but just return the
-
# unconverted text.
-
#
-
# Ditto if either parameter represents an unknown charset, like
-
# X-UNKNOWN.
-
output
-
end
-
else
-
output
-
end
-
end
-
-
2
def Encodings.address_encode(address, charset = 'utf-8')
-
16
if address.is_a?(Array)
-
# loop back through for each element
-
address.compact.map { |a| Encodings.address_encode(a, charset) }.join(", ")
-
else
-
# find any word boundary that is not ascii and encode it
-
16
encode_non_usascii(address, charset) if address
-
end
-
end
-
-
2
def Encodings.encode_non_usascii(address, charset)
-
16
return address if address.ascii_only? or charset.nil?
-
us_ascii = %Q{\x00-\x7f}
-
# Encode any non usascii strings embedded inside of quotes
-
address = address.gsub(/(".*?[^#{us_ascii}].*?")/) { |s| Encodings.b_value_encode(unquote(s), charset) }
-
# Then loop through all remaining items and encode as needed
-
tokens = address.split(/\s/)
-
map_with_index(tokens) do |word, i|
-
if word.ascii_only?
-
word
-
else
-
previous_non_ascii = i>0 && tokens[i-1] && !tokens[i-1].ascii_only?
-
if previous_non_ascii #why are we adding an extra space here?
-
word = " #{word}"
-
end
-
Encodings.b_value_encode(word, charset)
-
end
-
end.join(' ')
-
end
-
-
# Encode a string with Base64 Encoding and returns it ready to be inserted
-
# as a value for a field, that is, in the =?<charset>?B?<string>?= format
-
#
-
# Example:
-
#
-
# Encodings.b_value_encode('This is あ string', 'UTF-8')
-
# #=> "=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?="
-
2
def Encodings.b_value_encode(encoded_str, encoding = nil)
-
return encoded_str if encoded_str.to_s.ascii_only?
-
string, encoding = RubyVer.b_value_encode(encoded_str, encoding)
-
map_lines(string) do |str|
-
"=?#{encoding}?B?#{str.chomp}?="
-
end.join(" ")
-
end
-
-
# Encode a string with Quoted-Printable Encoding and returns it ready to be inserted
-
# as a value for a field, that is, in the =?<charset>?Q?<string>?= format
-
#
-
# Example:
-
#
-
# Encodings.q_value_encode('This is あ string', 'UTF-8')
-
# #=> "=?UTF-8?Q?This_is_=E3=81=82_string?="
-
2
def Encodings.q_value_encode(encoded_str, encoding = nil)
-
return encoded_str if encoded_str.to_s.ascii_only?
-
string, encoding = RubyVer.q_value_encode(encoded_str, encoding)
-
string.gsub!("=\r\n", '') # We already have limited the string to the length we want
-
map_lines(string) do |str|
-
"=?#{encoding}?Q?#{str.chomp.gsub(/ /, '_')}?="
-
end.join(" ")
-
end
-
-
2
private
-
-
# Decodes a Base64 string from the "=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?=" format
-
#
-
# Example:
-
#
-
# Encodings.b_value_decode("=?UTF-8?B?VGhpcyBpcyDjgYIgc3RyaW5n?=")
-
# #=> 'This is あ string'
-
2
def Encodings.b_value_decode(str)
-
RubyVer.b_value_decode(str)
-
end
-
-
# Decodes a Quoted-Printable string from the "=?UTF-8?Q?This_is_=E3=81=82_string?=" format
-
#
-
# Example:
-
#
-
# Encodings.q_value_decode("=?UTF-8?Q?This_is_=E3=81=82_string?=")
-
# #=> 'This is あ string'
-
2
def Encodings.q_value_decode(str)
-
RubyVer.q_value_decode(str)
-
end
-
-
2
def Encodings.split_encoding_from_string( str )
-
match = str.match(/\=\?([^?]+)?\?[QB]\?(.+)?\?\=/mi)
-
if match
-
match[1]
-
else
-
nil
-
end
-
end
-
-
2
def Encodings.find_encoding(str)
-
RUBY_VERSION >= '1.9' ? str.encoding : $KCODE
-
end
-
-
# Gets the encoding type (Q or B) from the string.
-
2
def Encodings.split_value_encoding_from_string(str)
-
match = str.match(/\=\?[^?]+?\?([QB])\?(.+)?\?\=/mi)
-
if match
-
match[1]
-
else
-
nil
-
end
-
end
-
-
# When the encoded string consists of multiple lines, lines with the same
-
# encoding (Q or B) can be joined together.
-
#
-
# String has to be of the format =?<encoding>?[QB]?<string>?=
-
2
def Encodings.collapse_adjacent_encodings(str)
-
lines = str.split(/(\?=)\s*(=\?)/).each_slice(2).map(&:join)
-
results = []
-
previous_encoding = nil
-
-
lines.each do |line|
-
encoding = split_value_encoding_from_string(line)
-
-
if encoding == previous_encoding
-
line = results.pop + line
-
line.gsub!(/\?\=\=\?.+?\?[QqBb]\?/m, '')
-
end
-
-
previous_encoding = encoding
-
results << line
-
end
-
-
results
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/encodings/8bit'
-
-
2
module Mail
-
2
module Encodings
-
2
class SevenBit < EightBit
-
2
NAME = '7bit'
-
-
2
PRIORITY = 1
-
-
# 7bit and 8bit operate the same
-
-
# Decode the string
-
2
def self.decode(str)
-
8
super
-
end
-
-
# Encode the string
-
2
def self.encode(str)
-
8
super
-
end
-
-
# Idenity encodings have a fixed cost, 1 byte out per 1 byte in
-
2
def self.cost(str)
-
super
-
end
-
-
2
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/encodings/binary'
-
-
2
module Mail
-
2
module Encodings
-
2
class EightBit < Binary
-
2
NAME = '8bit'
-
-
2
PRIORITY = 4
-
-
# 8bit is an identiy encoding, meaning nothing to do
-
-
# Decode the string
-
2
def self.decode(str)
-
8
str.to_lf
-
end
-
-
# Encode the string
-
2
def self.encode(str)
-
8
str.to_crlf
-
end
-
-
# Idenity encodings have a fixed cost, 1 byte out per 1 byte in
-
2
def self.cost(str)
-
1.0
-
end
-
-
2
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/encodings/7bit'
-
-
2
module Mail
-
2
module Encodings
-
2
class Base64 < SevenBit
-
2
NAME = 'base64'
-
-
2
PRIORITY = 3
-
-
2
def self.can_encode?(enc)
-
true
-
end
-
-
# Decode the string from Base64
-
2
def self.decode(str)
-
RubyVer.decode_base64( str )
-
end
-
-
# Encode the string to Base64
-
2
def self.encode(str)
-
RubyVer.encode_base64( str ).to_crlf
-
end
-
-
# Base64 has a fixed cost, 4 bytes out per 3 bytes in
-
2
def self.cost(str)
-
4.0/3
-
end
-
-
2
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/encodings/transfer_encoding'
-
-
2
module Mail
-
2
module Encodings
-
2
class Binary < TransferEncoding
-
2
NAME = 'binary'
-
-
2
PRIORITY = 5
-
-
# Binary is an identiy encoding, meaning nothing to do
-
-
# Decode the string
-
2
def self.decode(str)
-
str
-
end
-
-
# Encode the string
-
2
def self.encode(str)
-
str
-
end
-
-
# Idenity encodings have a fixed cost, 1 byte out per 1 byte in
-
2
def self.cost(str)
-
1.0
-
end
-
-
2
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/encodings/7bit'
-
-
2
module Mail
-
2
module Encodings
-
2
class QuotedPrintable < SevenBit
-
2
NAME='quoted-printable'
-
-
2
PRIORITY = 2
-
-
2
def self.can_encode?(str)
-
EightBit.can_encode? str
-
end
-
-
# Decode the string from Quoted-Printable. Cope with hard line breaks
-
# that were incorrectly encoded as hex instead of literal CRLF.
-
2
def self.decode(str)
-
str.gsub(/(?:=0D=0A|=0D|=0A)\r\n/, "\r\n").unpack("M*").first.to_lf
-
end
-
-
2
def self.encode(str)
-
[str.to_lf].pack("M").to_crlf
-
end
-
-
2
def self.cost(str)
-
# These bytes probably do not need encoding
-
c = str.count("\x9\xA\xD\x20-\x3C\x3E-\x7E")
-
# Everything else turns into =XX where XX is a
-
# two digit hex number (taking 3 bytes)
-
total = (str.bytesize - c)*3 + c
-
total.to_f/str.bytesize
-
end
-
-
2
private
-
-
2
Encodings.register(NAME, self)
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
module Encodings
-
2
class TransferEncoding
-
2
NAME = ''
-
-
2
PRIORITY = -1
-
-
2
def self.can_transport?(enc)
-
16
enc = Encodings.get_name(enc)
-
16
if Encodings.defined? enc
-
16
Encodings.get_encoding(enc).new.is_a? self
-
else
-
false
-
end
-
end
-
-
2
def self.can_encode?(enc)
-
can_transport? enc
-
end
-
-
2
def self.cost(str)
-
raise "Unimplemented"
-
end
-
-
2
def self.to_s
-
8
self::NAME
-
end
-
-
2
def self.get_best_compatible(source_encoding, str)
-
16
if self.can_transport? source_encoding then
-
16
source_encoding
-
else
-
choices = []
-
Encodings.get_all.each do |enc|
-
choices << enc if self.can_transport? enc and enc.can_encode? source_encoding
-
end
-
best = nil
-
best_cost = 100
-
choices.each do |enc|
-
this_cost = enc.cost str
-
if this_cost < best_cost then
-
best_cost = this_cost
-
best = enc
-
elsif this_cost == best_cost then
-
best = enc if enc::PRIORITY < best::PRIORITY
-
end
-
end
-
best
-
end
-
end
-
-
2
def to_s
-
self.class.to_s
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Mail Envelope
-
#
-
# The Envelope class provides a field for the first line in an
-
# mbox file, that looks like "From mikel@test.lindsaar.net DATETIME"
-
#
-
# This envelope class reads that line, and turns it into an
-
# Envelope.from and Envelope.date for your use.
-
2
module Mail
-
2
class Envelope < StructuredField
-
-
2
def initialize(*args)
-
super(FIELD_NAME, strip_field(FIELD_NAME, args.last))
-
end
-
-
2
def tree
-
@element ||= Mail::EnvelopeFromElement.new(value)
-
@tree ||= @element.tree
-
end
-
-
2
def element
-
@element ||= Mail::EnvelopeFromElement.new(value)
-
end
-
-
2
def date
-
::DateTime.parse("#{element.date_time}")
-
end
-
-
2
def from
-
element.address
-
end
-
-
end
-
end
-
2
require 'mail/fields'
-
-
# encoding: utf-8
-
2
module Mail
-
# Provides a single class to call to create a new structured or unstructured
-
# field. Works out per RFC what field of field it is being given and returns
-
# the correct field of class back on new.
-
#
-
# ===Per RFC 2822
-
#
-
# 2.2. Header Fields
-
#
-
# Header fields are lines composed of a field name, followed by a colon
-
# (":"), followed by a field body, and terminated by CRLF. A field
-
# name MUST be composed of printable US-ASCII characters (i.e.,
-
# characters that have values between 33 and 126, inclusive), except
-
# colon. A field body may be composed of any US-ASCII characters,
-
# except for CR and LF. However, a field body may contain CRLF when
-
# used in header "folding" and "unfolding" as described in section
-
# 2.2.3. All field bodies MUST conform to the syntax described in
-
# sections 3 and 4 of this standard.
-
#
-
2
class Field
-
-
2
include Patterns
-
2
include Comparable
-
-
2
STRUCTURED_FIELDS = %w[ bcc cc content-description content-disposition
-
content-id content-location content-transfer-encoding
-
content-type date from in-reply-to keywords message-id
-
mime-version received references reply-to
-
resent-bcc resent-cc resent-date resent-from
-
resent-message-id resent-sender resent-to
-
return-path sender to ]
-
-
2
KNOWN_FIELDS = STRUCTURED_FIELDS + ['comments', 'subject']
-
-
2
FIELDS_MAP = {
-
"to" => ToField,
-
"cc" => CcField,
-
"bcc" => BccField,
-
"message-id" => MessageIdField,
-
"in-reply-to" => InReplyToField,
-
"references" => ReferencesField,
-
"subject" => SubjectField,
-
"comments" => CommentsField,
-
"keywords" => KeywordsField,
-
"date" => DateField,
-
"from" => FromField,
-
"sender" => SenderField,
-
"reply-to" => ReplyToField,
-
"resent-date" => ResentDateField,
-
"resent-from" => ResentFromField,
-
"resent-sender" => ResentSenderField,
-
"resent-to" => ResentToField,
-
"resent-cc" => ResentCcField,
-
"resent-bcc" => ResentBccField,
-
"resent-message-id" => ResentMessageIdField,
-
"return-path" => ReturnPathField,
-
"received" => ReceivedField,
-
"mime-version" => MimeVersionField,
-
"content-transfer-encoding" => ContentTransferEncodingField,
-
"content-description" => ContentDescriptionField,
-
"content-disposition" => ContentDispositionField,
-
"content-type" => ContentTypeField,
-
"content-id" => ContentIdField,
-
"content-location" => ContentLocationField,
-
}
-
-
# Generic Field Exception
-
2
class FieldError < StandardError
-
end
-
-
# Raised when a parsing error has occurred (ie, a StructuredField has tried
-
# to parse a field that is invalid or improperly written)
-
2
class ParseError < FieldError #:nodoc:
-
2
attr_accessor :element, :value, :reason
-
-
2
def initialize(element, value, reason)
-
@element = element
-
@value = value
-
@reason = reason
-
super("#{element} can not parse |#{value}|\nReason was: #{reason}")
-
end
-
end
-
-
# Raised when attempting to set a structured field's contents to an invalid syntax
-
2
class SyntaxError < FieldError #:nodoc:
-
end
-
-
# Accepts a string:
-
#
-
# Field.new("field-name: field data")
-
#
-
# Or name, value pair:
-
#
-
# Field.new("field-name", "value")
-
#
-
# Or a name by itself:
-
#
-
# Field.new("field-name")
-
#
-
# Note, does not want a terminating carriage return. Returns
-
# self appropriately parsed. If value is not a string, then
-
# it will be passed through as is, for example, content-type
-
# field can accept an array with the type and a hash of
-
# parameters:
-
#
-
# Field.new('content-type', ['text', 'plain', {:charset => 'UTF-8'}])
-
2
def initialize(name, value = nil, charset = 'utf-8')
-
case
-
when name =~ /:/ # Field.new("field-name: field data")
-
charset = value unless value.blank?
-
name, value = split(name)
-
create_field(name, value, charset)
-
when name !~ /:/ && value.blank? # Field.new("field-name")
-
8
create_field(name, nil, charset)
-
else # Field.new("field-name", "value")
-
24
create_field(name, value, charset)
-
32
end
-
32
return self
-
end
-
-
2
def field=(value)
-
40
@field = value
-
end
-
-
2
def field
-
2612
@field
-
end
-
-
2
def name
-
144
field.name
-
end
-
-
2
def value
-
field.value
-
end
-
-
2
def value=(val)
-
create_field(name, val, charset)
-
end
-
-
2
def to_s
-
field.to_s
-
end
-
-
2
def update(name, value)
-
8
create_field(name, value, charset)
-
end
-
-
2
def same( other )
-
112
match_to_s(other.name, field.name)
-
end
-
-
2
alias_method :==, :same
-
-
2
def <=>( other )
-
80
self.field_order_id <=> other.field_order_id
-
end
-
-
2
def field_order_id
-
160
@field_order_id ||= (FIELD_ORDER_LOOKUP[self.name.to_s.downcase] || 100)
-
end
-
-
2
def method_missing(name, *args, &block)
-
2356
field.send(name, *args, &block)
-
end
-
-
2
FIELD_ORDER = %w[ return-path received
-
resent-date resent-from resent-sender resent-to
-
resent-cc resent-bcc resent-message-id
-
date from sender reply-to to cc bcc
-
message-id in-reply-to references
-
subject comments keywords
-
mime-version content-type content-transfer-encoding
-
content-location content-disposition content-description ]
-
-
2
FIELD_ORDER_LOOKUP = Hash[FIELD_ORDER.each_with_index.to_a]
-
-
2
private
-
-
2
def split(raw_field)
-
match_data = raw_field.mb_chars.match(FIELD_SPLIT)
-
[match_data[1].to_s.mb_chars.strip, match_data[2].to_s.mb_chars.strip]
-
rescue
-
STDERR.puts "WARNING: Could not parse (and so ignoring) '#{raw_field}'"
-
end
-
-
2
def create_field(name, value, charset)
-
40
begin
-
40
self.field = new_field(name, value, charset)
-
rescue Mail::Field::ParseError => e
-
self.field = Mail::UnstructuredField.new(name, value)
-
self.field.errors << [name, value, e]
-
self.field
-
end
-
end
-
-
2
def new_field(name, value, charset)
-
40
lower_case_name = name.to_s.downcase
-
40
if field_klass = FIELDS_MAP[lower_case_name]
-
40
field_klass.new(value, charset)
-
else
-
OptionalField.new(name, value, charset)
-
end
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
2
module Mail
-
-
# Field List class provides an enhanced array that keeps a list of
-
# email fields in order. And allows you to insert new fields without
-
# having to worry about the order they will appear in.
-
2
class FieldList < Array
-
-
2
include Enumerable
-
-
2
def <<( new_field )
-
32
current_entry = self.rindex(new_field)
-
32
if current_entry
-
self.insert((current_entry + 1), new_field)
-
else
-
32
insert_idx = -1
-
32
self.each_with_index do |item, idx|
-
80
case item <=> new_field
-
when -1
-
60
next
-
when 0
-
next
-
when 1
-
20
insert_idx = idx
-
20
break
-
end
-
end
-
32
insert(insert_idx, new_field)
-
end
-
end
-
-
end
-
end
-
2
module Mail
-
2
register_autoload :UnstructuredField, 'mail/fields/unstructured_field'
-
2
register_autoload :StructuredField, 'mail/fields/structured_field'
-
2
register_autoload :OptionalField, 'mail/fields/optional_field'
-
-
2
register_autoload :BccField, 'mail/fields/bcc_field'
-
2
register_autoload :CcField, 'mail/fields/cc_field'
-
2
register_autoload :CommentsField, 'mail/fields/comments_field'
-
2
register_autoload :ContentDescriptionField, 'mail/fields/content_description_field'
-
2
register_autoload :ContentDispositionField, 'mail/fields/content_disposition_field'
-
2
register_autoload :ContentIdField, 'mail/fields/content_id_field'
-
2
register_autoload :ContentLocationField, 'mail/fields/content_location_field'
-
2
register_autoload :ContentTransferEncodingField, 'mail/fields/content_transfer_encoding_field'
-
2
register_autoload :ContentTypeField, 'mail/fields/content_type_field'
-
2
register_autoload :DateField, 'mail/fields/date_field'
-
2
register_autoload :FromField, 'mail/fields/from_field'
-
2
register_autoload :InReplyToField, 'mail/fields/in_reply_to_field'
-
2
register_autoload :KeywordsField, 'mail/fields/keywords_field'
-
2
register_autoload :MessageIdField, 'mail/fields/message_id_field'
-
2
register_autoload :MimeVersionField, 'mail/fields/mime_version_field'
-
2
register_autoload :ReceivedField, 'mail/fields/received_field'
-
2
register_autoload :ReferencesField, 'mail/fields/references_field'
-
2
register_autoload :ReplyToField, 'mail/fields/reply_to_field'
-
2
register_autoload :ResentBccField, 'mail/fields/resent_bcc_field'
-
2
register_autoload :ResentCcField, 'mail/fields/resent_cc_field'
-
2
register_autoload :ResentDateField, 'mail/fields/resent_date_field'
-
2
register_autoload :ResentFromField, 'mail/fields/resent_from_field'
-
2
register_autoload :ResentMessageIdField, 'mail/fields/resent_message_id_field'
-
2
register_autoload :ResentSenderField, 'mail/fields/resent_sender_field'
-
2
register_autoload :ResentToField, 'mail/fields/resent_to_field'
-
2
register_autoload :ReturnPathField, 'mail/fields/return_path_field'
-
2
register_autoload :SenderField, 'mail/fields/sender_field'
-
2
register_autoload :SubjectField, 'mail/fields/subject_field'
-
2
register_autoload :ToField, 'mail/fields/to_field'
-
end
-
# encoding: utf-8
-
#
-
# = Blind Carbon Copy Field
-
#
-
# The Bcc field inherits from StructuredField and handles the Bcc: header
-
# field in the email.
-
#
-
# Sending bcc to a mail message will instantiate a Mail::Field object that
-
# has a BccField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Bcc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.bcc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:bcc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::BccField:0x180e1c4
-
# mail['bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::BccField:0x180e1c4
-
# mail['Bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::BccField:0x180e1c4
-
#
-
# mail[:bcc].encoded #=> '' # Bcc field does not get output into an email
-
# mail[:bcc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:bcc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:bcc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class BccField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'bcc'
-
2
CAPITALIZED_FIELD = 'Bcc'
-
-
2
def initialize(value = '', charset = 'utf-8')
-
@charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
# Bcc field should never be :encoded
-
2
def encoded
-
''
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Carbon Copy Field
-
#
-
# The Cc field inherits from StructuredField and handles the Cc: header
-
# field in the email.
-
#
-
# Sending cc to a mail message will instantiate a Mail::Field object that
-
# has a CcField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Cc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.cc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:cc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CcField:0x180e1c4
-
# mail['cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CcField:0x180e1c4
-
# mail['Cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CcField:0x180e1c4
-
#
-
# mail[:cc].encoded #=> 'Cc: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:cc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:cc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:cc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class CcField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'cc'
-
2
CAPITALIZED_FIELD = 'Cc'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Comments Field
-
#
-
# The Comments field inherits from UnstructuredField and handles the Comments:
-
# header field in the email.
-
#
-
# Sending comments to a mail message will instantiate a Mail::Field object that
-
# has a CommentsField as its field type.
-
#
-
# An email header can have as many comments fields as it wants. There is no upper
-
# limit, the comments field is also optional (that is, no comment is needed)
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.comments = 'This is a comment'
-
# mail.comments #=> 'This is a comment'
-
# mail[:comments] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CommentsField:0x180e1c4
-
# mail['comments'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CommentsField:0x180e1c4
-
# mail['comments'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::CommentsField:0x180e1c4
-
#
-
# mail.comments = "This is another comment"
-
# mail[:comments].map { |c| c.to_s }
-
# #=> ['This is a comment', "This is another comment"]
-
#
-
2
module Mail
-
2
class CommentsField < UnstructuredField
-
-
2
FIELD_NAME = 'comments'
-
2
CAPITALIZED_FIELD = 'Comments'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
@charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value))
-
self.parse
-
self
-
end
-
-
end
-
end
-
2
module Mail
-
-
2
class AddressContainer < Array
-
-
2
def initialize(field, list = [])
-
40
@field = field
-
40
super(list)
-
end
-
-
2
def << (address)
-
@field << address
-
end
-
-
end
-
-
end
-
# encoding: utf-8
-
2
require 'mail/fields/common/address_container'
-
-
2
module Mail
-
2
module CommonAddress # :nodoc:
-
-
2
def parse(val = value)
-
16
unless val.blank?
-
16
@tree = AddressList.new(encode_if_needed(val))
-
else
-
nil
-
end
-
end
-
-
2
def charset
-
16
@charset
-
end
-
-
2
def encode_if_needed(val)
-
16
Encodings.address_encode(val, charset)
-
end
-
-
# Allows you to iterate through each address object in the syntax tree
-
2
def each
-
tree.addresses.each do |address|
-
yield(address)
-
end
-
end
-
-
# Returns the address string of all the addresses in the address list
-
2
def addresses
-
80
list = tree.addresses.map { |a| a.address }
-
40
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns the formatted string of all the addresses in the address list
-
2
def formatted
-
list = tree.addresses.map { |a| a.format }
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns the display name of all the addresses in the address list
-
2
def display_names
-
list = tree.addresses.map { |a| a.display_name }
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns the actual address objects in the address list
-
2
def addrs
-
list = tree.addresses
-
Mail::AddressContainer.new(self, list)
-
end
-
-
# Returns a hash of group name => address strings for the address list
-
2
def groups
-
32
@groups = Hash.new
-
32
tree.group_recipients.each do |group|
-
@groups[group.group_name.text_value.to_str] = get_group_addresses(group.group_list)
-
end
-
32
@groups
-
end
-
-
# Returns the addresses that are part of groups
-
2
def group_addresses
-
decoded_group_addresses
-
end
-
-
# Returns a list of decoded group addresses
-
2
def decoded_group_addresses
-
groups.map { |k,v| v.map { |a| a.decoded } }.flatten
-
end
-
-
# Returns a list of encoded group addresses
-
2
def encoded_group_addresses
-
16
groups.map { |k,v| v.map { |a| a.encoded } }.flatten
-
end
-
-
# Returns the name of all the groups in a string
-
2
def group_names # :nodoc:
-
tree.group_names
-
end
-
-
2
def default
-
40
addresses
-
end
-
-
2
def <<(val)
-
case
-
when val.nil?
-
raise ArgumentError, "Need to pass an address to <<"
-
when val.blank?
-
parse(encoded)
-
else
-
self.value = [self.value, val].reject {|a| a.blank? }.join(", ")
-
end
-
end
-
-
2
def value=(val)
-
8
super
-
8
parse(self.value)
-
end
-
-
2
private
-
-
2
def do_encode(field_name)
-
16
return '' if value.blank?
-
48
address_array = tree.addresses.reject { |a| encoded_group_addresses.include?(a.encoded) }.compact.map { |a| a.encoded }
-
16
address_text = address_array.join(", \r\n\s")
-
16
group_array = groups.map { |k,v| "#{k}: #{v.map { |a| a.encoded }.join(", \r\n\s")};" }
-
16
group_text = group_array.join(" \r\n\s")
-
48
return_array = [address_text, group_text].reject { |a| a.blank? }
-
16
"#{field_name}: #{return_array.join(", \r\n\s")}\r\n"
-
end
-
-
2
def do_decode
-
return nil if value.blank?
-
address_array = tree.addresses.reject { |a| decoded_group_addresses.include?(a.decoded) }.map { |a| a.decoded }
-
address_text = address_array.join(", ")
-
group_array = groups.map { |k,v| "#{k}: #{v.map { |a| a.decoded }.join(", ")};" }
-
group_text = group_array.join(" ")
-
return_array = [address_text, group_text].reject { |a| a.blank? }
-
return_array.join(", ")
-
end
-
-
# Returns the syntax tree of the Addresses
-
2
def tree # :nodoc:
-
88
@tree ||= AddressList.new(value)
-
end
-
-
2
def get_group_addresses(group_list)
-
if group_list.respond_to?(:addresses)
-
group_list.addresses.map do |address_tree|
-
Mail::Address.new(address_tree)
-
end
-
else
-
[]
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
module CommonDate # :nodoc:
-
# Returns a date time object of the parsed date
-
2
def date_time
-
::DateTime.parse("#{element.date_string} #{element.time_string}")
-
end
-
-
2
def default
-
date_time
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::DateTimeElement.new(val)
-
@tree = @element.tree
-
else
-
nil
-
end
-
end
-
-
2
private
-
-
2
def do_encode(field_name)
-
8
"#{field_name}: #{value}\r\n"
-
end
-
-
2
def do_decode
-
"#{value}"
-
end
-
-
2
def element
-
@element ||= Mail::DateTimeElement.new(value)
-
end
-
-
# Returns the syntax tree of the Date
-
2
def tree
-
@tree ||= element.tree
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
module CommonField # :nodoc:
-
-
2
def name=(value)
-
40
@name = value
-
end
-
-
2
def name
-
2112
@name ||= nil
-
end
-
-
2
def value=(value)
-
48
@length = nil
-
48
@tree = nil
-
48
@element = nil
-
48
@value = value
-
end
-
-
2
def value
-
120
@value
-
end
-
-
2
def to_s
-
decoded.to_s
-
end
-
-
2
def default
-
decoded
-
end
-
-
2
def field_length
-
@length ||= "#{name}: #{encode(decoded)}".length
-
end
-
-
2
def responsible_for?( val )
-
2040
name.to_s.casecmp(val.to_s) == 0
-
end
-
-
2
private
-
-
2
def strip_field(field_name, value)
-
32
if value.is_a?(Array)
-
value
-
else
-
32
value.to_s.gsub(/#{field_name}:\s+/i, '')
-
end
-
end
-
-
2
FILENAME_RE = /\b(filename|name)=([^;"\r\n]+\s[^;"\r\n]+)/
-
2
def ensure_filename_quoted(value)
-
8
if value.is_a?(String)
-
8
value.sub! FILENAME_RE, '\1="\2"'
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
module CommonMessageId # :nodoc:
-
2
def element
-
32
@element ||= Mail::MessageIdsElement.new(value) unless value.blank?
-
end
-
-
2
def parse(val = value)
-
4
unless val.blank?
-
4
@element = Mail::MessageIdsElement.new(val)
-
else
-
nil
-
end
-
end
-
-
2
def message_id
-
16
element.message_id if element
-
end
-
-
2
def message_ids
-
element.message_ids if element
-
end
-
-
2
def default
-
return nil unless message_ids
-
if message_ids.length == 1
-
message_ids[0]
-
else
-
message_ids
-
end
-
end
-
-
2
private
-
-
2
def do_encode(field_name)
-
8
%Q{#{field_name}: #{formated_message_ids("\r\n ")}\r\n}
-
end
-
-
2
def do_decode
-
formated_message_ids(' ')
-
end
-
-
2
def formated_message_ids(join)
-
16
message_ids.map{ |m| "<#{m}>" }.join(join) if message_ids
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
-
# ParameterHash is an intelligent Hash that allows you to add
-
# parameter values including the MIME extension paramaters that
-
# have the name*0="blah", name*1="bleh" keys, and will just return
-
# a single key called name="blahbleh" and do any required un-encoding
-
# to make that happen
-
# Parameters are defined in RFC2045, split keys are in RFC2231
-
-
2
class ParameterHash < IndifferentHash
-
-
2
include Mail::Utilities
-
-
2
def [](key_name)
-
16
key_pattern = Regexp.escape(key_name.to_s)
-
16
pairs = []
-
16
exact = nil
-
16
each do |k,v|
-
8
if k =~ /^#{key_pattern}(\*|$)/i
-
8
if $1 == '*'
-
pairs << [k, v]
-
else
-
8
exact = k
-
end
-
end
-
end
-
16
if pairs.empty? # Just dealing with a single value pair
-
16
super(exact || key_name)
-
else # Dealing with a multiple value pair or a single encoded value pair
-
string = pairs.sort { |a,b| a.first.to_s <=> b.first.to_s }.map { |v| v.last }.join('')
-
if mt = string.match(/([\w\-]+)'(\w\w)'(.*)/)
-
string = mt[3]
-
encoding = mt[1]
-
else
-
encoding = nil
-
end
-
Mail::Encodings.param_decode(string, encoding)
-
end
-
end
-
-
2
def encoded
-
8
map.sort { |a,b| a.first.to_s <=> b.first.to_s }.map do |key_name, value|
-
8
unless value.ascii_only?
-
value = Mail::Encodings.param_encode(value)
-
key_name = "#{key_name}*"
-
end
-
8
%Q{#{key_name}=#{quote_token(value)}}
-
end.join(";\r\n\s")
-
end
-
-
2
def decoded
-
map.sort { |a,b| a.first.to_s <=> b.first.to_s }.map do |key_name, value|
-
%Q{#{key_name}=#{quote_token(value)}}
-
end.join("; ")
-
end
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
2
module Mail
-
2
class ContentDescriptionField < UnstructuredField
-
-
2
FIELD_NAME = 'content-description'
-
2
CAPITALIZED_FIELD = 'Content-Description'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/fields/common/parameter_hash'
-
-
2
module Mail
-
2
class ContentDispositionField < StructuredField
-
-
2
FIELD_NAME = 'content-disposition'
-
2
CAPITALIZED_FIELD = 'Content-Disposition'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
ensure_filename_quoted(value)
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::ContentDispositionElement.new(val)
-
end
-
end
-
-
2
def element
-
@element ||= Mail::ContentDispositionElement.new(value)
-
end
-
-
2
def disposition_type
-
element.disposition_type
-
end
-
-
2
def parameters
-
@parameters = ParameterHash.new
-
element.parameters.each { |p| @parameters.merge!(p) }
-
@parameters
-
end
-
-
2
def filename
-
case
-
when !parameters['filename'].blank?
-
@filename = parameters['filename']
-
when !parameters['name'].blank?
-
@filename = parameters['name']
-
else
-
@filename = nil
-
end
-
@filename
-
end
-
-
# TODO: Fix this up
-
2
def encoded
-
if parameters.length > 0
-
p = ";\r\n\s#{parameters.encoded}\r\n"
-
else
-
p = "\r\n"
-
end
-
"#{CAPITALIZED_FIELD}: #{disposition_type}" + p
-
end
-
-
2
def decoded
-
if parameters.length > 0
-
p = "; #{parameters.decoded}"
-
else
-
p = ""
-
end
-
"#{disposition_type}" + p
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
2
module Mail
-
2
class ContentIdField < StructuredField
-
-
2
FIELD_NAME = 'content-id'
-
2
CAPITALIZED_FIELD = "Content-ID"
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
@uniq = 1
-
if value.blank?
-
value = generate_content_id
-
else
-
value = strip_field(FIELD_NAME, value)
-
end
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::MessageIdsElement.new(val)
-
end
-
end
-
-
2
def element
-
@element ||= Mail::MessageIdsElement.new(value)
-
end
-
-
2
def name
-
'Content-ID'
-
end
-
-
2
def content_id
-
element.message_id
-
end
-
-
2
def to_s
-
"<#{content_id}>"
-
end
-
-
# TODO: Fix this up
-
2
def encoded
-
"#{CAPITALIZED_FIELD}: #{to_s}\r\n"
-
end
-
-
2
def decoded
-
"#{to_s}"
-
end
-
-
2
private
-
-
2
def generate_content_id
-
"<#{Mail.random_tag}@#{::Socket.gethostname}.mail>"
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
2
module Mail
-
2
class ContentLocationField < StructuredField
-
-
2
FIELD_NAME = 'content-location'
-
2
CAPITALIZED_FIELD = 'Content-Location'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::ContentLocationElement.new(val)
-
end
-
end
-
-
2
def element
-
@element ||= Mail::ContentLocationElement.new(value)
-
end
-
-
2
def location
-
element.location
-
end
-
-
# TODO: Fix this up
-
2
def encoded
-
"#{CAPITALIZED_FIELD}: #{location}\r\n"
-
end
-
-
2
def decoded
-
location
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
2
module Mail
-
2
class ContentTransferEncodingField < StructuredField
-
-
2
FIELD_NAME = 'content-transfer-encoding'
-
2
CAPITALIZED_FIELD = 'Content-Transfer-Encoding'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
8
self.charset = charset
-
8
value = '7bit' if value.to_s =~ /7-?bits?/i
-
8
value = '8bit' if value.to_s =~ /8-?bits?/i
-
8
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
8
self.parse
-
8
self
-
end
-
-
2
def parse(val = value)
-
8
unless val.blank?
-
8
@element = Mail::ContentTransferEncodingElement.new(val)
-
end
-
end
-
-
2
def tree
-
STDERR.puts("tree is deprecated. Please use encoding to get parse result\n#{caller}")
-
@element ||= Mail::ContentTransferEncodingElement.new(value)
-
@tree ||= @element.tree
-
end
-
-
2
def element
-
16
@element ||= Mail::ContentTransferEncodingElement.new(value)
-
end
-
-
2
def encoding
-
16
element.encoding
-
end
-
-
# TODO: Fix this up
-
2
def encoded
-
8
"#{CAPITALIZED_FIELD}: #{encoding}\r\n"
-
end
-
-
2
def decoded
-
8
encoding
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/fields/common/parameter_hash'
-
-
2
module Mail
-
2
class ContentTypeField < StructuredField
-
-
2
FIELD_NAME = 'content-type'
-
2
CAPITALIZED_FIELD = 'Content-Type'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
8
self.charset = charset
-
8
if value.class == Array
-
@main_type = value[0]
-
@sub_type = value[1]
-
@parameters = ParameterHash.new.merge!(value.last)
-
else
-
8
@main_type = nil
-
8
@sub_type = nil
-
8
@parameters = nil
-
8
value = strip_field(FIELD_NAME, value)
-
end
-
8
ensure_filename_quoted(value)
-
8
super(CAPITALIZED_FIELD, value, charset)
-
8
self.parse
-
8
self
-
end
-
-
2
def parse(val = value)
-
8
unless val.blank?
-
8
self.value = val
-
8
@element = nil
-
8
element
-
end
-
end
-
-
2
def element
-
32
begin
-
32
@element ||= Mail::ContentTypeElement.new(value)
-
rescue
-
attempt_to_clean
-
end
-
end
-
-
2
def attempt_to_clean
-
# Sanitize the value, handle special cases
-
@element ||= Mail::ContentTypeElement.new(sanatize(value))
-
rescue
-
# All else fails, just get the MIME media type
-
@element ||= Mail::ContentTypeElement.new(get_mime_type(value))
-
end
-
-
2
def main_type
-
56
@main_type ||= element.main_type
-
end
-
-
2
def sub_type
-
12
@sub_type ||= element.sub_type
-
end
-
-
2
def string
-
12
"#{main_type}/#{sub_type}"
-
end
-
-
2
def default
-
4
decoded
-
end
-
-
2
alias :content_type :string
-
-
2
def parameters
-
44
unless @parameters
-
8
@parameters = ParameterHash.new
-
8
element.parameters.each { |p| @parameters.merge!(p) }
-
end
-
44
@parameters
-
end
-
-
2
def ContentTypeField.with_boundary(type)
-
new("#{type}; boundary=#{generate_boundary}")
-
end
-
-
2
def ContentTypeField.generate_boundary
-
"--==_mimepart_#{Mail.random_tag}"
-
end
-
-
2
def value
-
16
if @value.class == Array
-
"#{@main_type}/#{@sub_type}; #{stringify(parameters)}"
-
else
-
16
@value
-
end
-
end
-
-
2
def stringify(params)
-
params.map { |k,v| "#{k}=#{Encodings.param_encode(v)}" }.join("; ")
-
end
-
-
2
def filename
-
case
-
when parameters['filename']
-
@filename = parameters['filename']
-
when parameters['name']
-
@filename = parameters['name']
-
else
-
@filename = nil
-
end
-
@filename
-
end
-
-
# TODO: Fix this up
-
2
def encoded
-
8
if parameters.length > 0
-
8
p = ";\r\n\s#{parameters.encoded}"
-
else
-
p = ""
-
end
-
8
"#{CAPITALIZED_FIELD}: #{content_type}#{p}\r\n"
-
end
-
-
2
def decoded
-
4
if parameters.length > 0
-
p = "; #{parameters.decoded}"
-
else
-
4
p = ""
-
end
-
4
"#{content_type}" + p
-
end
-
-
2
private
-
-
2
def method_missing(name, *args, &block)
-
if name.to_s =~ /(\w+)=/
-
self.parameters[$1] = args.first
-
@value = "#{content_type}; #{stringify(parameters)}"
-
else
-
super
-
end
-
end
-
-
# Various special cases from random emails found that I am not going to change
-
# the parser for
-
2
def sanatize( val )
-
-
# TODO: check if there are cases where whitespace is not a separator
-
val = val.
-
gsub(/\s*=\s*/,'='). # remove whitespaces around equal sign
-
tr(' ',';').
-
squeeze(';').
-
gsub(';', '; '). #use '; ' as a separator (or EOL)
-
gsub(/;\s*$/,'') #remove trailing to keep examples below
-
-
if val =~ /(boundary=(\S*))/i
-
val = "#{$`.downcase}boundary=#{$2}#{$'.downcase}"
-
else
-
val.downcase!
-
end
-
-
case
-
when val.chomp =~ /^\s*([\w\-]+)\/([\w\-]+)\s*;;+(.*)$/i
-
# Handles 'text/plain;; format="flowed"' (double semi colon)
-
"#{$1}/#{$2}; #{$3}"
-
when val.chomp =~ /^\s*([\w\-]+)\/([\w\-]+)\s*;\s?(ISO[\w\-]+)$/i
-
# Microsoft helper:
-
# Handles 'type/subtype;ISO-8559-1'
-
"#{$1}/#{$2}; charset=#{quote_atom($3)}"
-
when val.chomp =~ /^text;?$/i
-
# Handles 'text;' and 'text'
-
"text/plain;"
-
when val.chomp =~ /^(\w+);\s(.*)$/i
-
# Handles 'text; <parameters>'
-
"text/plain; #{$2}"
-
when val =~ /([\w\-]+\/[\w\-]+);\scharset="charset="(\w+)""/i
-
# Handles text/html; charset="charset="GB2312""
-
"#{$1}; charset=#{quote_atom($2)}"
-
when val =~ /([\w\-]+\/[\w\-]+);\s+(.*)/i
-
type = $1
-
# Handles misquoted param values
-
# e.g: application/octet-stream; name=archiveshelp1[1].htm
-
# and: audio/x-midi;\r\n\sname=Part .exe
-
params = $2.to_s.split(/\s+/)
-
params = params.map { |i| i.to_s.chomp.strip }
-
params = params.map { |i| i.split(/\s*\=\s*/) }
-
params = params.map { |i| "#{i[0]}=#{dquote(i[1].to_s.gsub(/;$/,""))}" }.join('; ')
-
"#{type}; #{params}"
-
when val =~ /^\s*$/
-
'text/plain'
-
else
-
''
-
end
-
end
-
-
2
def get_mime_type( val )
-
case
-
when val =~ /^([\w\-]+)\/([\w\-]+);.+$/i
-
"#{$1}/#{$2}"
-
else
-
'text/plain'
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Date Field
-
#
-
# The Date field inherits from StructuredField and handles the Date: header
-
# field in the email.
-
#
-
# Sending date to a mail message will instantiate a Mail::Field object that
-
# has a DateField as its field type. This includes all Mail::CommonAddress
-
# module instance methods.
-
#
-
# There must be excatly one Date field in an RFC2822 email.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.date = 'Mon, 24 Nov 1997 14:22:01 -0800'
-
# mail.date #=> #<DateTime: 211747170121/86400,-1/3,2299161>
-
# mail.date.to_s #=> 'Mon, 24 Nov 1997 14:22:01 -0800'
-
# mail[:date] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::DateField:0x180e1c4
-
# mail['date'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::DateField:0x180e1c4
-
# mail['Date'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::DateField:0x180e1c4
-
#
-
2
require 'mail/fields/common/common_date'
-
-
2
module Mail
-
2
class DateField < StructuredField
-
-
2
include Mail::CommonDate
-
-
2
FIELD_NAME = 'date'
-
2
CAPITALIZED_FIELD = "Date"
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
4
self.charset = charset
-
4
if value.blank?
-
4
value = ::DateTime.now.strftime('%a, %d %b %Y %H:%M:%S %z')
-
else
-
value = strip_field(FIELD_NAME, value)
-
value.to_s.gsub!(/\(.*?\)/, '')
-
value = ::DateTime.parse(value.to_s.squeeze(" ")).strftime('%a, %d %b %Y %H:%M:%S %z')
-
end
-
4
super(CAPITALIZED_FIELD, value, charset)
-
rescue ArgumentError => e
-
raise e unless "invalid date"==e.message
-
end
-
-
2
def encoded
-
8
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = From Field
-
#
-
# The From field inherits from StructuredField and handles the From: header
-
# field in the email.
-
#
-
# Sending from to a mail message will instantiate a Mail::Field object that
-
# has a FromField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one From field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.from = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:from] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::FromField:0x180e1c4
-
# mail['from'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::FromField:0x180e1c4
-
# mail['From'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::FromField:0x180e1c4
-
#
-
# mail[:from].encoded #=> 'from: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:from].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:from].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:from].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class FromField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'from'
-
2
CAPITALIZED_FIELD = 'From'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
4
self.charset = charset
-
4
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
4
self.parse
-
4
self
-
end
-
-
2
def encoded
-
8
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = In-Reply-To Field
-
#
-
# The In-Reply-To field inherits from StructuredField and handles the
-
# In-Reply-To: header field in the email.
-
#
-
# Sending in_reply_to to a mail message will instantiate a Mail::Field object that
-
# has a InReplyToField as its field type. This includes all Mail::CommonMessageId
-
# module instance metods.
-
#
-
# Note that, the #message_ids method will return an array of message IDs without the
-
# enclosing angle brackets which per RFC are not syntactically part of the message id.
-
#
-
# Only one InReplyTo field can appear in a header, though it can have multiple
-
# Message IDs.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.in_reply_to = '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail.in_reply_to #=> '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail[:in_reply_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
-
# mail['in_reply_to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
-
# mail['In-Reply-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::InReplyToField:0x180e1c4
-
#
-
# mail[:in_reply_to].message_ids #=> ['F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom']
-
#
-
2
require 'mail/fields/common/common_message_id'
-
-
2
module Mail
-
2
class InReplyToField < StructuredField
-
-
2
include Mail::CommonMessageId
-
-
2
FIELD_NAME = 'in-reply-to'
-
2
CAPITALIZED_FIELD = 'In-Reply-To'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
value = value.join("\r\n\s") if value.is_a?(Array)
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# keywords = "Keywords:" phrase *("," phrase) CRLF
-
2
module Mail
-
2
class KeywordsField < StructuredField
-
-
2
FIELD_NAME = 'keywords'
-
2
CAPITALIZED_FIELD = 'Keywords'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@phrase_list ||= PhraseList.new(value)
-
end
-
end
-
-
2
def phrase_list
-
@phrase_list ||= PhraseList.new(value)
-
end
-
-
2
def keywords
-
phrase_list.phrases
-
end
-
-
2
def encoded
-
"#{CAPITALIZED_FIELD}: #{keywords.join(",\r\n ")}\r\n"
-
end
-
-
2
def decoded
-
keywords.join(', ')
-
end
-
-
2
def default
-
keywords
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Message-ID Field
-
#
-
# The Message-ID field inherits from StructuredField and handles the
-
# Message-ID: header field in the email.
-
#
-
# Sending message_id to a mail message will instantiate a Mail::Field object that
-
# has a MessageIdField as its field type. This includes all Mail::CommonMessageId
-
# module instance metods.
-
#
-
# Only one MessageId field can appear in a header, and syntactically it can only have
-
# one Message ID. The message_ids method call has been left in however as it will only
-
# return the one message id, ie, an array of length 1.
-
#
-
# Note that, the #message_ids method will return an array of message IDs without the
-
# enclosing angle brackets which per RFC are not syntactically part of the message id.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.message_id = '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail.message_id #=> '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail[:message_id] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
-
# mail['message_id'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
-
# mail['Message-ID'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
-
#
-
# mail[:message_id].message_id #=> 'F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom'
-
# mail[:message_id].message_ids #=> ['F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom']
-
#
-
2
require 'mail/fields/common/common_message_id'
-
-
2
module Mail
-
2
class MessageIdField < StructuredField
-
-
2
include Mail::CommonMessageId
-
-
2
FIELD_NAME = 'message-id'
-
2
CAPITALIZED_FIELD = 'Message-ID'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
4
self.charset = charset
-
4
@uniq = 1
-
4
if value.blank?
-
4
self.name = CAPITALIZED_FIELD
-
4
self.value = generate_message_id
-
else
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
end
-
4
self.parse
-
4
self
-
-
end
-
-
2
def name
-
200
'Message-ID'
-
end
-
-
2
def message_ids
-
16
[message_id]
-
end
-
-
2
def to_s
-
"<#{message_id}>"
-
end
-
-
2
def encoded
-
8
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
2
private
-
-
2
def generate_message_id
-
4
"<#{Mail.random_tag}@#{::Socket.gethostname}.mail>"
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
#
-
#
-
2
module Mail
-
2
class MimeVersionField < StructuredField
-
-
2
FIELD_NAME = 'mime-version'
-
2
CAPITALIZED_FIELD = 'Mime-Version'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
4
self.charset = charset
-
4
if value.blank?
-
value = '1.0'
-
end
-
4
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
4
self.parse
-
4
self
-
-
end
-
-
2
def parse(val = value)
-
4
unless val.blank?
-
4
@element = Mail::MimeVersionElement.new(val)
-
end
-
end
-
-
2
def element
-
16
@element ||= Mail::MimeVersionElement.new(value)
-
end
-
-
2
def version
-
8
"#{element.major}.#{element.minor}"
-
end
-
-
2
def major
-
element.major.to_i
-
end
-
-
2
def minor
-
element.minor.to_i
-
end
-
-
2
def encoded
-
8
"#{CAPITALIZED_FIELD}: #{version}\r\n"
-
end
-
-
2
def decoded
-
version
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# trace = [return]
-
# 1*received
-
#
-
# return = "Return-Path:" path CRLF
-
#
-
# path = ([CFWS] "<" ([CFWS] / addr-spec) ">" [CFWS]) /
-
# obs-path
-
#
-
# received = "Received:" name-val-list ";" date-time CRLF
-
#
-
# name-val-list = [CFWS] [name-val-pair *(CFWS name-val-pair)]
-
#
-
# name-val-pair = item-name CFWS item-value
-
#
-
# item-name = ALPHA *(["-"] (ALPHA / DIGIT))
-
#
-
# item-value = 1*angle-addr / addr-spec /
-
# atom / domain / msg-id
-
#
-
2
module Mail
-
2
class ReceivedField < StructuredField
-
-
2
FIELD_NAME = 'received'
-
2
CAPITALIZED_FIELD = 'Received'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
-
end
-
-
2
def parse(val = value)
-
unless val.blank?
-
@element = Mail::ReceivedElement.new(val)
-
end
-
end
-
-
2
def element
-
@element ||= Mail::ReceivedElement.new(value)
-
end
-
-
2
def date_time
-
@datetime ||= ::DateTime.parse("#{element.date_time}")
-
end
-
-
2
def info
-
element.info
-
end
-
-
2
def formatted_date
-
date_time.strftime("%a, %d %b %Y %H:%M:%S ") + date_time.zone.delete(':')
-
end
-
-
2
def encoded
-
if value.blank?
-
"#{CAPITALIZED_FIELD}: \r\n"
-
else
-
"#{CAPITALIZED_FIELD}: #{info}; #{formatted_date}\r\n"
-
end
-
end
-
-
2
def decoded
-
if value.blank?
-
""
-
else
-
"#{info}; #{formatted_date}"
-
end
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = References Field
-
#
-
# The References field inherits references StructuredField and handles the References: header
-
# field in the email.
-
#
-
# Sending references to a mail message will instantiate a Mail::Field object that
-
# has a ReferencesField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Note that, the #message_ids method will return an array of message IDs without the
-
# enclosing angle brackets which per RFC are not syntactically part of the message id.
-
#
-
# Only one References field can appear in a header, though it can have multiple
-
# Message IDs.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.references = '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail.references #=> '<F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom>'
-
# mail[:references] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReferencesField:0x180e1c4
-
# mail['references'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReferencesField:0x180e1c4
-
# mail['References'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReferencesField:0x180e1c4
-
#
-
# mail[:references].message_ids #=> ['F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13@test.me.dom']
-
#
-
2
require 'mail/fields/common/common_message_id'
-
-
2
module Mail
-
2
class ReferencesField < StructuredField
-
-
2
include CommonMessageId
-
-
2
FIELD_NAME = 'references'
-
2
CAPITALIZED_FIELD = 'References'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
value = value.join("\r\n\s") if value.is_a?(Array)
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Reply-To Field
-
#
-
# The Reply-To field inherits reply-to StructuredField and handles the Reply-To: header
-
# field in the email.
-
#
-
# Sending reply_to to a mail message will instantiate a Mail::Field object that
-
# has a ReplyToField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Reply-To field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.reply_to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:reply_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
-
# mail['reply-to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
-
# mail['Reply-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ReplyToField:0x180e1c4
-
#
-
# mail[:reply_to].encoded #=> 'Reply-To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:reply_to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:reply_to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:reply_to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ReplyToField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'reply-to'
-
2
CAPITALIZED_FIELD = 'Reply-To'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-Bcc Field
-
#
-
# The Resent-Bcc field inherits resent-bcc StructuredField and handles the
-
# Resent-Bcc: header field in the email.
-
#
-
# Sending resent_bcc to a mail message will instantiate a Mail::Field object that
-
# has a ResentBccField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-Bcc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_bcc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_bcc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentBccField:0x180e1c4
-
# mail['resent-bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentBccField:0x180e1c4
-
# mail['Resent-Bcc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentBccField:0x180e1c4
-
#
-
# mail[:resent_bcc].encoded #=> 'Resent-Bcc: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_bcc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_bcc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_bcc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ResentBccField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'resent-bcc'
-
2
CAPITALIZED_FIELD = 'Resent-Bcc'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-Cc Field
-
#
-
# The Resent-Cc field inherits resent-cc StructuredField and handles the Resent-Cc: header
-
# field in the email.
-
#
-
# Sending resent_cc to a mail message will instantiate a Mail::Field object that
-
# has a ResentCcField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-Cc field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_cc = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_cc] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentCcField:0x180e1c4
-
# mail['resent-cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentCcField:0x180e1c4
-
# mail['Resent-Cc'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentCcField:0x180e1c4
-
#
-
# mail[:resent_cc].encoded #=> 'Resent-Cc: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_cc].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_cc].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_cc].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ResentCcField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'resent-cc'
-
2
CAPITALIZED_FIELD = 'Resent-Cc'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# resent-date = "Resent-Date:" date-time CRLF
-
2
require 'mail/fields/common/common_date'
-
-
2
module Mail
-
2
class ResentDateField < StructuredField
-
-
2
include Mail::CommonDate
-
-
2
FIELD_NAME = 'resent-date'
-
2
CAPITALIZED_FIELD = 'Resent-Date'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
if value.blank?
-
value = ::DateTime.now.strftime('%a, %d %b %Y %H:%M:%S %z')
-
else
-
value = strip_field(FIELD_NAME, value)
-
value = ::DateTime.parse(value.to_s).strftime('%a, %d %b %Y %H:%M:%S %z')
-
end
-
super(CAPITALIZED_FIELD, value, charset)
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-From Field
-
#
-
# The Resent-From field inherits resent-from StructuredField and handles the Resent-From: header
-
# field in the email.
-
#
-
# Sending resent_from to a mail message will instantiate a Mail::Field object that
-
# has a ResentFromField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-From field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_from = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_from] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4
-
# mail['resent-from'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4
-
# mail['Resent-From'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentFromField:0x180e1c4
-
#
-
# mail[:resent_from].encoded #=> 'Resent-From: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_from].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_from].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_from].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ResentFromField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'resent-from'
-
2
CAPITALIZED_FIELD = 'Resent-From'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# resent-msg-id = "Resent-Message-ID:" msg-id CRLF
-
2
require 'mail/fields/common/common_message_id'
-
-
2
module Mail
-
2
class ResentMessageIdField < StructuredField
-
-
2
include CommonMessageId
-
-
2
FIELD_NAME = 'resent-message-id'
-
2
CAPITALIZED_FIELD = 'Resent-Message-ID'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def name
-
'Resent-Message-ID'
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-Sender Field
-
#
-
# The Resent-Sender field inherits resent-sender StructuredField and handles the Resent-Sender: header
-
# field in the email.
-
#
-
# Sending resent_sender to a mail message will instantiate a Mail::Field object that
-
# has a ResentSenderField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-Sender field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_sender = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_sender #=> ['mikel@test.lindsaar.net']
-
# mail[:resent_sender] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentSenderField:0x180e1c4
-
# mail['resent-sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentSenderField:0x180e1c4
-
# mail['Resent-Sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentSenderField:0x180e1c4
-
#
-
# mail.resent_sender.to_s #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_sender.addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail.resent_sender.formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ResentSenderField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'resent-sender'
-
2
CAPITALIZED_FIELD = 'Resent-Sender'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def addresses
-
[address.address]
-
end
-
-
2
def address
-
tree.addresses.first
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Resent-To Field
-
#
-
# The Resent-To field inherits resent-to StructuredField and handles the Resent-To: header
-
# field in the email.
-
#
-
# Sending resent_to to a mail message will instantiate a Mail::Field object that
-
# has a ResentToField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Resent-To field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.resent_to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentToField:0x180e1c4
-
# mail['resent-to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentToField:0x180e1c4
-
# mail['Resent-To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ResentToField:0x180e1c4
-
#
-
# mail[:resent_to].encoded #=> 'Resent-To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:resent_to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:resent_to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:resent_to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ResentToField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'resent-to'
-
2
CAPITALIZED_FIELD = 'Resent-To'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# 4.4.3. REPLY-TO / RESENT-REPLY-TO
-
#
-
# Note: The "Return-Path" field is added by the mail transport
-
# service, at the time of final deliver. It is intended
-
# to identify a path back to the orginator of the mes-
-
# sage. The "Reply-To" field is added by the message
-
# originator and is intended to direct replies.
-
#
-
# trace = [return]
-
# 1*received
-
#
-
# return = "Return-Path:" path CRLF
-
#
-
# path = ([CFWS] "<" ([CFWS] / addr-spec) ">" [CFWS]) /
-
# obs-path
-
#
-
# received = "Received:" name-val-list ";" date-time CRLF
-
#
-
# name-val-list = [CFWS] [name-val-pair *(CFWS name-val-pair)]
-
#
-
# name-val-pair = item-name CFWS item-value
-
#
-
# item-name = ALPHA *(["-"] (ALPHA / DIGIT))
-
#
-
# item-value = 1*angle-addr / addr-spec /
-
# atom / domain / msg-id
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ReturnPathField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'return-path'
-
2
CAPITALIZED_FIELD = 'Return-Path'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
value = nil if value == '<>'
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def encoded
-
"#{CAPITALIZED_FIELD}: <#{address}>\r\n"
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
2
def address
-
addresses.first
-
end
-
-
2
def default
-
address
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = Sender Field
-
#
-
# The Sender field inherits sender StructuredField and handles the Sender: header
-
# field in the email.
-
#
-
# Sending sender to a mail message will instantiate a Mail::Field object that
-
# has a SenderField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one Sender field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.sender = 'Mikel Lindsaar <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
# mail[:sender] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::SenderField:0x180e1c4
-
# mail['sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::SenderField:0x180e1c4
-
# mail['Sender'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::SenderField:0x180e1c4
-
#
-
# mail[:sender].encoded #=> "Sender: Mikel Lindsaar <mikel@test.lindsaar.net>\r\n"
-
# mail[:sender].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>'
-
# mail[:sender].addresses #=> ['mikel@test.lindsaar.net']
-
# mail[:sender].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class SenderField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'sender'
-
2
CAPITALIZED_FIELD = 'Sender'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
self.charset = charset
-
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
self.parse
-
self
-
end
-
-
2
def addresses
-
[address.address]
-
end
-
-
2
def address
-
tree.addresses.first
-
end
-
-
2
def encoded
-
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
2
def default
-
address.address
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/fields/common/common_field'
-
-
2
module Mail
-
# Provides access to a structured header field
-
#
-
# ===Per RFC 2822:
-
# 2.2.2. Structured Header Field Bodies
-
#
-
# Some field bodies in this standard have specific syntactical
-
# structure more restrictive than the unstructured field bodies
-
# described above. These are referred to as "structured" field bodies.
-
# Structured field bodies are sequences of specific lexical tokens as
-
# described in sections 3 and 4 of this standard. Many of these tokens
-
# are allowed (according to their syntax) to be introduced or end with
-
# comments (as described in section 3.2.3) as well as the space (SP,
-
# ASCII value 32) and horizontal tab (HTAB, ASCII value 9) characters
-
# (together known as the white space characters, WSP), and those WSP
-
# characters are subject to header "folding" and "unfolding" as
-
# described in section 2.2.3. Semantic analysis of structured field
-
# bodies is given along with their syntax.
-
2
class StructuredField
-
-
2
include Mail::CommonField
-
2
include Mail::Utilities
-
-
2
def initialize(name = nil, value = nil, charset = nil)
-
32
self.name = name
-
32
self.value = value
-
32
self.charset = charset
-
32
self
-
end
-
-
2
def charset
-
8
@charset
-
end
-
-
2
def charset=(val)
-
68
@charset = val
-
end
-
-
2
def default
-
8
decoded
-
end
-
-
2
def errors
-
8
[]
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# subject = "Subject:" unstructured CRLF
-
2
module Mail
-
2
class SubjectField < UnstructuredField
-
-
2
FIELD_NAME = 'subject'
-
2
CAPITALIZED_FIELD = "Subject"
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
4
self.charset = charset
-
4
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
end
-
-
end
-
end
-
# encoding: utf-8
-
#
-
# = To Field
-
#
-
# The To field inherits to StructuredField and handles the To: header
-
# field in the email.
-
#
-
# Sending to to a mail message will instantiate a Mail::Field object that
-
# has a ToField as its field type. This includes all Mail::CommonAddress
-
# module instance metods.
-
#
-
# Only one To field can appear in a header, though it can have multiple
-
# addresses and groups of addresses.
-
#
-
# == Examples:
-
#
-
# mail = Mail.new
-
# mail.to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
-
# mail['to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
-
# mail['To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
-
#
-
# mail[:to].encoded #=> 'To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
-
# mail[:to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail[:to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
# mail[:to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
-
#
-
2
require 'mail/fields/common/common_address'
-
-
2
module Mail
-
2
class ToField < StructuredField
-
-
2
include Mail::CommonAddress
-
-
2
FIELD_NAME = 'to'
-
2
CAPITALIZED_FIELD = 'To'
-
-
2
def initialize(value = nil, charset = 'utf-8')
-
4
self.charset = charset
-
4
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
-
4
self.parse
-
4
self
-
end
-
-
2
def encoded
-
8
do_encode(CAPITALIZED_FIELD)
-
end
-
-
2
def decoded
-
do_decode
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
require 'mail/fields/common/common_field'
-
-
2
module Mail
-
# Provides access to an unstructured header field
-
#
-
# ===Per RFC 2822:
-
# 2.2.1. Unstructured Header Field Bodies
-
#
-
# Some field bodies in this standard are defined simply as
-
# "unstructured" (which is specified below as any US-ASCII characters,
-
# except for CR and LF) with no further restrictions. These are
-
# referred to as unstructured field bodies. Semantically, unstructured
-
# field bodies are simply to be treated as a single line of characters
-
# with no further processing (except for header "folding" and
-
# "unfolding" as described in section 2.2.3).
-
2
class UnstructuredField
-
-
2
include Mail::CommonField
-
2
include Mail::Utilities
-
-
2
attr_accessor :charset
-
2
attr_reader :errors
-
-
2
def initialize(name, value, charset = nil)
-
4
@errors = []
-
-
4
if value.is_a?(Array)
-
# Probably has arrived here from a failed parse of an AddressList Field
-
value = value.join(', ')
-
else
-
# Ensure we are dealing with a string
-
4
value = value.to_s
-
end
-
-
4
if charset
-
4
self.charset = charset
-
else
-
if value.respond_to?(:encoding)
-
self.charset = value.encoding
-
else
-
self.charset = $KCODE
-
end
-
end
-
4
self.name = name
-
4
self.value = value
-
4
self
-
end
-
-
2
def encoded
-
8
do_encode
-
end
-
-
2
def decoded
-
12
do_decode
-
end
-
-
2
def default
-
4
decoded
-
end
-
-
2
def parse # An unstructured field does not parse
-
self
-
end
-
-
2
private
-
-
2
def do_encode
-
8
value.nil? ? '' : "#{wrapped_value}\r\n"
-
end
-
-
2
def do_decode
-
12
value.blank? ? nil : Encodings.decode_encode(value, :decode)
-
end
-
-
# 2.2.3. Long Header Fields
-
#
-
# Each header field is logically a single line of characters comprising
-
# the field name, the colon, and the field body. For convenience
-
# however, and to deal with the 998/78 character limitations per line,
-
# the field body portion of a header field can be split into a multiple
-
# line representation; this is called "folding". The general rule is
-
# that wherever this standard allows for folding white space (not
-
# simply WSP characters), a CRLF may be inserted before any WSP. For
-
# example, the header field:
-
#
-
# Subject: This is a test
-
#
-
# can be represented as:
-
#
-
# Subject: This
-
# is a test
-
#
-
# Note: Though structured field bodies are defined in such a way that
-
# folding can take place between many of the lexical tokens (and even
-
# within some of the lexical tokens), folding SHOULD be limited to
-
# placing the CRLF at higher-level syntactic breaks. For instance, if
-
# a field body is defined as comma-separated values, it is recommended
-
# that folding occur after the comma separating the structured items in
-
# preference to other places where the field could be folded, even if
-
# it is allowed elsewhere.
-
2
def wrapped_value # :nodoc:
-
8
wrap_lines(name, fold("#{name}: ".length))
-
end
-
-
# 6.2. Display of 'encoded-word's
-
#
-
# When displaying a particular header field that contains multiple
-
# 'encoded-word's, any 'linear-white-space' that separates a pair of
-
# adjacent 'encoded-word's is ignored. (This is to allow the use of
-
# multiple 'encoded-word's to represent long strings of unencoded text,
-
# without having to separate 'encoded-word's where spaces occur in the
-
# unencoded text.)
-
2
def wrap_lines(name, folded_lines)
-
8
result = ["#{name}: #{folded_lines.shift}"]
-
8
result.concat(folded_lines)
-
8
result.join("\r\n\s")
-
end
-
-
2
def fold(prepend = 0) # :nodoc:
-
8
encoding = normalized_encoding
-
8
decoded_string = decoded.to_s
-
8
should_encode = decoded_string.not_ascii_only?
-
8
if should_encode
-
first = true
-
words = decoded_string.split(/[ \t]/).map do |word|
-
if first
-
first = !first
-
else
-
word = " " << word
-
end
-
if word.not_ascii_only?
-
word
-
else
-
word.scan(/.{7}|.+$/)
-
end
-
end.flatten
-
else
-
8
words = decoded_string.split(/[ \t]/)
-
end
-
-
8
folded_lines = []
-
8
while !words.empty?
-
8
limit = 78 - prepend
-
8
limit = limit - 7 - encoding.length if should_encode
-
8
line = ""
-
8
while !words.empty?
-
40
break unless word = words.first.dup
-
40
word.encode!(charset) if charset && word.respond_to?(:encode!)
-
40
word = encode(word) if should_encode
-
40
word = encode_crlf(word)
-
# Skip to next line if we're going to go past the limit
-
# Unless this is the first word, in which case we're going to add it anyway
-
# Note: This means that a word that's longer than 998 characters is going to break the spec. Please fix if this is a problem for you.
-
# (The fix, it seems, would be to use encoded-word encoding on it, because that way you can break it across multiple lines and
-
# the linebreak will be ignored)
-
40
break if !line.empty? && (line.length + word.length + 1 > limit)
-
# Remove the word from the queue ...
-
40
words.shift
-
# Add word separator
-
40
line << " " unless (line.empty? || should_encode)
-
# ... add it in encoded form to the current line
-
40
line << word
-
end
-
# Encode the line if necessary
-
8
line = "=?#{encoding}?Q?#{line}?=" if should_encode
-
# Add the line to the output and reset the prepend
-
8
folded_lines << line
-
8
prepend = 0
-
end
-
8
folded_lines
-
end
-
-
2
def encode(value)
-
value = [value].pack("M").gsub("=\n", '')
-
value.gsub!(/"/, '=22')
-
value.gsub!(/\(/, '=28')
-
value.gsub!(/\)/, '=29')
-
value.gsub!(/\?/, '=3F')
-
value.gsub!(/_/, '=5F')
-
value.gsub!(/ /, '_')
-
value
-
end
-
-
2
def encode_crlf(value)
-
40
value.gsub!("\r", '=0D')
-
40
value.gsub!("\n", '=0A')
-
40
value
-
end
-
-
2
def normalized_encoding
-
8
encoding = charset.to_s.upcase.gsub('_', '-')
-
8
encoding = 'UTF-8' if encoding == 'UTF8' # Ruby 1.8.x and $KCODE == 'u'
-
8
encoding
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
-
# Provides access to a header object.
-
#
-
# ===Per RFC2822
-
#
-
# 2.2. Header Fields
-
#
-
# Header fields are lines composed of a field name, followed by a colon
-
# (":"), followed by a field body, and terminated by CRLF. A field
-
# name MUST be composed of printable US-ASCII characters (i.e.,
-
# characters that have values between 33 and 126, inclusive), except
-
# colon. A field body may be composed of any US-ASCII characters,
-
# except for CR and LF. However, a field body may contain CRLF when
-
# used in header "folding" and "unfolding" as described in section
-
# 2.2.3. All field bodies MUST conform to the syntax described in
-
# sections 3 and 4 of this standard.
-
2
class Header
-
2
include Patterns
-
2
include Utilities
-
2
include Enumerable
-
-
2
@@maximum_amount = 1000
-
-
# Large amount of headers in Email might create extra high CPU load
-
# Use this parameter to limit number of headers that will be parsed by
-
# mail library.
-
# Default: 1000
-
2
def self.maximum_amount
-
@@maximum_amount
-
end
-
-
2
def self.maximum_amount=(value)
-
@@maximum_amount = value
-
end
-
-
# Creates a new header object.
-
#
-
# Accepts raw text or nothing. If given raw text will attempt to parse
-
# it and split it into the various fields, instantiating each field as
-
# it goes.
-
#
-
# If it finds a field that should be a structured field (such as content
-
# type), but it fails to parse it, it will simply make it an unstructured
-
# field and leave it alone. This will mean that the data is preserved but
-
# no automatic processing of that field will happen. If you find one of
-
# these cases, please make a patch and send it in, or at the least, send
-
# me the example so we can fix it.
-
2
def initialize(header_text = nil, charset = nil)
-
4
@errors = []
-
4
@charset = charset
-
4
self.raw_source = header_text.to_crlf.lstrip
-
4
split_header if header_text
-
end
-
-
# The preserved raw source of the header as you passed it in, untouched
-
# for your Regexing glory.
-
2
def raw_source
-
@raw_source
-
end
-
-
# Returns an array of all the fields in the header in order that they
-
# were read in.
-
2
def fields
-
368
@fields ||= FieldList.new
-
end
-
-
# 3.6. Field definitions
-
#
-
# It is important to note that the header fields are not guaranteed to
-
# be in a particular order. They may appear in any order, and they
-
# have been known to be reordered occasionally when transported over
-
# the Internet. However, for the purposes of this standard, header
-
# fields SHOULD NOT be reordered when a message is transported or
-
# transformed. More importantly, the trace header fields and resent
-
# header fields MUST NOT be reordered, and SHOULD be kept in blocks
-
# prepended to the message. See sections 3.6.6 and 3.6.7 for more
-
# information.
-
#
-
# Populates the fields container with Field objects in the order it
-
# receives them in.
-
#
-
# Acceps an array of field string values, for example:
-
#
-
# h = Header.new
-
# h.fields = ['From: mikel@me.com', 'To: bob@you.com']
-
2
def fields=(unfolded_fields)
-
@fields = Mail::FieldList.new
-
warn "Warning: more than #{self.class.maximum_amount} header fields only using the first #{self.class.maximum_amount}" if unfolded_fields.length > self.class.maximum_amount
-
unfolded_fields[0..(self.class.maximum_amount-1)].each do |field|
-
-
field = Field.new(field, nil, charset)
-
field.errors.each { |error| self.errors << error }
-
if limited_field?(field.name) && (selected = select_field_for(field.name)) && selected.any?
-
selected.first.update(field.name, field.value)
-
else
-
@fields << field
-
end
-
end
-
-
end
-
-
2
def errors
-
@errors
-
end
-
-
# 3.6. Field definitions
-
#
-
# The following table indicates limits on the number of times each
-
# field may occur in a message header as well as any special
-
# limitations on the use of those fields. An asterisk next to a value
-
# in the minimum or maximum column indicates that a special restriction
-
# appears in the Notes column.
-
#
-
# <snip table from 3.6>
-
#
-
# As per RFC, many fields can appear more than once, we will return a string
-
# of the value if there is only one header, or if there is more than one
-
# matching header, will return an array of values in order that they appear
-
# in the header ordered from top to bottom.
-
#
-
# Example:
-
#
-
# h = Header.new
-
# h.fields = ['To: mikel@me.com', 'X-Mail-SPAM: 15', 'X-Mail-SPAM: 20']
-
# h['To'] #=> 'mikel@me.com'
-
# h['X-Mail-SPAM'] #=> ['15', '20']
-
2
def [](name)
-
264
name = dasherize(name).downcase
-
264
selected = select_field_for(name)
-
case
-
when selected.length > 1
-
selected.map { |f| f }
-
when !selected.blank?
-
196
selected.first
-
else
-
nil
-
264
end
-
end
-
-
# Sets the FIRST matching field in the header to passed value, or deletes
-
# the FIRST field matched from the header if passed nil
-
#
-
# Example:
-
#
-
# h = Header.new
-
# h.fields = ['To: mikel@me.com', 'X-Mail-SPAM: 15', 'X-Mail-SPAM: 20']
-
# h['To'] = 'bob@you.com'
-
# h['To'] #=> 'bob@you.com'
-
# h['X-Mail-SPAM'] = '10000'
-
# h['X-Mail-SPAM'] # => ['15', '20', '10000']
-
# h['X-Mail-SPAM'] = nil
-
# h['X-Mail-SPAM'] # => nil
-
2
def []=(name, value)
-
40
name = dasherize(name)
-
40
if name.include?(':')
-
raise ArgumentError, "Header names may not contain a colon: #{name.inspect}"
-
end
-
40
fn = name.downcase
-
40
selected = select_field_for(fn)
-
-
case
-
# User wants to delete the field
-
when !selected.blank? && value == nil
-
fields.delete_if { |f| selected.include?(f) }
-
-
# User wants to change the field
-
when !selected.blank? && limited_field?(fn)
-
8
selected.first.update(fn, value)
-
-
# User wants to create the field
-
else
-
# Need to insert in correct order for trace fields
-
32
self.fields << Field.new(name.to_s, value, charset)
-
40
end
-
40
if dasherize(fn) == "content-type"
-
# Update charset if specified in Content-Type
-
8
params = self[:content_type].parameters rescue nil
-
8
@charset = params && params[:charset]
-
end
-
end
-
-
2
def charset
-
32
@charset
-
end
-
-
2
def charset=(val)
-
12
params = self[:content_type].parameters rescue nil
-
12
if params
-
4
params[:charset] = val
-
end
-
12
@charset = val
-
end
-
-
2
LIMITED_FIELDS = %w[ date from sender reply-to to cc bcc
-
message-id in-reply-to references subject
-
return-path content-type mime-version
-
content-transfer-encoding content-description
-
content-id content-disposition content-location]
-
-
2
def encoded
-
8
buffer = ''
-
8
buffer.force_encoding('us-ascii') if buffer.respond_to?(:force_encoding)
-
8
fields.each do |field|
-
64
buffer << field.encoded
-
end
-
8
buffer
-
end
-
-
2
def to_s
-
encoded
-
end
-
-
2
def decoded
-
raise NoMethodError, 'Can not decode an entire header as there could be character set conflicts, try calling #decoded on the various fields.'
-
end
-
-
2
def field_summary
-
fields.map { |f| "<#{f.name}: #{f.value}>" }.join(", ")
-
end
-
-
# Returns true if the header has a Message-ID defined (empty or not)
-
2
def has_message_id?
-
68
!fields.select { |f| f.responsible_for?('Message-ID') }.empty?
-
end
-
-
# Returns true if the header has a Content-ID defined (empty or not)
-
2
def has_content_id?
-
!fields.select { |f| f.responsible_for?('Content-ID') }.empty?
-
end
-
-
# Returns true if the header has a Date defined (empty or not)
-
2
def has_date?
-
64
!fields.select { |f| f.responsible_for?('Date') }.empty?
-
end
-
-
# Returns true if the header has a MIME version defined (empty or not)
-
2
def has_mime_version?
-
68
!fields.select { |f| f.responsible_for?('Mime-Version') }.empty?
-
end
-
-
2
private
-
-
2
def raw_source=(val)
-
4
@raw_source = val
-
end
-
-
# 2.2.3. Long Header Fields
-
#
-
# The process of moving from this folded multiple-line representation
-
# of a header field to its single line representation is called
-
# "unfolding". Unfolding is accomplished by simply removing any CRLF
-
# that is immediately followed by WSP. Each header field should be
-
# treated in its unfolded form for further syntactic and semantic
-
# evaluation.
-
2
def unfold(string)
-
string.gsub(/#{CRLF}#{WSP}+/, ' ').gsub(/#{WSP}+/, ' ')
-
end
-
-
# Returns the header with all the folds removed
-
2
def unfolded_header
-
@unfolded_header ||= unfold(raw_source)
-
end
-
-
# Splits an unfolded and line break cleaned header into individual field
-
# strings.
-
2
def split_header
-
self.fields = unfolded_header.split(CRLF)
-
end
-
-
2
def select_field_for(name)
-
2168
fields.select { |f| f.responsible_for?(name) }
-
end
-
-
2
def limited_field?(name)
-
8
LIMITED_FIELDS.include?(name.to_s.downcase)
-
end
-
-
# Enumerable support; yield each field in order to the block if there is one,
-
# or return an Enumerator for them if there isn't.
-
2
def each( &block )
-
return self.fields.each( &block ) if block
-
self.fields.each
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
# This is an almost cut and paste from ActiveSupport v3.0.6, copied in here so that Mail
-
# itself does not depend on ActiveSupport to avoid versioning conflicts
-
-
2
module Mail
-
2
class IndifferentHash < Hash
-
-
2
def initialize(constructor = {})
-
8
if constructor.is_a?(Hash)
-
8
super()
-
8
update(constructor)
-
else
-
super(constructor)
-
end
-
end
-
-
2
def default(key = nil)
-
8
if key.is_a?(Symbol) && include?(key = key.to_s)
-
self[key]
-
else
-
8
super
-
end
-
end
-
-
2
def self.new_from_hash_copying_default(hash)
-
IndifferentHash.new(hash).tap do |new_hash|
-
new_hash.default = hash.default
-
end
-
end
-
-
2
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
-
2
alias_method :regular_update, :update unless method_defined?(:regular_update)
-
-
# Assigns a new value to the hash:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash[:key] = "value"
-
#
-
2
def []=(key, value)
-
4
regular_writer(convert_key(key), convert_value(value))
-
end
-
-
2
alias_method :store, :[]=
-
-
# Updates the instantized hash with values from the second:
-
#
-
# hash_1 = HashWithIndifferentAccess.new
-
# hash_1[:key] = "value"
-
#
-
# hash_2 = HashWithIndifferentAccess.new
-
# hash_2[:key] = "New Value!"
-
#
-
# hash_1.update(hash_2) # => {"key"=>"New Value!"}
-
#
-
2
def update(other_hash)
-
8
other_hash.each_pair { |key, value| regular_writer(convert_key(key), convert_value(value)) }
-
8
self
-
end
-
-
2
alias_method :merge!, :update
-
-
# Checks the hash for a key matching the argument passed in:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash["key"] = "value"
-
# hash.key? :key # => true
-
# hash.key? "key" # => true
-
#
-
2
def key?(key)
-
8
super(convert_key(key))
-
end
-
-
2
alias_method :include?, :key?
-
2
alias_method :has_key?, :key?
-
2
alias_method :member?, :key?
-
-
# Fetches the value for the specified key, same as doing hash[key]
-
2
def fetch(key, *extras)
-
super(convert_key(key), *extras)
-
end
-
-
# Returns an array of the values at the specified indices:
-
#
-
# hash = HashWithIndifferentAccess.new
-
# hash[:a] = "x"
-
# hash[:b] = "y"
-
# hash.values_at("a", "b") # => ["x", "y"]
-
#
-
2
def values_at(*indices)
-
indices.collect {|key| self[convert_key(key)]}
-
end
-
-
# Returns an exact copy of the hash.
-
2
def dup
-
IndifferentHash.new(self)
-
end
-
-
# Merges the instantized and the specified hashes together, giving precedence to the values from the second hash
-
# Does not overwrite the existing hash.
-
2
def merge(hash)
-
self.dup.update(hash)
-
end
-
-
# Performs the opposite of merge, with the keys and values from the first hash taking precedence over the second.
-
# This overloaded definition prevents returning a regular hash, if reverse_merge is called on a HashWithDifferentAccess.
-
2
def reverse_merge(other_hash)
-
super self.class.new_from_hash_copying_default(other_hash)
-
end
-
-
2
def reverse_merge!(other_hash)
-
replace(reverse_merge( other_hash ))
-
end
-
-
# Removes a specified key from the hash.
-
2
def delete(key)
-
super(convert_key(key))
-
end
-
-
2
def stringify_keys!; self end
-
2
def stringify_keys; dup end
-
2
def symbolize_keys; to_hash.symbolize_keys end
-
2
def to_options!; self end
-
-
2
def to_hash
-
Hash.new(default).merge!(self)
-
end
-
-
2
protected
-
-
2
def convert_key(key)
-
12
key.kind_of?(Symbol) ? key.to_s : key
-
end
-
-
2
def convert_value(value)
-
4
if value.class == Hash
-
self.class.new_from_hash_copying_default(value)
-
4
elsif value.is_a?(Array)
-
value.dup.replace(value.map { |e| convert_value(e) })
-
else
-
4
value
-
end
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
-
# Allows you to create a new Mail::Message object.
-
#
-
# You can make an email via passing a string or passing a block.
-
#
-
# For example, the following two examples will create the same email
-
# message:
-
#
-
# Creating via a string:
-
#
-
# string = "To: mikel@test.lindsaar.net\r\n"
-
# string << "From: bob@test.lindsaar.net\r\n"
-
# string << "Subject: This is an email\r\n"
-
# string << "\r\n"
-
# string << "This is the body"
-
# Mail.new(string)
-
#
-
# Or creating via a block:
-
#
-
# message = Mail.new do
-
# to 'mikel@test.lindsaar.net'
-
# from 'bob@test.lindsaar.net'
-
# subject 'This is an email'
-
# body 'This is the body'
-
# end
-
#
-
# Or creating via a hash (or hash like object):
-
#
-
# message = Mail.new({:to => 'mikel@test.lindsaar.net',
-
# 'from' => 'bob@test.lindsaar.net',
-
# :subject => 'This is an email',
-
# :body => 'This is the body' })
-
#
-
# Note, the hash keys can be strings or symbols, the passed in object
-
# does not need to be a hash, it just needs to respond to :each_pair
-
# and yield each key value pair.
-
#
-
# As a side note, you can also create a new email through creating
-
# a Mail::Message object directly and then passing in values via string,
-
# symbol or direct method calls. See Mail::Message for more information.
-
#
-
# mail = Mail.new
-
# mail.to = 'mikel@test.lindsaar.net'
-
# mail[:from] = 'bob@test.lindsaar.net'
-
# mail['subject'] = 'This is an email'
-
# mail.body = 'This is the body'
-
2
def self.new(*args, &block)
-
4
Message.new(args, &block)
-
end
-
-
# Sets the default delivery method and retriever method for all new Mail objects.
-
# The delivery_method and retriever_method default to :smtp and :pop3, with defaults
-
# set.
-
#
-
# So sending a new email, if you have an SMTP server running on localhost is
-
# as easy as:
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'bob@test.lindsaar.net'
-
# subject 'hi there!'
-
# body 'this is a body'
-
# end
-
#
-
# If you do not specify anything, you will get the following equivalent code set in
-
# every new mail object:
-
#
-
# Mail.defaults do
-
# delivery_method :smtp, { :address => "localhost",
-
# :port => 25,
-
# :domain => 'localhost.localdomain',
-
# :user_name => nil,
-
# :password => nil,
-
# :authentication => nil,
-
# :enable_starttls_auto => true }
-
#
-
# retriever_method :pop3, { :address => "localhost",
-
# :port => 995,
-
# :user_name => nil,
-
# :password => nil,
-
# :enable_ssl => true }
-
# end
-
#
-
# Mail.delivery_method.new #=> Mail::SMTP instance
-
# Mail.retriever_method.new #=> Mail::POP3 instance
-
#
-
# Each mail object inherits the default set in Mail.delivery_method, however, on
-
# a per email basis, you can override the method:
-
#
-
# mail.delivery_method :sendmail
-
#
-
# Or you can override the method and pass in settings:
-
#
-
# mail.delivery_method :sendmail, { :address => 'some.host' }
-
#
-
# You can also just modify the settings:
-
#
-
# mail.delivery_settings = { :address => 'some.host' }
-
#
-
# The passed in hash is just merged against the defaults with +merge!+ and the result
-
# assigned the mail object. So the above example will change only the :address value
-
# of the global smtp_settings to be 'some.host', keeping all other values
-
2
def self.defaults(&block)
-
Configuration.instance.instance_eval(&block)
-
end
-
-
# Returns the delivery method selected, defaults to an instance of Mail::SMTP
-
2
def self.delivery_method
-
4
Configuration.instance.delivery_method
-
end
-
-
# Returns the retriever method selected, defaults to an instance of Mail::POP3
-
2
def self.retriever_method
-
Configuration.instance.retriever_method
-
end
-
-
# Send an email using the default configuration. You do need to set a default
-
# configuration first before you use self.deliver, if you don't, an appropriate
-
# error will be raised telling you to.
-
#
-
# If you do not specify a delivery type, SMTP will be used.
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'This is a test email'
-
# body 'Not much to say here'
-
# end
-
#
-
# You can also do:
-
#
-
# mail = Mail.read('email.eml')
-
# mail.deliver!
-
#
-
# And your email object will be created and sent.
-
2
def self.deliver(*args, &block)
-
mail = self.new(args, &block)
-
mail.deliver
-
mail
-
end
-
-
# Find emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
2
def self.find(*args, &block)
-
retriever_method.find(*args, &block)
-
end
-
-
# Finds and then deletes retrieved emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
2
def self.find_and_delete(*args, &block)
-
retriever_method.find_and_delete(*args, &block)
-
end
-
-
# Receive the first email(s) from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
2
def self.first(*args, &block)
-
retriever_method.first(*args, &block)
-
end
-
-
# Receive the first email(s) from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
2
def self.last(*args, &block)
-
retriever_method.last(*args, &block)
-
end
-
-
# Receive all emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
2
def self.all(*args, &block)
-
retriever_method.all(*args, &block)
-
end
-
-
# Reads in an email message from a path and instantiates it as a new Mail::Message
-
2
def self.read(filename)
-
self.new(File.open(filename, 'rb') { |f| f.read })
-
end
-
-
# Delete all emails from the default retriever
-
# See Mail::Retriever for a complete documentation.
-
2
def self.delete_all(*args, &block)
-
retriever_method.delete_all(*args, &block)
-
end
-
-
# Instantiates a new Mail::Message using a string
-
2
def Mail.read_from_string(mail_as_string)
-
Mail.new(mail_as_string)
-
end
-
-
2
def Mail.connection(&block)
-
retriever_method.connection(&block)
-
end
-
-
# Initialize the observers and interceptors arrays
-
2
@@delivery_notification_observers = []
-
2
@@delivery_interceptors = []
-
-
# You can register an object to be informed of every email that is sent through
-
# this method.
-
#
-
# Your object needs to respond to a single method #delivered_email(mail)
-
# which receives the email that is sent.
-
2
def self.register_observer(observer)
-
unless @@delivery_notification_observers.include?(observer)
-
@@delivery_notification_observers << observer
-
end
-
end
-
-
# You can register an object to be given every mail object that will be sent,
-
# before it is sent. So if you want to add special headers or modify any
-
# email that gets sent through the Mail library, you can do so.
-
#
-
# Your object needs to respond to a single method #delivering_email(mail)
-
# which receives the email that is about to be sent. Make your modifications
-
# directly to this object.
-
2
def self.register_interceptor(interceptor)
-
unless @@delivery_interceptors.include?(interceptor)
-
@@delivery_interceptors << interceptor
-
end
-
end
-
-
2
def self.inform_observers(mail)
-
4
@@delivery_notification_observers.each do |observer|
-
observer.delivered_email(mail)
-
end
-
end
-
-
2
def self.inform_interceptors(mail)
-
4
@@delivery_interceptors.each do |interceptor|
-
interceptor.delivering_email(mail)
-
end
-
end
-
-
2
protected
-
-
2
def self.random_tag
-
4
t = Time.now
-
4
sprintf('%x%x_%x%x%d%x',
-
t.to_i, t.tv_usec,
-
$$, Thread.current.object_id.abs, self.uniq, rand(255))
-
end
-
-
2
private
-
-
2
def self.something_random
-
2
(Thread.current.object_id * rand(255) / Time.now.to_f).to_s.slice(-3..-1).to_i
-
end
-
-
2
def self.uniq
-
4
@@uniq += 1
-
end
-
-
2
@@uniq = self.something_random
-
-
end
-
2
module Mail
-
2
module Matchers
-
2
def have_sent_email
-
HasSentEmailMatcher.new(self)
-
end
-
-
2
class HasSentEmailMatcher
-
2
def initialize(_context)
-
end
-
-
2
def matches?(subject)
-
matching_deliveries = filter_matched_deliveries(Mail::TestMailer.deliveries)
-
!(matching_deliveries.empty?)
-
end
-
-
2
def from(sender)
-
@sender = sender
-
self
-
end
-
-
2
def to(recipient_or_list)
-
@recipients ||= []
-
-
if recipient_or_list.kind_of?(Array)
-
@recipients += recipient_or_list
-
else
-
@recipients << recipient_or_list
-
end
-
self
-
end
-
-
2
def with_subject(subject)
-
@subject = subject
-
self
-
end
-
-
2
def matching_subject(subject_matcher)
-
@subject_matcher = subject_matcher
-
self
-
end
-
-
2
def with_body(body)
-
@body = body
-
self
-
end
-
-
2
def matching_body(body_matcher)
-
@body_matcher = body_matcher
-
self
-
end
-
-
2
def description
-
result = "send a matching email"
-
result
-
end
-
-
2
def failure_message
-
result = "Expected email to be sent "
-
result += explain_expectations
-
result += dump_deliveries
-
result
-
end
-
-
2
def negative_failure_message
-
result = "Expected no email to be sent "
-
result += explain_expectations
-
result += dump_deliveries
-
result
-
end
-
-
2
protected
-
-
2
def filter_matched_deliveries(deliveries)
-
candidate_deliveries = deliveries
-
-
%w(sender recipients subject subject_matcher body body_matcher).each do |modifier_name|
-
next unless instance_variable_defined?("@#{modifier_name}")
-
candidate_deliveries = candidate_deliveries.select{|matching_delivery| self.send("matches_on_#{modifier_name}?", matching_delivery)}
-
end
-
-
candidate_deliveries
-
end
-
-
2
def matches_on_sender?(delivery)
-
delivery.from.include?(@sender)
-
end
-
-
2
def matches_on_recipients?(delivery)
-
@recipients.all? {|recipient| delivery.to.include?(recipient) }
-
end
-
-
2
def matches_on_subject?(delivery)
-
delivery.subject == @subject
-
end
-
-
2
def matches_on_subject_matcher?(delivery)
-
@subject_matcher.match delivery.subject
-
end
-
-
2
def matches_on_body?(delivery)
-
delivery.body == @body
-
end
-
-
2
def matches_on_body_matcher?(delivery)
-
@body_matcher.match delivery.body.raw_source
-
end
-
-
2
def explain_expectations
-
result = ''
-
result += "from #{@sender} " if instance_variable_defined?('@sender')
-
result += "to #{@recipients.inspect} " if instance_variable_defined?('@recipients')
-
result += "with subject \"#{@subject}\" " if instance_variable_defined?('@subject')
-
result += "with subject matching \"#{@subject_matcher}\" " if instance_variable_defined?('@subject_matcher')
-
result += "with body \"#{@body}\" " if instance_variable_defined?('@body')
-
result += "with body matching \"#{@body_matcher}\" " if instance_variable_defined?('@body_matcher')
-
result
-
end
-
-
2
def dump_deliveries
-
"(actual deliveries: " + Mail::TestMailer.deliveries.inspect + ")"
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require "yaml"
-
-
2
module Mail
-
# The Message class provides a single point of access to all things to do with an
-
# email message.
-
#
-
# You create a new email message by calling the Mail::Message.new method, or just
-
# Mail.new
-
#
-
# A Message object by default has the following objects inside it:
-
#
-
# * A Header object which contains all information and settings of the header of the email
-
# * Body object which contains all parts of the email that are not part of the header, this
-
# includes any attachments, body text, MIME parts etc.
-
#
-
# ==Per RFC2822
-
#
-
# 2.1. General Description
-
#
-
# At the most basic level, a message is a series of characters. A
-
# message that is conformant with this standard is comprised of
-
# characters with values in the range 1 through 127 and interpreted as
-
# US-ASCII characters [ASCII]. For brevity, this document sometimes
-
# refers to this range of characters as simply "US-ASCII characters".
-
#
-
# Note: This standard specifies that messages are made up of characters
-
# in the US-ASCII range of 1 through 127. There are other documents,
-
# specifically the MIME document series [RFC2045, RFC2046, RFC2047,
-
# RFC2048, RFC2049], that extend this standard to allow for values
-
# outside of that range. Discussion of those mechanisms is not within
-
# the scope of this standard.
-
#
-
# Messages are divided into lines of characters. A line is a series of
-
# characters that is delimited with the two characters carriage-return
-
# and line-feed; that is, the carriage return (CR) character (ASCII
-
# value 13) followed immediately by the line feed (LF) character (ASCII
-
# value 10). (The carriage-return/line-feed pair is usually written in
-
# this document as "CRLF".)
-
#
-
# A message consists of header fields (collectively called "the header
-
# of the message") followed, optionally, by a body. The header is a
-
# sequence of lines of characters with special syntax as defined in
-
# this standard. The body is simply a sequence of characters that
-
# follows the header and is separated from the header by an empty line
-
# (i.e., a line with nothing preceding the CRLF).
-
2
class Message
-
-
2
include Patterns
-
2
include Utilities
-
-
# ==Making an email
-
#
-
# You can make an new mail object via a block, passing a string, file or direct assignment.
-
#
-
# ===Making an email via a block
-
#
-
# mail = Mail.new do
-
# from 'mikel@test.lindsaar.net'
-
# to 'you@test.lindsaar.net'
-
# subject 'This is a test email'
-
# body File.read('body.txt')
-
# end
-
#
-
# mail.to_s #=> "From: mikel@test.lindsaar.net\r\nTo: you@...
-
#
-
# ===Making an email via passing a string
-
#
-
# mail = Mail.new("To: mikel@test.lindsaar.net\r\nSubject: Hello\r\n\r\nHi there!")
-
# mail.body.to_s #=> 'Hi there!'
-
# mail.subject #=> 'Hello'
-
# mail.to #=> 'mikel@test.lindsaar.net'
-
#
-
# ===Making an email from a file
-
#
-
# mail = Mail.read('path/to/file.eml')
-
# mail.body.to_s #=> 'Hi there!'
-
# mail.subject #=> 'Hello'
-
# mail.to #=> 'mikel@test.lindsaar.net'
-
#
-
# ===Making an email via assignment
-
#
-
# You can assign values to a mail object via four approaches:
-
#
-
# * Message#field_name=(value)
-
# * Message#field_name(value)
-
# * Message#['field_name']=(value)
-
# * Message#[:field_name]=(value)
-
#
-
# Examples:
-
#
-
# mail = Mail.new
-
# mail['from'] = 'mikel@test.lindsaar.net'
-
# mail[:to] = 'you@test.lindsaar.net'
-
# mail.subject 'This is a test email'
-
# mail.body = 'This is a body'
-
#
-
# mail.to_s #=> "From: mikel@test.lindsaar.net\r\nTo: you@...
-
#
-
2
def initialize(*args, &block)
-
4
@body = nil
-
4
@body_raw = nil
-
4
@separate_parts = false
-
4
@text_part = nil
-
4
@html_part = nil
-
4
@errors = nil
-
4
@header = nil
-
4
@charset = 'UTF-8'
-
4
@defaulted_charset = true
-
-
4
@smtp_envelope_from = nil
-
4
@smtp_envelope_to = nil
-
-
4
@perform_deliveries = true
-
4
@raise_delivery_errors = true
-
-
4
@delivery_handler = nil
-
-
4
@delivery_method = Mail.delivery_method.dup
-
-
4
@transport_encoding = Mail::Encodings.get_encoding('7bit')
-
-
4
@mark_for_delete = false
-
-
4
if args.flatten.first.respond_to?(:each_pair)
-
init_with_hash(args.flatten.first)
-
else
-
4
init_with_string(args.flatten[0].to_s)
-
end
-
-
4
if block_given?
-
instance_eval(&block)
-
end
-
-
4
self
-
end
-
-
# If you assign a delivery handler, mail will call :deliver_mail on the
-
# object you assign to delivery_handler, it will pass itself as the
-
# single argument.
-
#
-
# If you define a delivery_handler, then you are responsible for the
-
# following actions in the delivery cycle:
-
#
-
# * Appending the mail object to Mail.deliveries as you see fit.
-
# * Checking the mail.perform_deliveries flag to decide if you should
-
# actually call :deliver! the mail object or not.
-
# * Checking the mail.raise_delivery_errors flag to decide if you
-
# should raise delivery errors if they occur.
-
# * Actually calling :deliver! (with the bang) on the mail object to
-
# get it to deliver itself.
-
#
-
# A simplest implementation of a delivery_handler would be
-
#
-
# class MyObject
-
#
-
# def initialize
-
# @mail = Mail.new('To: mikel@test.lindsaar.net')
-
# @mail.delivery_handler = self
-
# end
-
#
-
# attr_accessor :mail
-
#
-
# def deliver_mail(mail)
-
# yield
-
# end
-
# end
-
#
-
# Then doing:
-
#
-
# obj = MyObject.new
-
# obj.mail.deliver
-
#
-
# Would cause Mail to call obj.deliver_mail passing itself as a parameter,
-
# which then can just yield and let Mail do its own private do_delivery
-
# method.
-
2
attr_accessor :delivery_handler
-
-
# If set to false, mail will go through the motions of doing a delivery,
-
# but not actually call the delivery method or append the mail object to
-
# the Mail.deliveries collection. Useful for testing.
-
#
-
# Mail.deliveries.size #=> 0
-
# mail.delivery_method :smtp
-
# mail.perform_deliveries = false
-
# mail.deliver # Mail::SMTP not called here
-
# Mail.deliveries.size #=> 0
-
#
-
# If you want to test and query the Mail.deliveries collection to see what
-
# mail you sent, you should set perform_deliveries to true and use
-
# the :test mail delivery_method:
-
#
-
# Mail.deliveries.size #=> 0
-
# mail.delivery_method :test
-
# mail.perform_deliveries = true
-
# mail.deliver
-
# Mail.deliveries.size #=> 1
-
#
-
# This setting is ignored by mail (though still available as a flag) if you
-
# define a delivery_handler
-
2
attr_accessor :perform_deliveries
-
-
# If set to false, mail will silently catch and ignore any exceptions
-
# raised through attempting to deliver an email.
-
#
-
# This setting is ignored by mail (though still available as a flag) if you
-
# define a delivery_handler
-
2
attr_accessor :raise_delivery_errors
-
-
2
def register_for_delivery_notification(observer)
-
STDERR.puts("Message#register_for_delivery_notification is deprecated, please call Mail.register_observer instead")
-
Mail.register_observer(observer)
-
end
-
-
2
def inform_observers
-
4
Mail.inform_observers(self)
-
end
-
-
2
def inform_interceptors
-
4
Mail.inform_interceptors(self)
-
end
-
-
# Delivers an mail object.
-
#
-
# Examples:
-
#
-
# mail = Mail.read('file.eml')
-
# mail.deliver
-
2
def deliver
-
4
inform_interceptors
-
4
if delivery_handler
-
8
delivery_handler.deliver_mail(self) { do_delivery }
-
else
-
do_delivery
-
end
-
4
inform_observers
-
4
self
-
end
-
-
# This method bypasses checking perform_deliveries and raise_delivery_errors,
-
# so use with caution.
-
#
-
# It still however fires off the intercepters and calls the observers callbacks if they are defined.
-
#
-
# Returns self
-
2
def deliver!
-
inform_interceptors
-
response = delivery_method.deliver!(self)
-
inform_observers
-
delivery_method.settings[:return_response] ? response : self
-
end
-
-
2
def delivery_method(method = nil, settings = {})
-
8
unless method
-
4
@delivery_method
-
else
-
4
@delivery_method = Configuration.instance.lookup_delivery_method(method).new(settings)
-
end
-
end
-
-
2
def reply(*args, &block)
-
self.class.new.tap do |reply|
-
if message_id
-
bracketed_message_id = "<#{message_id}>"
-
reply.in_reply_to = bracketed_message_id
-
if !references.nil?
-
refs = [references].flatten.map { |r| "<#{r}>" }
-
refs << bracketed_message_id
-
reply.references = refs.join(' ')
-
elsif !in_reply_to.nil? && !in_reply_to.kind_of?(Array)
-
reply.references = "<#{in_reply_to}> #{bracketed_message_id}"
-
end
-
reply.references ||= bracketed_message_id
-
end
-
if subject
-
reply.subject = subject =~ /^Re:/i ? subject : "RE: #{subject}"
-
end
-
if reply_to || from
-
reply.to = self[reply_to ? :reply_to : :from].to_s
-
end
-
if to
-
reply.from = self[:to].formatted.first.to_s
-
end
-
-
unless args.empty?
-
if args.flatten.first.respond_to?(:each_pair)
-
reply.send(:init_with_hash, args.flatten.first)
-
else
-
reply.send(:init_with_string, args.flatten[0].to_s.strip)
-
end
-
end
-
-
if block_given?
-
reply.instance_eval(&block)
-
end
-
end
-
end
-
-
# Provides the operator needed for sort et al.
-
#
-
# Compares this mail object with another mail object, this is done by date, so an
-
# email that is older than another will appear first.
-
#
-
# Example:
-
#
-
# mail1 = Mail.new do
-
# date(Time.now)
-
# end
-
# mail2 = Mail.new do
-
# date(Time.now - 86400) # 1 day older
-
# end
-
# [mail2, mail1].sort #=> [mail2, mail1]
-
2
def <=>(other)
-
if other.nil?
-
1
-
else
-
self.date <=> other.date
-
end
-
end
-
-
# Two emails are the same if they have the same fields and body contents. One
-
# gotcha here is that Mail will insert Message-IDs when calling encoded, so doing
-
# mail1.encoded == mail2.encoded is most probably not going to return what you think
-
# as the assigned Message-IDs by Mail (if not already defined as the same) will ensure
-
# that the two objects are unique, and this comparison will ALWAYS return false.
-
#
-
# So the == operator has been defined like so: Two messages are the same if they have
-
# the same content, ignoring the Message-ID field, unless BOTH emails have a defined and
-
# different Message-ID value, then they are false.
-
#
-
# So, in practice the == operator works like this:
-
#
-
# m1 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Subject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> true
-
#
-
# m1 = Mail.new("Message-ID: <1234@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m2 = Mail.new("Message-ID: <DIFFERENT@test>\r\nSubject: Hello\r\n\r\nHello")
-
# m1 == m2 #=> false
-
2
def ==(other)
-
return false unless other.respond_to?(:encoded)
-
-
if self.message_id && other.message_id
-
result = (self.encoded == other.encoded)
-
else
-
self_message_id, other_message_id = self.message_id, other.message_id
-
self.message_id, other.message_id = '<temp@test>', '<temp@test>'
-
result = self.encoded == other.encoded
-
self.message_id = "<#{self_message_id}>" if self_message_id
-
other.message_id = "<#{other_message_id}>" if other_message_id
-
result
-
end
-
end
-
-
# Provides access to the raw source of the message as it was when it
-
# was instantiated. This is set at initialization and so is untouched
-
# by the parsers or decoder / encoders
-
#
-
# Example:
-
#
-
# mail = Mail.new('This is an invalid email message')
-
# mail.raw_source #=> "This is an invalid email message"
-
2
def raw_source
-
12
@raw_source
-
end
-
-
# Sets the envelope from for the email
-
2
def set_envelope( val )
-
@raw_envelope = val
-
@envelope = Mail::Envelope.new( val )
-
end
-
-
# The raw_envelope is the From mikel@test.lindsaar.net Mon May 2 16:07:05 2009
-
# type field that you can see at the top of any email that has come
-
# from a mailbox
-
2
def raw_envelope
-
@raw_envelope
-
end
-
-
2
def envelope_from
-
@envelope ? @envelope.from : nil
-
end
-
-
2
def envelope_date
-
@envelope ? @envelope.date : nil
-
end
-
-
# Sets the header of the message object.
-
#
-
# Example:
-
#
-
# mail.header = 'To: mikel@test.lindsaar.net\r\nFrom: Bob@bob.com'
-
# mail.header #=> <#Mail::Header
-
2
def header=(value)
-
4
@header = Mail::Header.new(value, charset)
-
end
-
-
# Returns the header object of the message object. Or, if passed
-
# a parameter sets the value.
-
#
-
# Example:
-
#
-
# mail = Mail::Message.new('To: mikel\r\nFrom: you')
-
# mail.header #=> #<Mail::Header:0x13ce14 @raw_source="To: mikel\r\nFr...
-
#
-
# mail.header #=> nil
-
# mail.header 'To: mikel\r\nFrom: you'
-
# mail.header #=> #<Mail::Header:0x13ce14 @raw_source="To: mikel\r\nFr...
-
2
def header(value = nil)
-
316
value ? self.header = value : @header
-
end
-
-
# Provides a way to set custom headers, by passing in a hash
-
2
def headers(hash = {})
-
hash.each_pair do |k,v|
-
header[k] = v
-
end
-
end
-
-
# Returns a list of parser errors on the header, each field that had an error
-
# will be reparsed as an unstructured field to preserve the data inside, but
-
# will not be used for further processing.
-
#
-
# It returns a nested array of [field_name, value, original_error_message]
-
# per error found.
-
#
-
# Example:
-
#
-
# message = Mail.new("Content-Transfer-Encoding: weirdo\r\n")
-
# message.errors.size #=> 1
-
# message.errors.first[0] #=> "Content-Transfer-Encoding"
-
# message.errors.first[1] #=> "weirdo"
-
# message.errors.first[3] #=> <The original error message exception>
-
#
-
# This is a good first defence on detecting spam by the way. Some spammers send
-
# invalid emails to try and get email parsers to give up parsing them.
-
2
def errors
-
header.errors
-
end
-
-
# Returns the Bcc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc #=> ['mikel@test.lindsaar.net']
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc << 'ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def bcc( val = nil )
-
12
default :bcc, val
-
end
-
-
# Sets the Bcc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.bcc #=> ['mikel@test.lindsaar.net']
-
# mail.bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def bcc=( val )
-
header[:bcc] = val
-
end
-
-
# Returns the Cc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc #=> ['mikel@test.lindsaar.net']
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc << 'ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def cc( val = nil )
-
12
default :cc, val
-
end
-
-
# Sets the Cc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.cc #=> ['mikel@test.lindsaar.net']
-
# mail.cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def cc=( val )
-
header[:cc] = val
-
end
-
-
2
def comments( val = nil )
-
default :comments, val
-
end
-
-
2
def comments=( val )
-
header[:comments] = val
-
end
-
-
2
def content_description( val = nil )
-
default :content_description, val
-
end
-
-
2
def content_description=( val )
-
header[:content_description] = val
-
end
-
-
2
def content_disposition( val = nil )
-
default :content_disposition, val
-
end
-
-
2
def content_disposition=( val )
-
header[:content_disposition] = val
-
end
-
-
2
def content_id( val = nil )
-
default :content_id, val
-
end
-
-
2
def content_id=( val )
-
header[:content_id] = val
-
end
-
-
2
def content_location( val = nil )
-
default :content_location, val
-
end
-
-
2
def content_location=( val )
-
header[:content_location] = val
-
end
-
-
2
def content_transfer_encoding( val = nil )
-
8
default :content_transfer_encoding, val
-
end
-
-
2
def content_transfer_encoding=( val )
-
8
header[:content_transfer_encoding] = val
-
end
-
-
2
def content_type( val = nil )
-
4
default :content_type, val
-
end
-
-
2
def content_type=( val )
-
4
header[:content_type] = val
-
end
-
-
2
def date( val = nil )
-
4
default :date, val
-
end
-
-
2
def date=( val )
-
header[:date] = val
-
end
-
-
2
def transport_encoding( val = nil)
-
if val
-
self.transport_encoding = val
-
else
-
@transport_encoding
-
end
-
end
-
-
2
def transport_encoding=( val )
-
@transport_encoding = Mail::Encodings.get_encoding(val)
-
end
-
-
# Returns the From value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from #=> ['mikel@test.lindsaar.net']
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from << 'ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def from( val = nil )
-
20
default :from, val
-
end
-
-
# Sets the From value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.from #=> ['mikel@test.lindsaar.net']
-
# mail.from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def from=( val )
-
header[:from] = val
-
end
-
-
2
def in_reply_to( val = nil )
-
default :in_reply_to, val
-
end
-
-
2
def in_reply_to=( val )
-
header[:in_reply_to] = val
-
end
-
-
2
def keywords( val = nil )
-
default :keywords, val
-
end
-
-
2
def keywords=( val )
-
header[:keywords] = val
-
end
-
-
# Returns the Message-ID of the mail object. Note, per RFC 2822 the Message ID
-
# consists of what is INSIDE the < > usually seen in the mail header, so this method
-
# will return only what is inside.
-
#
-
# Example:
-
#
-
# mail.message_id = '<1234@message.id>'
-
# mail.message_id #=> '1234@message.id'
-
#
-
# Also allows you to set the Message-ID by passing a string as a parameter
-
#
-
# mail.message_id '<1234@message.id>'
-
# mail.message_id #=> '1234@message.id'
-
2
def message_id( val = nil )
-
4
default :message_id, val
-
end
-
-
# Sets the Message-ID. Note, per RFC 2822 the Message ID consists of what is INSIDE
-
# the < > usually seen in the mail header, so this method will return only what is inside.
-
#
-
# mail.message_id = '<1234@message.id>'
-
# mail.message_id #=> '1234@message.id'
-
2
def message_id=( val )
-
header[:message_id] = val
-
end
-
-
# Returns the MIME version of the email as a string
-
#
-
# Example:
-
#
-
# mail.mime_version = '1.0'
-
# mail.mime_version #=> '1.0'
-
#
-
# Also allows you to set the MIME version by passing a string as a parameter.
-
#
-
# Example:
-
#
-
# mail.mime_version '1.0'
-
# mail.mime_version #=> '1.0'
-
2
def mime_version( val = nil )
-
default :mime_version, val
-
end
-
-
# Sets the MIME version of the email by accepting a string
-
#
-
# Example:
-
#
-
# mail.mime_version = '1.0'
-
# mail.mime_version #=> '1.0'
-
2
def mime_version=( val )
-
header[:mime_version] = val
-
end
-
-
2
def received( val = nil )
-
if val
-
header[:received] = val
-
else
-
header[:received]
-
end
-
end
-
-
2
def received=( val )
-
header[:received] = val
-
end
-
-
2
def references( val = nil )
-
default :references, val
-
end
-
-
2
def references=( val )
-
header[:references] = val
-
end
-
-
# Returns the Reply-To value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net']
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.reply_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.reply_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to << 'ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def reply_to( val = nil )
-
default :reply_to, val
-
end
-
-
# Sets the Reply-To value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net']
-
# mail.reply_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.reply_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def reply_to=( val )
-
header[:reply_to] = val
-
end
-
-
# Returns the Resent-Bcc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_bcc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc << 'ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_bcc( val = nil )
-
default :resent_bcc, val
-
end
-
-
# Sets the Resent-Bcc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_bcc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_bcc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_bcc=( val )
-
header[:resent_bcc] = val
-
end
-
-
# Returns the Resent-Cc value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_cc 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc << 'ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_cc( val = nil )
-
default :resent_cc, val
-
end
-
-
# Sets the Resent-Cc value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net']
-
# mail.resent_cc = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_cc #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_cc=( val )
-
header[:resent_cc] = val
-
end
-
-
2
def resent_date( val = nil )
-
default :resent_date, val
-
end
-
-
2
def resent_date=( val )
-
header[:resent_date] = val
-
end
-
-
# Returns the Resent-From value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net']
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_from ['Mikel <mikel@test.lindsaar.net>']
-
# mail.resent_from #=> 'mikel@test.lindsaar.net'
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_from << 'ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_from( val = nil )
-
default :resent_from, val
-
end
-
-
# Sets the Resent-From value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net']
-
# mail.resent_from = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_from #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_from=( val )
-
header[:resent_from] = val
-
end
-
-
2
def resent_message_id( val = nil )
-
default :resent_message_id, val
-
end
-
-
2
def resent_message_id=( val )
-
header[:resent_message_id] = val
-
end
-
-
# Returns the Resent-Sender value of the mail object, as a single string of an address
-
# spec. A sender per RFC 2822 must be a single address, so you can not append to
-
# this address.
-
#
-
# Example:
-
#
-
# mail.resent_sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_sender 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
-
2
def resent_sender( val = nil )
-
default :resent_sender, val
-
end
-
-
# Sets the Resent-Sender value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_sender #=> 'mikel@test.lindsaar.net'
-
2
def resent_sender=( val )
-
header[:resent_sender] = val
-
end
-
-
# Returns the Resent-To value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net']
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.resent_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.resent_to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to << 'ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_to( val = nil )
-
default :resent_to, val
-
end
-
-
# Sets the Resent-To value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net']
-
# mail.resent_to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.resent_to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def resent_to=( val )
-
header[:resent_to] = val
-
end
-
-
# Returns the return path of the mail object, or sets it if you pass a string
-
2
def return_path( val = nil )
-
8
default :return_path, val
-
end
-
-
# Sets the return path of the object
-
2
def return_path=( val )
-
header[:return_path] = val
-
end
-
-
# Returns the Sender value of the mail object, as a single string of an address
-
# spec. A sender per RFC 2822 must be a single address.
-
#
-
# Example:
-
#
-
# mail.sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.sender 'Mikel <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
2
def sender( val = nil )
-
8
default :sender, val
-
end
-
-
# Sets the Sender value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.sender = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.sender #=> 'mikel@test.lindsaar.net'
-
2
def sender=( val )
-
header[:sender] = val
-
end
-
-
# Returns the SMTP Envelope From value of the mail object, as a single
-
# string of an address spec.
-
#
-
# Defaults to Return-Path, Sender, or the first From address.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_from 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
-
2
def smtp_envelope_from( val = nil )
-
8
if val
-
self.smtp_envelope_from = val
-
else
-
8
@smtp_envelope_from || return_path || sender || from_addrs.first
-
end
-
end
-
-
# Sets the From address on the SMTP Envelope.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_from = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_from #=> 'mikel@test.lindsaar.net'
-
2
def smtp_envelope_from=( val )
-
@smtp_envelope_from = val
-
end
-
-
# Returns the SMTP Envelope To value of the mail object.
-
#
-
# Defaults to #destinations: To, Cc, and Bcc addresses.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_to #=> 'mikel@test.lindsaar.net'
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_to ['Mikel <mikel@test.lindsaar.net>', 'Lindsaar <lindsaar@test.lindsaar.net>']
-
# mail.smtp_envelope_to #=> ['mikel@test.lindsaar.net', 'lindsaar@test.lindsaar.net']
-
2
def smtp_envelope_to( val = nil )
-
8
if val
-
self.smtp_envelope_to = val
-
else
-
8
@smtp_envelope_to || destinations
-
end
-
end
-
-
# Sets the To addresses on the SMTP Envelope.
-
#
-
# Example:
-
#
-
# mail.smtp_envelope_to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.smtp_envelope_to #=> 'mikel@test.lindsaar.net'
-
#
-
# mail.smtp_envelope_to = ['Mikel <mikel@test.lindsaar.net>', 'Lindsaar <lindsaar@test.lindsaar.net>']
-
# mail.smtp_envelope_to #=> ['mikel@test.lindsaar.net', 'lindsaar@test.lindsaar.net']
-
2
def smtp_envelope_to=( val )
-
@smtp_envelope_to =
-
case val
-
when Array, NilClass
-
val
-
else
-
[val]
-
end
-
end
-
-
# Returns the decoded value of the subject field, as a single string.
-
#
-
# Example:
-
#
-
# mail.subject = "G'Day mate"
-
# mail.subject #=> "G'Day mate"
-
# mail.subject = '=?UTF-8?Q?This_is_=E3=81=82_string?='
-
# mail.subject #=> "This is あ string"
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.subject "G'Day mate"
-
# mail.subject #=> "G'Day mate"
-
2
def subject( val = nil )
-
4
default :subject, val
-
end
-
-
# Sets the Subject value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.subject = '=?UTF-8?Q?This_is_=E3=81=82_string?='
-
# mail.subject #=> "This is あ string"
-
2
def subject=( val )
-
header[:subject] = val
-
end
-
-
# Returns the To value of the mail object as an array of strings of
-
# address specs.
-
#
-
# Example:
-
#
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to #=> ['mikel@test.lindsaar.net']
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
#
-
# Also allows you to set the value by passing a value as a parameter
-
#
-
# Example:
-
#
-
# mail.to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to #=> ['mikel@test.lindsaar.net']
-
#
-
# Additionally, you can append new addresses to the returned Array like
-
# object.
-
#
-
# Example:
-
#
-
# mail.to 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to << 'ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def to( val = nil )
-
20
default :to, val
-
end
-
-
# Sets the To value of the mail object, pass in a string of the field
-
#
-
# Example:
-
#
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>'
-
# mail.to #=> ['mikel@test.lindsaar.net']
-
# mail.to = 'Mikel <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
-
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
-
2
def to=( val )
-
header[:to] = val
-
end
-
-
# Returns the default value of the field requested as a symbol.
-
#
-
# Each header field has a :default method which returns the most common use case for
-
# that field, for example, the date field types will return a DateTime object when
-
# sent :default, the subject, or unstructured fields will return a decoded string of
-
# their value, the address field types will return a single addr_spec or an array of
-
# addr_specs if there is more than one.
-
2
def default( sym, val = nil )
-
104
if val
-
header[sym] = val
-
else
-
104
header[sym].default if header[sym]
-
end
-
end
-
-
# Sets the body object of the message object.
-
#
-
# Example:
-
#
-
# mail.body = 'This is the body'
-
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is the bo...
-
#
-
# You can also reset the body of an Message object by setting body to nil
-
#
-
# Example:
-
#
-
# mail.body = 'this is the body'
-
# mail.body.encoded #=> 'this is the body'
-
# mail.body = nil
-
# mail.body.encoded #=> ''
-
#
-
# If you try and set the body of an email that is a multipart email, then instead
-
# of deleting all the parts of your email, mail will add a text/plain part to
-
# your email:
-
#
-
# mail.add_file 'somefilename.png'
-
# mail.parts.length #=> 1
-
# mail.body = "This is a body"
-
# mail.parts.length #=> 2
-
# mail.parts.last.content_type.content_type #=> 'This is a body'
-
2
def body=(value)
-
8
body_lazy(value)
-
end
-
-
# Returns the body of the message object. Or, if passed
-
# a parameter sets the value.
-
#
-
# Example:
-
#
-
# mail = Mail::Message.new('To: mikel\r\n\r\nThis is the body')
-
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is the bo...
-
#
-
# mail.body 'This is another body'
-
# mail.body #=> #<Mail::Body:0x13919c @raw_source="This is anothe...
-
2
def body(value = nil)
-
64
if value
-
self.body = value
-
# add_encoding_to_body
-
else
-
64
process_body_raw if @body_raw
-
64
@body
-
end
-
end
-
-
2
def body_encoding(value)
-
if value.nil?
-
body.encoding
-
else
-
body.encoding = value
-
end
-
end
-
-
2
def body_encoding=(value)
-
body.encoding = value
-
end
-
-
# Returns the list of addresses this message should be sent to by
-
# collecting the addresses off the to, cc and bcc fields.
-
#
-
# Example:
-
#
-
# mail.to = 'mikel@test.lindsaar.net'
-
# mail.cc = 'sam@test.lindsaar.net'
-
# mail.bcc = 'bob@test.lindsaar.net'
-
# mail.destinations.length #=> 3
-
# mail.destinations.first #=> 'mikel@test.lindsaar.net'
-
2
def destinations
-
8
[to_addrs, cc_addrs, bcc_addrs].compact.flatten
-
end
-
-
# Returns an array of addresses (the encoded value) in the From field,
-
# if no From field, returns an empty array
-
2
def from_addrs
-
8
from ? [from].flatten : []
-
end
-
-
# Returns an array of addresses (the encoded value) in the To field,
-
# if no To field, returns an empty array
-
2
def to_addrs
-
8
to ? [to].flatten : []
-
end
-
-
# Returns an array of addresses (the encoded value) in the Cc field,
-
# if no Cc field, returns an empty array
-
2
def cc_addrs
-
8
cc ? [cc].flatten : []
-
end
-
-
# Returns an array of addresses (the encoded value) in the Bcc field,
-
# if no Bcc field, returns an empty array
-
2
def bcc_addrs
-
8
bcc ? [bcc].flatten : []
-
end
-
-
# Allows you to add an arbitrary header
-
#
-
# Example:
-
#
-
# mail['foo'] = '1234'
-
# mail['foo'].to_s #=> '1234'
-
2
def []=(name, value)
-
28
if name.to_s == 'body'
-
4
self.body = value
-
24
elsif name.to_s =~ /content[-_]type/i
-
4
header[name] = value
-
20
elsif name.to_s == 'charset'
-
4
self.charset = value
-
else
-
16
header[name] = value
-
end
-
end
-
-
# Allows you to read an arbitrary header
-
#
-
# Example:
-
#
-
# mail['foo'] = '1234'
-
# mail['foo'].to_s #=> '1234'
-
2
def [](name)
-
header[underscoreize(name)]
-
end
-
-
# Method Missing in this implementation allows you to set any of the
-
# standard fields directly as you would the "to", "subject" etc.
-
#
-
# Those fields used most often (to, subject et al) are given their
-
# own method for ease of documentation and also to avoid the hook
-
# call to method missing.
-
#
-
# This will only catch the known fields listed in:
-
#
-
# Mail::Field::KNOWN_FIELDS
-
#
-
# as per RFC 2822, any ruby string or method name could pretty much
-
# be a field name, so we don't want to just catch ANYTHING sent to
-
# a message object and interpret it as a header.
-
#
-
# This method provides all three types of header call to set, read
-
# and explicitly set with the = operator
-
#
-
# Examples:
-
#
-
# mail.comments = 'These are some comments'
-
# mail.comments #=> 'These are some comments'
-
#
-
# mail.comments 'These are other comments'
-
# mail.comments #=> 'These are other comments'
-
#
-
#
-
# mail.date = 'Tue, 1 Jul 2003 10:52:37 +0200'
-
# mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'
-
#
-
# mail.date 'Tue, 1 Jul 2003 10:52:37 +0200'
-
# mail.date.to_s #=> 'Tue, 1 Jul 2003 10:52:37 +0200'
-
#
-
#
-
# mail.resent_msg_id = '<1234@resent_msg_id.lindsaar.net>'
-
# mail.resent_msg_id #=> '<1234@resent_msg_id.lindsaar.net>'
-
#
-
# mail.resent_msg_id '<4567@resent_msg_id.lindsaar.net>'
-
# mail.resent_msg_id #=> '<4567@resent_msg_id.lindsaar.net>'
-
2
def method_missing(name, *args, &block)
-
#:nodoc:
-
# Only take the structured fields, as we could take _anything_ really
-
# as it could become an optional field... "but therin lies the dark side"
-
field_name = underscoreize(name).chomp("=")
-
if Mail::Field::KNOWN_FIELDS.include?(field_name)
-
if args.empty?
-
header[field_name]
-
else
-
header[field_name] = args.first
-
end
-
else
-
super # otherwise pass it on
-
end
-
#:startdoc:
-
end
-
-
# Returns an FieldList of all the fields in the header in the order that
-
# they appear in the header
-
2
def header_fields
-
header.fields
-
end
-
-
# Returns true if the message has a message ID field, the field may or may
-
# not have a value, but the field exists or not.
-
2
def has_message_id?
-
8
header.has_message_id?
-
end
-
-
# Returns true if the message has a Date field, the field may or may
-
# not have a value, but the field exists or not.
-
2
def has_date?
-
8
header.has_date?
-
end
-
-
# Returns true if the message has a Date field, the field may or may
-
# not have a value, but the field exists or not.
-
2
def has_mime_version?
-
8
header.has_mime_version?
-
end
-
-
2
def has_content_type?
-
40
tmp = header[:content_type].main_type rescue nil
-
40
!!tmp
-
end
-
-
2
def has_charset?
-
8
tmp = header[:content_type].parameters rescue nil
-
8
!!(has_content_type? && tmp && tmp['charset'])
-
end
-
-
2
def has_content_transfer_encoding?
-
16
header[:content_transfer_encoding] && header[:content_transfer_encoding].errors.blank?
-
end
-
-
2
def has_transfer_encoding? # :nodoc:
-
STDERR.puts(":has_transfer_encoding? is deprecated in Mail 1.4.3. Please use has_content_transfer_encoding?\n#{caller}")
-
has_content_transfer_encoding?
-
end
-
-
# Creates a new empty Message-ID field and inserts it in the correct order
-
# into the Header. The MessageIdField object will automatically generate
-
# a unique message ID if you try and encode it or output it to_s without
-
# specifying a message id.
-
#
-
# It will preserve the message ID you specify if you do.
-
2
def add_message_id(msg_id_val = '')
-
4
header['message-id'] = msg_id_val
-
end
-
-
# Creates a new empty Date field and inserts it in the correct order
-
# into the Header. The DateField object will automatically generate
-
# DateTime.now's date if you try and encode it or output it to_s without
-
# specifying a date yourself.
-
#
-
# It will preserve any date you specify if you do.
-
2
def add_date(date_val = '')
-
4
header['date'] = date_val
-
end
-
-
# Creates a new empty Mime Version field and inserts it in the correct order
-
# into the Header. The MimeVersion object will automatically generate
-
# set itself to '1.0' if you try and encode it or output it to_s without
-
# specifying a version yourself.
-
#
-
# It will preserve any date you specify if you do.
-
2
def add_mime_version(ver_val = '')
-
header['mime-version'] = ver_val
-
end
-
-
# Adds a content type and charset if the body is US-ASCII
-
#
-
# Otherwise raises a warning
-
2
def add_content_type
-
header[:content_type] = 'text/plain'
-
end
-
-
# Adds a content type and charset if the body is US-ASCII
-
#
-
# Otherwise raises a warning
-
2
def add_charset
-
if !body.empty?
-
# Only give a warning if this isn't an attachment, has non US-ASCII and the user
-
# has not specified an encoding explicitly.
-
if @defaulted_charset && body.raw_source.not_ascii_only? && !self.attachment?
-
warning = "Non US-ASCII detected and no charset defined.\nDefaulting to UTF-8, set your own if this is incorrect.\n"
-
STDERR.puts(warning)
-
end
-
header[:content_type].parameters['charset'] = @charset
-
end
-
end
-
-
# Adds a content transfer encoding
-
#
-
# Otherwise raises a warning
-
2
def add_content_transfer_encoding
-
if body.only_us_ascii?
-
header[:content_transfer_encoding] = '7bit'
-
else
-
warning = "Non US-ASCII detected and no content-transfer-encoding defined.\nDefaulting to 8bit, set your own if this is incorrect.\n"
-
STDERR.puts(warning)
-
header[:content_transfer_encoding] = '8bit'
-
end
-
end
-
-
2
def add_transfer_encoding # :nodoc:
-
STDERR.puts(":add_transfer_encoding is deprecated in Mail 1.4.3. Please use add_content_transfer_encoding\n#{caller}")
-
add_content_transfer_encoding
-
end
-
-
2
def transfer_encoding # :nodoc:
-
STDERR.puts(":transfer_encoding is deprecated in Mail 1.4.3. Please use content_transfer_encoding\n#{caller}")
-
content_transfer_encoding
-
end
-
-
# Returns the MIME media type of part we are on, this is taken from the content-type header
-
2
def mime_type
-
has_content_type? ? header[:content_type].string : nil rescue nil
-
end
-
-
2
def message_content_type
-
STDERR.puts(":message_content_type is deprecated in Mail 1.4.3. Please use mime_type\n#{caller}")
-
mime_type
-
end
-
-
# Returns the character set defined in the content type field
-
2
def charset
-
4
if @header
-
has_content_type? ? content_type_parameters['charset'] : @charset
-
else
-
4
@charset
-
end
-
end
-
-
# Sets the charset to the supplied value.
-
2
def charset=(value)
-
12
@defaulted_charset = false
-
12
@charset = value
-
12
@header.charset = value
-
end
-
-
# Returns the main content type
-
2
def main_type
-
8
has_content_type? ? header[:content_type].main_type : nil rescue nil
-
end
-
-
# Returns the sub content type
-
2
def sub_type
-
has_content_type? ? header[:content_type].sub_type : nil rescue nil
-
end
-
-
# Returns the content type parameters
-
2
def mime_parameters
-
STDERR.puts(':mime_parameters is deprecated in Mail 1.4.3, please use :content_type_parameters instead')
-
content_type_parameters
-
end
-
-
# Returns the content type parameters
-
2
def content_type_parameters
-
4
has_content_type? ? header[:content_type].parameters : nil rescue nil
-
end
-
-
# Returns true if the message is multipart
-
2
def multipart?
-
12
has_content_type? ? !!(main_type =~ /^multipart$/i) : false
-
end
-
-
# Returns true if the message is a multipart/report
-
2
def multipart_report?
-
multipart? && sub_type =~ /^report$/i
-
end
-
-
# Returns true if the message is a multipart/report; report-type=delivery-status;
-
2
def delivery_status_report?
-
multipart_report? && content_type_parameters['report-type'] =~ /^delivery-status$/i
-
end
-
-
# returns the part in a multipart/report email that has the content-type delivery-status
-
2
def delivery_status_part
-
@delivery_stats_part ||= parts.select { |p| p.delivery_status_report_part? }.first
-
end
-
-
2
def bounced?
-
delivery_status_part and delivery_status_part.bounced?
-
end
-
-
2
def action
-
delivery_status_part and delivery_status_part.action
-
end
-
-
2
def final_recipient
-
delivery_status_part and delivery_status_part.final_recipient
-
end
-
-
2
def error_status
-
delivery_status_part and delivery_status_part.error_status
-
end
-
-
2
def diagnostic_code
-
delivery_status_part and delivery_status_part.diagnostic_code
-
end
-
-
2
def remote_mta
-
delivery_status_part and delivery_status_part.remote_mta
-
end
-
-
2
def retryable?
-
delivery_status_part and delivery_status_part.retryable?
-
end
-
-
# Returns the current boundary for this message part
-
2
def boundary
-
content_type_parameters ? content_type_parameters['boundary'] : nil
-
end
-
-
# Returns a parts list object of all the parts in the message
-
2
def parts
-
24
body.parts
-
end
-
-
# Returns an AttachmentsList object, which holds all of the attachments in
-
# the receiver object (either the entier email or a part within) and all
-
# of its descendants.
-
#
-
# It also allows you to add attachments to the mail object directly, like so:
-
#
-
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
-
#
-
# If you do this, then Mail will take the file name and work out the MIME media type
-
# set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
-
# base64 encode the contents of the attachment all for you.
-
#
-
# You can also specify overrides if you want by passing a hash instead of a string:
-
#
-
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
-
# :content => File.read('/path/to/filename.jpg')}
-
#
-
# If you want to use a different encoding than Base64, you can pass an encoding in,
-
# but then it is up to you to pass in the content pre-encoded, and don't expect
-
# Mail to know how to decode this data:
-
#
-
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
-
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
-
# :encoding => 'SpecialEncoding',
-
# :content => file_content }
-
#
-
# You can also search for specific attachments:
-
#
-
# # By Filename
-
# mail.attachments['filename.jpg'] #=> Mail::Part object or nil
-
#
-
# # or by index
-
# mail.attachments[0] #=> Mail::Part (first attachment)
-
#
-
2
def attachments
-
8
parts.attachments
-
end
-
-
2
def has_attachments?
-
8
!attachments.empty?
-
end
-
-
# Accessor for html_part
-
2
def html_part(&block)
-
if block_given?
-
self.html_part = Mail::Part.new(:content_type => 'text/html', &block)
-
else
-
@html_part || find_first_mime_type('text/html')
-
end
-
end
-
-
# Accessor for text_part
-
2
def text_part(&block)
-
if block_given?
-
self.text_part = Mail::Part.new(:content_type => 'text/plain', &block)
-
else
-
@text_part || find_first_mime_type('text/plain')
-
end
-
end
-
-
# Helper to add a html part to a multipart/alternative email. If this and
-
# text_part are both defined in a message, then it will be a multipart/alternative
-
# message and set itself that way.
-
2
def html_part=(msg)
-
# Assign the html part and set multipart/alternative if there's a text part.
-
if msg
-
@html_part = msg
-
@html_part.content_type = 'text/html' unless @html_part.has_content_type?
-
add_multipart_alternate_header if text_part
-
add_part @html_part
-
-
# If nil, delete the html part and back out of multipart/alternative.
-
elsif @html_part
-
parts.delete_if { |p| p.object_id == @html_part.object_id }
-
@html_part = nil
-
if text_part
-
self.content_type = nil
-
body.boundary = nil
-
end
-
end
-
end
-
-
# Helper to add a text part to a multipart/alternative email. If this and
-
# html_part are both defined in a message, then it will be a multipart/alternative
-
# message and set itself that way.
-
2
def text_part=(msg)
-
# Assign the text part and set multipart/alternative if there's an html part.
-
if msg
-
@text_part = msg
-
@text_part.content_type = 'text/plain' unless @text_part.has_content_type?
-
add_multipart_alternate_header if html_part
-
add_part @text_part
-
-
# If nil, delete the text part and back out of multipart/alternative.
-
elsif @text_part
-
parts.delete_if { |p| p.object_id == @text_part.object_id }
-
@text_part = nil
-
if html_part
-
self.content_type = nil
-
body.boundary = nil
-
end
-
end
-
end
-
-
# Adds a part to the parts list or creates the part list
-
2
def add_part(part)
-
if !body.multipart? && !self.body.decoded.blank?
-
@text_part = Mail::Part.new('Content-Type: text/plain;')
-
@text_part.body = body.decoded
-
self.body << @text_part
-
add_multipart_alternate_header
-
end
-
add_boundary
-
self.body << part
-
end
-
-
# Allows you to add a part in block form to an existing mail message object
-
#
-
# Example:
-
#
-
# mail = Mail.new do
-
# part :content_type => "multipart/alternative", :content_disposition => "inline" do |p|
-
# p.part :content_type => "text/plain", :body => "test text\nline #2"
-
# p.part :content_type => "text/html", :body => "<b>test</b> HTML<br/>\nline #2"
-
# end
-
# end
-
2
def part(params = {})
-
new_part = Part.new(params)
-
yield new_part if block_given?
-
add_part(new_part)
-
end
-
-
# Adds a file to the message. You have two options with this method, you can
-
# just pass in the absolute path to the file you want and Mail will read the file,
-
# get the filename from the path you pass in and guess the MIME media type, or you
-
# can pass in the filename as a string, and pass in the file content as a blob.
-
#
-
# Example:
-
#
-
# m = Mail.new
-
# m.add_file('/path/to/filename.png')
-
#
-
# m = Mail.new
-
# m.add_file(:filename => 'filename.png', :content => File.read('/path/to/file.jpg'))
-
#
-
# Note also that if you add a file to an existing message, Mail will convert that message
-
# to a MIME multipart email, moving whatever plain text body you had into its own text
-
# plain part.
-
#
-
# Example:
-
#
-
# m = Mail.new do
-
# body 'this is some text'
-
# end
-
# m.multipart? #=> false
-
# m.add_file('/path/to/filename.png')
-
# m.multipart? #=> true
-
# m.parts.first.content_type.content_type #=> 'text/plain'
-
# m.parts.last.content_type.content_type #=> 'image/png'
-
#
-
# See also #attachments
-
2
def add_file(values)
-
convert_to_multipart unless self.multipart? || self.body.decoded.blank?
-
add_multipart_mixed_header
-
if values.is_a?(String)
-
basename = File.basename(values)
-
filedata = File.open(values, 'rb') { |f| f.read }
-
else
-
basename = values[:filename]
-
filedata = values[:content] || File.open(values[:filename], 'rb') { |f| f.read }
-
end
-
self.attachments[basename] = filedata
-
end
-
-
2
def convert_to_multipart
-
text = body.decoded
-
self.body = ''
-
text_part = Mail::Part.new({:content_type => 'text/plain;',
-
:body => text})
-
text_part.charset = charset unless @defaulted_charset
-
self.body << text_part
-
end
-
-
# Encodes the message, calls encode on all its parts, gets an email message
-
# ready to send
-
2
def ready_to_send!
-
8
identify_and_set_transfer_encoding
-
8
parts.sort!([ "text/plain", "text/enriched", "text/html", "multipart/alternative" ])
-
8
parts.each do |part|
-
part.transport_encoding = transport_encoding
-
part.ready_to_send!
-
end
-
8
add_required_fields
-
end
-
-
2
def encode!
-
STDERR.puts("Deprecated in 1.1.0 in favour of :ready_to_send! as it is less confusing with encoding and decoding.")
-
ready_to_send!
-
end
-
-
# Outputs an encoded string representation of the mail message including
-
# all headers, attachments, etc. This is an encoded email in US-ASCII,
-
# so it is able to be directly sent to an email server.
-
2
def encoded
-
8
ready_to_send!
-
8
buffer = header.encoded
-
8
buffer << "\r\n"
-
8
buffer << body.encoded(content_transfer_encoding)
-
8
buffer
-
end
-
-
2
def without_attachments!
-
return self unless has_attachments?
-
-
parts.delete_if { |p| p.attachment? }
-
body_raw = if parts.empty?
-
''
-
else
-
body.encoded
-
end
-
-
@body = Mail::Body.new(body_raw)
-
-
self
-
end
-
-
2
def to_yaml(opts = {})
-
hash = {}
-
hash['headers'] = {}
-
header.fields.each do |field|
-
hash['headers'][field.name] = field.value
-
end
-
hash['delivery_handler'] = delivery_handler.to_s if delivery_handler
-
hash['transport_encoding'] = transport_encoding.to_s
-
special_variables = [:@header, :@delivery_handler, :@transport_encoding]
-
if multipart?
-
hash['multipart_body'] = []
-
body.parts.map { |part| hash['multipart_body'] << part.to_yaml }
-
special_variables.push(:@body, :@text_part, :@html_part)
-
end
-
(instance_variables.map(&:to_sym) - special_variables).each do |var|
-
hash[var.to_s] = instance_variable_get(var)
-
end
-
hash.to_yaml(opts)
-
end
-
-
2
def self.from_yaml(str)
-
hash = YAML.load(str)
-
m = self.new(:headers => hash['headers'])
-
hash.delete('headers')
-
hash.each do |k,v|
-
case
-
when k == 'delivery_handler'
-
begin
-
m.delivery_handler = Object.const_get(v) unless v.blank?
-
rescue NameError
-
end
-
when k == 'transport_encoding'
-
m.transport_encoding(v)
-
when k == 'multipart_body'
-
v.map {|part| m.add_part Mail::Part.from_yaml(part) }
-
when k =~ /^@/
-
m.instance_variable_set(k.to_sym, v)
-
end
-
end
-
m
-
end
-
-
2
def self.from_hash(hash)
-
Mail::Message.new(hash)
-
end
-
-
2
def to_s
-
encoded
-
end
-
-
2
def inspect
-
"#<#{self.class}:#{self.object_id}, Multipart: #{multipart?}, Headers: #{header.field_summary}>"
-
end
-
-
2
def decoded
-
case
-
when self.text?
-
decode_body_as_text
-
when self.attachment?
-
decode_body
-
when !self.multipart?
-
body.decoded
-
else
-
raise NoMethodError, 'Can not decode an entire message, try calling #decoded on the various fields and body or parts if it is a multipart message.'
-
end
-
end
-
-
2
def read
-
if self.attachment?
-
decode_body
-
else
-
raise NoMethodError, 'Can not call read on a part unless it is an attachment.'
-
end
-
end
-
-
2
def decode_body
-
body.decoded
-
end
-
-
# Returns true if this part is an attachment,
-
# false otherwise.
-
2
def attachment?
-
!!find_attachment
-
end
-
-
# Returns the attachment data if there is any
-
2
def attachment
-
@attachment
-
end
-
-
# Returns the filename of the attachment
-
2
def filename
-
find_attachment
-
end
-
-
2
def all_parts
-
parts.map { |p| [p, p.all_parts] }.flatten
-
end
-
-
2
def find_first_mime_type(mt)
-
all_parts.detect { |p| p.mime_type == mt && !p.attachment? }
-
end
-
-
# Skips the deletion of this message. All other messages
-
# flagged for delete still will be deleted at session close (i.e. when
-
# #find exits). Only has an effect if you're using #find_and_delete
-
# or #find with :delete_after_find set to true.
-
2
def skip_deletion
-
@mark_for_delete = false
-
end
-
-
# Sets whether this message should be deleted at session close (i.e.
-
# after #find). Message will only be deleted if messages are retrieved
-
# using the #find_and_delete method, or by calling #find with
-
# :delete_after_find set to true.
-
2
def mark_for_delete=(value = true)
-
@mark_for_delete = value
-
end
-
-
# Returns whether message will be marked for deletion.
-
# If so, the message will be deleted at session close (i.e. after #find
-
# exits), but only if also using the #find_and_delete method, or by
-
# calling #find with :delete_after_find set to true.
-
#
-
# Side-note: Just to be clear, this method will return true even if
-
# the message hasn't yet been marked for delete on the mail server.
-
# However, if this method returns true, it *will be* marked on the
-
# server after each block yields back to #find or #find_and_delete.
-
2
def is_marked_for_delete?
-
return @mark_for_delete
-
end
-
-
2
def text?
-
has_content_type? ? !!(main_type =~ /^text$/i) : false
-
end
-
-
2
private
-
-
# 2.1. General Description
-
# A message consists of header fields (collectively called "the header
-
# of the message") followed, optionally, by a body. The header is a
-
# sequence of lines of characters with special syntax as defined in
-
# this standard. The body is simply a sequence of characters that
-
# follows the header and is separated from the header by an empty line
-
# (i.e., a line with nothing preceding the CRLF).
-
#
-
# Additionally, I allow for the case where someone might have put whitespace
-
# on the "gap line"
-
2
def parse_message
-
4
header_part, body_part = raw_source.lstrip.split(/#{CRLF}#{CRLF}|#{CRLF}#{WSP}*#{CRLF}(?!#{WSP})/m, 2)
-
4
self.header = header_part
-
4
self.body = body_part
-
end
-
-
2
def raw_source=(value)
-
4
value.force_encoding("binary") if RUBY_VERSION >= "1.9.1"
-
4
@raw_source = value.to_crlf
-
end
-
-
# see comments to body=. We take data and process it lazily
-
2
def body_lazy(value)
-
8
process_body_raw if @body_raw && value
-
case
-
when value == nil || value.length<=0
-
4
@body = Mail::Body.new('')
-
4
@body_raw = nil
-
4
add_encoding_to_body
-
when @body && @body.multipart?
-
@body << Mail::Part.new(value)
-
add_encoding_to_body
-
else
-
4
@body_raw = value
-
# process_body_raw
-
8
end
-
end
-
-
-
2
def process_body_raw
-
4
@body = Mail::Body.new(@body_raw)
-
4
@body_raw = nil
-
4
separate_parts if @separate_parts
-
-
4
add_encoding_to_body
-
end
-
-
2
def set_envelope_header
-
4
raw_string = raw_source.to_s
-
4
if match_data = raw_source.to_s.match(/\AFrom\s(#{TEXT}+)#{CRLF}/m)
-
set_envelope(match_data[1])
-
self.raw_source = raw_string.sub(match_data[0], "")
-
end
-
end
-
-
2
def separate_parts
-
body.split!(boundary)
-
end
-
-
2
def add_encoding_to_body
-
8
if has_content_transfer_encoding?
-
@body.encoding = content_transfer_encoding
-
end
-
end
-
-
2
def identify_and_set_transfer_encoding
-
8
if body && body.multipart?
-
self.content_transfer_encoding = @transport_encoding
-
else
-
8
self.content_transfer_encoding = body.get_best_encoding(@transport_encoding)
-
end
-
end
-
-
2
def add_required_fields
-
8
add_required_message_fields
-
8
add_multipart_mixed_header if body.multipart?
-
8
add_content_type unless has_content_type?
-
8
add_charset unless has_charset?
-
8
add_content_transfer_encoding unless has_content_transfer_encoding?
-
end
-
-
2
def add_required_message_fields
-
8
add_date unless has_date?
-
8
add_mime_version unless has_mime_version?
-
8
add_message_id unless has_message_id?
-
end
-
-
2
def add_multipart_alternate_header
-
header['content-type'] = ContentTypeField.with_boundary('multipart/alternative').value
-
header['content_type'].parameters[:charset] = @charset
-
body.boundary = boundary
-
end
-
-
2
def add_boundary
-
unless body.boundary && boundary
-
header['content-type'] = 'multipart/mixed' unless header['content-type']
-
header['content-type'].parameters[:boundary] = ContentTypeField.generate_boundary
-
header['content_type'].parameters[:charset] = @charset
-
body.boundary = boundary
-
end
-
end
-
-
2
def add_multipart_mixed_header
-
unless header['content-type']
-
header['content-type'] = ContentTypeField.with_boundary('multipart/mixed').value
-
header['content_type'].parameters[:charset] = @charset
-
body.boundary = boundary
-
end
-
end
-
-
2
def init_with_hash(hash)
-
passed_in_options = IndifferentHash.new(hash)
-
self.raw_source = ''
-
-
@header = Mail::Header.new
-
@body = Mail::Body.new
-
@body_raw = nil
-
-
# We need to store the body until last, as we need all headers added first
-
body_content = nil
-
-
passed_in_options.each_pair do |k,v|
-
k = underscoreize(k).to_sym if k.class == String
-
if k == :headers
-
self.headers(v)
-
elsif k == :body
-
body_content = v
-
else
-
self[k] = v
-
end
-
end
-
-
if body_content
-
self.body = body_content
-
if has_content_transfer_encoding?
-
body.encoding = content_transfer_encoding
-
end
-
end
-
end
-
-
2
def init_with_string(string)
-
4
self.raw_source = string
-
4
set_envelope_header
-
4
parse_message
-
4
@separate_parts = multipart?
-
end
-
-
# Returns the filename of the attachment (if it exists) or returns nil
-
2
def find_attachment
-
content_type_name = header[:content_type].filename rescue nil
-
content_disp_name = header[:content_disposition].filename rescue nil
-
content_loc_name = header[:content_location].location rescue nil
-
case
-
when content_type && content_type_name
-
filename = content_type_name
-
when content_disposition && content_disp_name
-
filename = content_disp_name
-
when content_location && content_loc_name
-
filename = content_loc_name
-
else
-
filename = nil
-
end
-
filename = Mail::Encodings.decode_encode(filename, :decode) if filename rescue filename
-
filename
-
end
-
-
2
def do_delivery
-
4
begin
-
4
if perform_deliveries
-
4
delivery_method.deliver!(self)
-
end
-
rescue Exception => e # Net::SMTP errors or sendmail pipe errors
-
raise e if raise_delivery_errors
-
end
-
end
-
-
2
def decode_body_as_text
-
body_text = decode_body
-
if charset
-
if RUBY_VERSION < '1.9'
-
require 'iconv'
-
return Iconv.conv("UTF-8//TRANSLIT//IGNORE", charset, body_text)
-
else
-
if encoding = Encoding.find(charset) rescue nil
-
body_text.force_encoding(encoding)
-
return body_text.encode(Encoding::UTF_8, :undef => :replace, :invalid => :replace, :replace => '')
-
end
-
end
-
end
-
body_text
-
end
-
-
end
-
end
-
2
require 'mail/network/retriever_methods/base'
-
-
2
module Mail
-
2
register_autoload :SMTP, 'mail/network/delivery_methods/smtp'
-
2
register_autoload :FileDelivery, 'mail/network/delivery_methods/file_delivery'
-
2
register_autoload :Sendmail, 'mail/network/delivery_methods/sendmail'
-
2
register_autoload :Exim, 'mail/network/delivery_methods/exim'
-
2
register_autoload :SMTPConnection, 'mail/network/delivery_methods/smtp_connection'
-
2
register_autoload :TestMailer, 'mail/network/delivery_methods/test_mailer'
-
-
2
register_autoload :POP3, 'mail/network/retriever_methods/pop3'
-
2
register_autoload :IMAP, 'mail/network/retriever_methods/imap'
-
2
register_autoload :TestRetriever, 'mail/network/retriever_methods/test_retriever'
-
end
-
2
require 'mail/check_delivery_params'
-
-
2
module Mail
-
-
# FileDelivery class delivers emails into multiple files based on the destination
-
# address. Each file is appended to if it already exists.
-
#
-
# So if you have an email going to fred@test, bob@test, joe@anothertest, and you
-
# set your location path to /path/to/mails then FileDelivery will create the directory
-
# if it does not exist, and put one copy of the email in three files, called
-
# by their message id
-
#
-
# Make sure the path you specify with :location is writable by the Ruby process
-
# running Mail.
-
2
class FileDelivery
-
2
include Mail::CheckDeliveryParams
-
-
2
if RUBY_VERSION >= '1.9.1'
-
2
require 'fileutils'
-
else
-
require 'ftools'
-
end
-
-
2
def initialize(values)
-
self.settings = { :location => './mails' }.merge!(values)
-
end
-
-
2
attr_accessor :settings
-
-
2
def deliver!(mail)
-
check_delivery_params(mail)
-
-
if ::File.respond_to?(:makedirs)
-
::File.makedirs settings[:location]
-
else
-
::FileUtils.mkdir_p settings[:location]
-
end
-
-
mail.destinations.uniq.each do |to|
-
::File.open(::File.join(settings[:location], File.basename(to.to_s)), 'a') { |f| "#{f.write(mail.encoded)}\r\n\r\n" }
-
end
-
end
-
-
end
-
end
-
2
require 'mail/check_delivery_params'
-
-
2
module Mail
-
# A delivery method implementation which sends via sendmail.
-
#
-
# To use this, first find out where the sendmail binary is on your computer,
-
# if you are on a mac or unix box, it is usually in /usr/sbin/sendmail, this will
-
# be your sendmail location.
-
#
-
# Mail.defaults do
-
# delivery_method :sendmail
-
# end
-
#
-
# Or if your sendmail binary is not at '/usr/sbin/sendmail'
-
#
-
# Mail.defaults do
-
# delivery_method :sendmail, :location => '/absolute/path/to/your/sendmail'
-
# end
-
#
-
# Then just deliver the email as normal:
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# Or by calling deliver on a Mail message
-
#
-
# mail = Mail.new do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# mail.deliver!
-
2
class Sendmail
-
2
include Mail::CheckDeliveryParams
-
-
2
def initialize(values)
-
self.settings = { :location => '/usr/sbin/sendmail',
-
:arguments => '-i' }.merge(values)
-
end
-
-
2
attr_accessor :settings
-
-
2
def deliver!(mail)
-
smtp_from, smtp_to, message = check_delivery_params(mail)
-
-
from = "-f #{self.class.shellquote(smtp_from)}"
-
to = smtp_to.map { |to| self.class.shellquote(to) }.join(' ')
-
-
arguments = "#{settings[:arguments]} #{from} --"
-
self.class.call(settings[:location], arguments, to, message)
-
end
-
-
2
def self.call(path, arguments, destinations, encoded_message)
-
popen "#{path} #{arguments} #{destinations}" do |io|
-
io.puts encoded_message.to_lf
-
io.flush
-
end
-
end
-
-
2
if RUBY_VERSION < '1.9.0'
-
def self.popen(command, &block)
-
IO.popen "#{command} 2>&1", 'w+', &block
-
end
-
else
-
2
def self.popen(command, &block)
-
IO.popen command, 'w+', :err => :out, &block
-
end
-
end
-
-
# The following is an adaptation of ruby 1.9.2's shellwords.rb file,
-
# it is modified to include '+' in the allowed list to allow for
-
# sendmail to accept email addresses as the sender with a + in them.
-
2
def self.shellquote(address)
-
# Process as a single byte sequence because not all shell
-
# implementations are multibyte aware.
-
#
-
# A LF cannot be escaped with a backslash because a backslash + LF
-
# combo is regarded as line continuation and simply ignored. Strip it.
-
escaped = address.gsub(/([^A-Za-z0-9_\s\+\-.,:\/@])/n, "\\\\\\1").gsub("\n", '')
-
%("#{escaped}")
-
end
-
end
-
end
-
2
require 'mail/check_delivery_params'
-
-
2
module Mail
-
# == Sending Email with SMTP
-
#
-
# Mail allows you to send emails using SMTP. This is done by wrapping Net::SMTP in
-
# an easy to use manner.
-
#
-
# === Sending via SMTP server on Localhost
-
#
-
# Sending locally (to a postfix or sendmail server running on localhost) requires
-
# no special setup. Just to Mail.deliver &block or message.deliver! and it will
-
# be sent in this method.
-
#
-
# === Sending via MobileMe
-
#
-
# Mail.defaults do
-
# delivery_method :smtp, { :address => "smtp.me.com",
-
# :port => 587,
-
# :domain => 'your.host.name',
-
# :user_name => '<username>',
-
# :password => '<password>',
-
# :authentication => 'plain',
-
# :enable_starttls_auto => true }
-
# end
-
#
-
# === Sending via GMail
-
#
-
# Mail.defaults do
-
# delivery_method :smtp, { :address => "smtp.gmail.com",
-
# :port => 587,
-
# :domain => 'your.host.name',
-
# :user_name => '<username>',
-
# :password => '<password>',
-
# :authentication => 'plain',
-
# :enable_starttls_auto => true }
-
# end
-
#
-
# === Certificate verification
-
#
-
# When using TLS, some mail servers provide certificates that are self-signed
-
# or whose names do not exactly match the hostname given in the address.
-
# OpenSSL will reject these by default. The best remedy is to use the correct
-
# hostname or update the certificate authorities trusted by your ruby. If
-
# that isn't possible, you can control this behavior with
-
# an :openssl_verify_mode setting. Its value may be either an OpenSSL
-
# verify mode constant (OpenSSL::SSL::VERIFY_NONE), or a string containing
-
# the name of an OpenSSL verify mode (none, peer, client_once,
-
# fail_if_no_peer_cert).
-
#
-
# === Others
-
#
-
# Feel free to send me other examples that were tricky
-
#
-
# === Delivering the email
-
#
-
# Once you have the settings right, sending the email is done by:
-
#
-
# Mail.deliver do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# Or by calling deliver on a Mail message
-
#
-
# mail = Mail.new do
-
# to 'mikel@test.lindsaar.net'
-
# from 'ada@test.lindsaar.net'
-
# subject 'testing sendmail'
-
# body 'testing sendmail'
-
# end
-
#
-
# mail.deliver!
-
2
class SMTP
-
2
include Mail::CheckDeliveryParams
-
-
2
def initialize(values)
-
1
self.settings = { :address => "localhost",
-
:port => 25,
-
:domain => 'localhost.localdomain',
-
:user_name => nil,
-
:password => nil,
-
:authentication => nil,
-
:enable_starttls_auto => true,
-
:openssl_verify_mode => nil,
-
:ssl => nil,
-
:tls => nil
-
}.merge!(values)
-
end
-
-
2
attr_accessor :settings
-
-
# Send the message via SMTP.
-
# The from and to attributes are optional. If not set, they are retrieve from the Message.
-
2
def deliver!(mail)
-
smtp_from, smtp_to, message = check_delivery_params(mail)
-
-
smtp = Net::SMTP.new(settings[:address], settings[:port])
-
if settings[:tls] || settings[:ssl]
-
if smtp.respond_to?(:enable_tls)
-
smtp.enable_tls(ssl_context)
-
end
-
elsif settings[:enable_starttls_auto]
-
if smtp.respond_to?(:enable_starttls_auto)
-
smtp.enable_starttls_auto(ssl_context)
-
end
-
end
-
-
response = nil
-
smtp.start(settings[:domain], settings[:user_name], settings[:password], settings[:authentication]) do |smtp_obj|
-
response = smtp_obj.sendmail(message, smtp_from, smtp_to)
-
end
-
-
if settings[:return_response]
-
response
-
else
-
self
-
end
-
end
-
-
-
2
private
-
-
# Allow SSL context to be configured via settings, for Ruby >= 1.9
-
# Just returns openssl verify mode for Ruby 1.8.x
-
2
def ssl_context
-
openssl_verify_mode = settings[:openssl_verify_mode]
-
-
if openssl_verify_mode.kind_of?(String)
-
openssl_verify_mode = "OpenSSL::SSL::VERIFY_#{openssl_verify_mode.upcase}".constantize
-
end
-
-
if RUBY_VERSION < '1.9.0'
-
openssl_verify_mode
-
else
-
context = Net::SMTP.default_ssl_context
-
context.verify_mode = openssl_verify_mode
-
context.ca_path = settings[:ca_path] if settings[:ca_path]
-
context.ca_file = settings[:ca_file] if settings[:ca_file]
-
context
-
end
-
end
-
end
-
end
-
2
require 'mail/check_delivery_params'
-
-
2
module Mail
-
# The TestMailer is a bare bones mailer that does nothing. It is useful
-
# when you are testing.
-
#
-
# It also provides a template of the minimum methods you require to implement
-
# if you want to make a custom mailer for Mail
-
2
class TestMailer
-
2
include Mail::CheckDeliveryParams
-
-
# Provides a store of all the emails sent with the TestMailer so you can check them.
-
2
def TestMailer.deliveries
-
4
@@deliveries ||= []
-
end
-
-
# Allows you to over write the default deliveries store from an array to some
-
# other object. If you just want to clear the store,
-
# call TestMailer.deliveries.clear.
-
#
-
# If you place another object here, please make sure it responds to:
-
#
-
# * << (message)
-
# * clear
-
# * length
-
# * size
-
# * and other common Array methods
-
2
def TestMailer.deliveries=(val)
-
@@deliveries = val
-
end
-
-
2
def initialize(values)
-
4
@settings = values.dup
-
end
-
-
2
attr_accessor :settings
-
-
2
def deliver!(mail)
-
4
check_delivery_params(mail)
-
4
Mail::TestMailer.deliveries << mail
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
2
module Mail
-
-
2
class Retriever
-
-
# Get the oldest received email(s)
-
#
-
# Possible options:
-
# count: number of emails to retrieve. The default value is 1.
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
#
-
2
def first(options = {}, &block)
-
options ||= {}
-
options[:what] = :first
-
options[:count] ||= 1
-
find(options, &block)
-
end
-
-
# Get the most recent received email(s)
-
#
-
# Possible options:
-
# count: number of emails to retrieve. The default value is 1.
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
#
-
2
def last(options = {}, &block)
-
options ||= {}
-
options[:what] = :last
-
options[:count] ||= 1
-
find(options, &block)
-
end
-
-
# Get all emails.
-
#
-
# Possible options:
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
#
-
2
def all(options = {}, &block)
-
options ||= {}
-
options[:count] = :all
-
find(options, &block)
-
end
-
-
# Find emails in the mailbox, and then deletes them. Without any options, the
-
# five last received emails are returned.
-
#
-
# Possible options:
-
# what: last or first emails. The default is :first.
-
# order: order of emails returned. Possible values are :asc or :desc. Default value is :asc.
-
# count: number of emails to retrieve. The default value is 10. A value of 1 returns an
-
# instance of Message, not an array of Message instances.
-
# delete_after_find: flag for whether to delete each retreived email after find. Default
-
# is true. Call #find if you would like this to default to false.
-
#
-
2
def find_and_delete(options = {}, &block)
-
options ||= {}
-
options[:delete_after_find] ||= true
-
find(options, &block)
-
end
-
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module AddressLists
-
2
include Treetop::Runtime
-
-
2
def root
-
16
@root ||= :primary_address
-
end
-
-
2
include RFC2822
-
-
2
module PrimaryAddress0
-
2
def addresses
-
32
([first_addr] + other_addr.elements.map { |o| o.addr_value }).reject { |e| e.empty? }
-
end
-
end
-
-
2
module PrimaryAddress1
-
2
def addresses
-
[first_addr] + other_addr.elements.map { |o| o.addr_value }
-
end
-
end
-
-
2
def _nt_primary_address
-
16
start_index = index
-
16
if node_cache[:primary_address].has_key?(index)
-
cached = node_cache[:primary_address][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
i0 = index
-
16
r1 = _nt_address_list
-
16
r1.extend(PrimaryAddress0)
-
16
if r1
-
16
r0 = r1
-
else
-
r2 = _nt_obs_addr_list
-
r2.extend(PrimaryAddress1)
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
16
node_cache[:primary_address][start_index] = r0
-
-
16
r0
-
end
-
-
end
-
-
2
class AddressListsParser < Treetop::Runtime::CompiledParser
-
2
include AddressLists
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module ContentDisposition
-
2
include Treetop::Runtime
-
-
2
def root
-
@root ||= :content_disposition
-
end
-
-
2
include RFC2822
-
-
2
include RFC2045
-
-
2
module ContentDisposition0
-
2
def CFWS1
-
elements[0]
-
end
-
-
2
def parameter
-
elements[2]
-
end
-
-
2
def CFWS2
-
elements[3]
-
end
-
end
-
-
2
module ContentDisposition1
-
2
def disposition_type
-
elements[0]
-
end
-
-
2
def param_hashes
-
elements[1]
-
end
-
end
-
-
2
module ContentDisposition2
-
2
def parameters
-
param_hashes.elements.map do |param|
-
param.parameter.param_hash
-
end
-
end
-
end
-
-
2
def _nt_content_disposition
-
start_index = index
-
if node_cache[:content_disposition].has_key?(index)
-
cached = node_cache[:content_disposition][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_disposition_type
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
r4 = _nt_CFWS
-
s3 << r4
-
if r4
-
if has_terminal?(";", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r5 = nil
-
end
-
s3 << r5
-
if r5
-
r6 = _nt_parameter
-
s3 << r6
-
if r6
-
r7 = _nt_CFWS
-
s3 << r7
-
end
-
end
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ContentDisposition0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ContentDisposition1)
-
r0.extend(ContentDisposition2)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:content_disposition][start_index] = r0
-
-
r0
-
end
-
-
2
module DispositionType0
-
end
-
-
2
module DispositionType1
-
end
-
-
2
def _nt_disposition_type
-
start_index = index
-
if node_cache[:disposition_type].has_key?(index)
-
cached = node_cache[:disposition_type][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
if has_terminal?('\G[iI]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
s1 << r2
-
if r2
-
if has_terminal?('\G[nN]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
s1 << r3
-
if r3
-
if has_terminal?('\G[lL]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
s1 << r4
-
if r4
-
if has_terminal?('\G[iI]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
s1 << r5
-
if r5
-
if has_terminal?('\G[nN]', true, index)
-
r6 = true
-
@index += 1
-
else
-
r6 = nil
-
end
-
s1 << r6
-
if r6
-
if has_terminal?('\G[eE]', true, index)
-
r7 = true
-
@index += 1
-
else
-
r7 = nil
-
end
-
s1 << r7
-
end
-
end
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(DispositionType0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
i8, s8 = index, []
-
if has_terminal?('\G[aA]', true, index)
-
r9 = true
-
@index += 1
-
else
-
r9 = nil
-
end
-
s8 << r9
-
if r9
-
if has_terminal?('\G[tT]', true, index)
-
r10 = true
-
@index += 1
-
else
-
r10 = nil
-
end
-
s8 << r10
-
if r10
-
if has_terminal?('\G[tT]', true, index)
-
r11 = true
-
@index += 1
-
else
-
r11 = nil
-
end
-
s8 << r11
-
if r11
-
if has_terminal?('\G[aA]', true, index)
-
r12 = true
-
@index += 1
-
else
-
r12 = nil
-
end
-
s8 << r12
-
if r12
-
if has_terminal?('\G[cC]', true, index)
-
r13 = true
-
@index += 1
-
else
-
r13 = nil
-
end
-
s8 << r13
-
if r13
-
if has_terminal?('\G[hH]', true, index)
-
r14 = true
-
@index += 1
-
else
-
r14 = nil
-
end
-
s8 << r14
-
if r14
-
if has_terminal?('\G[mM]', true, index)
-
r15 = true
-
@index += 1
-
else
-
r15 = nil
-
end
-
s8 << r15
-
if r15
-
if has_terminal?('\G[eE]', true, index)
-
r16 = true
-
@index += 1
-
else
-
r16 = nil
-
end
-
s8 << r16
-
if r16
-
if has_terminal?('\G[nN]', true, index)
-
r17 = true
-
@index += 1
-
else
-
r17 = nil
-
end
-
s8 << r17
-
if r17
-
if has_terminal?('\G[tT]', true, index)
-
r18 = true
-
@index += 1
-
else
-
r18 = nil
-
end
-
s8 << r18
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
if s8.last
-
r8 = instantiate_node(SyntaxNode,input, i8...index, s8)
-
r8.extend(DispositionType1)
-
else
-
@index = i8
-
r8 = nil
-
end
-
if r8
-
r0 = r8
-
else
-
r19 = _nt_extension_token
-
if r19
-
r0 = r19
-
else
-
if has_terminal?('', false, index)
-
r20 = instantiate_node(SyntaxNode,input, index...(index + 0))
-
@index += 0
-
else
-
terminal_parse_failure('')
-
r20 = nil
-
end
-
if r20
-
r0 = r20
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
-
node_cache[:disposition_type][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_extension_token
-
start_index = index
-
if node_cache[:extension_token].has_key?(index)
-
cached = node_cache[:extension_token][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_ietf_token
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_custom_x_token
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:extension_token][start_index] = r0
-
-
r0
-
end
-
-
2
module Parameter0
-
2
def attr
-
elements[1]
-
end
-
-
2
def val
-
elements[3]
-
end
-
-
end
-
-
2
module Parameter1
-
2
def param_hash
-
{attr.text_value => val.text_value}
-
end
-
end
-
-
2
def _nt_parameter
-
start_index = index
-
if node_cache[:parameter].has_key?(index)
-
cached = node_cache[:parameter][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r3 = _nt_attribute
-
s0 << r3
-
if r3
-
if has_terminal?("=", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("=")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_value
-
s0 << r5
-
if r5
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Parameter0)
-
r0.extend(Parameter1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:parameter][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_attribute
-
start_index = index
-
if node_cache[:attribute].has_key?(index)
-
cached = node_cache[:attribute][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
r1 = _nt_token
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
node_cache[:attribute][start_index] = r0
-
-
r0
-
end
-
-
2
module Value0
-
2
def text_value
-
quoted_content.text_value
-
end
-
end
-
-
2
def _nt_value
-
start_index = index
-
if node_cache[:value].has_key?(index)
-
cached = node_cache[:value][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_quoted_string
-
r1.extend(Value0)
-
if r1
-
r0 = r1
-
else
-
s2, i2 = [], index
-
loop do
-
i3 = index
-
r4 = _nt_token
-
if r4
-
r3 = r4
-
else
-
if has_terminal?('\G[\\x3d]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
if r5
-
r3 = r5
-
else
-
@index = i3
-
r3 = nil
-
end
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:value][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
2
class ContentDispositionParser < Treetop::Runtime::CompiledParser
-
2
include ContentDisposition
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module ContentLocation
-
2
include Treetop::Runtime
-
-
2
def root
-
@root ||= :primary
-
end
-
-
2
include RFC2822
-
-
2
include RFC2045
-
-
2
module Primary0
-
2
def CFWS1
-
elements[0]
-
end
-
-
2
def location
-
elements[1]
-
end
-
-
2
def CFWS2
-
elements[2]
-
end
-
end
-
-
2
def _nt_primary
-
start_index = index
-
if node_cache[:primary].has_key?(index)
-
cached = node_cache[:primary][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_CFWS
-
s0 << r1
-
if r1
-
r2 = _nt_location
-
s0 << r2
-
if r2
-
r3 = _nt_CFWS
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Primary0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:primary][start_index] = r0
-
-
r0
-
end
-
-
2
module Location0
-
2
def text_value
-
quoted_content.text_value
-
end
-
end
-
-
2
def _nt_location
-
start_index = index
-
if node_cache[:location].has_key?(index)
-
cached = node_cache[:location][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_quoted_string
-
r1.extend(Location0)
-
if r1
-
r0 = r1
-
else
-
s2, i2 = [], index
-
loop do
-
i3 = index
-
r4 = _nt_token
-
if r4
-
r3 = r4
-
else
-
if has_terminal?('\G[\\x3d]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
if r5
-
r3 = r5
-
else
-
@index = i3
-
r3 = nil
-
end
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:location][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
2
class ContentLocationParser < Treetop::Runtime::CompiledParser
-
2
include ContentLocation
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module ContentTransferEncoding
-
2
include Treetop::Runtime
-
-
2
def root
-
8
@root ||= :primary
-
end
-
-
2
include RFC2822
-
-
2
include RFC2045
-
-
2
module Primary0
-
2
def CFWS1
-
elements[0]
-
end
-
-
2
def encoding
-
8
elements[1]
-
end
-
-
2
def CFWS2
-
elements[2]
-
end
-
-
2
def CFWS3
-
elements[4]
-
end
-
end
-
-
2
def _nt_primary
-
8
start_index = index
-
8
if node_cache[:primary].has_key?(index)
-
cached = node_cache[:primary][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
8
i0, s0 = index, []
-
8
r1 = _nt_CFWS
-
8
s0 << r1
-
8
if r1
-
8
r2 = _nt_encoding
-
8
s0 << r2
-
8
if r2
-
8
r3 = _nt_CFWS
-
8
s0 << r3
-
8
if r3
-
8
if has_terminal?(";", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure(";")
-
8
r5 = nil
-
end
-
8
if r5
-
r4 = r5
-
else
-
8
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
8
s0 << r4
-
8
if r4
-
8
r6 = _nt_CFWS
-
8
s0 << r6
-
end
-
end
-
end
-
end
-
8
if s0.last
-
8
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
8
r0.extend(Primary0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
8
node_cache[:primary][start_index] = r0
-
-
8
r0
-
end
-
-
2
def _nt_encoding
-
8
start_index = index
-
8
if node_cache[:encoding].has_key?(index)
-
cached = node_cache[:encoding][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
8
i0 = index
-
8
if has_terminal?("7bits", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 5))
-
@index += 5
-
else
-
8
terminal_parse_failure("7bits")
-
8
r1 = nil
-
end
-
8
if r1
-
r0 = r1
-
else
-
8
if has_terminal?("8bits", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 5))
-
@index += 5
-
else
-
8
terminal_parse_failure("8bits")
-
8
r2 = nil
-
end
-
8
if r2
-
r0 = r2
-
else
-
8
if has_terminal?("7bit", false, index)
-
8
r3 = instantiate_node(SyntaxNode,input, index...(index + 4))
-
8
@index += 4
-
else
-
terminal_parse_failure("7bit")
-
r3 = nil
-
end
-
8
if r3
-
8
r0 = r3
-
else
-
if has_terminal?("8bit", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 4))
-
@index += 4
-
else
-
terminal_parse_failure("8bit")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("binary", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 6))
-
@index += 6
-
else
-
terminal_parse_failure("binary")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?("quoted-printable", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 16))
-
@index += 16
-
else
-
terminal_parse_failure("quoted-printable")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?("base64", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 6))
-
@index += 6
-
else
-
terminal_parse_failure("base64")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
r8 = _nt_ietf_token
-
if r8
-
r0 = r8
-
else
-
r9 = _nt_custom_x_token
-
if r9
-
r0 = r9
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
8
node_cache[:encoding][start_index] = r0
-
-
8
r0
-
end
-
-
end
-
-
2
class ContentTransferEncodingParser < Treetop::Runtime::CompiledParser
-
2
include ContentTransferEncoding
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module ContentType
-
2
include Treetop::Runtime
-
-
2
def root
-
8
@root ||= :content_type
-
end
-
-
2
include RFC2822
-
-
2
include RFC2045
-
-
2
module ContentType0
-
2
def CFWS1
-
elements[0]
-
end
-
-
2
def parameter
-
elements[2]
-
end
-
-
2
def CFWS2
-
elements[3]
-
end
-
end
-
-
2
module ContentType1
-
2
def main_type
-
8
elements[0]
-
end
-
-
2
def sub_type
-
8
elements[2]
-
end
-
-
2
def param_hashes
-
8
elements[3]
-
end
-
end
-
-
2
module ContentType2
-
2
def parameters
-
8
param_hashes.elements.map do |param|
-
param.parameter.param_hash
-
end
-
end
-
end
-
-
2
def _nt_content_type
-
8
start_index = index
-
8
if node_cache[:content_type].has_key?(index)
-
cached = node_cache[:content_type][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
8
i0, s0 = index, []
-
8
r1 = _nt_main_type
-
8
s0 << r1
-
8
if r1
-
8
if has_terminal?("/", false, index)
-
8
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
8
@index += 1
-
else
-
terminal_parse_failure("/")
-
r2 = nil
-
end
-
8
s0 << r2
-
8
if r2
-
8
r3 = _nt_sub_type
-
8
s0 << r3
-
8
if r3
-
8
s4, i4 = [], index
-
8
loop do
-
8
i5, s5 = index, []
-
8
r6 = _nt_CFWS
-
8
s5 << r6
-
8
if r6
-
8
s7, i7 = [], index
-
8
loop do
-
8
if has_terminal?(";", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure(";")
-
8
r8 = nil
-
end
-
8
if r8
-
s7 << r8
-
else
-
8
break
-
end
-
end
-
8
r7 = instantiate_node(SyntaxNode,input, i7...index, s7)
-
8
s5 << r7
-
8
if r7
-
8
r9 = _nt_parameter
-
8
s5 << r9
-
8
if r9
-
r10 = _nt_CFWS
-
s5 << r10
-
end
-
end
-
end
-
8
if s5.last
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
r5.extend(ContentType0)
-
else
-
8
@index = i5
-
8
r5 = nil
-
end
-
8
if r5
-
s4 << r5
-
else
-
8
break
-
end
-
end
-
8
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
8
s0 << r4
-
end
-
end
-
end
-
8
if s0.last
-
8
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
8
r0.extend(ContentType1)
-
8
r0.extend(ContentType2)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
8
node_cache[:content_type][start_index] = r0
-
-
8
r0
-
end
-
-
2
def _nt_main_type
-
8
start_index = index
-
8
if node_cache[:main_type].has_key?(index)
-
cached = node_cache[:main_type][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
8
i0 = index
-
8
r1 = _nt_discrete_type
-
8
if r1
-
8
r0 = r1
-
else
-
r2 = _nt_composite_type
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
8
node_cache[:main_type][start_index] = r0
-
-
8
r0
-
end
-
-
2
module DiscreteType0
-
end
-
-
2
module DiscreteType1
-
end
-
-
2
module DiscreteType2
-
end
-
-
2
module DiscreteType3
-
end
-
-
2
module DiscreteType4
-
end
-
-
2
def _nt_discrete_type
-
8
start_index = index
-
8
if node_cache[:discrete_type].has_key?(index)
-
cached = node_cache[:discrete_type][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
8
i0 = index
-
8
i1, s1 = index, []
-
8
if has_terminal?('\G[tT]', true, index)
-
8
r2 = true
-
8
@index += 1
-
else
-
r2 = nil
-
end
-
8
s1 << r2
-
8
if r2
-
8
if has_terminal?('\G[eE]', true, index)
-
8
r3 = true
-
8
@index += 1
-
else
-
r3 = nil
-
end
-
8
s1 << r3
-
8
if r3
-
8
if has_terminal?('\G[xX]', true, index)
-
8
r4 = true
-
8
@index += 1
-
else
-
r4 = nil
-
end
-
8
s1 << r4
-
8
if r4
-
8
if has_terminal?('\G[tT]', true, index)
-
8
r5 = true
-
8
@index += 1
-
else
-
r5 = nil
-
end
-
8
s1 << r5
-
end
-
end
-
end
-
8
if s1.last
-
8
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
8
r1.extend(DiscreteType0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
8
if r1
-
8
r0 = r1
-
else
-
i6, s6 = index, []
-
if has_terminal?('\G[iI]', true, index)
-
r7 = true
-
@index += 1
-
else
-
r7 = nil
-
end
-
s6 << r7
-
if r7
-
if has_terminal?('\G[mM]', true, index)
-
r8 = true
-
@index += 1
-
else
-
r8 = nil
-
end
-
s6 << r8
-
if r8
-
if has_terminal?('\G[aA]', true, index)
-
r9 = true
-
@index += 1
-
else
-
r9 = nil
-
end
-
s6 << r9
-
if r9
-
if has_terminal?('\G[gG]', true, index)
-
r10 = true
-
@index += 1
-
else
-
r10 = nil
-
end
-
s6 << r10
-
if r10
-
if has_terminal?('\G[eE]', true, index)
-
r11 = true
-
@index += 1
-
else
-
r11 = nil
-
end
-
s6 << r11
-
end
-
end
-
end
-
end
-
if s6.last
-
r6 = instantiate_node(SyntaxNode,input, i6...index, s6)
-
r6.extend(DiscreteType1)
-
else
-
@index = i6
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
i12, s12 = index, []
-
if has_terminal?('\G[aA]', true, index)
-
r13 = true
-
@index += 1
-
else
-
r13 = nil
-
end
-
s12 << r13
-
if r13
-
if has_terminal?('\G[uU]', true, index)
-
r14 = true
-
@index += 1
-
else
-
r14 = nil
-
end
-
s12 << r14
-
if r14
-
if has_terminal?('\G[dD]', true, index)
-
r15 = true
-
@index += 1
-
else
-
r15 = nil
-
end
-
s12 << r15
-
if r15
-
if has_terminal?('\G[iI]', true, index)
-
r16 = true
-
@index += 1
-
else
-
r16 = nil
-
end
-
s12 << r16
-
if r16
-
if has_terminal?('\G[oO]', true, index)
-
r17 = true
-
@index += 1
-
else
-
r17 = nil
-
end
-
s12 << r17
-
end
-
end
-
end
-
end
-
if s12.last
-
r12 = instantiate_node(SyntaxNode,input, i12...index, s12)
-
r12.extend(DiscreteType2)
-
else
-
@index = i12
-
r12 = nil
-
end
-
if r12
-
r0 = r12
-
else
-
i18, s18 = index, []
-
if has_terminal?('\G[vV]', true, index)
-
r19 = true
-
@index += 1
-
else
-
r19 = nil
-
end
-
s18 << r19
-
if r19
-
if has_terminal?('\G[iI]', true, index)
-
r20 = true
-
@index += 1
-
else
-
r20 = nil
-
end
-
s18 << r20
-
if r20
-
if has_terminal?('\G[dD]', true, index)
-
r21 = true
-
@index += 1
-
else
-
r21 = nil
-
end
-
s18 << r21
-
if r21
-
if has_terminal?('\G[eE]', true, index)
-
r22 = true
-
@index += 1
-
else
-
r22 = nil
-
end
-
s18 << r22
-
if r22
-
if has_terminal?('\G[oO]', true, index)
-
r23 = true
-
@index += 1
-
else
-
r23 = nil
-
end
-
s18 << r23
-
end
-
end
-
end
-
end
-
if s18.last
-
r18 = instantiate_node(SyntaxNode,input, i18...index, s18)
-
r18.extend(DiscreteType3)
-
else
-
@index = i18
-
r18 = nil
-
end
-
if r18
-
r0 = r18
-
else
-
i24, s24 = index, []
-
if has_terminal?('\G[aA]', true, index)
-
r25 = true
-
@index += 1
-
else
-
r25 = nil
-
end
-
s24 << r25
-
if r25
-
if has_terminal?('\G[pP]', true, index)
-
r26 = true
-
@index += 1
-
else
-
r26 = nil
-
end
-
s24 << r26
-
if r26
-
if has_terminal?('\G[pP]', true, index)
-
r27 = true
-
@index += 1
-
else
-
r27 = nil
-
end
-
s24 << r27
-
if r27
-
if has_terminal?('\G[lL]', true, index)
-
r28 = true
-
@index += 1
-
else
-
r28 = nil
-
end
-
s24 << r28
-
if r28
-
if has_terminal?('\G[iI]', true, index)
-
r29 = true
-
@index += 1
-
else
-
r29 = nil
-
end
-
s24 << r29
-
if r29
-
if has_terminal?('\G[cC]', true, index)
-
r30 = true
-
@index += 1
-
else
-
r30 = nil
-
end
-
s24 << r30
-
if r30
-
if has_terminal?('\G[aA]', true, index)
-
r31 = true
-
@index += 1
-
else
-
r31 = nil
-
end
-
s24 << r31
-
if r31
-
if has_terminal?('\G[tT]', true, index)
-
r32 = true
-
@index += 1
-
else
-
r32 = nil
-
end
-
s24 << r32
-
if r32
-
if has_terminal?('\G[iI]', true, index)
-
r33 = true
-
@index += 1
-
else
-
r33 = nil
-
end
-
s24 << r33
-
if r33
-
if has_terminal?('\G[oO]', true, index)
-
r34 = true
-
@index += 1
-
else
-
r34 = nil
-
end
-
s24 << r34
-
if r34
-
if has_terminal?('\G[nN]', true, index)
-
r35 = true
-
@index += 1
-
else
-
r35 = nil
-
end
-
s24 << r35
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
if s24.last
-
r24 = instantiate_node(SyntaxNode,input, i24...index, s24)
-
r24.extend(DiscreteType4)
-
else
-
@index = i24
-
r24 = nil
-
end
-
if r24
-
r0 = r24
-
else
-
r36 = _nt_extension_token
-
if r36
-
r0 = r36
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
-
8
node_cache[:discrete_type][start_index] = r0
-
-
8
r0
-
end
-
-
2
module CompositeType0
-
end
-
-
2
module CompositeType1
-
end
-
-
2
def _nt_composite_type
-
start_index = index
-
if node_cache[:composite_type].has_key?(index)
-
cached = node_cache[:composite_type][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
if has_terminal?('\G[mM]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
s1 << r2
-
if r2
-
if has_terminal?('\G[eE]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
s1 << r3
-
if r3
-
if has_terminal?('\G[sS]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
s1 << r4
-
if r4
-
if has_terminal?('\G[sS]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
s1 << r5
-
if r5
-
if has_terminal?('\G[aA]', true, index)
-
r6 = true
-
@index += 1
-
else
-
r6 = nil
-
end
-
s1 << r6
-
if r6
-
if has_terminal?('\G[gG]', true, index)
-
r7 = true
-
@index += 1
-
else
-
r7 = nil
-
end
-
s1 << r7
-
if r7
-
if has_terminal?('\G[eE]', true, index)
-
r8 = true
-
@index += 1
-
else
-
r8 = nil
-
end
-
s1 << r8
-
end
-
end
-
end
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(CompositeType0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
i9, s9 = index, []
-
if has_terminal?('\G[mM]', true, index)
-
r10 = true
-
@index += 1
-
else
-
r10 = nil
-
end
-
s9 << r10
-
if r10
-
if has_terminal?('\G[uU]', true, index)
-
r11 = true
-
@index += 1
-
else
-
r11 = nil
-
end
-
s9 << r11
-
if r11
-
if has_terminal?('\G[lL]', true, index)
-
r12 = true
-
@index += 1
-
else
-
r12 = nil
-
end
-
s9 << r12
-
if r12
-
if has_terminal?('\G[tT]', true, index)
-
r13 = true
-
@index += 1
-
else
-
r13 = nil
-
end
-
s9 << r13
-
if r13
-
if has_terminal?('\G[iI]', true, index)
-
r14 = true
-
@index += 1
-
else
-
r14 = nil
-
end
-
s9 << r14
-
if r14
-
if has_terminal?('\G[pP]', true, index)
-
r15 = true
-
@index += 1
-
else
-
r15 = nil
-
end
-
s9 << r15
-
if r15
-
if has_terminal?('\G[aA]', true, index)
-
r16 = true
-
@index += 1
-
else
-
r16 = nil
-
end
-
s9 << r16
-
if r16
-
if has_terminal?('\G[rR]', true, index)
-
r17 = true
-
@index += 1
-
else
-
r17 = nil
-
end
-
s9 << r17
-
if r17
-
if has_terminal?('\G[tT]', true, index)
-
r18 = true
-
@index += 1
-
else
-
r18 = nil
-
end
-
s9 << r18
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
if s9.last
-
r9 = instantiate_node(SyntaxNode,input, i9...index, s9)
-
r9.extend(CompositeType1)
-
else
-
@index = i9
-
r9 = nil
-
end
-
if r9
-
r0 = r9
-
else
-
r19 = _nt_extension_token
-
if r19
-
r0 = r19
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:composite_type][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_extension_token
-
8
start_index = index
-
8
if node_cache[:extension_token].has_key?(index)
-
cached = node_cache[:extension_token][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
8
i0 = index
-
8
r1 = _nt_ietf_token
-
8
if r1
-
8
r0 = r1
-
else
-
r2 = _nt_custom_x_token
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
8
node_cache[:extension_token][start_index] = r0
-
-
8
r0
-
end
-
-
2
def _nt_sub_type
-
8
start_index = index
-
8
if node_cache[:sub_type].has_key?(index)
-
cached = node_cache[:sub_type][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
8
i0 = index
-
8
r1 = _nt_extension_token
-
8
if r1
-
8
r0 = r1
-
else
-
r2 = _nt_iana_token
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
8
node_cache[:sub_type][start_index] = r0
-
-
8
r0
-
end
-
-
2
module Parameter0
-
2
def attr
-
elements[1]
-
end
-
-
2
def val
-
elements[3]
-
end
-
-
end
-
-
2
module Parameter1
-
2
def param_hash
-
{attr.text_value => val.text_value}
-
end
-
end
-
-
2
def _nt_parameter
-
8
start_index = index
-
8
if node_cache[:parameter].has_key?(index)
-
cached = node_cache[:parameter][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
8
i0, s0 = index, []
-
8
r2 = _nt_CFWS
-
8
if r2
-
8
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
8
s0 << r1
-
8
if r1
-
8
r3 = _nt_attribute
-
8
s0 << r3
-
8
if r3
-
if has_terminal?("=", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("=")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_value
-
s0 << r5
-
if r5
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
end
-
end
-
8
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Parameter0)
-
r0.extend(Parameter1)
-
else
-
8
@index = i0
-
8
r0 = nil
-
end
-
-
8
node_cache[:parameter][start_index] = r0
-
-
8
r0
-
end
-
-
2
def _nt_attribute
-
8
start_index = index
-
8
if node_cache[:attribute].has_key?(index)
-
cached = node_cache[:attribute][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
8
s0, i0 = [], index
-
8
loop do
-
8
r1 = _nt_token
-
8
if r1
-
s0 << r1
-
else
-
8
break
-
end
-
end
-
8
if s0.empty?
-
8
@index = i0
-
8
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
8
node_cache[:attribute][start_index] = r0
-
-
8
r0
-
end
-
-
2
module Value0
-
2
def text_value
-
quoted_content.text_value
-
end
-
end
-
-
2
def _nt_value
-
start_index = index
-
if node_cache[:value].has_key?(index)
-
cached = node_cache[:value][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_quoted_string
-
r1.extend(Value0)
-
if r1
-
r0 = r1
-
else
-
s2, i2 = [], index
-
loop do
-
i3 = index
-
r4 = _nt_token
-
if r4
-
r3 = r4
-
else
-
if has_terminal?('\G[\\x3d]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
if r5
-
r3 = r5
-
else
-
@index = i3
-
r3 = nil
-
end
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:value][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
2
class ContentTypeParser < Treetop::Runtime::CompiledParser
-
2
include ContentType
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module DateTime
-
2
include Treetop::Runtime
-
-
2
def root
-
@root ||= :primary
-
end
-
-
2
include RFC2822
-
-
2
module Primary0
-
2
def day_of_week
-
elements[0]
-
end
-
-
end
-
-
2
module Primary1
-
2
def date
-
elements[1]
-
end
-
-
2
def FWS
-
elements[2]
-
end
-
-
2
def time
-
elements[3]
-
end
-
-
end
-
-
2
def _nt_primary
-
start_index = index
-
if node_cache[:primary].has_key?(index)
-
cached = node_cache[:primary][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
i2, s2 = index, []
-
r3 = _nt_day_of_week
-
s2 << r3
-
if r3
-
if has_terminal?(",", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r4 = nil
-
end
-
s2 << r4
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(Primary0)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r5 = _nt_date
-
s0 << r5
-
if r5
-
r6 = _nt_FWS
-
s0 << r6
-
if r6
-
r7 = _nt_time
-
s0 << r7
-
if r7
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r8
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Primary1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:primary][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
2
class DateTimeParser < Treetop::Runtime::CompiledParser
-
2
include DateTime
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module EnvelopeFrom
-
2
include Treetop::Runtime
-
-
2
def root
-
@root ||= :primary
-
end
-
-
2
include RFC2822
-
-
2
module Primary0
-
2
def addr_spec
-
elements[0]
-
end
-
-
2
def ctime_date
-
elements[1]
-
end
-
end
-
-
2
def _nt_primary
-
start_index = index
-
if node_cache[:primary].has_key?(index)
-
cached = node_cache[:primary][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_addr_spec
-
s0 << r1
-
if r1
-
r2 = _nt_ctime_date
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Primary0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:primary][start_index] = r0
-
-
r0
-
end
-
-
2
module CtimeDate0
-
2
def day_name
-
elements[0]
-
end
-
-
2
def month_name
-
elements[2]
-
end
-
-
2
def day
-
elements[4]
-
end
-
-
2
def time_of_day
-
elements[6]
-
end
-
-
2
def year
-
elements[8]
-
end
-
end
-
-
2
def _nt_ctime_date
-
start_index = index
-
if node_cache[:ctime_date].has_key?(index)
-
cached = node_cache[:ctime_date][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_day_name
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
if has_terminal?(" ", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(" ")
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
s0 << r2
-
if r2
-
r4 = _nt_month_name
-
s0 << r4
-
if r4
-
s5, i5 = [], index
-
loop do
-
if has_terminal?(" ", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(" ")
-
r6 = nil
-
end
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
if s5.empty?
-
@index = i5
-
r5 = nil
-
else
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
end
-
s0 << r5
-
if r5
-
r7 = _nt_day
-
s0 << r7
-
if r7
-
if has_terminal?(" ", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(" ")
-
r8 = nil
-
end
-
s0 << r8
-
if r8
-
r9 = _nt_time_of_day
-
s0 << r9
-
if r9
-
if has_terminal?(" ", false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(" ")
-
r10 = nil
-
end
-
s0 << r10
-
if r10
-
r11 = _nt_year
-
s0 << r11
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(CtimeDate0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:ctime_date][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
2
class EnvelopeFromParser < Treetop::Runtime::CompiledParser
-
2
include EnvelopeFrom
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module MessageIds
-
2
include Treetop::Runtime
-
-
2
def root
-
4
@root ||= :primary
-
end
-
-
2
include RFC2822
-
-
2
module Primary0
-
2
def message_ids
-
4
[first_msg_id] + other_msg_ids.elements.map { |o| o.msg_id_value }
-
end
-
end
-
-
2
def _nt_primary
-
4
start_index = index
-
4
if node_cache[:primary].has_key?(index)
-
cached = node_cache[:primary][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
4
r0 = _nt_message_ids
-
4
r0.extend(Primary0)
-
-
4
node_cache[:primary][start_index] = r0
-
-
4
r0
-
end
-
-
end
-
-
2
class MessageIdsParser < Treetop::Runtime::CompiledParser
-
2
include MessageIds
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module MimeVersion
-
2
include Treetop::Runtime
-
-
2
def root
-
4
@root ||= :version
-
end
-
-
2
include RFC2822
-
-
2
module Version0
-
2
def CFWS1
-
elements[0]
-
end
-
-
2
def major_digits
-
4
elements[1]
-
end
-
-
2
def minor_digits
-
4
elements[5]
-
end
-
-
2
def CFWS2
-
elements[6]
-
end
-
end
-
-
2
module Version1
-
2
def major
-
4
major_digits
-
end
-
-
2
def minor
-
4
minor_digits
-
end
-
end
-
-
2
def _nt_version
-
4
start_index = index
-
4
if node_cache[:version].has_key?(index)
-
cached = node_cache[:version][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
4
i0, s0 = index, []
-
4
r1 = _nt_CFWS
-
4
s0 << r1
-
4
if r1
-
4
s2, i2 = [], index
-
4
loop do
-
8
r3 = _nt_DIGIT
-
8
if r3
-
4
s2 << r3
-
else
-
4
break
-
end
-
end
-
4
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
4
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
4
s0 << r2
-
4
if r2
-
4
r5 = _nt_comment
-
4
if r5
-
r4 = r5
-
else
-
4
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
4
s0 << r4
-
4
if r4
-
4
if has_terminal?(".", false, index)
-
4
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
4
@index += 1
-
else
-
terminal_parse_failure(".")
-
r6 = nil
-
end
-
4
s0 << r6
-
4
if r6
-
4
r8 = _nt_comment
-
4
if r8
-
r7 = r8
-
else
-
4
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
4
s0 << r7
-
4
if r7
-
4
s9, i9 = [], index
-
4
loop do
-
8
r10 = _nt_DIGIT
-
8
if r10
-
4
s9 << r10
-
else
-
4
break
-
end
-
end
-
4
if s9.empty?
-
@index = i9
-
r9 = nil
-
else
-
4
r9 = instantiate_node(SyntaxNode,input, i9...index, s9)
-
end
-
4
s0 << r9
-
4
if r9
-
4
r11 = _nt_CFWS
-
4
s0 << r11
-
end
-
end
-
end
-
end
-
end
-
end
-
4
if s0.last
-
4
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
4
r0.extend(Version0)
-
4
r0.extend(Version1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
4
node_cache[:version][start_index] = r0
-
-
4
r0
-
end
-
-
end
-
-
2
class MimeVersionParser < Treetop::Runtime::CompiledParser
-
2
include MimeVersion
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module PhraseLists
-
2
include Treetop::Runtime
-
-
2
def root
-
@root ||= :primary_phrase
-
end
-
-
2
include RFC2822
-
-
2
module PrimaryPhrase0
-
2
def phrases
-
[first_phrase] + other_phrases.elements.map { |o| o.phrase_value }
-
end
-
end
-
-
2
def _nt_primary_phrase
-
start_index = index
-
if node_cache[:primary_phrase].has_key?(index)
-
cached = node_cache[:primary_phrase][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_phrase_list
-
r0.extend(PrimaryPhrase0)
-
-
node_cache[:primary_phrase][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
2
class PhraseListsParser < Treetop::Runtime::CompiledParser
-
2
include PhraseLists
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module Received
-
2
include Treetop::Runtime
-
-
2
def root
-
@root ||= :primary
-
end
-
-
2
include RFC2822
-
-
2
module Primary0
-
2
def name_val_list
-
elements[0]
-
end
-
-
2
def date_time
-
elements[2]
-
end
-
end
-
-
2
def _nt_primary
-
start_index = index
-
if node_cache[:primary].has_key?(index)
-
cached = node_cache[:primary][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_name_val_list
-
s0 << r1
-
if r1
-
if has_terminal?(";", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r2 = nil
-
end
-
s0 << r2
-
if r2
-
r3 = _nt_date_time
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Primary0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:primary][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
2
class ReceivedParser < Treetop::Runtime::CompiledParser
-
2
include Received
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module RFC2045
-
2
include Treetop::Runtime
-
-
2
def root
-
@root ||= :tspecials
-
end
-
-
2
def _nt_tspecials
-
start_index = index
-
if node_cache[:tspecials].has_key?(index)
-
cached = node_cache[:tspecials][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?("(", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("(")
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?(")", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(")")
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("<", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("<")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?(">", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("@", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("@")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?(",", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?(";", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
if has_terminal?(":", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r8 = nil
-
end
-
if r8
-
r0 = r8
-
else
-
if has_terminal?('\\', false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure('\\')
-
r9 = nil
-
end
-
if r9
-
r0 = r9
-
else
-
if has_terminal?("<", false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("<")
-
r10 = nil
-
end
-
if r10
-
r0 = r10
-
else
-
if has_terminal?(">", false, index)
-
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r11 = nil
-
end
-
if r11
-
r0 = r11
-
else
-
if has_terminal?("/", false, index)
-
r12 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("/")
-
r12 = nil
-
end
-
if r12
-
r0 = r12
-
else
-
if has_terminal?("[", false, index)
-
r13 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("[")
-
r13 = nil
-
end
-
if r13
-
r0 = r13
-
else
-
if has_terminal?("]", false, index)
-
r14 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("]")
-
r14 = nil
-
end
-
if r14
-
r0 = r14
-
else
-
if has_terminal?("?", false, index)
-
r15 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("?")
-
r15 = nil
-
end
-
if r15
-
r0 = r15
-
else
-
if has_terminal?("=", false, index)
-
r16 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("=")
-
r16 = nil
-
end
-
if r16
-
r0 = r16
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:tspecials][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_ietf_token
-
8
start_index = index
-
8
if node_cache[:ietf_token].has_key?(index)
-
cached = node_cache[:ietf_token][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
8
s0, i0 = [], index
-
8
loop do
-
40
r1 = _nt_token
-
40
if r1
-
32
s0 << r1
-
else
-
8
break
-
end
-
end
-
8
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
8
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
8
node_cache[:ietf_token][start_index] = r0
-
-
8
r0
-
end
-
-
2
module CustomXToken0
-
end
-
-
2
def _nt_custom_x_token
-
start_index = index
-
if node_cache[:custom_x_token].has_key?(index)
-
cached = node_cache[:custom_x_token][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?('\G[xX]', true, index)
-
r1 = true
-
@index += 1
-
else
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
if has_terminal?("-", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("-")
-
r2 = nil
-
end
-
s0 << r2
-
if r2
-
s3, i3 = [], index
-
loop do
-
r4 = _nt_token
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
if s3.empty?
-
@index = i3
-
r3 = nil
-
else
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
end
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(CustomXToken0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:custom_x_token][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_iana_token
-
start_index = index
-
if node_cache[:iana_token].has_key?(index)
-
cached = node_cache[:iana_token][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
r1 = _nt_token
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
node_cache[:iana_token][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_token
-
48
start_index = index
-
48
if node_cache[:token].has_key?(index)
-
8
cached = node_cache[:token][index]
-
8
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
8
return cached
-
end
-
-
40
i0 = index
-
40
if has_terminal?('\G[\\x21-\\x27]', true, index)
-
r1 = true
-
@index += 1
-
else
-
40
r1 = nil
-
end
-
40
if r1
-
r0 = r1
-
else
-
40
if has_terminal?('\G[\\x2a-\\x2b]', true, index)
-
r2 = true
-
@index += 1
-
else
-
40
r2 = nil
-
end
-
40
if r2
-
r0 = r2
-
else
-
40
if has_terminal?('\G[\\x2c-\\x2e]', true, index)
-
r3 = true
-
@index += 1
-
else
-
40
r3 = nil
-
end
-
40
if r3
-
r0 = r3
-
else
-
40
if has_terminal?('\G[\\x30-\\x39]', true, index)
-
r4 = true
-
@index += 1
-
else
-
40
r4 = nil
-
end
-
40
if r4
-
r0 = r4
-
else
-
40
if has_terminal?('\G[\\x41-\\x5a]', true, index)
-
r5 = true
-
@index += 1
-
else
-
40
r5 = nil
-
end
-
40
if r5
-
r0 = r5
-
else
-
40
if has_terminal?('\G[\\x5e-\\x7e]', true, index)
-
32
r6 = true
-
32
@index += 1
-
else
-
8
r6 = nil
-
end
-
40
if r6
-
32
r0 = r6
-
else
-
8
@index = i0
-
8
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
-
40
node_cache[:token][start_index] = r0
-
-
40
r0
-
end
-
-
end
-
-
2
class RFC2045Parser < Treetop::Runtime::CompiledParser
-
2
include RFC2045
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module RFC2822
-
2
include Treetop::Runtime
-
-
2
def root
-
@root ||= :ALPHA
-
end
-
-
2
include RFC2822Obsolete
-
-
2
def _nt_ALPHA
-
519
start_index = index
-
519
if node_cache[:ALPHA].has_key?(index)
-
cached = node_cache[:ALPHA][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
519
if has_terminal?('\G[a-zA-Z]', true, index)
-
347
r0 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
347
@index += 1
-
else
-
172
r0 = nil
-
end
-
-
519
node_cache[:ALPHA][start_index] = r0
-
-
519
r0
-
end
-
-
2
def _nt_DIGIT
-
188
start_index = index
-
188
if node_cache[:DIGIT].has_key?(index)
-
cached = node_cache[:DIGIT][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
188
if has_terminal?('\G[0-9]', true, index)
-
100
r0 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
100
@index += 1
-
else
-
88
r0 = nil
-
end
-
-
188
node_cache[:DIGIT][start_index] = r0
-
-
188
r0
-
end
-
-
2
def _nt_DQUOTE
-
156
start_index = index
-
156
if node_cache[:DQUOTE].has_key?(index)
-
32
cached = node_cache[:DQUOTE][index]
-
32
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
32
return cached
-
end
-
-
124
if has_terminal?('"', false, index)
-
r0 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
124
terminal_parse_failure('"')
-
124
r0 = nil
-
end
-
-
124
node_cache[:DQUOTE][start_index] = r0
-
-
124
r0
-
end
-
-
2
def _nt_LF
-
start_index = index
-
if node_cache[:LF].has_key?(index)
-
cached = node_cache[:LF][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
if has_terminal?("\n", false, index)
-
r0 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("\n")
-
r0 = nil
-
end
-
-
node_cache[:LF][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_CR
-
start_index = index
-
if node_cache[:CR].has_key?(index)
-
cached = node_cache[:CR][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
if has_terminal?("\r", false, index)
-
r0 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("\r")
-
r0 = nil
-
end
-
-
node_cache[:CR][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_CRLF
-
304
start_index = index
-
304
if node_cache[:CRLF].has_key?(index)
-
152
cached = node_cache[:CRLF][index]
-
152
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
152
return cached
-
end
-
-
152
if has_terminal?("\r\n", false, index)
-
r0 = instantiate_node(SyntaxNode,input, index...(index + 2))
-
@index += 2
-
else
-
152
terminal_parse_failure("\r\n")
-
152
r0 = nil
-
end
-
-
152
node_cache[:CRLF][start_index] = r0
-
-
152
r0
-
end
-
-
2
def _nt_WSP
-
304
start_index = index
-
304
if node_cache[:WSP].has_key?(index)
-
152
cached = node_cache[:WSP][index]
-
152
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
152
return cached
-
end
-
-
152
if has_terminal?('\G[\\x09\\x20]', true, index)
-
r0 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
152
r0 = nil
-
end
-
-
152
node_cache[:WSP][start_index] = r0
-
-
152
r0
-
end
-
-
2
module FWS0
-
2
def CRLF
-
elements[1]
-
end
-
-
end
-
-
2
module FWS1
-
2
def CRLF
-
elements[0]
-
end
-
-
end
-
-
2
def _nt_FWS
-
320
start_index = index
-
320
if node_cache[:FWS].has_key?(index)
-
168
cached = node_cache[:FWS][index]
-
168
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
168
return cached
-
end
-
-
152
i0 = index
-
152
i1, s1 = index, []
-
152
s2, i2 = [], index
-
152
loop do
-
152
r3 = _nt_WSP
-
152
if r3
-
s2 << r3
-
else
-
152
break
-
end
-
end
-
152
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
152
s1 << r2
-
152
if r2
-
152
r4 = _nt_CRLF
-
152
s1 << r4
-
152
if r4
-
s5, i5 = [], index
-
loop do
-
r6 = _nt_WSP
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
if s5.empty?
-
@index = i5
-
r5 = nil
-
else
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
end
-
s1 << r5
-
end
-
end
-
152
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(FWS0)
-
else
-
152
@index = i1
-
152
r1 = nil
-
end
-
152
if r1
-
r0 = r1
-
else
-
152
i7, s7 = index, []
-
152
r8 = _nt_CRLF
-
152
s7 << r8
-
152
if r8
-
s9, i9 = [], index
-
loop do
-
r10 = _nt_WSP
-
if r10
-
s9 << r10
-
else
-
break
-
end
-
end
-
if s9.empty?
-
@index = i9
-
r9 = nil
-
else
-
r9 = instantiate_node(SyntaxNode,input, i9...index, s9)
-
end
-
s7 << r9
-
end
-
152
if s7.last
-
r7 = instantiate_node(SyntaxNode,input, i7...index, s7)
-
r7.extend(FWS1)
-
else
-
152
@index = i7
-
152
r7 = nil
-
end
-
152
if r7
-
r0 = r7
-
else
-
152
r11 = _nt_obs_FWS
-
152
if r11
-
r0 = r11
-
else
-
152
@index = i0
-
152
r0 = nil
-
end
-
end
-
end
-
-
152
node_cache[:FWS][start_index] = r0
-
-
152
r0
-
end
-
-
2
module CFWS0
-
2
def comment
-
elements[1]
-
end
-
end
-
-
2
module CFWS1
-
end
-
-
2
def _nt_CFWS
-
416
start_index = index
-
416
if node_cache[:CFWS].has_key?(index)
-
264
cached = node_cache[:CFWS][index]
-
264
if cached
-
264
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
264
@index = cached.interval.end
-
end
-
264
return cached
-
end
-
-
152
i0, s0 = index, []
-
152
s1, i1 = [], index
-
152
loop do
-
152
i2, s2 = index, []
-
152
s3, i3 = [], index
-
152
loop do
-
152
r4 = _nt_FWS
-
152
if r4
-
s3 << r4
-
else
-
152
break
-
end
-
end
-
152
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
152
s2 << r3
-
152
if r3
-
152
r5 = _nt_comment
-
152
s2 << r5
-
end
-
152
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(CFWS0)
-
else
-
152
@index = i2
-
152
r2 = nil
-
end
-
152
if r2
-
s1 << r2
-
else
-
152
break
-
end
-
end
-
152
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
152
s0 << r1
-
152
if r1
-
152
r7 = _nt_FWS
-
152
if r7
-
r6 = r7
-
else
-
152
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
152
s0 << r6
-
end
-
152
if s0.last
-
152
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
152
r0.extend(CFWS1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
152
node_cache[:CFWS][start_index] = r0
-
-
152
r0
-
end
-
-
2
def _nt_NO_WS_CTL
-
start_index = index
-
if node_cache[:NO_WS_CTL].has_key?(index)
-
cached = node_cache[:NO_WS_CTL][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?('\G[\\x01-\\x08]', true, index)
-
r1 = true
-
@index += 1
-
else
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x0B-\\x0C]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x0E-\\x1F]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?('\G[\\x7f]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
-
node_cache[:NO_WS_CTL][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_specials
-
start_index = index
-
if node_cache[:specials].has_key?(index)
-
cached = node_cache[:specials][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?("(", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("(")
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?(")", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(")")
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("<", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("<")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?(">", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("[", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("[")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?("]", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("]")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?(":", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
if has_terminal?(";", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r8 = nil
-
end
-
if r8
-
r0 = r8
-
else
-
if has_terminal?("@", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("@")
-
r9 = nil
-
end
-
if r9
-
r0 = r9
-
else
-
if has_terminal?('\\', false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure('\\')
-
r10 = nil
-
end
-
if r10
-
r0 = r10
-
else
-
if has_terminal?(",", false, index)
-
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r11 = nil
-
end
-
if r11
-
r0 = r11
-
else
-
if has_terminal?(".", false, index)
-
r12 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r12 = nil
-
end
-
if r12
-
r0 = r12
-
else
-
r13 = _nt_DQUOTE
-
if r13
-
r0 = r13
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:specials][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_ctext
-
start_index = index
-
if node_cache[:ctext].has_key?(index)
-
cached = node_cache[:ctext][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_NO_WS_CTL
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x21-\\x27]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x2a-\\x5b]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?('\G[\\x5d-\\x7e]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
-
node_cache[:ctext][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_ccontent
-
start_index = index
-
if node_cache[:ccontent].has_key?(index)
-
cached = node_cache[:ccontent][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_ctext
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_quoted_pair
-
if r2
-
r0 = r2
-
else
-
r3 = _nt_comment
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:ccontent][start_index] = r0
-
-
r0
-
end
-
-
2
module Comment0
-
2
def ccontent
-
elements[1]
-
end
-
end
-
-
2
module Comment1
-
end
-
-
2
def _nt_comment
-
160
start_index = index
-
160
if node_cache[:comment].has_key?(index)
-
cached = node_cache[:comment][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
160
i0, s0 = index, []
-
160
if has_terminal?("(", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
160
terminal_parse_failure("(")
-
160
r1 = nil
-
end
-
160
s0 << r1
-
160
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
r5 = _nt_FWS
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s3 << r4
-
if r4
-
r6 = _nt_ccontent
-
s3 << r6
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(Comment0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
r8 = _nt_FWS
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r7
-
if r7
-
if has_terminal?(")", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(")")
-
r9 = nil
-
end
-
s0 << r9
-
end
-
end
-
end
-
160
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Comment1)
-
else
-
160
@index = i0
-
160
r0 = nil
-
end
-
-
160
node_cache[:comment][start_index] = r0
-
-
160
r0
-
end
-
-
2
def _nt_atext
-
899
start_index = index
-
899
if node_cache[:atext].has_key?(index)
-
436
cached = node_cache[:atext][index]
-
436
if cached
-
288
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
288
@index = cached.interval.end
-
end
-
436
return cached
-
end
-
-
463
i0 = index
-
463
r1 = _nt_ALPHA
-
463
if r1
-
299
r0 = r1
-
else
-
164
r2 = _nt_DIGIT
-
164
if r2
-
92
r0 = r2
-
else
-
72
if has_terminal?("!", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
72
terminal_parse_failure("!")
-
72
r3 = nil
-
end
-
72
if r3
-
r0 = r3
-
else
-
72
if has_terminal?("#", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
72
terminal_parse_failure("#")
-
72
r4 = nil
-
end
-
72
if r4
-
r0 = r4
-
else
-
72
if has_terminal?("$", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
72
terminal_parse_failure("$")
-
72
r5 = nil
-
end
-
72
if r5
-
r0 = r5
-
else
-
72
if has_terminal?("%", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
72
terminal_parse_failure("%")
-
72
r6 = nil
-
end
-
72
if r6
-
r0 = r6
-
else
-
72
if has_terminal?("&", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
72
terminal_parse_failure("&")
-
72
r7 = nil
-
end
-
72
if r7
-
r0 = r7
-
else
-
72
if has_terminal?("'", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
72
terminal_parse_failure("'")
-
72
r8 = nil
-
end
-
72
if r8
-
r0 = r8
-
else
-
72
if has_terminal?("*", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
72
terminal_parse_failure("*")
-
72
r9 = nil
-
end
-
72
if r9
-
r0 = r9
-
else
-
72
if has_terminal?("+", false, index)
-
8
r10 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
8
@index += 1
-
else
-
64
terminal_parse_failure("+")
-
64
r10 = nil
-
end
-
72
if r10
-
8
r0 = r10
-
else
-
64
if has_terminal?("-", false, index)
-
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
64
terminal_parse_failure("-")
-
64
r11 = nil
-
end
-
64
if r11
-
r0 = r11
-
else
-
64
if has_terminal?("/", false, index)
-
r12 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
64
terminal_parse_failure("/")
-
64
r12 = nil
-
end
-
64
if r12
-
r0 = r12
-
else
-
64
if has_terminal?("=", false, index)
-
r13 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
64
terminal_parse_failure("=")
-
64
r13 = nil
-
end
-
64
if r13
-
r0 = r13
-
else
-
64
if has_terminal?("?", false, index)
-
r14 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
64
terminal_parse_failure("?")
-
64
r14 = nil
-
end
-
64
if r14
-
r0 = r14
-
else
-
64
if has_terminal?("^", false, index)
-
r15 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
64
terminal_parse_failure("^")
-
64
r15 = nil
-
end
-
64
if r15
-
r0 = r15
-
else
-
64
if has_terminal?("_", false, index)
-
4
r16 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
4
@index += 1
-
else
-
60
terminal_parse_failure("_")
-
60
r16 = nil
-
end
-
64
if r16
-
4
r0 = r16
-
else
-
60
if has_terminal?("`", false, index)
-
r17 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
60
terminal_parse_failure("`")
-
60
r17 = nil
-
end
-
60
if r17
-
r0 = r17
-
else
-
60
if has_terminal?("{", false, index)
-
r18 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
60
terminal_parse_failure("{")
-
60
r18 = nil
-
end
-
60
if r18
-
r0 = r18
-
else
-
60
if has_terminal?("|", false, index)
-
r19 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
60
terminal_parse_failure("|")
-
60
r19 = nil
-
end
-
60
if r19
-
r0 = r19
-
else
-
60
if has_terminal?("}", false, index)
-
r20 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
60
terminal_parse_failure("}")
-
60
r20 = nil
-
end
-
60
if r20
-
r0 = r20
-
else
-
60
if has_terminal?("~", false, index)
-
r21 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
60
terminal_parse_failure("~")
-
60
r21 = nil
-
end
-
60
if r21
-
r0 = r21
-
else
-
60
@index = i0
-
60
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
463
node_cache[:atext][start_index] = r0
-
-
463
r0
-
end
-
-
2
def _nt_mtext
-
8
start_index = index
-
8
if node_cache[:mtext].has_key?(index)
-
cached = node_cache[:mtext][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
8
s0, i0 = [], index
-
8
loop do
-
123
i1 = index
-
123
r2 = _nt_atext
-
123
if r2
-
115
r1 = r2
-
else
-
8
if has_terminal?(".", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure(".")
-
8
r3 = nil
-
end
-
8
if r3
-
r1 = r3
-
else
-
8
@index = i1
-
8
r1 = nil
-
end
-
end
-
123
if r1
-
115
s0 << r1
-
else
-
8
break
-
end
-
end
-
8
if s0.empty?
-
4
@index = i0
-
4
r0 = nil
-
else
-
4
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
8
node_cache[:mtext][start_index] = r0
-
-
8
r0
-
end
-
-
2
module Atom0
-
end
-
-
2
def _nt_atom
-
112
start_index = index
-
112
if node_cache[:atom].has_key?(index)
-
cached = node_cache[:atom][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
112
i0, s0 = index, []
-
112
r2 = _nt_CFWS
-
112
if r2
-
112
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
112
s0 << r1
-
112
if r1
-
112
s3, i3 = [], index
-
112
loop do
-
400
r4 = _nt_atext
-
400
if r4
-
288
s3 << r4
-
else
-
112
break
-
end
-
end
-
112
if s3.empty?
-
56
@index = i3
-
56
r3 = nil
-
else
-
56
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
end
-
112
s0 << r3
-
112
if r3
-
56
r6 = _nt_CFWS
-
56
if r6
-
56
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
56
s0 << r5
-
end
-
end
-
112
if s0.last
-
56
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
56
r0.extend(Atom0)
-
else
-
56
@index = i0
-
56
r0 = nil
-
end
-
-
112
node_cache[:atom][start_index] = r0
-
-
112
r0
-
end
-
-
2
module DotAtom0
-
2
def dot_atom_text
-
elements[1]
-
end
-
-
end
-
-
2
def _nt_dot_atom
-
16
start_index = index
-
16
if node_cache[:dot_atom].has_key?(index)
-
cached = node_cache[:dot_atom][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
i0, s0 = index, []
-
16
r2 = _nt_CFWS
-
16
if r2
-
16
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
16
s0 << r1
-
16
if r1
-
16
r3 = _nt_dot_atom_text
-
16
s0 << r3
-
16
if r3
-
16
r5 = _nt_CFWS
-
16
if r5
-
16
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
16
s0 << r4
-
end
-
end
-
16
if s0.last
-
16
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
16
r0.extend(DotAtom0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
16
node_cache[:dot_atom][start_index] = r0
-
-
16
r0
-
end
-
-
2
module LocalDotAtom0
-
2
def local_dot_atom_text
-
elements[1]
-
end
-
-
end
-
-
2
def _nt_local_dot_atom
-
16
start_index = index
-
16
if node_cache[:local_dot_atom].has_key?(index)
-
cached = node_cache[:local_dot_atom][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
i0, s0 = index, []
-
16
r2 = _nt_CFWS
-
16
if r2
-
16
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
16
s0 << r1
-
16
if r1
-
16
r3 = _nt_local_dot_atom_text
-
16
s0 << r3
-
16
if r3
-
16
r5 = _nt_CFWS
-
16
if r5
-
16
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
16
s0 << r4
-
end
-
end
-
16
if s0.last
-
16
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
16
r0.extend(LocalDotAtom0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
16
node_cache[:local_dot_atom][start_index] = r0
-
-
16
r0
-
end
-
-
2
def _nt_message_id_text
-
4
start_index = index
-
4
if node_cache[:message_id_text].has_key?(index)
-
cached = node_cache[:message_id_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
4
s0, i0 = [], index
-
4
loop do
-
8
r1 = _nt_mtext
-
8
if r1
-
4
s0 << r1
-
else
-
4
break
-
end
-
end
-
4
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
4
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
4
node_cache[:message_id_text][start_index] = r0
-
-
4
r0
-
end
-
-
2
module DotAtomText0
-
2
def domain_text
-
elements[0]
-
end
-
-
end
-
-
2
def _nt_dot_atom_text
-
16
start_index = index
-
16
if node_cache[:dot_atom_text].has_key?(index)
-
cached = node_cache[:dot_atom_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
s0, i0 = [], index
-
16
loop do
-
56
i1, s1 = index, []
-
56
r2 = _nt_domain_text
-
56
s1 << r2
-
56
if r2
-
40
if has_terminal?(".", false, index)
-
24
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
24
@index += 1
-
else
-
16
terminal_parse_failure(".")
-
16
r4 = nil
-
end
-
40
if r4
-
24
r3 = r4
-
else
-
16
r3 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
40
s1 << r3
-
end
-
56
if s1.last
-
40
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
40
r1.extend(DotAtomText0)
-
else
-
16
@index = i1
-
16
r1 = nil
-
end
-
56
if r1
-
40
s0 << r1
-
else
-
16
break
-
end
-
end
-
16
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
16
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
16
node_cache[:dot_atom_text][start_index] = r0
-
-
16
r0
-
end
-
-
2
module LocalDotAtomText0
-
2
def domain_text
-
elements[1]
-
end
-
-
end
-
-
2
def _nt_local_dot_atom_text
-
16
start_index = index
-
16
if node_cache[:local_dot_atom_text].has_key?(index)
-
cached = node_cache[:local_dot_atom_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
s0, i0 = [], index
-
16
loop do
-
32
i1, s1 = index, []
-
32
s2, i2 = [], index
-
32
loop do
-
32
if has_terminal?(".", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
32
terminal_parse_failure(".")
-
32
r3 = nil
-
end
-
32
if r3
-
s2 << r3
-
else
-
32
break
-
end
-
end
-
32
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
32
s1 << r2
-
32
if r2
-
32
r4 = _nt_domain_text
-
32
s1 << r4
-
32
if r4
-
16
s5, i5 = [], index
-
16
loop do
-
16
if has_terminal?(".", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
16
terminal_parse_failure(".")
-
16
r6 = nil
-
end
-
16
if r6
-
s5 << r6
-
else
-
16
break
-
end
-
end
-
16
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
16
s1 << r5
-
end
-
end
-
32
if s1.last
-
16
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
16
r1.extend(LocalDotAtomText0)
-
else
-
16
@index = i1
-
16
r1 = nil
-
end
-
32
if r1
-
16
s0 << r1
-
else
-
16
break
-
end
-
end
-
16
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
16
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
16
node_cache[:local_dot_atom_text][start_index] = r0
-
-
16
r0
-
end
-
-
2
module DomainText0
-
2
def quoted_domain
-
elements[1]
-
end
-
end
-
-
2
module DomainText1
-
2
def DQUOTE1
-
elements[0]
-
end
-
-
2
def DQUOTE2
-
elements[3]
-
end
-
end
-
-
2
def _nt_domain_text
-
88
start_index = index
-
88
if node_cache[:domain_text].has_key?(index)
-
cached = node_cache[:domain_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
88
i0 = index
-
88
i1, s1 = index, []
-
88
r2 = _nt_DQUOTE
-
88
s1 << r2
-
88
if r2
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
r6 = _nt_FWS
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r5
-
if r5
-
r7 = _nt_quoted_domain
-
s4 << r7
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(DomainText0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
if s3.empty?
-
@index = i3
-
r3 = nil
-
else
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
end
-
s1 << r3
-
if r3
-
r9 = _nt_FWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r8
-
if r8
-
r10 = _nt_DQUOTE
-
s1 << r10
-
end
-
end
-
end
-
88
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(DomainText1)
-
else
-
88
@index = i1
-
88
r1 = nil
-
end
-
88
if r1
-
r0 = r1
-
else
-
88
s11, i11 = [], index
-
88
loop do
-
376
r12 = _nt_atext
-
376
if r12
-
288
s11 << r12
-
else
-
88
break
-
end
-
end
-
88
if s11.empty?
-
32
@index = i11
-
32
r11 = nil
-
else
-
56
r11 = instantiate_node(SyntaxNode,input, i11...index, s11)
-
end
-
88
if r11
-
56
r0 = r11
-
else
-
32
@index = i0
-
32
r0 = nil
-
end
-
end
-
-
88
node_cache[:domain_text][start_index] = r0
-
-
88
r0
-
end
-
-
2
module QuotedDomain0
-
2
def text
-
elements[1]
-
end
-
end
-
-
2
def _nt_quoted_domain
-
start_index = index
-
if node_cache[:quoted_domain].has_key?(index)
-
cached = node_cache[:quoted_domain][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_qdcontent
-
if r1
-
r0 = r1
-
else
-
i2, s2 = index, []
-
if has_terminal?("\\", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("\\")
-
r3 = nil
-
end
-
s2 << r3
-
if r3
-
r4 = _nt_text
-
s2 << r4
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(QuotedDomain0)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:quoted_domain][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_qdcontent
-
start_index = index
-
if node_cache[:qdcontent].has_key?(index)
-
cached = node_cache[:qdcontent][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_NO_WS_CTL
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x21]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x23-\\x45]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?('\G[\\x47-\\x5b]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?('\G[\\x5d-\\x7e]', true, index)
-
r5 = true
-
@index += 1
-
else
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:qdcontent][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_phrase
-
16
start_index = index
-
16
if node_cache[:phrase].has_key?(index)
-
cached = node_cache[:phrase][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
i0 = index
-
16
r1 = _nt_obs_phrase
-
16
if r1
-
16
r0 = r1
-
else
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_word
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
16
node_cache[:phrase][start_index] = r0
-
-
16
r0
-
end
-
-
2
def _nt_word
-
112
start_index = index
-
112
if node_cache[:word].has_key?(index)
-
cached = node_cache[:word][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
112
i0 = index
-
112
r1 = _nt_atom
-
112
if r1
-
56
r0 = r1
-
else
-
56
r2 = _nt_quoted_string
-
56
if r2
-
r0 = r2
-
else
-
56
@index = i0
-
56
r0 = nil
-
end
-
end
-
-
112
node_cache[:word][start_index] = r0
-
-
112
r0
-
end
-
-
2
module PhraseList0
-
2
def phrase_value
-
elements[2]
-
end
-
end
-
-
2
module PhraseList1
-
2
def first_phrase
-
elements[0]
-
end
-
-
2
def other_phrases
-
elements[1]
-
end
-
end
-
-
2
def _nt_phrase_list
-
start_index = index
-
if node_cache[:phrase_list].has_key?(index)
-
cached = node_cache[:phrase_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_phrase
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
if has_terminal?(",", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r4 = nil
-
end
-
s3 << r4
-
if r4
-
s5, i5 = [], index
-
loop do
-
r6 = _nt_FWS
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
s3 << r5
-
if r5
-
r7 = _nt_phrase
-
s3 << r7
-
end
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(PhraseList0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(PhraseList1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:phrase_list][start_index] = r0
-
-
r0
-
end
-
-
2
module DomainLiteral0
-
2
def dcontent
-
elements[1]
-
end
-
end
-
-
2
module DomainLiteral1
-
end
-
-
2
def _nt_domain_literal
-
start_index = index
-
if node_cache[:domain_literal].has_key?(index)
-
cached = node_cache[:domain_literal][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
if has_terminal?("[", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("[")
-
r3 = nil
-
end
-
s0 << r3
-
if r3
-
s4, i4 = [], index
-
loop do
-
i5, s5 = index, []
-
r7 = _nt_FWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s5 << r6
-
if r6
-
r8 = _nt_dcontent
-
s5 << r8
-
end
-
if s5.last
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
r5.extend(DomainLiteral0)
-
else
-
@index = i5
-
r5 = nil
-
end
-
if r5
-
s4 << r5
-
else
-
break
-
end
-
end
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
s0 << r4
-
if r4
-
r10 = _nt_FWS
-
if r10
-
r9 = r10
-
else
-
r9 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r9
-
if r9
-
if has_terminal?("]", false, index)
-
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("]")
-
r11 = nil
-
end
-
s0 << r11
-
if r11
-
r13 = _nt_CFWS
-
if r13
-
r12 = r13
-
else
-
r12 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r12
-
end
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(DomainLiteral1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:domain_literal][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_dcontent
-
start_index = index
-
if node_cache[:dcontent].has_key?(index)
-
cached = node_cache[:dcontent][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_dtext
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_quoted_pair
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:dcontent][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_dtext
-
start_index = index
-
if node_cache[:dtext].has_key?(index)
-
cached = node_cache[:dtext][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_NO_WS_CTL
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x21-\\x5a]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x5e-\\x7e]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:dtext][start_index] = r0
-
-
r0
-
end
-
-
2
module AngleAddr0
-
2
def addr_spec
-
elements[2]
-
end
-
-
end
-
-
2
def _nt_angle_addr
-
32
start_index = index
-
32
if node_cache[:angle_addr].has_key?(index)
-
cached = node_cache[:angle_addr][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
32
i0 = index
-
32
i1, s1 = index, []
-
32
r3 = _nt_CFWS
-
32
if r3
-
32
r2 = r3
-
else
-
r2 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
32
s1 << r2
-
32
if r2
-
32
if has_terminal?("<", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
32
terminal_parse_failure("<")
-
32
r4 = nil
-
end
-
32
s1 << r4
-
32
if r4
-
r5 = _nt_addr_spec
-
s1 << r5
-
if r5
-
if has_terminal?(">", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r6 = nil
-
end
-
s1 << r6
-
if r6
-
r8 = _nt_CFWS
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r7
-
end
-
end
-
end
-
end
-
32
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(AngleAddr0)
-
else
-
32
@index = i1
-
32
r1 = nil
-
end
-
32
if r1
-
r0 = r1
-
else
-
32
r9 = _nt_obs_angle_addr
-
32
if r9
-
r0 = r9
-
else
-
32
@index = i0
-
32
r0 = nil
-
end
-
end
-
-
32
node_cache[:angle_addr][start_index] = r0
-
-
32
r0
-
end
-
-
2
module AddrSpec0
-
2
def local_part
-
208
elements[0]
-
end
-
-
2
def domain
-
8
elements[2]
-
end
-
end
-
-
2
def _nt_addr_spec
-
16
start_index = index
-
16
if node_cache[:addr_spec].has_key?(index)
-
cached = node_cache[:addr_spec][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
i0 = index
-
16
i1, s1 = index, []
-
16
r2 = _nt_local_part
-
16
s1 << r2
-
16
if r2
-
16
if has_terminal?("@", false, index)
-
16
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
16
@index += 1
-
else
-
terminal_parse_failure("@")
-
r3 = nil
-
end
-
16
s1 << r3
-
16
if r3
-
16
r4 = _nt_domain
-
16
s1 << r4
-
end
-
end
-
16
if s1.last
-
16
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
16
r1.extend(AddrSpec0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
16
if r1
-
16
r0 = r1
-
else
-
r5 = _nt_local_part
-
if r5
-
r0 = r5
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
16
node_cache[:addr_spec][start_index] = r0
-
-
16
r0
-
end
-
-
2
def _nt_local_part
-
16
start_index = index
-
16
if node_cache[:local_part].has_key?(index)
-
cached = node_cache[:local_part][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
i0 = index
-
16
r1 = _nt_local_dot_atom
-
16
if r1
-
16
r0 = r1
-
else
-
r2 = _nt_quoted_string
-
if r2
-
r0 = r2
-
else
-
r3 = _nt_obs_local_part
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
16
node_cache[:local_part][start_index] = r0
-
-
16
r0
-
end
-
-
2
def _nt_domain
-
16
start_index = index
-
16
if node_cache[:domain].has_key?(index)
-
cached = node_cache[:domain][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
i0 = index
-
16
r1 = _nt_dot_atom
-
16
if r1
-
16
r0 = r1
-
else
-
r2 = _nt_domain_literal
-
if r2
-
r0 = r2
-
else
-
r3 = _nt_obs_domain
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
16
node_cache[:domain][start_index] = r0
-
-
16
r0
-
end
-
-
2
module Group0
-
2
def group_name
-
elements[0]
-
end
-
-
2
def group_list
-
elements[2]
-
end
-
-
end
-
-
2
def _nt_group
-
16
start_index = index
-
16
if node_cache[:group].has_key?(index)
-
cached = node_cache[:group][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
i0, s0 = index, []
-
16
r1 = _nt_display_name
-
16
s0 << r1
-
16
if r1
-
16
if has_terminal?(":", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
16
terminal_parse_failure(":")
-
16
r2 = nil
-
end
-
16
s0 << r2
-
16
if r2
-
i4 = index
-
r5 = _nt_mailbox_list_group
-
if r5
-
r4 = r5
-
else
-
r6 = _nt_CFWS
-
if r6
-
r4 = r6
-
else
-
@index = i4
-
r4 = nil
-
end
-
end
-
if r4
-
r3 = r4
-
else
-
r3 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r3
-
if r3
-
if has_terminal?(";", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r7 = nil
-
end
-
s0 << r7
-
if r7
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r8
-
end
-
end
-
end
-
end
-
16
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Group0)
-
else
-
16
@index = i0
-
16
r0 = nil
-
end
-
-
16
node_cache[:group][start_index] = r0
-
-
16
r0
-
end
-
-
2
module MailboxListGroup0
-
2
def addresses
-
[first_addr] + other_addr.elements.map { |o| o.addr_value }
-
end
-
end
-
-
2
def _nt_mailbox_list_group
-
start_index = index
-
if node_cache[:mailbox_list_group].has_key?(index)
-
cached = node_cache[:mailbox_list_group][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_mailbox_list
-
r0.extend(MailboxListGroup0)
-
-
node_cache[:mailbox_list_group][start_index] = r0
-
-
r0
-
end
-
-
2
module QuotedString0
-
2
def qcontent
-
elements[1]
-
end
-
end
-
-
2
module QuotedString1
-
2
def DQUOTE1
-
elements[1]
-
end
-
-
2
def quoted_content
-
elements[2]
-
end
-
-
2
def DQUOTE2
-
elements[4]
-
end
-
-
end
-
-
2
def _nt_quoted_string
-
56
start_index = index
-
56
if node_cache[:quoted_string].has_key?(index)
-
cached = node_cache[:quoted_string][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
56
i0, s0 = index, []
-
56
r2 = _nt_CFWS
-
56
if r2
-
56
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
56
s0 << r1
-
56
if r1
-
56
r3 = _nt_DQUOTE
-
56
s0 << r3
-
56
if r3
-
s4, i4 = [], index
-
loop do
-
i5, s5 = index, []
-
r7 = _nt_FWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s5 << r6
-
if r6
-
r8 = _nt_qcontent
-
s5 << r8
-
end
-
if s5.last
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
r5.extend(QuotedString0)
-
else
-
@index = i5
-
r5 = nil
-
end
-
if r5
-
s4 << r5
-
else
-
break
-
end
-
end
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
s0 << r4
-
if r4
-
r10 = _nt_FWS
-
if r10
-
r9 = r10
-
else
-
r9 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r9
-
if r9
-
r11 = _nt_DQUOTE
-
s0 << r11
-
if r11
-
r13 = _nt_CFWS
-
if r13
-
r12 = r13
-
else
-
r12 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r12
-
end
-
end
-
end
-
end
-
end
-
56
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(QuotedString1)
-
else
-
56
@index = i0
-
56
r0 = nil
-
end
-
-
56
node_cache[:quoted_string][start_index] = r0
-
-
56
r0
-
end
-
-
2
def _nt_qcontent
-
start_index = index
-
if node_cache[:qcontent].has_key?(index)
-
cached = node_cache[:qcontent][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_qtext
-
if r1
-
r0 = r1
-
else
-
r2 = _nt_quoted_pair
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:qcontent][start_index] = r0
-
-
r0
-
end
-
-
2
module QuotedPair0
-
2
def text
-
elements[1]
-
end
-
end
-
-
2
def _nt_quoted_pair
-
start_index = index
-
if node_cache[:quoted_pair].has_key?(index)
-
cached = node_cache[:quoted_pair][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
if has_terminal?("\\", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("\\")
-
r2 = nil
-
end
-
s1 << r2
-
if r2
-
r3 = _nt_text
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(QuotedPair0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r4 = _nt_obs_qp
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:quoted_pair][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_qtext
-
start_index = index
-
if node_cache[:qtext].has_key?(index)
-
cached = node_cache[:qtext][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_NO_WS_CTL
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x21]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x23-\\x5b]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?('\G[\\x5d-\\x7e]', true, index)
-
r4 = true
-
@index += 1
-
else
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
-
node_cache[:qtext][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_text
-
start_index = index
-
if node_cache[:text].has_key?(index)
-
cached = node_cache[:text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?('\G[\\x01-\\x09]', true, index)
-
r1 = true
-
@index += 1
-
else
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x0b-\\x0c]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x0e-\\x7e]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
r4 = _nt_obs_text
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
-
node_cache[:text][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_display_name
-
32
start_index = index
-
32
if node_cache[:display_name].has_key?(index)
-
16
cached = node_cache[:display_name][index]
-
16
if cached
-
16
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
16
@index = cached.interval.end
-
end
-
16
return cached
-
end
-
-
16
r0 = _nt_phrase
-
-
16
node_cache[:display_name][start_index] = r0
-
-
16
r0
-
end
-
-
2
module NameAddr0
-
2
def display_name
-
elements[0]
-
end
-
-
2
def angle_addr
-
elements[1]
-
end
-
end
-
-
2
def _nt_name_addr
-
16
start_index = index
-
16
if node_cache[:name_addr].has_key?(index)
-
cached = node_cache[:name_addr][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
i0 = index
-
16
i1, s1 = index, []
-
16
r2 = _nt_display_name
-
16
s1 << r2
-
16
if r2
-
16
r3 = _nt_angle_addr
-
16
s1 << r3
-
end
-
16
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(NameAddr0)
-
else
-
16
@index = i1
-
16
r1 = nil
-
end
-
16
if r1
-
r0 = r1
-
else
-
16
r4 = _nt_angle_addr
-
16
if r4
-
r0 = r4
-
else
-
16
@index = i0
-
16
r0 = nil
-
end
-
end
-
-
16
node_cache[:name_addr][start_index] = r0
-
-
16
r0
-
end
-
-
2
module MailboxList0
-
2
def addr_value
-
elements[1]
-
end
-
end
-
-
2
module MailboxList1
-
2
def first_addr
-
elements[0]
-
end
-
-
2
def other_addr
-
elements[1]
-
end
-
end
-
-
2
def _nt_mailbox_list
-
start_index = index
-
if node_cache[:mailbox_list].has_key?(index)
-
cached = node_cache[:mailbox_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_mailbox
-
s1 << r2
-
if r2
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
i5 = index
-
if has_terminal?(",", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r6 = nil
-
end
-
if r6
-
r5 = r6
-
else
-
if has_terminal?(";", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r7 = nil
-
end
-
if r7
-
r5 = r7
-
else
-
@index = i5
-
r5 = nil
-
end
-
end
-
s4 << r5
-
if r5
-
r8 = _nt_mailbox
-
s4 << r8
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(MailboxList0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(MailboxList1)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r9 = _nt_obs_mbox_list
-
if r9
-
r0 = r9
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:mailbox_list][start_index] = r0
-
-
r0
-
end
-
-
2
module Mailbox0
-
2
def dig_comments(comments, elements)
-
5984
elements.each { |elem|
-
12648
if elem.respond_to?(:comment)
-
comments << elem.comment
-
end
-
12648
dig_comments(comments, elem.elements) if elem.elements
-
}
-
end
-
-
2
def comments
-
272
comments = []
-
272
dig_comments(comments, elements)
-
272
comments
-
end
-
end
-
-
2
def _nt_mailbox
-
16
start_index = index
-
16
if node_cache[:mailbox].has_key?(index)
-
cached = node_cache[:mailbox][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
i0 = index
-
16
r1 = _nt_name_addr
-
16
if r1
-
r0 = r1
-
r0.extend(Mailbox0)
-
else
-
16
r2 = _nt_addr_spec
-
16
if r2
-
16
r0 = r2
-
16
r0.extend(Mailbox0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
16
node_cache[:mailbox][start_index] = r0
-
-
16
r0
-
end
-
-
2
module Address0
-
-
2
def dig_comments(comments, elements)
-
elements.each { |elem|
-
if elem.respond_to?(:comment)
-
comments << elem.comment
-
end
-
dig_comments(comments, elem.elements) if elem.elements
-
}
-
end
-
-
2
def comments
-
comments = []
-
dig_comments(comments, elements)
-
comments
-
end
-
end
-
-
2
def _nt_address
-
16
start_index = index
-
16
if node_cache[:address].has_key?(index)
-
cached = node_cache[:address][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
i0 = index
-
16
r1 = _nt_group
-
16
r1.extend(Address0)
-
16
if r1
-
r0 = r1
-
else
-
16
r2 = _nt_mailbox
-
16
if r2
-
16
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
16
node_cache[:address][start_index] = r0
-
-
16
r0
-
end
-
-
2
module AddressList0
-
2
def addr_value
-
elements[3]
-
end
-
end
-
-
2
module AddressList1
-
2
def first_addr
-
16
elements[0]
-
end
-
-
2
def other_addr
-
16
elements[1]
-
end
-
end
-
-
2
def _nt_address_list
-
16
start_index = index
-
16
if node_cache[:address_list].has_key?(index)
-
cached = node_cache[:address_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
i0, s0 = index, []
-
16
r2 = _nt_address
-
16
if r2
-
16
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
16
s0 << r1
-
16
if r1
-
16
s3, i3 = [], index
-
16
loop do
-
16
i4, s4 = index, []
-
16
s5, i5 = [], index
-
16
loop do
-
16
r6 = _nt_FWS
-
16
if r6
-
s5 << r6
-
else
-
16
break
-
end
-
end
-
16
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
16
s4 << r5
-
16
if r5
-
16
i7 = index
-
16
if has_terminal?(",", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
16
terminal_parse_failure(",")
-
16
r8 = nil
-
end
-
16
if r8
-
r7 = r8
-
else
-
16
if has_terminal?(";", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
16
terminal_parse_failure(";")
-
16
r9 = nil
-
end
-
16
if r9
-
r7 = r9
-
else
-
16
@index = i7
-
16
r7 = nil
-
end
-
end
-
16
s4 << r7
-
16
if r7
-
s10, i10 = [], index
-
loop do
-
r11 = _nt_FWS
-
if r11
-
s10 << r11
-
else
-
break
-
end
-
end
-
r10 = instantiate_node(SyntaxNode,input, i10...index, s10)
-
s4 << r10
-
if r10
-
r13 = _nt_address
-
if r13
-
r12 = r13
-
else
-
r12 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r12
-
end
-
end
-
end
-
16
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(AddressList0)
-
else
-
16
@index = i4
-
16
r4 = nil
-
end
-
16
if r4
-
s3 << r4
-
else
-
16
break
-
end
-
end
-
16
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
16
s0 << r3
-
end
-
16
if s0.last
-
16
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
16
r0.extend(AddressList1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
16
node_cache[:address_list][start_index] = r0
-
-
16
r0
-
end
-
-
2
module DateTime0
-
2
def day_of_week
-
elements[0]
-
end
-
-
end
-
-
2
module DateTime1
-
2
def date
-
elements[1]
-
end
-
-
2
def FWS
-
elements[2]
-
end
-
-
2
def time
-
elements[3]
-
end
-
-
end
-
-
2
def _nt_date_time
-
start_index = index
-
if node_cache[:date_time].has_key?(index)
-
cached = node_cache[:date_time][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
i2, s2 = index, []
-
r3 = _nt_day_of_week
-
s2 << r3
-
if r3
-
if has_terminal?(",", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r4 = nil
-
end
-
s2 << r4
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(DateTime0)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r5 = _nt_date
-
s0 << r5
-
if r5
-
r6 = _nt_FWS
-
s0 << r6
-
if r6
-
r7 = _nt_time
-
s0 << r7
-
if r7
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r8
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(DateTime1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:date_time][start_index] = r0
-
-
r0
-
end
-
-
2
module DayOfWeek0
-
2
def day_name
-
elements[1]
-
end
-
end
-
-
2
def _nt_day_of_week
-
start_index = index
-
if node_cache[:day_of_week].has_key?(index)
-
cached = node_cache[:day_of_week][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r3 = _nt_FWS
-
if r3
-
r2 = r3
-
else
-
r2 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r2
-
if r2
-
r4 = _nt_day_name
-
s1 << r4
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(DayOfWeek0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r5 = _nt_obs_day_of_week
-
if r5
-
r0 = r5
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:day_of_week][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_day_name
-
start_index = index
-
if node_cache[:day_name].has_key?(index)
-
cached = node_cache[:day_name][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?("Mon", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Mon")
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?("Tue", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Tue")
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("Wed", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Wed")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?("Thu", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Thu")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("Fri", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Fri")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?("Sat", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Sat")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?("Sun", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Sun")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:day_name][start_index] = r0
-
-
r0
-
end
-
-
2
module Date0
-
2
def day
-
elements[0]
-
end
-
-
2
def month
-
elements[1]
-
end
-
-
2
def year
-
elements[2]
-
end
-
end
-
-
2
def _nt_date
-
start_index = index
-
if node_cache[:date].has_key?(index)
-
cached = node_cache[:date][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_day
-
s0 << r1
-
if r1
-
r2 = _nt_month
-
s0 << r2
-
if r2
-
r3 = _nt_year
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Date0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:date][start_index] = r0
-
-
r0
-
end
-
-
2
module Year0
-
2
def DIGIT1
-
elements[0]
-
end
-
-
2
def DIGIT2
-
elements[1]
-
end
-
-
2
def DIGIT3
-
elements[2]
-
end
-
-
2
def DIGIT4
-
elements[3]
-
end
-
end
-
-
2
def _nt_year
-
start_index = index
-
if node_cache[:year].has_key?(index)
-
cached = node_cache[:year][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_DIGIT
-
s1 << r2
-
if r2
-
r3 = _nt_DIGIT
-
s1 << r3
-
if r3
-
r4 = _nt_DIGIT
-
s1 << r4
-
if r4
-
r5 = _nt_DIGIT
-
s1 << r5
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Year0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r6 = _nt_obs_year
-
if r6
-
r0 = r6
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:year][start_index] = r0
-
-
r0
-
end
-
-
2
module Month0
-
2
def FWS1
-
elements[0]
-
end
-
-
2
def month_name
-
elements[1]
-
end
-
-
2
def FWS2
-
elements[2]
-
end
-
end
-
-
2
def _nt_month
-
start_index = index
-
if node_cache[:month].has_key?(index)
-
cached = node_cache[:month][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_FWS
-
s1 << r2
-
if r2
-
r3 = _nt_month_name
-
s1 << r3
-
if r3
-
r4 = _nt_FWS
-
s1 << r4
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Month0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r5 = _nt_obs_month
-
if r5
-
r0 = r5
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:month][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_month_name
-
start_index = index
-
if node_cache[:month_name].has_key?(index)
-
cached = node_cache[:month_name][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?("Jan", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Jan")
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?("Feb", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Feb")
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("Mar", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Mar")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?("Apr", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Apr")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("May", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("May")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?("Jun", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Jun")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?("Jul", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Jul")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
if has_terminal?("Aug", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Aug")
-
r8 = nil
-
end
-
if r8
-
r0 = r8
-
else
-
if has_terminal?("Sep", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Sep")
-
r9 = nil
-
end
-
if r9
-
r0 = r9
-
else
-
if has_terminal?("Oct", false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Oct")
-
r10 = nil
-
end
-
if r10
-
r0 = r10
-
else
-
if has_terminal?("Nov", false, index)
-
r11 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Nov")
-
r11 = nil
-
end
-
if r11
-
r0 = r11
-
else
-
if has_terminal?("Dec", false, index)
-
r12 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Dec")
-
r12 = nil
-
end
-
if r12
-
r0 = r12
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:month_name][start_index] = r0
-
-
r0
-
end
-
-
2
module Day0
-
2
def DIGIT
-
elements[1]
-
end
-
-
end
-
-
2
def _nt_day
-
start_index = index
-
if node_cache[:day].has_key?(index)
-
cached = node_cache[:day][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r3 = _nt_FWS
-
if r3
-
r2 = r3
-
else
-
r2 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r2
-
if r2
-
r4 = _nt_DIGIT
-
s1 << r4
-
if r4
-
r6 = _nt_DIGIT
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r5
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Day0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r7 = _nt_obs_day
-
if r7
-
r0 = r7
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:day][start_index] = r0
-
-
r0
-
end
-
-
2
module Time0
-
2
def time_of_day
-
elements[0]
-
end
-
-
2
def FWS
-
elements[1]
-
end
-
-
2
def zone
-
elements[2]
-
end
-
end
-
-
2
def _nt_time
-
start_index = index
-
if node_cache[:time].has_key?(index)
-
cached = node_cache[:time][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_time_of_day
-
s0 << r1
-
if r1
-
r2 = _nt_FWS
-
s0 << r2
-
if r2
-
r3 = _nt_zone
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Time0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:time][start_index] = r0
-
-
r0
-
end
-
-
2
module TimeOfDay0
-
2
def second
-
elements[1]
-
end
-
end
-
-
2
module TimeOfDay1
-
2
def hour
-
elements[0]
-
end
-
-
2
def minute
-
elements[2]
-
end
-
-
end
-
-
2
def _nt_time_of_day
-
start_index = index
-
if node_cache[:time_of_day].has_key?(index)
-
cached = node_cache[:time_of_day][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_hour
-
s0 << r1
-
if r1
-
if has_terminal?(":", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r2 = nil
-
end
-
s0 << r2
-
if r2
-
r3 = _nt_minute
-
s0 << r3
-
if r3
-
i5, s5 = index, []
-
if has_terminal?(":", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r6 = nil
-
end
-
s5 << r6
-
if r6
-
r7 = _nt_second
-
s5 << r7
-
end
-
if s5.last
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
r5.extend(TimeOfDay0)
-
else
-
@index = i5
-
r5 = nil
-
end
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r4
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(TimeOfDay1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:time_of_day][start_index] = r0
-
-
r0
-
end
-
-
2
module Hour0
-
2
def DIGIT1
-
elements[0]
-
end
-
-
2
def DIGIT2
-
elements[1]
-
end
-
end
-
-
2
def _nt_hour
-
start_index = index
-
if node_cache[:hour].has_key?(index)
-
cached = node_cache[:hour][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_DIGIT
-
s1 << r2
-
if r2
-
r3 = _nt_DIGIT
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Hour0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r4 = _nt_obs_hour
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:hour][start_index] = r0
-
-
r0
-
end
-
-
2
module Minute0
-
2
def DIGIT1
-
elements[0]
-
end
-
-
2
def DIGIT2
-
elements[1]
-
end
-
end
-
-
2
def _nt_minute
-
start_index = index
-
if node_cache[:minute].has_key?(index)
-
cached = node_cache[:minute][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_DIGIT
-
s1 << r2
-
if r2
-
r3 = _nt_DIGIT
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Minute0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r4 = _nt_obs_minute
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:minute][start_index] = r0
-
-
r0
-
end
-
-
2
module Second0
-
2
def DIGIT1
-
elements[0]
-
end
-
-
2
def DIGIT2
-
elements[1]
-
end
-
end
-
-
2
def _nt_second
-
start_index = index
-
if node_cache[:second].has_key?(index)
-
cached = node_cache[:second][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r2 = _nt_DIGIT
-
s1 << r2
-
if r2
-
r3 = _nt_DIGIT
-
s1 << r3
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Second0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r4 = _nt_obs_second
-
if r4
-
r0 = r4
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:second][start_index] = r0
-
-
r0
-
end
-
-
2
module Zone0
-
2
def DIGIT1
-
elements[1]
-
end
-
-
2
def DIGIT2
-
elements[2]
-
end
-
-
2
def DIGIT3
-
elements[3]
-
end
-
-
2
def DIGIT4
-
elements[4]
-
end
-
end
-
-
2
def _nt_zone
-
start_index = index
-
if node_cache[:zone].has_key?(index)
-
cached = node_cache[:zone][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
i2 = index
-
if has_terminal?("+", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("+")
-
r3 = nil
-
end
-
if r3
-
r2 = r3
-
else
-
if has_terminal?("-", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("-")
-
r4 = nil
-
end
-
if r4
-
r2 = r4
-
else
-
@index = i2
-
r2 = nil
-
end
-
end
-
s1 << r2
-
if r2
-
r5 = _nt_DIGIT
-
s1 << r5
-
if r5
-
r6 = _nt_DIGIT
-
s1 << r6
-
if r6
-
r7 = _nt_DIGIT
-
s1 << r7
-
if r7
-
r8 = _nt_DIGIT
-
s1 << r8
-
end
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Zone0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r9 = _nt_obs_zone
-
if r9
-
r0 = r9
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:zone][start_index] = r0
-
-
r0
-
end
-
-
2
module Return0
-
2
def path
-
elements[0]
-
end
-
-
2
def CRLF
-
elements[1]
-
end
-
end
-
-
2
def _nt_return
-
start_index = index
-
if node_cache[:return].has_key?(index)
-
cached = node_cache[:return][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_path
-
s0 << r1
-
if r1
-
r2 = _nt_CRLF
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Return0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:return][start_index] = r0
-
-
r0
-
end
-
-
2
module Path0
-
end
-
-
2
def _nt_path
-
start_index = index
-
if node_cache[:path].has_key?(index)
-
cached = node_cache[:path][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
i1, s1 = index, []
-
r3 = _nt_CFWS
-
if r3
-
r2 = r3
-
else
-
r2 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r2
-
if r2
-
if has_terminal?("<", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("<")
-
r4 = nil
-
end
-
s1 << r4
-
if r4
-
i5 = index
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
if r6
-
r5 = r6
-
else
-
r8 = _nt_addr_spec
-
if r8
-
r5 = r8
-
else
-
@index = i5
-
r5 = nil
-
end
-
end
-
s1 << r5
-
if r5
-
if has_terminal?(">", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r9 = nil
-
end
-
s1 << r9
-
if r9
-
r11 = _nt_CFWS
-
if r11
-
r10 = r11
-
else
-
r10 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r10
-
end
-
end
-
end
-
end
-
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(Path0)
-
else
-
@index = i1
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
r12 = _nt_obs_path
-
if r12
-
r0 = r12
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:path][start_index] = r0
-
-
r0
-
end
-
-
2
module Received0
-
2
def name_val_list
-
elements[0]
-
end
-
-
2
def date_time
-
elements[2]
-
end
-
-
2
def CRLF
-
elements[3]
-
end
-
end
-
-
2
def _nt_received
-
start_index = index
-
if node_cache[:received].has_key?(index)
-
cached = node_cache[:received][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_name_val_list
-
s0 << r1
-
if r1
-
if has_terminal?(";", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(";")
-
r2 = nil
-
end
-
s0 << r2
-
if r2
-
r3 = _nt_date_time
-
s0 << r3
-
if r3
-
r4 = _nt_CRLF
-
s0 << r4
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(Received0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:received][start_index] = r0
-
-
r0
-
end
-
-
2
module NameValList0
-
2
def CFWS
-
elements[0]
-
end
-
-
2
def name_val_pair
-
elements[1]
-
end
-
end
-
-
2
module NameValList1
-
2
def name_val_pair
-
elements[0]
-
end
-
-
end
-
-
2
module NameValList2
-
end
-
-
2
def _nt_name_val_list
-
start_index = index
-
if node_cache[:name_val_list].has_key?(index)
-
cached = node_cache[:name_val_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
i4, s4 = index, []
-
r5 = _nt_name_val_pair
-
s4 << r5
-
if r5
-
s6, i6 = [], index
-
loop do
-
i7, s7 = index, []
-
r8 = _nt_CFWS
-
s7 << r8
-
if r8
-
r9 = _nt_name_val_pair
-
s7 << r9
-
end
-
if s7.last
-
r7 = instantiate_node(SyntaxNode,input, i7...index, s7)
-
r7.extend(NameValList0)
-
else
-
@index = i7
-
r7 = nil
-
end
-
if r7
-
s6 << r7
-
else
-
break
-
end
-
end
-
r6 = instantiate_node(SyntaxNode,input, i6...index, s6)
-
s4 << r6
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(NameValList1)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
r3 = r4
-
else
-
r3 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r3
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(NameValList2)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:name_val_list][start_index] = r0
-
-
r0
-
end
-
-
2
module NameValPair0
-
2
def item_name
-
elements[0]
-
end
-
-
2
def CFWS
-
elements[1]
-
end
-
-
2
def item_value
-
elements[2]
-
end
-
end
-
-
2
def _nt_name_val_pair
-
start_index = index
-
if node_cache[:name_val_pair].has_key?(index)
-
cached = node_cache[:name_val_pair][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_item_name
-
s0 << r1
-
if r1
-
r2 = _nt_CFWS
-
s0 << r2
-
if r2
-
r3 = _nt_item_value
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(NameValPair0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:name_val_pair][start_index] = r0
-
-
r0
-
end
-
-
2
module ItemName0
-
end
-
-
2
module ItemName1
-
2
def ALPHA
-
elements[0]
-
end
-
-
end
-
-
2
def _nt_item_name
-
start_index = index
-
if node_cache[:item_name].has_key?(index)
-
cached = node_cache[:item_name][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_ALPHA
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
if has_terminal?("-", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("-")
-
r5 = nil
-
end
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s3 << r4
-
if r4
-
i6 = index
-
r7 = _nt_ALPHA
-
if r7
-
r6 = r7
-
else
-
r8 = _nt_DIGIT
-
if r8
-
r6 = r8
-
else
-
@index = i6
-
r6 = nil
-
end
-
end
-
s3 << r6
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ItemName0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ItemName1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:item_name][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_item_value
-
start_index = index
-
if node_cache[:item_value].has_key?(index)
-
cached = node_cache[:item_value][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
s1, i1 = [], index
-
loop do
-
r2 = _nt_angle_addr
-
if r2
-
s1 << r2
-
else
-
break
-
end
-
end
-
if s1.empty?
-
@index = i1
-
r1 = nil
-
else
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
end
-
if r1
-
r0 = r1
-
else
-
r3 = _nt_addr_spec
-
if r3
-
r0 = r3
-
else
-
r4 = _nt_atom
-
if r4
-
r0 = r4
-
else
-
r5 = _nt_domain
-
if r5
-
r0 = r5
-
else
-
r6 = _nt_msg_id
-
if r6
-
r0 = r6
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:item_value][start_index] = r0
-
-
r0
-
end
-
-
2
module MessageIds0
-
2
def CFWS
-
elements[0]
-
end
-
-
2
def msg_id_value
-
elements[1]
-
end
-
end
-
-
2
module MessageIds1
-
2
def first_msg_id
-
4
elements[0]
-
end
-
-
2
def other_msg_ids
-
4
elements[1]
-
end
-
end
-
-
2
def _nt_message_ids
-
4
start_index = index
-
4
if node_cache[:message_ids].has_key?(index)
-
cached = node_cache[:message_ids][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
4
i0, s0 = index, []
-
4
r1 = _nt_msg_id
-
4
s0 << r1
-
4
if r1
-
4
s2, i2 = [], index
-
4
loop do
-
4
i3, s3 = index, []
-
4
r4 = _nt_CFWS
-
4
s3 << r4
-
4
if r4
-
4
r5 = _nt_msg_id
-
4
s3 << r5
-
end
-
4
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(MessageIds0)
-
else
-
4
@index = i3
-
4
r3 = nil
-
end
-
4
if r3
-
s2 << r3
-
else
-
4
break
-
end
-
end
-
4
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
4
s0 << r2
-
end
-
4
if s0.last
-
4
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
4
r0.extend(MessageIds1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
4
node_cache[:message_ids][start_index] = r0
-
-
4
r0
-
end
-
-
2
module MsgId0
-
2
def msg_id_value
-
elements[2]
-
end
-
-
end
-
-
2
def _nt_msg_id
-
8
start_index = index
-
8
if node_cache[:msg_id].has_key?(index)
-
cached = node_cache[:msg_id][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
8
i0, s0 = index, []
-
8
r2 = _nt_CFWS
-
8
if r2
-
8
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
8
s0 << r1
-
8
if r1
-
8
if has_terminal?("<", false, index)
-
4
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
4
@index += 1
-
else
-
4
terminal_parse_failure("<")
-
4
r3 = nil
-
end
-
8
s0 << r3
-
8
if r3
-
4
r4 = _nt_msg_id_value
-
4
s0 << r4
-
4
if r4
-
4
if has_terminal?(">", false, index)
-
4
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
4
@index += 1
-
else
-
terminal_parse_failure(">")
-
r5 = nil
-
end
-
4
s0 << r5
-
4
if r5
-
4
r7 = _nt_CFWS
-
4
if r7
-
4
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
4
s0 << r6
-
end
-
end
-
end
-
end
-
8
if s0.last
-
4
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
4
r0.extend(MsgId0)
-
else
-
4
@index = i0
-
4
r0 = nil
-
end
-
-
8
node_cache[:msg_id][start_index] = r0
-
-
8
r0
-
end
-
-
2
module MsgIdValue0
-
2
def id_left
-
elements[0]
-
end
-
-
2
def id_right
-
elements[2]
-
end
-
end
-
-
2
def _nt_msg_id_value
-
4
start_index = index
-
4
if node_cache[:msg_id_value].has_key?(index)
-
cached = node_cache[:msg_id_value][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
4
i0, s0 = index, []
-
4
r1 = _nt_id_left
-
4
s0 << r1
-
4
if r1
-
4
if has_terminal?("@", false, index)
-
4
r2 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
4
@index += 1
-
else
-
terminal_parse_failure("@")
-
r2 = nil
-
end
-
4
s0 << r2
-
4
if r2
-
4
r3 = _nt_id_right
-
4
s0 << r3
-
end
-
end
-
4
if s0.last
-
4
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
4
r0.extend(MsgIdValue0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
4
node_cache[:msg_id_value][start_index] = r0
-
-
4
r0
-
end
-
-
2
def _nt_id_left
-
4
start_index = index
-
4
if node_cache[:id_left].has_key?(index)
-
cached = node_cache[:id_left][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
4
i0 = index
-
4
r1 = _nt_message_id_text
-
4
if r1
-
4
r0 = r1
-
else
-
r2 = _nt_no_fold_quote
-
if r2
-
r0 = r2
-
else
-
r3 = _nt_obs_id_left
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
4
node_cache[:id_left][start_index] = r0
-
-
4
r0
-
end
-
-
2
def _nt_id_right
-
4
start_index = index
-
4
if node_cache[:id_right].has_key?(index)
-
cached = node_cache[:id_right][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
4
i0 = index
-
4
r1 = _nt_msg_id_dot_atom_text
-
4
if r1
-
4
r0 = r1
-
else
-
r2 = _nt_no_fold_literal
-
if r2
-
r0 = r2
-
else
-
r3 = _nt_obs_id_right
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
4
node_cache[:id_right][start_index] = r0
-
-
4
r0
-
end
-
-
2
module MsgIdDotAtomText0
-
2
def msg_id_domain_text
-
elements[0]
-
end
-
-
end
-
-
2
def _nt_msg_id_dot_atom_text
-
4
start_index = index
-
4
if node_cache[:msg_id_dot_atom_text].has_key?(index)
-
cached = node_cache[:msg_id_dot_atom_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
4
s0, i0 = [], index
-
4
loop do
-
12
i1, s1 = index, []
-
12
r2 = _nt_msg_id_domain_text
-
12
s1 << r2
-
12
if r2
-
8
if has_terminal?(".", false, index)
-
4
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
4
@index += 1
-
else
-
4
terminal_parse_failure(".")
-
4
r4 = nil
-
end
-
8
if r4
-
4
r3 = r4
-
else
-
4
r3 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
8
s1 << r3
-
end
-
12
if s1.last
-
8
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
8
r1.extend(MsgIdDotAtomText0)
-
else
-
4
@index = i1
-
4
r1 = nil
-
end
-
12
if r1
-
8
s0 << r1
-
else
-
4
break
-
end
-
end
-
4
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
4
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
4
node_cache[:msg_id_dot_atom_text][start_index] = r0
-
-
4
r0
-
end
-
-
2
module MsgIdDomainText0
-
2
def quoted_domain
-
elements[1]
-
end
-
end
-
-
2
module MsgIdDomainText1
-
2
def DQUOTE1
-
elements[0]
-
end
-
-
2
def DQUOTE2
-
elements[3]
-
end
-
end
-
-
2
def _nt_msg_id_domain_text
-
12
start_index = index
-
12
if node_cache[:msg_id_domain_text].has_key?(index)
-
cached = node_cache[:msg_id_domain_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
12
i0 = index
-
12
i1, s1 = index, []
-
12
r2 = _nt_DQUOTE
-
12
s1 << r2
-
12
if r2
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
r6 = _nt_FWS
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r5
-
if r5
-
r7 = _nt_quoted_domain
-
s4 << r7
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(MsgIdDomainText0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
if s3.empty?
-
@index = i3
-
r3 = nil
-
else
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
end
-
s1 << r3
-
if r3
-
r9 = _nt_FWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s1 << r8
-
if r8
-
r10 = _nt_DQUOTE
-
s1 << r10
-
end
-
end
-
end
-
12
if s1.last
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
r1.extend(MsgIdDomainText1)
-
else
-
12
@index = i1
-
12
r1 = nil
-
end
-
12
if r1
-
r0 = r1
-
else
-
12
s11, i11 = [], index
-
12
loop do
-
60
r12 = _nt_msg_id_atext
-
60
if r12
-
48
s11 << r12
-
else
-
12
break
-
end
-
end
-
12
if s11.empty?
-
4
@index = i11
-
4
r11 = nil
-
else
-
8
r11 = instantiate_node(SyntaxNode,input, i11...index, s11)
-
end
-
12
if r11
-
8
r0 = r11
-
else
-
4
@index = i0
-
4
r0 = nil
-
end
-
end
-
-
12
node_cache[:msg_id_domain_text][start_index] = r0
-
-
12
r0
-
end
-
-
2
def _nt_msg_id_atext
-
60
start_index = index
-
60
if node_cache[:msg_id_atext].has_key?(index)
-
4
cached = node_cache[:msg_id_atext][index]
-
4
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
4
return cached
-
end
-
-
56
i0 = index
-
56
r1 = _nt_ALPHA
-
56
if r1
-
48
r0 = r1
-
else
-
8
r2 = _nt_DIGIT
-
8
if r2
-
r0 = r2
-
else
-
8
if has_terminal?("!", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("!")
-
8
r3 = nil
-
end
-
8
if r3
-
r0 = r3
-
else
-
8
if has_terminal?("#", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("#")
-
8
r4 = nil
-
end
-
8
if r4
-
r0 = r4
-
else
-
8
if has_terminal?("$", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("$")
-
8
r5 = nil
-
end
-
8
if r5
-
r0 = r5
-
else
-
8
if has_terminal?("%", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("%")
-
8
r6 = nil
-
end
-
8
if r6
-
r0 = r6
-
else
-
8
if has_terminal?("&", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("&")
-
8
r7 = nil
-
end
-
8
if r7
-
r0 = r7
-
else
-
8
if has_terminal?("'", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("'")
-
8
r8 = nil
-
end
-
8
if r8
-
r0 = r8
-
else
-
8
if has_terminal?("*", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("*")
-
8
r9 = nil
-
end
-
8
if r9
-
r0 = r9
-
else
-
8
if has_terminal?("+", false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("+")
-
8
r10 = nil
-
end
-
8
if r10
-
r0 = r10
-
else
-
8
if has_terminal?("-", false, index)
-
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("-")
-
8
r11 = nil
-
end
-
8
if r11
-
r0 = r11
-
else
-
8
if has_terminal?("/", false, index)
-
r12 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("/")
-
8
r12 = nil
-
end
-
8
if r12
-
r0 = r12
-
else
-
8
if has_terminal?("=", false, index)
-
r13 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("=")
-
8
r13 = nil
-
end
-
8
if r13
-
r0 = r13
-
else
-
8
if has_terminal?("?", false, index)
-
r14 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("?")
-
8
r14 = nil
-
end
-
8
if r14
-
r0 = r14
-
else
-
8
if has_terminal?("^", false, index)
-
r15 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("^")
-
8
r15 = nil
-
end
-
8
if r15
-
r0 = r15
-
else
-
8
if has_terminal?("_", false, index)
-
r16 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("_")
-
8
r16 = nil
-
end
-
8
if r16
-
r0 = r16
-
else
-
8
if has_terminal?("`", false, index)
-
r17 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("`")
-
8
r17 = nil
-
end
-
8
if r17
-
r0 = r17
-
else
-
8
if has_terminal?("{", false, index)
-
r18 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("{")
-
8
r18 = nil
-
end
-
8
if r18
-
r0 = r18
-
else
-
8
if has_terminal?("|", false, index)
-
r19 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("|")
-
8
r19 = nil
-
end
-
8
if r19
-
r0 = r19
-
else
-
8
if has_terminal?("}", false, index)
-
r20 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("}")
-
8
r20 = nil
-
end
-
8
if r20
-
r0 = r20
-
else
-
8
if has_terminal?("~", false, index)
-
r21 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("~")
-
8
r21 = nil
-
end
-
8
if r21
-
r0 = r21
-
else
-
8
if has_terminal?("@", false, index)
-
r22 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
8
terminal_parse_failure("@")
-
8
r22 = nil
-
end
-
8
if r22
-
r0 = r22
-
else
-
8
@index = i0
-
8
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
56
node_cache[:msg_id_atext][start_index] = r0
-
-
56
r0
-
end
-
-
2
module NoFoldQuote0
-
2
def DQUOTE1
-
elements[0]
-
end
-
-
2
def DQUOTE2
-
elements[2]
-
end
-
end
-
-
2
def _nt_no_fold_quote
-
start_index = index
-
if node_cache[:no_fold_quote].has_key?(index)
-
cached = node_cache[:no_fold_quote][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_DQUOTE
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3 = index
-
r4 = _nt_qtext
-
if r4
-
r3 = r4
-
else
-
r5 = _nt_quoted_pair
-
if r5
-
r3 = r5
-
else
-
@index = i3
-
r3 = nil
-
end
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
s0 << r2
-
if r2
-
r6 = _nt_DQUOTE
-
s0 << r6
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(NoFoldQuote0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:no_fold_quote][start_index] = r0
-
-
r0
-
end
-
-
2
module NoFoldLiteral0
-
end
-
-
2
def _nt_no_fold_literal
-
start_index = index
-
if node_cache[:no_fold_literal].has_key?(index)
-
cached = node_cache[:no_fold_literal][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("[", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("[")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3 = index
-
r4 = _nt_dtext
-
if r4
-
r3 = r4
-
else
-
r5 = _nt_quoted_pair
-
if r5
-
r3 = r5
-
else
-
@index = i3
-
r3 = nil
-
end
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
if s2.empty?
-
@index = i2
-
r2 = nil
-
else
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
end
-
s0 << r2
-
if r2
-
if has_terminal?("]", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("]")
-
r6 = nil
-
end
-
s0 << r6
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(NoFoldLiteral0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:no_fold_literal][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
2
class RFC2822Parser < Treetop::Runtime::CompiledParser
-
2
include RFC2822
-
end
-
-
end
-
# Autogenerated from a Treetop grammar. Edits may be lost.
-
-
-
2
module Mail
-
2
module RFC2822Obsolete
-
2
include Treetop::Runtime
-
-
2
def root
-
@root ||= :obs_qp
-
end
-
-
2
module ObsQp0
-
end
-
-
2
def _nt_obs_qp
-
start_index = index
-
if node_cache[:obs_qp].has_key?(index)
-
cached = node_cache[:obs_qp][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("\\", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("\\")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
if has_terminal?('\G[\\x00-\\x7F]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsQp0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_qp][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsText0
-
2
def obs_char
-
elements[0]
-
end
-
-
end
-
-
2
module ObsText1
-
end
-
-
2
def _nt_obs_text
-
start_index = index
-
if node_cache[:obs_text].has_key?(index)
-
cached = node_cache[:obs_text][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
s1, i1 = [], index
-
loop do
-
r2 = _nt_LF
-
if r2
-
s1 << r2
-
else
-
break
-
end
-
end
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
s0 << r1
-
if r1
-
s3, i3 = [], index
-
loop do
-
r4 = _nt_CR
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
s0 << r3
-
if r3
-
s5, i5 = [], index
-
loop do
-
i6, s6 = index, []
-
r7 = _nt_obs_char
-
s6 << r7
-
if r7
-
s8, i8 = [], index
-
loop do
-
r9 = _nt_LF
-
if r9
-
s8 << r9
-
else
-
break
-
end
-
end
-
r8 = instantiate_node(SyntaxNode,input, i8...index, s8)
-
s6 << r8
-
if r8
-
s10, i10 = [], index
-
loop do
-
r11 = _nt_CR
-
if r11
-
s10 << r11
-
else
-
break
-
end
-
end
-
r10 = instantiate_node(SyntaxNode,input, i10...index, s10)
-
s6 << r10
-
end
-
end
-
if s6.last
-
r6 = instantiate_node(SyntaxNode,input, i6...index, s6)
-
r6.extend(ObsText0)
-
else
-
@index = i6
-
r6 = nil
-
end
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
s0 << r5
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsText1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_text][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_obs_char
-
start_index = index
-
if node_cache[:obs_char].has_key?(index)
-
cached = node_cache[:obs_char][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?('\G[\\x00-\\x09]', true, index)
-
r1 = true
-
@index += 1
-
else
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?('\G[\\x0B-\\x0C]', true, index)
-
r2 = true
-
@index += 1
-
else
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?('\G[\\x0E-\\x7F]', true, index)
-
r3 = true
-
@index += 1
-
else
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
-
node_cache[:obs_char][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_obs_utext
-
start_index = index
-
if node_cache[:obs_utext].has_key?(index)
-
cached = node_cache[:obs_utext][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_obs_text
-
-
node_cache[:obs_utext][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_obs_phrase
-
16
start_index = index
-
16
if node_cache[:obs_phrase].has_key?(index)
-
cached = node_cache[:obs_phrase][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
16
s0, i0 = [], index
-
16
loop do
-
112
i1 = index
-
112
r2 = _nt_word
-
112
if r2
-
56
r1 = r2
-
else
-
56
if has_terminal?(".", false, index)
-
24
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
24
@index += 1
-
else
-
32
terminal_parse_failure(".")
-
32
r3 = nil
-
end
-
56
if r3
-
24
r1 = r3
-
else
-
32
if has_terminal?("@", false, index)
-
16
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
16
@index += 1
-
else
-
16
terminal_parse_failure("@")
-
16
r4 = nil
-
end
-
32
if r4
-
16
r1 = r4
-
else
-
16
@index = i1
-
16
r1 = nil
-
end
-
end
-
end
-
112
if r1
-
96
s0 << r1
-
else
-
16
break
-
end
-
end
-
16
if s0.empty?
-
@index = i0
-
r0 = nil
-
else
-
16
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
end
-
-
16
node_cache[:obs_phrase][start_index] = r0
-
-
16
r0
-
end
-
-
2
module ObsPhraseList0
-
end
-
-
2
module ObsPhraseList1
-
end
-
-
2
def _nt_obs_phrase_list
-
start_index = index
-
if node_cache[:obs_phrase_list].has_key?(index)
-
cached = node_cache[:obs_phrase_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
r1 = _nt_phrase
-
if r1
-
r0 = r1
-
else
-
i2, s2 = index, []
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
r6 = _nt_phrase
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r5
-
if r5
-
r8 = _nt_CFWS
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r7
-
if r7
-
if has_terminal?(",", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r9 = nil
-
end
-
s4 << r9
-
if r9
-
r11 = _nt_CFWS
-
if r11
-
r10 = r11
-
else
-
r10 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r10
-
end
-
end
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(ObsPhraseList0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
if s3.empty?
-
@index = i3
-
r3 = nil
-
else
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
end
-
s2 << r3
-
if r3
-
r13 = _nt_phrase
-
if r13
-
r12 = r13
-
else
-
r12 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r12
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(ObsPhraseList1)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
-
node_cache[:obs_phrase_list][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsFWS0
-
2
def CRLF
-
elements[0]
-
end
-
-
end
-
-
2
module ObsFWS1
-
end
-
-
2
def _nt_obs_FWS
-
152
start_index = index
-
152
if node_cache[:obs_FWS].has_key?(index)
-
cached = node_cache[:obs_FWS][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
152
i0, s0 = index, []
-
152
s1, i1 = [], index
-
152
loop do
-
152
r2 = _nt_WSP
-
152
if r2
-
s1 << r2
-
else
-
152
break
-
end
-
end
-
152
if s1.empty?
-
152
@index = i1
-
152
r1 = nil
-
else
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
end
-
152
s0 << r1
-
152
if r1
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
r5 = _nt_CRLF
-
s4 << r5
-
if r5
-
s6, i6 = [], index
-
loop do
-
r7 = _nt_WSP
-
if r7
-
s6 << r7
-
else
-
break
-
end
-
end
-
if s6.empty?
-
@index = i6
-
r6 = nil
-
else
-
r6 = instantiate_node(SyntaxNode,input, i6...index, s6)
-
end
-
s4 << r6
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(ObsFWS0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
s0 << r3
-
end
-
152
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsFWS1)
-
else
-
152
@index = i0
-
152
r0 = nil
-
end
-
-
152
node_cache[:obs_FWS][start_index] = r0
-
-
152
r0
-
end
-
-
2
module ObsDayOfWeek0
-
2
def day_name
-
elements[1]
-
end
-
-
end
-
-
2
def _nt_obs_day_of_week
-
start_index = index
-
if node_cache[:obs_day_of_week].has_key?(index)
-
cached = node_cache[:obs_day_of_week][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r3 = _nt_day_name
-
s0 << r3
-
if r3
-
r5 = _nt_CFWS
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r4
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsDayOfWeek0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_day_of_week][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsYear0
-
2
def DIGIT1
-
elements[0]
-
end
-
-
2
def DIGIT2
-
elements[1]
-
end
-
end
-
-
2
module ObsYear1
-
end
-
-
2
def _nt_obs_year
-
start_index = index
-
if node_cache[:obs_year].has_key?(index)
-
cached = node_cache[:obs_year][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
i3, s3 = index, []
-
r4 = _nt_DIGIT
-
s3 << r4
-
if r4
-
r5 = _nt_DIGIT
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ObsYear0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
s0 << r3
-
if r3
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsYear1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_year][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsMonth0
-
2
def CFWS1
-
elements[0]
-
end
-
-
2
def month_name
-
elements[1]
-
end
-
-
2
def CFWS2
-
elements[2]
-
end
-
end
-
-
2
def _nt_obs_month
-
start_index = index
-
if node_cache[:obs_month].has_key?(index)
-
cached = node_cache[:obs_month][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_CFWS
-
s0 << r1
-
if r1
-
r2 = _nt_month_name
-
s0 << r2
-
if r2
-
r3 = _nt_CFWS
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsMonth0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_month][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsDay0
-
2
def DIGIT1
-
elements[0]
-
end
-
-
2
def DIGIT2
-
elements[1]
-
end
-
end
-
-
2
module ObsDay1
-
end
-
-
2
def _nt_obs_day
-
start_index = index
-
if node_cache[:obs_day].has_key?(index)
-
cached = node_cache[:obs_day][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
i3 = index
-
r4 = _nt_DIGIT
-
if r4
-
r3 = r4
-
else
-
i5, s5 = index, []
-
r6 = _nt_DIGIT
-
s5 << r6
-
if r6
-
r7 = _nt_DIGIT
-
s5 << r7
-
end
-
if s5.last
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
r5.extend(ObsDay0)
-
else
-
@index = i5
-
r5 = nil
-
end
-
if r5
-
r3 = r5
-
else
-
@index = i3
-
r3 = nil
-
end
-
end
-
s0 << r3
-
if r3
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r8
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsDay1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_day][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsHour0
-
2
def DIGIT1
-
elements[0]
-
end
-
-
2
def DIGIT2
-
elements[1]
-
end
-
end
-
-
2
module ObsHour1
-
end
-
-
2
def _nt_obs_hour
-
start_index = index
-
if node_cache[:obs_hour].has_key?(index)
-
cached = node_cache[:obs_hour][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
i3, s3 = index, []
-
r4 = _nt_DIGIT
-
s3 << r4
-
if r4
-
r5 = _nt_DIGIT
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ObsHour0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
s0 << r3
-
if r3
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsHour1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_hour][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsMinute0
-
2
def DIGIT1
-
elements[0]
-
end
-
-
2
def DIGIT2
-
elements[1]
-
end
-
end
-
-
2
module ObsMinute1
-
end
-
-
2
def _nt_obs_minute
-
start_index = index
-
if node_cache[:obs_minute].has_key?(index)
-
cached = node_cache[:obs_minute][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
i3, s3 = index, []
-
r4 = _nt_DIGIT
-
s3 << r4
-
if r4
-
r5 = _nt_DIGIT
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ObsMinute0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
s0 << r3
-
if r3
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsMinute1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_minute][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsSecond0
-
2
def DIGIT1
-
elements[0]
-
end
-
-
2
def DIGIT2
-
elements[1]
-
end
-
end
-
-
2
module ObsSecond1
-
end
-
-
2
def _nt_obs_second
-
start_index = index
-
if node_cache[:obs_second].has_key?(index)
-
cached = node_cache[:obs_second][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
i3, s3 = index, []
-
r4 = _nt_DIGIT
-
s3 << r4
-
if r4
-
r5 = _nt_DIGIT
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ObsSecond0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
s0 << r3
-
if r3
-
r7 = _nt_CFWS
-
if r7
-
r6 = r7
-
else
-
r6 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r6
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsSecond1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_second][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_obs_zone
-
start_index = index
-
if node_cache[:obs_zone].has_key?(index)
-
cached = node_cache[:obs_zone][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0 = index
-
if has_terminal?("UT", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 2))
-
@index += 2
-
else
-
terminal_parse_failure("UT")
-
r1 = nil
-
end
-
if r1
-
r0 = r1
-
else
-
if has_terminal?("GMT", false, index)
-
r2 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("GMT")
-
r2 = nil
-
end
-
if r2
-
r0 = r2
-
else
-
if has_terminal?("EST", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("EST")
-
r3 = nil
-
end
-
if r3
-
r0 = r3
-
else
-
if has_terminal?("EDT", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("EDT")
-
r4 = nil
-
end
-
if r4
-
r0 = r4
-
else
-
if has_terminal?("CST", false, index)
-
r5 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("CST")
-
r5 = nil
-
end
-
if r5
-
r0 = r5
-
else
-
if has_terminal?("CDT", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("CDT")
-
r6 = nil
-
end
-
if r6
-
r0 = r6
-
else
-
if has_terminal?("MST", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("MST")
-
r7 = nil
-
end
-
if r7
-
r0 = r7
-
else
-
if has_terminal?("MDT", false, index)
-
r8 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("MDT")
-
r8 = nil
-
end
-
if r8
-
r0 = r8
-
else
-
if has_terminal?("PST", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("PST")
-
r9 = nil
-
end
-
if r9
-
r0 = r9
-
else
-
if has_terminal?("PDT", false, index)
-
r10 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("PDT")
-
r10 = nil
-
end
-
if r10
-
r0 = r10
-
else
-
if has_terminal?('\G[\\x41-\\x49]', true, index)
-
r11 = true
-
@index += 1
-
else
-
r11 = nil
-
end
-
if r11
-
r0 = r11
-
else
-
if has_terminal?('\G[\\x4B-\\x5A]', true, index)
-
r12 = true
-
@index += 1
-
else
-
r12 = nil
-
end
-
if r12
-
r0 = r12
-
else
-
if has_terminal?('\G[\\x61-\\x69]', true, index)
-
r13 = true
-
@index += 1
-
else
-
r13 = nil
-
end
-
if r13
-
r0 = r13
-
else
-
if has_terminal?('\G[\\x6B-\\x7A]', true, index)
-
r14 = true
-
@index += 1
-
else
-
r14 = nil
-
end
-
if r14
-
r0 = r14
-
else
-
@index = i0
-
r0 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
-
node_cache[:obs_zone][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsAngleAddr0
-
2
def addr_spec
-
elements[3]
-
end
-
-
end
-
-
2
def _nt_obs_angle_addr
-
32
start_index = index
-
32
if node_cache[:obs_angle_addr].has_key?(index)
-
cached = node_cache[:obs_angle_addr][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
32
i0, s0 = index, []
-
32
r2 = _nt_CFWS
-
32
if r2
-
32
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
32
s0 << r1
-
32
if r1
-
32
if has_terminal?("<", false, index)
-
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
32
terminal_parse_failure("<")
-
32
r3 = nil
-
end
-
32
s0 << r3
-
32
if r3
-
r5 = _nt_obs_route
-
if r5
-
r4 = r5
-
else
-
r4 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r4
-
if r4
-
r6 = _nt_addr_spec
-
s0 << r6
-
if r6
-
if has_terminal?(">", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(">")
-
r7 = nil
-
end
-
s0 << r7
-
if r7
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r8
-
end
-
end
-
end
-
end
-
end
-
32
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsAngleAddr0)
-
else
-
32
@index = i0
-
32
r0 = nil
-
end
-
-
32
node_cache[:obs_angle_addr][start_index] = r0
-
-
32
r0
-
end
-
-
2
module ObsRoute0
-
2
def obs_domain_list
-
elements[1]
-
end
-
-
end
-
-
2
def _nt_obs_route
-
start_index = index
-
if node_cache[:obs_route].has_key?(index)
-
cached = node_cache[:obs_route][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r2 = _nt_CFWS
-
if r2
-
r1 = r2
-
else
-
r1 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r1
-
if r1
-
r3 = _nt_obs_domain_list
-
s0 << r3
-
if r3
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r6 = _nt_CFWS
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r5
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsRoute0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_route][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsDomainList0
-
2
def domain
-
elements[3]
-
end
-
end
-
-
2
module ObsDomainList1
-
2
def domain
-
elements[1]
-
end
-
-
end
-
-
2
def _nt_obs_domain_list
-
start_index = index
-
if node_cache[:obs_domain_list].has_key?(index)
-
cached = node_cache[:obs_domain_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("@", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("@")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
r2 = _nt_domain
-
s0 << r2
-
if r2
-
s3, i3 = [], index
-
loop do
-
i4, s4 = index, []
-
s5, i5 = [], index
-
loop do
-
if has_terminal?(",", false, index)
-
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r6 = nil
-
end
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
s4 << r5
-
if r5
-
r8 = _nt_CFWS
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s4 << r7
-
if r7
-
if has_terminal?("@", false, index)
-
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure("@")
-
r9 = nil
-
end
-
s4 << r9
-
if r9
-
r10 = _nt_domain
-
s4 << r10
-
end
-
end
-
end
-
if s4.last
-
r4 = instantiate_node(SyntaxNode,input, i4...index, s4)
-
r4.extend(ObsDomainList0)
-
else
-
@index = i4
-
r4 = nil
-
end
-
if r4
-
s3 << r4
-
else
-
break
-
end
-
end
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
s0 << r3
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsDomainList1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_domain_list][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsLocalPart0
-
2
def word
-
elements[1]
-
end
-
end
-
-
2
module ObsLocalPart1
-
2
def word
-
elements[0]
-
end
-
-
end
-
-
2
def _nt_obs_local_part
-
start_index = index
-
if node_cache[:obs_local_part].has_key?(index)
-
cached = node_cache[:obs_local_part][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_word
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
if has_terminal?(".", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r4 = nil
-
end
-
s3 << r4
-
if r4
-
r5 = _nt_word
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ObsLocalPart0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsLocalPart1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_local_part][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsDomain0
-
2
def atom
-
elements[1]
-
end
-
end
-
-
2
module ObsDomain1
-
2
def atom
-
elements[0]
-
end
-
-
end
-
-
2
def _nt_obs_domain
-
start_index = index
-
if node_cache[:obs_domain].has_key?(index)
-
cached = node_cache[:obs_domain][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_atom
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
i3, s3 = index, []
-
if has_terminal?(".", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(".")
-
r4 = nil
-
end
-
s3 << r4
-
if r4
-
r5 = _nt_atom
-
s3 << r5
-
end
-
if s3.last
-
r3 = instantiate_node(SyntaxNode,input, i3...index, s3)
-
r3.extend(ObsDomain0)
-
else
-
@index = i3
-
r3 = nil
-
end
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsDomain1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_domain][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsMboxList0
-
end
-
-
2
module ObsMboxList1
-
end
-
-
2
def _nt_obs_mbox_list
-
start_index = index
-
if node_cache[:obs_mbox_list].has_key?(index)
-
cached = node_cache[:obs_mbox_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
s1, i1 = [], index
-
loop do
-
i2, s2 = index, []
-
r4 = _nt_mailbox
-
if r4
-
r3 = r4
-
else
-
r3 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r3
-
if r3
-
r6 = _nt_CFWS
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r5
-
if r5
-
if has_terminal?(",", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r7 = nil
-
end
-
s2 << r7
-
if r7
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r8
-
end
-
end
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(ObsMboxList0)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
s1 << r2
-
else
-
break
-
end
-
end
-
if s1.empty?
-
@index = i1
-
r1 = nil
-
else
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
end
-
s0 << r1
-
if r1
-
r11 = _nt_mailbox
-
if r11
-
r10 = r11
-
else
-
r10 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r10
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsMboxList1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_mbox_list][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsAddrList0
-
end
-
-
2
module ObsAddrList1
-
end
-
-
2
def _nt_obs_addr_list
-
start_index = index
-
if node_cache[:obs_addr_list].has_key?(index)
-
cached = node_cache[:obs_addr_list][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
s1, i1 = [], index
-
loop do
-
i2, s2 = index, []
-
r4 = _nt_address
-
if r4
-
r3 = r4
-
else
-
r3 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r3
-
if r3
-
r6 = _nt_CFWS
-
if r6
-
r5 = r6
-
else
-
r5 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r5
-
if r5
-
if has_terminal?(",", false, index)
-
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(",")
-
r7 = nil
-
end
-
s2 << r7
-
if r7
-
r9 = _nt_CFWS
-
if r9
-
r8 = r9
-
else
-
r8 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s2 << r8
-
end
-
end
-
end
-
if s2.last
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
r2.extend(ObsAddrList0)
-
else
-
@index = i2
-
r2 = nil
-
end
-
if r2
-
s1 << r2
-
else
-
break
-
end
-
end
-
if s1.empty?
-
@index = i1
-
r1 = nil
-
else
-
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
-
end
-
s0 << r1
-
if r1
-
r11 = _nt_address
-
if r11
-
r10 = r11
-
else
-
r10 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
s0 << r10
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsAddrList1)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_addr_list][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_obs_fields
-
start_index = index
-
if node_cache[:obs_fields].has_key?(index)
-
cached = node_cache[:obs_fields][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
s0, i0 = [], index
-
loop do
-
i1 = index
-
r2 = _nt_obs_return
-
if r2
-
r1 = r2
-
else
-
r3 = _nt_obs_received
-
if r3
-
r1 = r3
-
else
-
r4 = _nt_obs_orig_date
-
if r4
-
r1 = r4
-
else
-
r5 = _nt_obs_from
-
if r5
-
r1 = r5
-
else
-
r6 = _nt_obs_sender
-
if r6
-
r1 = r6
-
else
-
r7 = _nt_obs_reply_to
-
if r7
-
r1 = r7
-
else
-
r8 = _nt_obs_to
-
if r8
-
r1 = r8
-
else
-
r9 = _nt_obs_cc
-
if r9
-
r1 = r9
-
else
-
r10 = _nt_obs_bcc
-
if r10
-
r1 = r10
-
else
-
r11 = _nt_obs_message_id
-
if r11
-
r1 = r11
-
else
-
r12 = _nt_obs_in_reply_to
-
if r12
-
r1 = r12
-
else
-
r13 = _nt_obs_references
-
if r13
-
r1 = r13
-
else
-
r14 = _nt_obs_subject
-
if r14
-
r1 = r14
-
else
-
r15 = _nt_obs_comments
-
if r15
-
r1 = r15
-
else
-
r16 = _nt_obs_keywords
-
if r16
-
r1 = r16
-
else
-
r17 = _nt_obs_resent_date
-
if r17
-
r1 = r17
-
else
-
r18 = _nt_obs_resent_from
-
if r18
-
r1 = r18
-
else
-
r19 = _nt_obs_resent_send
-
if r19
-
r1 = r19
-
else
-
r20 = _nt_obs_resent_rply
-
if r20
-
r1 = r20
-
else
-
r21 = _nt_obs_resent_to
-
if r21
-
r1 = r21
-
else
-
r22 = _nt_obs_resent_cc
-
if r22
-
r1 = r22
-
else
-
r23 = _nt_obs_resent_bcc
-
if r23
-
r1 = r23
-
else
-
r24 = _nt_obs_resent_mid
-
if r24
-
r1 = r24
-
else
-
r25 = _nt_obs_optional
-
if r25
-
r1 = r25
-
else
-
@index = i1
-
r1 = nil
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
if r1
-
s0 << r1
-
else
-
break
-
end
-
end
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
-
node_cache[:obs_fields][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsOrigDate0
-
2
def date_time
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_orig_date
-
start_index = index
-
if node_cache[:obs_orig_date].has_key?(index)
-
cached = node_cache[:obs_orig_date][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Date", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 4))
-
@index += 4
-
else
-
terminal_parse_failure("Date")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_date_time
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsOrigDate0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_orig_date][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsFrom0
-
2
def mailbox_list
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_from
-
start_index = index
-
if node_cache[:obs_from].has_key?(index)
-
cached = node_cache[:obs_from][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("From", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 4))
-
@index += 4
-
else
-
terminal_parse_failure("From")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_mailbox_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsFrom0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_from][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsSender0
-
2
def mailbox
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_sender
-
start_index = index
-
if node_cache[:obs_sender].has_key?(index)
-
cached = node_cache[:obs_sender][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Sender", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 6))
-
@index += 6
-
else
-
terminal_parse_failure("Sender")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_mailbox
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsSender0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_sender][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsReplyTo0
-
2
def mailbox_list
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_reply_to
-
start_index = index
-
if node_cache[:obs_reply_to].has_key?(index)
-
cached = node_cache[:obs_reply_to][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Reply-To", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 8))
-
@index += 8
-
else
-
terminal_parse_failure("Reply-To")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_mailbox_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsReplyTo0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_reply_to][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsTo0
-
2
def address_list
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_to
-
start_index = index
-
if node_cache[:obs_to].has_key?(index)
-
cached = node_cache[:obs_to][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("To", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 2))
-
@index += 2
-
else
-
terminal_parse_failure("To")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_address_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsTo0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_to][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsCc0
-
2
def address_list
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_cc
-
start_index = index
-
if node_cache[:obs_cc].has_key?(index)
-
cached = node_cache[:obs_cc][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Cc", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 2))
-
@index += 2
-
else
-
terminal_parse_failure("Cc")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_address_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsCc0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_cc][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsBcc0
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_bcc
-
start_index = index
-
if node_cache[:obs_bcc].has_key?(index)
-
cached = node_cache[:obs_bcc][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Bcc", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 3))
-
@index += 3
-
else
-
terminal_parse_failure("Bcc")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
i5 = index
-
r6 = _nt_address_list
-
if r6
-
r5 = r6
-
else
-
r8 = _nt_CFWS
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
if r7
-
r5 = r7
-
else
-
@index = i5
-
r5 = nil
-
end
-
end
-
s0 << r5
-
if r5
-
r9 = _nt_CRLF
-
s0 << r9
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsBcc0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_bcc][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsMessageId0
-
2
def msg_id
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_message_id
-
start_index = index
-
if node_cache[:obs_message_id].has_key?(index)
-
cached = node_cache[:obs_message_id][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Message-ID", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 10))
-
@index += 10
-
else
-
terminal_parse_failure("Message-ID")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_msg_id
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsMessageId0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_message_id][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsInReplyTo0
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_in_reply_to
-
start_index = index
-
if node_cache[:obs_in_reply_to].has_key?(index)
-
cached = node_cache[:obs_in_reply_to][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("In-Reply-To", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 11))
-
@index += 11
-
else
-
terminal_parse_failure("In-Reply-To")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
s5, i5 = [], index
-
loop do
-
i6 = index
-
r7 = _nt_phrase
-
if r7
-
r6 = r7
-
else
-
r8 = _nt_msg_id
-
if r8
-
r6 = r8
-
else
-
@index = i6
-
r6 = nil
-
end
-
end
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
s0 << r5
-
if r5
-
r9 = _nt_CRLF
-
s0 << r9
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsInReplyTo0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_in_reply_to][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsReferences0
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_references
-
start_index = index
-
if node_cache[:obs_references].has_key?(index)
-
cached = node_cache[:obs_references][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("References", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 10))
-
@index += 10
-
else
-
terminal_parse_failure("References")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
s5, i5 = [], index
-
loop do
-
i6 = index
-
r7 = _nt_phrase
-
if r7
-
r6 = r7
-
else
-
r8 = _nt_msg_id
-
if r8
-
r6 = r8
-
else
-
@index = i6
-
r6 = nil
-
end
-
end
-
if r6
-
s5 << r6
-
else
-
break
-
end
-
end
-
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
-
s0 << r5
-
if r5
-
r9 = _nt_CRLF
-
s0 << r9
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsReferences0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_references][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_obs_id_left
-
start_index = index
-
if node_cache[:obs_id_left].has_key?(index)
-
cached = node_cache[:obs_id_left][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_local_part
-
-
node_cache[:obs_id_left][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_obs_id_right
-
start_index = index
-
if node_cache[:obs_id_right].has_key?(index)
-
cached = node_cache[:obs_id_right][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_domain
-
-
node_cache[:obs_id_right][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsSubject0
-
2
def unstructured
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_subject
-
start_index = index
-
if node_cache[:obs_subject].has_key?(index)
-
cached = node_cache[:obs_subject][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Subject", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 7))
-
@index += 7
-
else
-
terminal_parse_failure("Subject")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_unstructured
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsSubject0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_subject][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsComments0
-
2
def unstructured
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_comments
-
start_index = index
-
if node_cache[:obs_comments].has_key?(index)
-
cached = node_cache[:obs_comments][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Comments", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 8))
-
@index += 8
-
else
-
terminal_parse_failure("Comments")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_unstructured
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsComments0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_comments][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsKeywords0
-
2
def obs_phrase_list
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_keywords
-
start_index = index
-
if node_cache[:obs_keywords].has_key?(index)
-
cached = node_cache[:obs_keywords][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Keywords", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 8))
-
@index += 8
-
else
-
terminal_parse_failure("Keywords")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_obs_phrase_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsKeywords0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_keywords][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsResentFrom0
-
2
def mailbox_list
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_resent_from
-
start_index = index
-
if node_cache[:obs_resent_from].has_key?(index)
-
cached = node_cache[:obs_resent_from][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-From", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 11))
-
@index += 11
-
else
-
terminal_parse_failure("Resent-From")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_mailbox_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentFrom0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_from][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsResentSend0
-
2
def mailbox
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_resent_send
-
start_index = index
-
if node_cache[:obs_resent_send].has_key?(index)
-
cached = node_cache[:obs_resent_send][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-Sender", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 13))
-
@index += 13
-
else
-
terminal_parse_failure("Resent-Sender")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_mailbox
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentSend0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_send][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsResentDate0
-
2
def date_time
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_resent_date
-
start_index = index
-
if node_cache[:obs_resent_date].has_key?(index)
-
cached = node_cache[:obs_resent_date][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-Date", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 11))
-
@index += 11
-
else
-
terminal_parse_failure("Resent-Date")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_date_time
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentDate0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_date][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsResentTo0
-
2
def address_list
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_resent_to
-
start_index = index
-
if node_cache[:obs_resent_to].has_key?(index)
-
cached = node_cache[:obs_resent_to][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-To", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 9))
-
@index += 9
-
else
-
terminal_parse_failure("Resent-To")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_address_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentTo0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_to][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsResentCc0
-
2
def address_list
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_resent_cc
-
start_index = index
-
if node_cache[:obs_resent_cc].has_key?(index)
-
cached = node_cache[:obs_resent_cc][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-Cc", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 9))
-
@index += 9
-
else
-
terminal_parse_failure("Resent-Cc")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_address_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentCc0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_cc][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsResentBcc0
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_resent_bcc
-
start_index = index
-
if node_cache[:obs_resent_bcc].has_key?(index)
-
cached = node_cache[:obs_resent_bcc][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-Bcc", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 10))
-
@index += 10
-
else
-
terminal_parse_failure("Resent-Bcc")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
i5 = index
-
r6 = _nt_address_list
-
if r6
-
r5 = r6
-
else
-
r8 = _nt_CFWS
-
if r8
-
r7 = r8
-
else
-
r7 = instantiate_node(SyntaxNode,input, index...index)
-
end
-
if r7
-
r5 = r7
-
else
-
@index = i5
-
r5 = nil
-
end
-
end
-
s0 << r5
-
if r5
-
r9 = _nt_CRLF
-
s0 << r9
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentBcc0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_bcc][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsResentMid0
-
2
def msg_id
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_resent_mid
-
start_index = index
-
if node_cache[:obs_resent_mid].has_key?(index)
-
cached = node_cache[:obs_resent_mid][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-Message-ID", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 17))
-
@index += 17
-
else
-
terminal_parse_failure("Resent-Message-ID")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_msg_id
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentMid0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_mid][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsResentRply0
-
2
def address_list
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_resent_rply
-
start_index = index
-
if node_cache[:obs_resent_rply].has_key?(index)
-
cached = node_cache[:obs_resent_rply][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Resent-Reply-To", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 15))
-
@index += 15
-
else
-
terminal_parse_failure("Resent-Reply-To")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_address_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsResentRply0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_resent_rply][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsReturn0
-
2
def path
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_return
-
start_index = index
-
if node_cache[:obs_return].has_key?(index)
-
cached = node_cache[:obs_return][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Return-Path", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 11))
-
@index += 11
-
else
-
terminal_parse_failure("Return-Path")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_path
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsReturn0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_return][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsReceived0
-
2
def name_val_list
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_received
-
start_index = index
-
if node_cache[:obs_received].has_key?(index)
-
cached = node_cache[:obs_received][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
if has_terminal?("Received", false, index)
-
r1 = instantiate_node(SyntaxNode,input, index...(index + 8))
-
@index += 8
-
else
-
terminal_parse_failure("Received")
-
r1 = nil
-
end
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_name_val_list
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsReceived0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_received][start_index] = r0
-
-
r0
-
end
-
-
2
def _nt_obs_path
-
start_index = index
-
if node_cache[:obs_path].has_key?(index)
-
cached = node_cache[:obs_path][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
r0 = _nt_obs_angle_addr
-
-
node_cache[:obs_path][start_index] = r0
-
-
r0
-
end
-
-
2
module ObsOptional0
-
2
def field_name
-
elements[0]
-
end
-
-
2
def unstructured
-
elements[3]
-
end
-
-
2
def CRLF
-
elements[4]
-
end
-
end
-
-
2
def _nt_obs_optional
-
start_index = index
-
if node_cache[:obs_optional].has_key?(index)
-
cached = node_cache[:obs_optional][index]
-
if cached
-
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
-
@index = cached.interval.end
-
end
-
return cached
-
end
-
-
i0, s0 = index, []
-
r1 = _nt_field_name
-
s0 << r1
-
if r1
-
s2, i2 = [], index
-
loop do
-
r3 = _nt_WSP
-
if r3
-
s2 << r3
-
else
-
break
-
end
-
end
-
r2 = instantiate_node(SyntaxNode,input, i2...index, s2)
-
s0 << r2
-
if r2
-
if has_terminal?(":", false, index)
-
r4 = instantiate_node(SyntaxNode,input, index...(index + 1))
-
@index += 1
-
else
-
terminal_parse_failure(":")
-
r4 = nil
-
end
-
s0 << r4
-
if r4
-
r5 = _nt_unstructured
-
s0 << r5
-
if r5
-
r6 = _nt_CRLF
-
s0 << r6
-
end
-
end
-
end
-
end
-
if s0.last
-
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
-
r0.extend(ObsOptional0)
-
else
-
@index = i0
-
r0 = nil
-
end
-
-
node_cache[:obs_optional][start_index] = r0
-
-
r0
-
end
-
-
end
-
-
2
class RFC2822ObsoleteParser < Treetop::Runtime::CompiledParser
-
2
include RFC2822Obsolete
-
end
-
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
class Part < Message
-
-
# Creates a new empty Content-ID field and inserts it in the correct order
-
# into the Header. The ContentIdField object will automatically generate
-
# a unique content ID if you try and encode it or output it to_s without
-
# specifying a content id.
-
#
-
# It will preserve the content ID you specify if you do.
-
2
def add_content_id(content_id_val = '')
-
header['content-id'] = content_id_val
-
end
-
-
# Returns true if the part has a content ID field, the field may or may
-
# not have a value, but the field exists or not.
-
2
def has_content_id?
-
header.has_content_id?
-
end
-
-
2
def inline_content_id
-
# TODO: Deprecated in 2.2.2 - Remove in 2.3
-
STDERR.puts("Part#inline_content_id is deprecated, please call Part#cid instead")
-
cid
-
end
-
-
2
def cid
-
add_content_id unless has_content_id?
-
uri_escape(unbracket(content_id))
-
end
-
-
2
def url
-
"cid:#{cid}"
-
end
-
-
2
def inline?
-
header[:content_disposition].disposition_type == 'inline' if header[:content_disposition]
-
end
-
-
2
def add_required_fields
-
super
-
add_content_id if !has_content_id? && inline?
-
end
-
-
2
def add_required_message_fields
-
# Override so we don't add Date, MIME-Version, or Message-ID.
-
end
-
-
2
def delivery_status_report_part?
-
(main_type =~ /message/i && sub_type =~ /delivery-status/i) && body =~ /Status:/
-
end
-
-
2
def delivery_status_data
-
delivery_status_report_part? ? parse_delivery_status_report : {}
-
end
-
-
2
def bounced?
-
if action.is_a?(Array)
-
!!(action.first =~ /failed/i)
-
else
-
!!(action =~ /failed/i)
-
end
-
end
-
-
-
# Either returns the action if the message has just a single report, or an
-
# array of all the actions, one for each report
-
2
def action
-
get_return_values('action')
-
end
-
-
2
def final_recipient
-
get_return_values('final-recipient')
-
end
-
-
2
def error_status
-
get_return_values('status')
-
end
-
-
2
def diagnostic_code
-
get_return_values('diagnostic-code')
-
end
-
-
2
def remote_mta
-
get_return_values('remote-mta')
-
end
-
-
2
def retryable?
-
!(error_status =~ /^5/)
-
end
-
-
2
private
-
-
2
def get_return_values(key)
-
if delivery_status_data[key].is_a?(Array)
-
delivery_status_data[key].map { |a| a.value }
-
else
-
delivery_status_data[key].value
-
end
-
end
-
-
# A part may not have a header.... so, just init a body if no header
-
2
def parse_message
-
header_part, body_part = raw_source.split(/#{CRLF}#{WSP}*#{CRLF}/m, 2)
-
if header_part =~ HEADER_LINE
-
self.header = header_part
-
self.body = body_part
-
else
-
self.header = "Content-Type: text/plain\r\n"
-
self.body = raw_source
-
end
-
end
-
-
2
def parse_delivery_status_report
-
@delivery_status_data ||= Header.new(body.to_s.gsub("\r\n\r\n", "\r\n"))
-
end
-
-
end
-
-
end
-
2
module Mail
-
2
class PartsList < Array
-
-
2
def attachments
-
8
Mail::AttachmentsList.new(self)
-
end
-
-
2
def collect
-
8
if block_given?
-
8
ary = PartsList.new
-
8
each { |o| ary << yield(o) }
-
8
ary
-
else
-
to_a
-
end
-
end
-
-
2
undef :map
-
2
alias_method :map, :collect
-
-
2
def map!
-
raise NoMethodError, "#map! is not defined, please call #collect and create a new PartsList"
-
end
-
-
2
def collect!
-
raise NoMethodError, "#collect! is not defined, please call #collect and create a new PartsList"
-
end
-
-
2
def sort
-
8
self.class.new(super)
-
end
-
-
2
def sort!(order)
-
8
sorted = self.sort do |a, b|
-
# OK, 10000 is arbitrary... if anyone actually wants to explicitly sort 10000 parts of a
-
# single email message... please show me a use case and I'll put more work into this method,
-
# in the meantime, it works :)
-
get_order_value(a, order) <=> get_order_value(b, order)
-
end
-
8
self.clear
-
8
sorted.each { |p| self << p }
-
end
-
-
2
private
-
-
2
def get_order_value(part, order)
-
if part.respond_to?(:content_type)
-
order.index(part[:content_type].string.downcase) || 10000
-
else
-
10000
-
end
-
end
-
-
end
-
end
-
# encoding: us-ascii
-
2
module Mail
-
2
module Patterns
-
2
white_space = %Q|\x9\x20|
-
2
text = %Q|\x1-\x8\xB\xC\xE-\x7f|
-
2
field_name = %Q|\x21-\x39\x3b-\x7e|
-
2
qp_safe = %Q|\x20-\x3c\x3e-\x7e|
-
-
2
aspecial = %Q|()<>[]:;@\\,."| # RFC5322
-
2
tspecial = %Q|()<>@,;:\\"/[]?=| # RFC2045
-
2
sp = %Q| |
-
2
control = %Q|\x00-\x1f\x7f-\xff|
-
-
2
if control.respond_to?(:force_encoding)
-
2
control = control.force_encoding(Encoding::BINARY)
-
end
-
-
2
CRLF = /\r\n/
-
2
WSP = /[#{white_space}]/
-
2
FWS = /#{CRLF}#{WSP}*/
-
2
TEXT = /[#{text}]/ # + obs-text
-
2
FIELD_NAME = /[#{field_name}]+/
-
2
FIELD_BODY = /.+/
-
2
FIELD_LINE = /^[#{field_name}]+:\s*.+$/
-
2
FIELD_SPLIT = /^(#{FIELD_NAME})\s*:\s*(#{FIELD_BODY})?$/
-
2
HEADER_LINE = /^([#{field_name}]+:\s*.+)$/
-
-
2
QP_UNSAFE = /[^#{qp_safe}]/
-
2
QP_SAFE = /[#{qp_safe}]/
-
2
CONTROL_CHAR = /[#{control}]/n
-
2
ATOM_UNSAFE = /[#{Regexp.quote aspecial}#{control}#{sp}]/n
-
2
PHRASE_UNSAFE = /[#{Regexp.quote aspecial}#{control}]/n
-
2
TOKEN_UNSAFE = /[#{Regexp.quote tspecial}#{control}#{sp}]/n
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
module Utilities
-
2
include Patterns
-
-
# Returns true if the string supplied is free from characters not allowed as an ATOM
-
2
def atom_safe?( str )
-
not ATOM_UNSAFE === str
-
end
-
-
# If the string supplied has ATOM unsafe characters in it, will return the string quoted
-
# in double quotes, otherwise returns the string unmodified
-
2
def quote_atom( str )
-
atom_safe?( str ) ? str : dquote(str)
-
end
-
-
# If the string supplied has PHRASE unsafe characters in it, will return the string quoted
-
# in double quotes, otherwise returns the string unmodified
-
2
def quote_phrase( str )
-
if RUBY_VERSION >= '1.9'
-
original_encoding = str.encoding
-
str.force_encoding('ASCII-8BIT')
-
if (PHRASE_UNSAFE === str)
-
dquote(str).force_encoding(original_encoding)
-
else
-
str.force_encoding(original_encoding)
-
end
-
else
-
(PHRASE_UNSAFE === str) ? dquote(str) : str
-
end
-
end
-
-
# Returns true if the string supplied is free from characters not allowed as a TOKEN
-
2
def token_safe?( str )
-
8
not TOKEN_UNSAFE === str
-
end
-
-
# If the string supplied has TOKEN unsafe characters in it, will return the string quoted
-
# in double quotes, otherwise returns the string unmodified
-
2
def quote_token( str )
-
8
token_safe?( str ) ? str : dquote(str)
-
end
-
-
# Wraps supplied string in double quotes and applies \-escaping as necessary,
-
# unless it is already wrapped.
-
#
-
# Example:
-
#
-
# string = 'This is a string'
-
# dquote(string) #=> '"This is a string"'
-
#
-
# string = 'This is "a string"'
-
# dquote(string #=> '"This is \"a string\"'
-
2
def dquote( str )
-
'"' + unquote(str).gsub(/[\\"]/n) {|s| '\\' + s } + '"'
-
end
-
-
# Unwraps supplied string from inside double quotes and
-
# removes any \-escaping.
-
#
-
# Example:
-
#
-
# string = '"This is a string"'
-
# unquote(string) #=> 'This is a string'
-
#
-
# string = '"This is \"a string\""'
-
# unqoute(string) #=> 'This is "a string"'
-
2
def unquote( str )
-
if str =~ /^"(.*?)"$/
-
$1.gsub(/\\(.)/, '\1')
-
else
-
str
-
end
-
end
-
-
# Wraps a string in parenthesis and escapes any that are in the string itself.
-
#
-
# Example:
-
#
-
# paren( 'This is a string' ) #=> '(This is a string)'
-
2
def paren( str )
-
RubyVer.paren( str )
-
end
-
-
# Unwraps a string from being wrapped in parenthesis
-
#
-
# Example:
-
#
-
# str = '(This is a string)'
-
# unparen( str ) #=> 'This is a string'
-
2
def unparen( str )
-
match = str.match(/^\((.*?)\)$/)
-
match ? match[1] : str
-
end
-
-
# Wraps a string in angle brackets and escapes any that are in the string itself
-
#
-
# Example:
-
#
-
# bracket( 'This is a string' ) #=> '<This is a string>'
-
2
def bracket( str )
-
RubyVer.bracket( str )
-
end
-
-
# Unwraps a string from being wrapped in parenthesis
-
#
-
# Example:
-
#
-
# str = '<This is a string>'
-
# unbracket( str ) #=> 'This is a string'
-
2
def unbracket( str )
-
match = str.match(/^\<(.*?)\>$/)
-
match ? match[1] : str
-
end
-
-
# Escape parenthesies in a string
-
#
-
# Example:
-
#
-
# str = 'This is (a) string'
-
# escape_paren( str ) #=> 'This is \(a\) string'
-
2
def escape_paren( str )
-
RubyVer.escape_paren( str )
-
end
-
-
2
def uri_escape( str )
-
uri_parser.escape(str)
-
end
-
-
2
def uri_unescape( str )
-
uri_parser.unescape(str)
-
end
-
-
2
def uri_parser
-
@uri_parser ||= URI.const_defined?(:Parser) ? URI::Parser.new : URI
-
end
-
-
# Matches two objects with their to_s values case insensitively
-
#
-
# Example:
-
#
-
# obj2 = "This_is_An_object"
-
# obj1 = :this_IS_an_object
-
# match_to_s( obj1, obj2 ) #=> true
-
2
def match_to_s( obj1, obj2 )
-
112
obj1.to_s.casecmp(obj2.to_s) == 0
-
end
-
-
# Capitalizes a string that is joined by hyphens correctly.
-
#
-
# Example:
-
#
-
# string = 'resent-from-field'
-
# capitalize_field( string ) #=> 'Resent-From-Field'
-
2
def capitalize_field( str )
-
str.to_s.split("-").map { |v| v.capitalize }.join("-")
-
end
-
-
# Takes an underscored word and turns it into a class name
-
#
-
# Example:
-
#
-
# constantize("hello") #=> "Hello"
-
# constantize("hello-there") #=> "HelloThere"
-
# constantize("hello-there-mate") #=> "HelloThereMate"
-
2
def constantize( str )
-
str.to_s.split(/[-_]/).map { |v| v.capitalize }.to_s
-
end
-
-
# Swaps out all underscores (_) for hyphens (-) good for stringing from symbols
-
# a field name.
-
#
-
# Example:
-
#
-
# string = :resent_from_field
-
# dasherize ( string ) #=> 'resent_from_field'
-
2
def dasherize( str )
-
344
str.to_s.gsub('_', '-')
-
end
-
-
# Swaps out all hyphens (-) for underscores (_) good for stringing to symbols
-
# a field name.
-
#
-
# Example:
-
#
-
# string = :resent_from_field
-
# underscoreize ( string ) #=> 'resent_from_field'
-
2
def underscoreize( str )
-
str.to_s.downcase.gsub('-', '_')
-
end
-
-
2
if RUBY_VERSION <= '1.8.6'
-
-
def map_lines( str, &block )
-
results = []
-
str.each_line do |line|
-
results << yield(line)
-
end
-
results
-
end
-
-
def map_with_index( enum, &block )
-
results = []
-
enum.each_with_index do |token, i|
-
results[i] = yield(token, i)
-
end
-
results
-
end
-
-
else
-
-
2
def map_lines( str, &block )
-
str.each_line.map(&block)
-
end
-
-
2
def map_with_index( enum, &block )
-
enum.each_with_index.map(&block)
-
end
-
-
end
-
-
end
-
end
-
# encoding: utf-8
-
2
module Mail
-
2
module VERSION
-
-
2
version = {}
-
2
File.read(File.join(File.dirname(__FILE__), '../', 'VERSION')).each_line do |line|
-
8
type, value = line.chomp.split(":")
-
8
next if type =~ /^\s+$/ || value =~ /^\s+$/
-
8
version[type] = value
-
end
-
-
2
MAJOR = version['major']
-
2
MINOR = version['minor']
-
2
PATCH = version['patch']
-
2
BUILD = version['build']
-
-
2
STRING = [MAJOR, MINOR, PATCH, BUILD].compact.join('.')
-
-
2
def self.version
-
STRING
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
2
module Mail
-
2
class Ruby19
-
-
# Escapes any parenthesis in a string that are unescaped this uses
-
# a Ruby 1.9.1 regexp feature of negative look behind
-
2
def Ruby19.escape_paren( str )
-
re = /(?<!\\)([\(\)])/ # Only match unescaped parens
-
str.gsub(re) { |s| '\\' + s }
-
end
-
-
2
def Ruby19.paren( str )
-
str = $1 if str =~ /^\((.*)?\)$/
-
str = escape_paren( str )
-
'(' + str + ')'
-
end
-
-
2
def Ruby19.escape_bracket( str )
-
re = /(?<!\\)([\<\>])/ # Only match unescaped brackets
-
str.gsub(re) { |s| '\\' + s }
-
end
-
-
2
def Ruby19.bracket( str )
-
str = $1 if str =~ /^\<(.*)?\>$/
-
str = escape_bracket( str )
-
'<' + str + '>'
-
end
-
-
2
def Ruby19.decode_base64(str)
-
str.unpack( 'm' ).first
-
end
-
-
2
def Ruby19.encode_base64(str)
-
[str].pack( 'm' )
-
end
-
-
2
def Ruby19.has_constant?(klass, string)
-
klass.const_defined?( string, false )
-
end
-
-
2
def Ruby19.get_constant(klass, string)
-
klass.const_get( string )
-
end
-
-
2
def Ruby19.b_value_encode(str, encoding = nil)
-
encoding = str.encoding.to_s
-
[Ruby19.encode_base64(str), encoding]
-
end
-
-
2
def Ruby19.b_value_decode(str)
-
match = str.match(/\=\?(.+)?\?[Bb]\?(.+)?\?\=/m)
-
if match
-
charset = match[1]
-
str = Ruby19.decode_base64(match[2])
-
str.force_encoding(pick_encoding(charset))
-
end
-
decoded = str.encode("utf-8", :invalid => :replace, :replace => "")
-
decoded.valid_encoding? ? decoded : decoded.encode("utf-16le", :invalid => :replace, :replace => "").encode("utf-8")
-
end
-
-
2
def Ruby19.q_value_encode(str, encoding = nil)
-
encoding = str.encoding.to_s
-
[Encodings::QuotedPrintable.encode(str), encoding]
-
end
-
-
2
def Ruby19.q_value_decode(str)
-
match = str.match(/\=\?(.+)?\?[Qq]\?(.+)?\?\=/m)
-
if match
-
charset = match[1]
-
string = match[2].gsub(/_/, '=20')
-
# Remove trailing = if it exists in a Q encoding
-
string = string.sub(/\=$/, '')
-
str = Encodings::QuotedPrintable.decode(string)
-
str.force_encoding(pick_encoding(charset))
-
end
-
decoded = str.encode("utf-8", :invalid => :replace, :replace => "")
-
decoded.valid_encoding? ? decoded : decoded.encode("utf-16le", :invalid => :replace, :replace => "").encode("utf-8")
-
rescue Encoding::UndefinedConversionError
-
str.dup.force_encoding("utf-8")
-
end
-
-
2
def Ruby19.param_decode(str, encoding)
-
string = uri_parser.unescape(str)
-
string.force_encoding(encoding) if encoding
-
string
-
end
-
-
2
def Ruby19.param_encode(str)
-
encoding = str.encoding.to_s.downcase
-
language = Configuration.instance.param_encode_language
-
"#{encoding}'#{language}'#{uri_parser.escape(str)}"
-
end
-
-
2
def Ruby19.uri_parser
-
@uri_parser ||= URI::Parser.new
-
end
-
-
# Pick a Ruby encoding corresponding to the message charset. Most
-
# charsets have a Ruby encoding, but some need manual aliasing here.
-
#
-
# TODO: add this as a test somewhere:
-
# Encoding.list.map { |e| [e.to_s.upcase == pick_encoding(e.to_s.downcase.gsub("-", "")), e.to_s] }.select {|a,b| !b}
-
# Encoding.list.map { |e| [e.to_s == pick_encoding(e.to_s), e.to_s] }.select {|a,b| !b}
-
2
def Ruby19.pick_encoding(charset)
-
case charset
-
-
# ISO-8859-15, ISO-2022-JP and alike
-
when /iso-?(\d{4})-?(\w{1,2})/i
-
"ISO-#{$1}-#{$2}"
-
-
# "ISO-2022-JP-KDDI" and alike
-
when /iso-?(\d{4})-?(\w{1,2})-?(\w*)/i
-
"ISO-#{$1}-#{$2}-#{$3}"
-
-
# UTF-8, UTF-32BE and alike
-
when /utf-?(\d{1,2})?(\w{1,2})/i
-
"UTF-#{$1}#{$2}".gsub(/\A(UTF-(?:16|32))\z/, '\\1BE')
-
-
# Windows-1252 and alike
-
when /Windows-?(.*)/i
-
"Windows-#{$1}"
-
-
when /^8bit$/
-
Encoding::ASCII_8BIT
-
-
# Microsoft-specific alias for CP949 (Korean)
-
when 'ks_c_5601-1987'
-
Encoding::CP949
-
-
# Wrongly written Shift_JIS (Japanese)
-
when 'shift-jis'
-
Encoding::Shift_JIS
-
-
# GB2312 (Chinese charset) is a subset of GB18030 (its replacement)
-
when /gb2312/i
-
Encoding::GB18030
-
-
else
-
charset
-
end
-
end
-
end
-
end
-
# -*- ruby encoding: utf-8 -*-
-
-
# The namespace for MIME applications, tools, and libraries.
-
2
module MIME
-
# Reflects a MIME Content-Type which is in invalid format (e.g., it isn't
-
# in the form of type/subtype).
-
2
class InvalidContentType < RuntimeError; end
-
-
# The definition of one MIME content-type.
-
#
-
# == Usage
-
# require 'mime/types'
-
#
-
# plaintext = MIME::Types['text/plain'].first
-
# # returns [text/plain, text/plain]
-
# text = plaintext.first
-
# print text.media_type # => 'text'
-
# print text.sub_type # => 'plain'
-
#
-
# puts text.extensions.join(" ") # => 'asc txt c cc h hh cpp'
-
#
-
# puts text.encoding # => 8bit
-
# puts text.binary? # => false
-
# puts text.ascii? # => true
-
# puts text == 'text/plain' # => true
-
# puts MIME::Type.simplified('x-appl/x-zip') # => 'appl/zip'
-
#
-
# puts MIME::Types.any? { |type|
-
# type.content_type == 'text/plain'
-
# } # => true
-
# puts MIME::Types.all?(&:registered?)
-
# # => false
-
#
-
2
class Type
-
# The released version of Ruby MIME::Types
-
2
VERSION = '1.25.1'
-
-
2
include Comparable
-
-
2
MEDIA_TYPE_RE = %r{([-\w.+]+)/([-\w.+]*)}o
-
2
UNREG_RE = %r{[Xx]-}o
-
2
ENCODING_RE = %r{(?:base64|7bit|8bit|quoted\-printable)}o
-
2
PLATFORM_RE = %r|#{RUBY_PLATFORM}|o
-
-
2
SIGNATURES = %w(application/pgp-keys application/pgp
-
application/pgp-signature application/pkcs10
-
application/pkcs7-mime application/pkcs7-signature
-
text/vcard)
-
-
2
IANA_URL = "http://www.iana.org/assignments/media-types/%s/%s"
-
2
RFC_URL = "http://rfc-editor.org/rfc/rfc%s.txt"
-
2
DRAFT_URL = "http://datatracker.ietf.org/public/idindex.cgi?command=id_details&filename=%s"
-
2
LTSW_URL = "http://www.ltsw.se/knbase/internet/%s.htp"
-
2
CONTACT_URL = "http://www.iana.org/assignments/contact-people.htm#%s"
-
-
# Returns +true+ if the simplified type matches the current
-
2
def like?(other)
-
if other.respond_to?(:simplified)
-
@simplified == other.simplified
-
else
-
@simplified == Type.simplified(other)
-
end
-
end
-
-
# Compares the MIME::Type against the exact content type or the
-
# simplified type (the simplified type will be used if comparing against
-
# something that can be treated as a String with #to_s). In comparisons,
-
# this is done against the lowercase version of the MIME::Type.
-
2
def <=>(other)
-
148
if other.respond_to?(:content_type)
-
148
@content_type.downcase <=> other.content_type.downcase
-
elsif other.respond_to?(:to_s)
-
@simplified <=> Type.simplified(other.to_s)
-
else
-
@content_type.downcase <=> other.downcase
-
end
-
end
-
-
# Compares the MIME::Type based on how reliable it is before doing a
-
# normal <=> comparison. Used by MIME::Types#[] to sort types. The
-
# comparisons involved are:
-
#
-
# 1. self.simplified <=> other.simplified (ensures that we
-
# don't try to compare different types)
-
# 2. IANA-registered definitions < other definitions.
-
# 3. Generic definitions < platform definitions.
-
# 3. Complete definitions < incomplete definitions.
-
# 4. Current definitions < obsolete definitions.
-
# 5. Obselete with use-instead references < obsolete without.
-
# 6. Obsolete use-instead definitions are compared.
-
2
def priority_compare(other)
-
pc = simplified <=> other.simplified
-
-
if pc.zero?
-
pc = if registered? != other.registered?
-
registered? ? -1 : 1 # registered < unregistered
-
elsif platform? != other.platform?
-
platform? ? 1 : -1 # generic < platform
-
elsif complete? != other.complete?
-
complete? ? -1 : 1 # complete < incomplete
-
elsif obsolete? != other.obsolete?
-
obsolete? ? 1 : -1 # current < obsolete
-
else
-
0
-
end
-
-
if pc.zero? and obsolete? and (use_instead != other.use_instead)
-
pc = if use_instead.nil?
-
-1
-
elsif other.use_instead.nil?
-
1
-
else
-
use_instead <=> other.use_instead
-
end
-
end
-
end
-
-
pc
-
end
-
-
# Returns +true+ if the other object is a MIME::Type and the content
-
# types match.
-
2
def eql?(other)
-
other.kind_of?(MIME::Type) and self == other
-
end
-
-
# Returns the whole MIME content-type string.
-
#
-
# text/plain => text/plain
-
# x-chemical/x-pdb => x-chemical/x-pdb
-
2
attr_reader :content_type
-
# Returns the media type of the simplified MIME type.
-
#
-
# text/plain => text
-
# x-chemical/x-pdb => chemical
-
2
attr_reader :media_type
-
# Returns the media type of the unmodified MIME type.
-
#
-
# text/plain => text
-
# x-chemical/x-pdb => x-chemical
-
2
attr_reader :raw_media_type
-
# Returns the sub-type of the simplified MIME type.
-
#
-
# text/plain => plain
-
# x-chemical/x-pdb => pdb
-
2
attr_reader :sub_type
-
# Returns the media type of the unmodified MIME type.
-
#
-
# text/plain => plain
-
# x-chemical/x-pdb => x-pdb
-
2
attr_reader :raw_sub_type
-
# The MIME types main- and sub-label can both start with <tt>x-</tt>,
-
# which indicates that it is a non-registered name. Of course, after
-
# registration this flag can disappear, adds to the confusing
-
# proliferation of MIME types. The simplified string has the <tt>x-</tt>
-
# removed and are translated to lowercase.
-
#
-
# text/plain => text/plain
-
# x-chemical/x-pdb => chemical/pdb
-
2
attr_reader :simplified
-
# The list of extensions which are known to be used for this MIME::Type.
-
# Non-array values will be coerced into an array with #to_a. Array
-
# values will be flattened and +nil+ values removed.
-
2
attr_accessor :extensions
-
2
remove_method :extensions= ;
-
2
def extensions=(ext) #:nodoc:
-
6572
@extensions = [ext].flatten.compact
-
end
-
-
# The encoding (7bit, 8bit, quoted-printable, or base64) required to
-
# transport the data of this content type safely across a network, which
-
# roughly corresponds to Content-Transfer-Encoding. A value of +nil+ or
-
# <tt>:default</tt> will reset the #encoding to the #default_encoding
-
# for the MIME::Type. Raises ArgumentError if the encoding provided is
-
# invalid.
-
#
-
# If the encoding is not provided on construction, this will be either
-
# 'quoted-printable' (for text/* media types) and 'base64' for eveything
-
# else.
-
2
attr_accessor :encoding
-
2
remove_method :encoding= ;
-
2
def encoding=(enc) #:nodoc:
-
6572
if enc.nil? or enc == :default
-
6258
@encoding = self.default_encoding
-
314
elsif enc =~ ENCODING_RE
-
314
@encoding = enc
-
else
-
raise ArgumentError, "The encoding must be nil, :default, base64, 7bit, 8bit, or quoted-printable."
-
end
-
end
-
-
# The regexp for the operating system that this MIME::Type is specific
-
# to.
-
2
attr_accessor :system
-
2
remove_method :system= ;
-
2
def system=(os) #:nodoc:
-
6572
if os.nil? or os.kind_of?(Regexp)
-
6564
@system = os
-
else
-
8
@system = %r|#{os}|
-
end
-
end
-
# Returns the default encoding for the MIME::Type based on the media
-
# type.
-
2
attr_reader :default_encoding
-
2
remove_method :default_encoding
-
2
def default_encoding
-
6258
(@media_type == 'text') ? 'quoted-printable' : 'base64'
-
end
-
-
# Returns the media type or types that should be used instead of this
-
# media type, if it is obsolete. If there is no replacement media type,
-
# or it is not obsolete, +nil+ will be returned.
-
2
attr_reader :use_instead
-
2
remove_method :use_instead
-
2
def use_instead
-
return nil unless @obsolete
-
@use_instead
-
end
-
-
# Returns +true+ if the media type is obsolete.
-
2
def obsolete?
-
@obsolete ? true : false
-
end
-
# Sets the obsolescence indicator for this media type.
-
2
attr_writer :obsolete
-
-
# The documentation for this MIME::Type. Documentation about media
-
# types will be found on a media type definition as a comment.
-
# Documentation will be found through #docs.
-
2
attr_accessor :docs
-
2
remove_method :docs= ;
-
2
def docs=(d)
-
6572
if d
-
90
a = d.scan(%r{use-instead:#{MEDIA_TYPE_RE}})
-
-
90
if a.empty?
-
4
@use_instead = nil
-
else
-
172
@use_instead = a.map { |el| "#{el[0]}/#{el[1]}" }
-
end
-
end
-
6572
@docs = d
-
end
-
-
# The encoded URL list for this MIME::Type. See #urls for more
-
# information.
-
2
attr_accessor :url
-
# The decoded URL list for this MIME::Type.
-
# The special URL value IANA will be translated into:
-
# http://www.iana.org/assignments/media-types/<mediatype>/<subtype>
-
#
-
# The special URL value RFC### will be translated into:
-
# http://www.rfc-editor.org/rfc/rfc###.txt
-
#
-
# The special URL value DRAFT:name will be translated into:
-
# https://datatracker.ietf.org/public/idindex.cgi?
-
# command=id_detail&filename=<name>
-
#
-
# The special URL value LTSW will be translated into:
-
# http://www.ltsw.se/knbase/internet/<mediatype>.htp
-
#
-
# The special URL value [token] will be translated into:
-
# http://www.iana.org/assignments/contact-people.htm#<token>
-
#
-
# These values will be accessible through #urls, which always returns an
-
# array.
-
2
def urls
-
@url.map do |el|
-
case el
-
when %r{^IANA$}
-
IANA_URL % [ @media_type, @sub_type ]
-
when %r{^RFC(\d+)$}
-
RFC_URL % $1
-
when %r{^DRAFT:(.+)$}
-
DRAFT_URL % $1
-
when %r{^LTSW$}
-
LTSW_URL % @media_type
-
when %r{^\{([^=]+)=([^\}]+)\}}
-
[$1, $2]
-
when %r{^\[([^=]+)=([^\]]+)\]}
-
[$1, CONTACT_URL % $2]
-
when %r{^\[([^\]]+)\]}
-
CONTACT_URL % $1
-
else
-
el
-
end
-
end
-
end
-
-
2
class << self
-
# The MIME types main- and sub-label can both start with <tt>x-</tt>,
-
# which indicates that it is a non-registered name. Of course, after
-
# registration this flag can disappear, adds to the confusing
-
# proliferation of MIME types. The simplified string has the
-
# <tt>x-</tt> removed and are translated to lowercase.
-
2
def simplified(content_type)
-
3286
matchdata = MEDIA_TYPE_RE.match(content_type)
-
-
3286
if matchdata.nil?
-
simplified = nil
-
else
-
3286
media_type = matchdata.captures[0].downcase.gsub(UNREG_RE, '')
-
3286
subtype = matchdata.captures[1].downcase.gsub(UNREG_RE, '')
-
3286
simplified = "#{media_type}/#{subtype}"
-
end
-
3286
simplified
-
end
-
-
# Creates a MIME::Type from an array in the form of:
-
# [type-name, [extensions], encoding, system]
-
#
-
# +extensions+, +encoding+, and +system+ are optional.
-
#
-
# MIME::Type.from_array("application/x-ruby", ['rb'], '8bit')
-
# MIME::Type.from_array(["application/x-ruby", ['rb'], '8bit'])
-
#
-
# These are equivalent to:
-
#
-
# MIME::Type.new('application/x-ruby') do |t|
-
# t.extensions = %w(rb)
-
# t.encoding = '8bit'
-
# end
-
2
def from_array(*args) #:yields MIME::Type.new:
-
# Dereferences the array one level, if necessary.
-
args = args.first if args.first.kind_of? Array
-
-
unless args.size.between?(1, 8)
-
raise ArgumentError, "Array provided must contain between one and eight elements."
-
end
-
-
MIME::Type.new(args.shift) do |t|
-
t.extensions, t.encoding, t.system, t.obsolete, t.docs, t.url,
-
t.registered = *args
-
yield t if block_given?
-
end
-
end
-
-
# Creates a MIME::Type from a hash. Keys are case-insensitive,
-
# dashes may be replaced with underscores, and the internal Symbol
-
# of the lowercase-underscore version can be used as well. That is,
-
# Content-Type can be provided as content-type, Content_Type,
-
# content_type, or :content_type.
-
#
-
# Known keys are <tt>Content-Type</tt>,
-
# <tt>Content-Transfer-Encoding</tt>, <tt>Extensions</tt>, and
-
# <tt>System</tt>.
-
#
-
# MIME::Type.from_hash('Content-Type' => 'text/x-yaml',
-
# 'Content-Transfer-Encoding' => '8bit',
-
# 'System' => 'linux',
-
# 'Extensions' => ['yaml', 'yml'])
-
#
-
# This is equivalent to:
-
#
-
# MIME::Type.new('text/x-yaml') do |t|
-
# t.encoding = '8bit'
-
# t.system = 'linux'
-
# t.extensions = ['yaml', 'yml']
-
# end
-
2
def from_hash(hash) #:yields MIME::Type.new:
-
type = {}
-
hash.each_pair do |k, v|
-
type[k.to_s.tr('A-Z', 'a-z').gsub(/-/, '_').to_sym] = v
-
end
-
-
MIME::Type.new(type[:content_type]) do |t|
-
t.extensions = type[:extensions]
-
t.encoding = type[:content_transfer_encoding]
-
t.system = type[:system]
-
t.obsolete = type[:obsolete]
-
t.docs = type[:docs]
-
t.url = type[:url]
-
t.registered = type[:registered]
-
-
yield t if block_given?
-
end
-
end
-
-
# Essentially a copy constructor.
-
#
-
# MIME::Type.from_mime_type(plaintext)
-
#
-
# is equivalent to:
-
#
-
# MIME::Type.new(plaintext.content_type.dup) do |t|
-
# t.extensions = plaintext.extensions.dup
-
# t.system = plaintext.system.dup
-
# t.encoding = plaintext.encoding.dup
-
# end
-
2
def from_mime_type(mime_type) #:yields the new MIME::Type:
-
MIME::Type.new(mime_type.content_type.dup) do |t|
-
t.extensions = mime_type.extensions.map { |e| e.dup }
-
t.url = mime_type.url && mime_type.url.map { |e| e.dup }
-
-
mime_type.system && t.system = mime_type.system.dup
-
mime_type.encoding && t.encoding = mime_type.encoding.dup
-
-
t.obsolete = mime_type.obsolete?
-
t.registered = mime_type.registered?
-
-
mime_type.docs && t.docs = mime_type.docs.dup
-
-
yield t if block_given?
-
end
-
end
-
end
-
-
# Builds a MIME::Type object from the provided MIME Content Type value
-
# (e.g., 'text/plain' or 'applicaton/x-eruby'). The constructed object
-
# is yielded to an optional block for additional configuration, such as
-
# associating extensions and encoding information.
-
2
def initialize(content_type) #:yields self:
-
3286
matchdata = MEDIA_TYPE_RE.match(content_type)
-
-
3286
if matchdata.nil?
-
raise InvalidContentType, "Invalid Content-Type provided ('#{content_type}')"
-
end
-
-
3286
@content_type = content_type
-
3286
@raw_media_type = matchdata.captures[0]
-
3286
@raw_sub_type = matchdata.captures[1]
-
-
3286
@simplified = MIME::Type.simplified(@content_type)
-
3286
matchdata = MEDIA_TYPE_RE.match(@simplified)
-
3286
@media_type = matchdata.captures[0]
-
3286
@sub_type = matchdata.captures[1]
-
-
3286
self.extensions = nil
-
3286
self.encoding = :default
-
3286
self.system = nil
-
3286
self.registered = true
-
3286
self.url = nil
-
3286
self.obsolete = nil
-
3286
self.docs = nil
-
-
3286
yield self if block_given?
-
end
-
-
# MIME content-types which are not regestered by IANA nor defined in
-
# RFCs are required to start with <tt>x-</tt>. This counts as well for
-
# a new media type as well as a new sub-type of an existing media
-
# type. If either the media-type or the content-type begins with
-
# <tt>x-</tt>, this method will return +false+.
-
2
def registered?
-
if (@raw_media_type =~ UNREG_RE) || (@raw_sub_type =~ UNREG_RE)
-
false
-
else
-
@registered
-
end
-
end
-
2
attr_writer :registered #:nodoc:
-
-
# MIME types can be specified to be sent across a network in particular
-
# formats. This method returns +true+ when the MIME type encoding is set
-
# to <tt>base64</tt>.
-
2
def binary?
-
@encoding == 'base64'
-
end
-
-
# MIME types can be specified to be sent across a network in particular
-
# formats. This method returns +false+ when the MIME type encoding is
-
# set to <tt>base64</tt>.
-
2
def ascii?
-
not binary?
-
end
-
-
# Returns +true+ when the simplified MIME type is in the list of known
-
# digital signatures.
-
2
def signature?
-
SIGNATURES.include?(@simplified.downcase)
-
end
-
-
# Returns +true+ if the MIME::Type is specific to an operating system.
-
2
def system?
-
not @system.nil?
-
end
-
-
# Returns +true+ if the MIME::Type is specific to the current operating
-
# system as represented by RUBY_PLATFORM.
-
2
def platform?
-
system? and (RUBY_PLATFORM =~ @system)
-
end
-
-
# Returns +true+ if the MIME::Type specifies an extension list,
-
# indicating that it is a complete MIME::Type.
-
2
def complete?
-
not @extensions.empty?
-
end
-
-
# Returns the MIME type as a string.
-
2
def to_s
-
@content_type
-
end
-
-
# Returns the MIME type as a string for implicit conversions.
-
2
def to_str
-
@content_type
-
end
-
-
# Returns the MIME type as an array suitable for use with
-
# MIME::Type.from_array.
-
2
def to_a
-
[ @content_type, @extensions, @encoding, @system, @obsolete, @docs,
-
@url, registered? ]
-
end
-
-
# Returns the MIME type as an array suitable for use with
-
# MIME::Type.from_hash.
-
2
def to_hash
-
{ 'Content-Type' => @content_type,
-
'Content-Transfer-Encoding' => @encoding,
-
'Extensions' => @extensions,
-
'System' => @system,
-
'Obsolete' => @obsolete,
-
'Docs' => @docs,
-
'URL' => @url,
-
'Registered' => registered?,
-
}
-
end
-
end
-
-
# = MIME::Types
-
# MIME types are used in MIME-compliant communications, as in e-mail or
-
# HTTP traffic, to indicate the type of content which is transmitted.
-
# MIME::Types provides the ability for detailed information about MIME
-
# entities (provided as a set of MIME::Type objects) to be determined and
-
# used programmatically. There are many types defined by RFCs and vendors,
-
# so the list is long but not complete; don't hesitate to ask to add
-
# additional information. This library follows the IANA collection of MIME
-
# types (see below for reference).
-
#
-
# == Description
-
# MIME types are used in MIME entities, as in email or HTTP traffic. It is
-
# useful at times to have information available about MIME types (or,
-
# inversely, about files). A MIME::Type stores the known information about
-
# one MIME type.
-
#
-
# == Usage
-
# require 'mime/types'
-
#
-
# plaintext = MIME::Types['text/plain']
-
# print plaintext.media_type # => 'text'
-
# print plaintext.sub_type # => 'plain'
-
#
-
# puts plaintext.extensions.join(" ") # => 'asc txt c cc h hh cpp'
-
#
-
# puts plaintext.encoding # => 8bit
-
# puts plaintext.binary? # => false
-
# puts plaintext.ascii? # => true
-
# puts plaintext.obsolete? # => false
-
# puts plaintext.registered? # => true
-
# puts plaintext == 'text/plain' # => true
-
# puts MIME::Type.simplified('x-appl/x-zip') # => 'appl/zip'
-
#
-
# This module is built to conform to the MIME types of RFCs 2045 and 2231.
-
# It follows the official IANA registry at
-
# http://www.iana.org/assignments/media-types/ and
-
# ftp://ftp.iana.org/assignments/media-types with some unofficial types
-
# added from the the collection at
-
# http://www.ltsw.se/knbase/internet/mime.htp
-
2
class Types
-
# The released version of Ruby MIME::Types
-
2
VERSION = MIME::Type::VERSION
-
2
DATA_VERSION = (VERSION.to_f * 100).to_i
-
-
# The data version.
-
2
attr_reader :data_version
-
-
2
class HashWithArrayDefault < Hash # :nodoc:
-
2
def initialize
-
8820
super { |h, k| h[k] = [] }
-
end
-
-
2
def marshal_dump
-
{}.merge(self)
-
end
-
-
2
def marshal_load(hash)
-
self.merge!(hash)
-
end
-
end
-
-
2
class CacheContainer # :nodoc:
-
2
attr_reader :version, :data
-
2
def initialize(version, data)
-
@version, @data = version, data
-
end
-
end
-
-
2
def initialize(data_version = DATA_VERSION)
-
50
@type_variants = HashWithArrayDefault.new
-
50
@extension_index = HashWithArrayDefault.new
-
50
@data_version = data_version
-
end
-
-
2
def add_type_variant(mime_type) #:nodoc:
-
6572
@type_variants[mime_type.simplified] << mime_type
-
end
-
-
2
def index_extensions(mime_type) #:nodoc:
-
9116
mime_type.extensions.each { |ext| @extension_index[ext] << mime_type }
-
end
-
-
2
def defined_types #:nodoc:
-
48
@type_variants.values.flatten
-
end
-
-
# Returns the number of known types. A shortcut of MIME::Types[//].size.
-
# (Keep in mind that this is memory intensive, cache the result to spare
-
# resources)
-
2
def count
-
defined_types.size
-
end
-
-
2
def each
-
defined_types.each { |t| yield t }
-
end
-
-
2
@__types__ = nil
-
-
# Returns a list of MIME::Type objects, which may be empty. The optional
-
# flag parameters are :complete (finds only complete MIME::Type objects)
-
# and :platform (finds only MIME::Types for the current platform). It is
-
# possible for multiple matches to be returned for either type (in the
-
# example below, 'text/plain' returns two values -- one for the general
-
# case, and one for VMS systems.
-
#
-
# puts "\nMIME::Types['text/plain']"
-
# MIME::Types['text/plain'].each { |t| puts t.to_a.join(", ") }
-
#
-
# puts "\nMIME::Types[/^image/, :complete => true]"
-
# MIME::Types[/^image/, :complete => true].each do |t|
-
# puts t.to_a.join(", ")
-
# end
-
#
-
# If multiple type definitions are returned, returns them sorted as
-
# follows:
-
# 1. Complete definitions sort before incomplete ones;
-
# 2. IANA-registered definitions sort before LTSW-recorded
-
# definitions.
-
# 3. Generic definitions sort before platform-specific ones;
-
# 4. Current definitions sort before obsolete ones;
-
# 5. Obsolete definitions with use-instead clauses sort before those
-
# without;
-
# 6. Obsolete definitions use-instead clauses are compared.
-
# 7. Sort on name.
-
2
def [](type_id, flags = {})
-
matches = case type_id
-
when MIME::Type
-
@type_variants[type_id.simplified]
-
when Regexp
-
match(type_id)
-
else
-
@type_variants[MIME::Type.simplified(type_id)]
-
end
-
-
prune_matches(matches, flags).sort { |a, b| a.priority_compare(b) }
-
end
-
-
# Return the list of MIME::Types which belongs to the file based on its
-
# filename extension. If +platform+ is +true+, then only file types that
-
# are specific to the current platform will be returned.
-
#
-
# This will always return an array.
-
#
-
# puts "MIME::Types.type_for('citydesk.xml')
-
# => [application/xml, text/xml]
-
# puts "MIME::Types.type_for('citydesk.gif')
-
# => [image/gif]
-
2
def type_for(filename, platform = false)
-
ext = filename.chomp.downcase.gsub(/.*\./o, '')
-
list = @extension_index[ext]
-
list.delete_if { |e| not e.platform? } if platform
-
list
-
end
-
-
# A synonym for MIME::Types.type_for
-
2
def of(filename, platform = false)
-
type_for(filename, platform)
-
end
-
-
# Add one or more MIME::Type objects to the set of known types. Each
-
# type should be experimental (e.g., 'application/x-ruby'). If the type
-
# is already known, a warning will be displayed.
-
#
-
# <strong>Please inform the maintainer of this module when registered
-
# types are missing.</strong>
-
2
def add(*types)
-
3382
types.each do |mime_type|
-
6620
if mime_type.kind_of? MIME::Types
-
48
add(*mime_type.defined_types)
-
else
-
6572
if @type_variants.include?(mime_type.simplified)
-
146
if @type_variants[mime_type.simplified].include?(mime_type)
-
12
warn "Type #{mime_type} already registered as a variant of #{mime_type.simplified}." unless defined? MIME::Types::LOAD
-
end
-
end
-
6572
add_type_variant(mime_type)
-
6572
index_extensions(mime_type)
-
end
-
end
-
end
-
-
2
private
-
2
def prune_matches(matches, flags)
-
matches.delete_if { |e| not e.complete? } if flags[:complete]
-
matches.delete_if { |e| not e.platform? } if flags[:platform]
-
matches
-
end
-
-
2
def match(pattern)
-
matches = @type_variants.select { |k, v| k =~ pattern }
-
if matches.respond_to? :values
-
matches.values.flatten
-
else
-
matches.map { |m| m.last }.flatten
-
end
-
end
-
-
2
class << self
-
2
def add_type_variant(mime_type) #:nodoc:
-
__types__.add_type_variant(mime_type)
-
end
-
-
2
def index_extensions(mime_type) #:nodoc:
-
__types__.index_extensions(mime_type)
-
end
-
-
# The regular expression used to match a file-based MIME type
-
# definition.
-
2
TEXT_FORMAT_RE = %r{
-
\A
-
\s*
-
([*])? # 0: Unregistered?
-
(!)? # 1: Obsolete?
-
(?:(\w+):)? # 2: Platform marker
-
#{MIME::Type::MEDIA_TYPE_RE}? # 3,4: Media type
-
(?:\s+@([^\s]+))? # 5: Extensions
-
(?:\s+:(#{MIME::Type::ENCODING_RE}))? # 6: Encoding
-
(?:\s+'(.+))? # 7: URL list
-
(?:\s+=(.+))? # 8: Documentation
-
(?:\s*([#].*)?)?
-
\s*
-
\z
-
}x
-
-
# Build the type list from a file in the format:
-
#
-
# [*][!][os:]mt/st[<ws>@ext][<ws>:enc][<ws>'url-list][<ws>=docs]
-
#
-
# == *
-
# An unofficial MIME type. This should be used if and only if the MIME type
-
# is not properly specified (that is, not under either x-type or
-
# vnd.name.type).
-
#
-
# == !
-
# An obsolete MIME type. May be used with an unofficial MIME type.
-
#
-
# == os:
-
# Platform-specific MIME type definition.
-
#
-
# == mt
-
# The media type.
-
#
-
# == st
-
# The media subtype.
-
#
-
# == <ws>@ext
-
# The list of comma-separated extensions.
-
#
-
# == <ws>:enc
-
# The encoding.
-
#
-
# == <ws>'url-list
-
# The list of comma-separated URLs.
-
#
-
# == <ws>=docs
-
# The documentation string.
-
#
-
# That is, everything except the media type and the subtype is optional. The
-
# more information that's available, though, the richer the values that can
-
# be provided.
-
2
def load_from_file(filename) #:nodoc:
-
48
if defined? ::Encoding
-
96
data = File.open(filename, 'r:UTF-8:-') { |f| f.read }
-
else
-
data = File.open(filename) { |f| f.read }
-
end
-
48
data = data.split($/)
-
48
mime = MIME::Types.new
-
48
data.each_with_index { |line, index|
-
3286
item = line.chomp.strip
-
3286
next if item.empty?
-
-
3286
begin
-
3286
m = TEXT_FORMAT_RE.match(item).captures
-
rescue Exception
-
puts "#{filename}:#{index}: Parsing error in MIME type definitions."
-
puts "=> #{line}"
-
raise
-
end
-
-
unregistered, obsolete, platform, mediatype, subtype, extensions,
-
3286
encoding, urls, docs, comment = *m
-
-
3286
if mediatype.nil?
-
if comment.nil?
-
puts "#{filename}:#{index}: Parsing error in MIME type definitions."
-
puts "=> #{line}"
-
raise RuntimeError
-
end
-
-
next
-
end
-
-
3286
extensions &&= extensions.split(/,/)
-
3286
urls &&= urls.split(/,/)
-
-
3286
mime_type = MIME::Type.new("#{mediatype}/#{subtype}") do |t|
-
3286
t.extensions = extensions
-
3286
t.encoding = encoding
-
3286
t.system = platform
-
3286
t.obsolete = obsolete
-
3286
t.registered = false if unregistered
-
3286
t.docs = docs
-
3286
t.url = urls
-
end
-
-
3286
mime.add(mime_type)
-
}
-
48
mime
-
end
-
-
# Returns a list of MIME::Type objects, which may be empty. The
-
# optional flag parameters are :complete (finds only complete
-
# MIME::Type objects) and :platform (finds only MIME::Types for the
-
# current platform). It is possible for multiple matches to be
-
# returned for either type (in the example below, 'text/plain' returns
-
# two values -- one for the general case, and one for VMS systems.
-
#
-
# puts "\nMIME::Types['text/plain']"
-
# MIME::Types['text/plain'].each { |t| puts t.to_a.join(", ") }
-
#
-
# puts "\nMIME::Types[/^image/, :complete => true]"
-
# MIME::Types[/^image/, :complete => true].each do |t|
-
# puts t.to_a.join(", ")
-
# end
-
2
def [](type_id, flags = {})
-
__types__[type_id, flags]
-
end
-
-
2
include Enumerable
-
-
2
def count
-
__types__.count
-
end
-
-
2
def each
-
__types__.each {|t| yield t }
-
end
-
-
# Return the list of MIME::Types which belongs to the file based on
-
# its filename extension. If +platform+ is +true+, then only file
-
# types that are specific to the current platform will be returned.
-
#
-
# This will always return an array.
-
#
-
# puts "MIME::Types.type_for('citydesk.xml')
-
# => [application/xml, text/xml]
-
# puts "MIME::Types.type_for('citydesk.gif')
-
# => [image/gif]
-
2
def type_for(filename, platform = false)
-
__types__.type_for(filename, platform)
-
end
-
-
# A synonym for MIME::Types.type_for
-
2
def of(filename, platform = false)
-
__types__.type_for(filename, platform)
-
end
-
-
# Add one or more MIME::Type objects to the set of known types. Each
-
# type should be experimental (e.g., 'application/x-ruby'). If the
-
# type is already known, a warning will be displayed.
-
#
-
# <strong>Please inform the maintainer of this module when registered
-
# types are missing.</strong>
-
2
def add(*types)
-
48
__types__.add(*types)
-
end
-
-
# Returns the currently defined cache file, if any.
-
2
def cache_file
-
4
ENV['RUBY_MIME_TYPES_CACHE']
-
end
-
-
2
private
-
2
def load_mime_types_from_cache
-
2
load_mime_types_from_cache! if cache_file
-
end
-
-
2
def load_mime_types_from_cache!
-
raise ArgumentError, "No RUBY_MIME_TYPES_CACHE set." unless cache_file
-
return false unless File.exists? cache_file
-
-
begin
-
data = File.read(cache_file)
-
container = Marshal.load(data)
-
-
if container.version == VERSION
-
@__types__ = Marshal.load(container.data)
-
true
-
else
-
false
-
end
-
rescue => e
-
warn "Could not load MIME::Types cache: #{e}"
-
false
-
end
-
end
-
-
2
def write_mime_types_to_cache
-
2
write_mime_types_to_cache! if cache_file
-
end
-
-
2
def write_mime_types_to_cache!
-
raise ArgumentError, "No RUBY_MIME_TYPES_CACHE set." unless cache_file
-
-
File.open(cache_file, 'w') do |f|
-
cache = MIME::Types::CacheContainer.new(VERSION,
-
Marshal.dump(__types__))
-
f.write Marshal.dump(cache)
-
end
-
-
true
-
end
-
-
2
def load_and_parse_mime_types
-
2
const_set(:LOAD, true) unless $DEBUG
-
2
Dir[File.join(File.dirname(__FILE__), 'types', '*')].sort.each { |f|
-
48
add(load_from_file(f))
-
}
-
2
remove_const :LOAD if defined? LOAD
-
end
-
-
2
def lazy_load?
-
2
(lazy = ENV['RUBY_MIME_TYPES_LAZY_LOAD']) && (lazy != 'false')
-
end
-
-
2
def __types__
-
48
load_mime_types unless @__types__
-
48
@__types__
-
end
-
-
2
def load_mime_types
-
2
@__types__ = new(VERSION)
-
2
unless load_mime_types_from_cache
-
2
load_and_parse_mime_types
-
2
write_mime_types_to_cache
-
end
-
end
-
end
-
-
2
load_mime_types unless lazy_load?
-
end
-
end
-
-
# vim: ft=ruby
-
# support multiple ruby version (fat binaries under windows)
-
2
begin
-
2
RUBY_VERSION =~ /(\d+.\d+)/
-
2
require "mysql/#{$1}/mysql_api"
-
rescue LoadError
-
2
require 'mysql/mysql_api'
-
end
-
-
2
require 'mysql/version'
-
# define version string to be used internally for the Gem by Hoe.
-
2
class Mysql
-
2
module GemVersion
-
2
VERSION = '2.9.1'
-
end
-
end
-
2
require "nested_form/engine"
-
2
module NestedForm
-
2
module BuilderMixin
-
# Adds a link to insert a new associated records. The first argument is the name of the link, the second is the name of the association.
-
#
-
# f.link_to_add("Add Task", :tasks)
-
#
-
# You can pass HTML options in a hash at the end and a block for the content.
-
#
-
# <%= f.link_to_add(:tasks, :class => "add_task", :href => new_task_path) do %>
-
# Add Task
-
# <% end %>
-
#
-
# You can also pass <tt>model_object</tt> option with an object for use in
-
# the blueprint, e.g.:
-
#
-
# <%= f.link_to_add(:tasks, :model_object => Task.new(:name => 'Task')) %>
-
#
-
# See the README for more details on where to call this method.
-
2
def link_to_add(*args, &block)
-
options = args.extract_options!.symbolize_keys
-
association = args.pop
-
-
unless object.respond_to?("#{association}_attributes=")
-
raise ArgumentError, "Invalid association. Make sure that accepts_nested_attributes_for is used for #{association.inspect} association."
-
end
-
-
model_object = options.delete(:model_object) do
-
reflection = object.class.reflect_on_association(association)
-
reflection.klass.new
-
end
-
-
options[:class] = [options[:class], "add_nested_fields"].compact.join(" ")
-
options["data-association"] = association
-
options["data-blueprint-id"] = fields_blueprint_id = fields_blueprint_id_for(association)
-
args << (options.delete(:href) || "javascript:void(0)")
-
args << options
-
-
@fields ||= {}
-
@template.after_nested_form(fields_blueprint_id) do
-
blueprint = {:id => fields_blueprint_id, :style => 'display: none'}
-
block, options = @fields[fields_blueprint_id].values_at(:block, :options)
-
options[:child_index] = "new_#{association}"
-
blueprint[:"data-blueprint"] = fields_for(association, model_object, options, &block).to_str
-
@template.content_tag(:div, nil, blueprint)
-
end
-
@template.link_to(*args, &block)
-
end
-
-
# Adds a link to remove the associated record. The first argment is the name of the link.
-
#
-
# f.link_to_remove("Remove Task")
-
#
-
# You can pass HTML options in a hash at the end and a block for the content.
-
#
-
# <%= f.link_to_remove(:class => "remove_task", :href => "#") do %>
-
# Remove Task
-
# <% end %>
-
#
-
# See the README for more details on where to call this method.
-
2
def link_to_remove(*args, &block)
-
options = args.extract_options!.symbolize_keys
-
options[:class] = [options[:class], "remove_nested_fields"].compact.join(" ")
-
-
# Extracting "milestones" from "...[milestones_attributes][...]"
-
md = object_name.to_s.match /(\w+)_attributes\]\[[\w\d]+\]$/
-
association = md && md[1]
-
options["data-association"] = association
-
-
args << (options.delete(:href) || "javascript:void(0)")
-
args << options
-
hidden_field(:_destroy) << @template.link_to(*args, &block)
-
end
-
-
2
def fields_for_with_nested_attributes(association_name, *args)
-
# TODO Test this better
-
block = args.pop || Proc.new { |fields| @template.render(:partial => "#{association_name.to_s.singularize}_fields", :locals => {:f => fields}) }
-
-
options = args.dup.extract_options!
-
-
# Rails 3.0.x
-
if options.empty? && args[0].kind_of?(Array)
-
options = args[0].dup.extract_options!
-
end
-
-
@fields ||= {}
-
@fields[fields_blueprint_id_for(association_name)] = { :block => block, :options => options }
-
super(association_name, *(args << block))
-
end
-
-
2
def fields_for_nested_model(name, object, options, block)
-
classes = 'fields'
-
classes << ' marked_for_destruction' if object.respond_to?(:marked_for_destruction?) && object.marked_for_destruction?
-
-
perform_wrap = options.fetch(:nested_wrapper, true)
-
perform_wrap &&= options[:wrapper] != false # wrap even if nil
-
-
if perform_wrap
-
@template.content_tag(:div, super, :class => classes)
-
else
-
super
-
end
-
end
-
-
2
private
-
-
2
def fields_blueprint_id_for(association)
-
assocs = object_name.to_s.scan(/(\w+)_attributes/).map(&:first)
-
assocs << association
-
assocs.join('_') + '_fields_blueprint'
-
end
-
end
-
end
-
2
require 'nested_form/builder_mixin'
-
-
2
module NestedForm
-
2
class Builder < ::ActionView::Helpers::FormBuilder
-
2
include ::NestedForm::BuilderMixin
-
end
-
-
2
begin
-
2
require 'simple_form'
-
class SimpleBuilder < ::SimpleForm::FormBuilder
-
include ::NestedForm::BuilderMixin
-
end
-
rescue LoadError
-
end
-
-
2
begin
-
2
require 'formtastic'
-
class FormtasticBuilder < (defined?(::Formtastic::FormBuilder) ? Formtastic::FormBuilder : ::Formtastic::SemanticFormBuilder)
-
include ::NestedForm::BuilderMixin
-
end
-
rescue LoadError
-
end
-
-
2
begin
-
2
require 'formtastic-bootstrap'
-
class FormtasticBootstrapBuilder < ::FormtasticBootstrap::FormBuilder
-
include ::NestedForm::BuilderMixin
-
end
-
rescue LoadError
-
end
-
end
-
2
require 'rails'
-
-
2
module NestedForm
-
2
class Engine < ::Rails::Engine
-
2
initializer 'nested_form' do |app|
-
2
ActiveSupport.on_load(:action_view) do
-
2
require "nested_form/view_helper"
-
2
class ActionView::Base
-
2
include NestedForm::ViewHelper
-
end
-
end
-
end
-
end
-
end
-
2
require 'nested_form/builders'
-
-
2
module NestedForm
-
2
module ViewHelper
-
2
def nested_form_for(*args, &block)
-
options = args.extract_options!.reverse_merge(:builder => NestedForm::Builder)
-
form_for(*(args << options)) do |f|
-
capture(f, &block).to_s << after_nested_form_callbacks
-
end
-
end
-
-
2
if defined?(NestedForm::SimpleBuilder)
-
def simple_nested_form_for(*args, &block)
-
options = args.extract_options!.reverse_merge(:builder => NestedForm::SimpleBuilder)
-
simple_form_for(*(args << options)) do |f|
-
capture(f, &block).to_s << after_nested_form_callbacks
-
end
-
end
-
end
-
-
2
if defined?(NestedForm::FormtasticBuilder)
-
def semantic_nested_form_for(*args, &block)
-
options = args.extract_options!.reverse_merge(:builder => NestedForm::FormtasticBuilder)
-
semantic_form_for(*(args << options)) do |f|
-
capture(f, &block).to_s << after_nested_form_callbacks
-
end
-
end
-
end
-
-
2
if defined?(NestedForm::FormtasticBootstrapBuilder)
-
def semantic_bootstrap_nested_form_for(*args, &block)
-
options = args.extract_options!.reverse_merge(:builder => NestedForm::FormtasticBootstrapBuilder)
-
semantic_form_for(*(args << options)) do |f|
-
capture(f, &block).to_s << after_nested_form_callbacks
-
end
-
end
-
end
-
-
2
def after_nested_form(association, &block)
-
@associations ||= []
-
@after_nested_form_callbacks ||= []
-
unless @associations.include?(association)
-
@associations << association
-
@after_nested_form_callbacks << block
-
end
-
end
-
-
2
private
-
2
def after_nested_form_callbacks
-
@after_nested_form_callbacks ||= []
-
fields = []
-
while callback = @after_nested_form_callbacks.shift
-
fields << callback.call
-
end
-
fields.join(" ").html_safe
-
end
-
end
-
end
-
# Copyright (C) 2007, 2008, 2009, 2010 Christian Neukirchen <purl.org/net/chneukirchen>
-
#
-
# Rack is freely distributable under the terms of an MIT-style license.
-
# See COPYING or http://www.opensource.org/licenses/mit-license.php.
-
-
# The Rack main module, serving as a namespace for all core Rack
-
# modules and classes.
-
#
-
# All modules meant for use in your application are <tt>autoload</tt>ed here,
-
# so it should be enough just to <tt>require rack.rb</tt> in your code.
-
-
2
module Rack
-
# The Rack protocol version number implemented.
-
2
VERSION = [1,1]
-
-
# Return the Rack protocol version as a dotted string.
-
2
def self.version
-
VERSION.join(".")
-
end
-
-
# Return the Rack release as a dotted string.
-
2
def self.release
-
"1.4"
-
end
-
-
2
autoload :Builder, "rack/builder"
-
2
autoload :BodyProxy, "rack/body_proxy"
-
2
autoload :Cascade, "rack/cascade"
-
2
autoload :Chunked, "rack/chunked"
-
2
autoload :CommonLogger, "rack/commonlogger"
-
2
autoload :ConditionalGet, "rack/conditionalget"
-
2
autoload :Config, "rack/config"
-
2
autoload :ContentLength, "rack/content_length"
-
2
autoload :ContentType, "rack/content_type"
-
2
autoload :ETag, "rack/etag"
-
2
autoload :File, "rack/file"
-
2
autoload :Deflater, "rack/deflater"
-
2
autoload :Directory, "rack/directory"
-
2
autoload :ForwardRequest, "rack/recursive"
-
2
autoload :Handler, "rack/handler"
-
2
autoload :Head, "rack/head"
-
2
autoload :Lint, "rack/lint"
-
2
autoload :Lock, "rack/lock"
-
2
autoload :Logger, "rack/logger"
-
2
autoload :MethodOverride, "rack/methodoverride"
-
2
autoload :Mime, "rack/mime"
-
2
autoload :NullLogger, "rack/nulllogger"
-
2
autoload :Recursive, "rack/recursive"
-
2
autoload :Reloader, "rack/reloader"
-
2
autoload :Runtime, "rack/runtime"
-
2
autoload :Sendfile, "rack/sendfile"
-
2
autoload :Server, "rack/server"
-
2
autoload :ShowExceptions, "rack/showexceptions"
-
2
autoload :ShowStatus, "rack/showstatus"
-
2
autoload :Static, "rack/static"
-
2
autoload :URLMap, "rack/urlmap"
-
2
autoload :Utils, "rack/utils"
-
2
autoload :Multipart, "rack/multipart"
-
-
2
autoload :MockRequest, "rack/mock"
-
2
autoload :MockResponse, "rack/mock"
-
-
2
autoload :Request, "rack/request"
-
2
autoload :Response, "rack/response"
-
-
2
module Auth
-
2
autoload :Basic, "rack/auth/basic"
-
2
autoload :AbstractRequest, "rack/auth/abstract/request"
-
2
autoload :AbstractHandler, "rack/auth/abstract/handler"
-
2
module Digest
-
2
autoload :MD5, "rack/auth/digest/md5"
-
2
autoload :Nonce, "rack/auth/digest/nonce"
-
2
autoload :Params, "rack/auth/digest/params"
-
2
autoload :Request, "rack/auth/digest/request"
-
end
-
-
# Not all of the following schemes are "standards", but they are used often.
-
2
@schemes = %w[basic digest bearer mac token oauth oauth2]
-
-
2
def self.add_scheme scheme
-
@schemes << scheme
-
@schemes.uniq!
-
end
-
-
2
def self.schemes
-
@schemes.dup
-
end
-
end
-
-
2
module Session
-
2
autoload :Cookie, "rack/session/cookie"
-
2
autoload :Pool, "rack/session/pool"
-
2
autoload :Memcache, "rack/session/memcache"
-
end
-
end
-
# :stopdoc:
-
-
2
require 'uri/common'
-
-
# Issue:
-
# http://bugs.ruby-lang.org/issues/5925
-
#
-
# Relevant commit:
-
# https://github.com/ruby/ruby/commit/edb7cdf1eabaff78dfa5ffedfbc2e91b29fa9ca1
-
-
2
module URI
-
2
256.times do |i|
-
512
TBLENCWWWCOMP_[i.chr] = '%%%02X' % i
-
end
-
2
TBLENCWWWCOMP_[' '] = '+'
-
2
TBLENCWWWCOMP_.freeze
-
-
2
256.times do |i|
-
512
h, l = i>>4, i&15
-
512
TBLDECWWWCOMP_['%%%X%X' % [h, l]] = i.chr
-
512
TBLDECWWWCOMP_['%%%x%X' % [h, l]] = i.chr
-
512
TBLDECWWWCOMP_['%%%X%x' % [h, l]] = i.chr
-
512
TBLDECWWWCOMP_['%%%x%x' % [h, l]] = i.chr
-
end
-
2
TBLDECWWWCOMP_['+'] = ' '
-
2
TBLDECWWWCOMP_.freeze
-
end
-
-
# :startdoc:
-
2
module Rack
-
2
class BodyProxy
-
2
def initialize(body, &block)
-
@body, @block, @closed = body, block, false
-
end
-
-
2
def respond_to?(*args)
-
return false if args.first.to_s =~ /^to_ary$/
-
super or @body.respond_to?(*args)
-
end
-
-
2
def close
-
return if @closed
-
@closed = true
-
begin
-
@body.close if @body.respond_to? :close
-
ensure
-
@block.call
-
end
-
end
-
-
2
def closed?
-
@closed
-
end
-
-
# N.B. This method is a special case to address the bug described by #434.
-
# We are applying this special case for #each only. Future bugs of this
-
# class will be handled by requesting users to patch their ruby
-
# implementation, to save adding too many methods in this class.
-
2
def each(*args, &block)
-
@body.each(*args, &block)
-
end
-
-
2
def method_missing(*args, &block)
-
super if args.first.to_s =~ /^to_ary$/
-
@body.__send__(*args, &block)
-
end
-
end
-
end
-
2
require 'rack/utils'
-
-
2
module Rack
-
-
# Middleware that applies chunked transfer encoding to response bodies
-
# when the response does not include a Content-Length header.
-
2
class Chunked
-
2
include Rack::Utils
-
-
# A body wrapper that emits chunked responses
-
2
class Body
-
2
TERM = "\r\n"
-
2
TAIL = "0#{TERM}#{TERM}"
-
-
2
include Rack::Utils
-
-
2
def initialize(body)
-
@body = body
-
end
-
-
2
def each
-
term = TERM
-
@body.each do |chunk|
-
size = bytesize(chunk)
-
next if size == 0
-
-
chunk = chunk.dup.force_encoding(Encoding::BINARY) if chunk.respond_to?(:force_encoding)
-
yield [size.to_s(16), term, chunk, term].join
-
end
-
yield TAIL
-
end
-
-
2
def close
-
@body.close if @body.respond_to?(:close)
-
end
-
end
-
-
2
def initialize(app)
-
@app = app
-
end
-
-
2
def call(env)
-
status, headers, body = @app.call(env)
-
headers = HeaderHash.new(headers)
-
-
if env['HTTP_VERSION'] == 'HTTP/1.0' ||
-
STATUS_WITH_NO_ENTITY_BODY.include?(status) ||
-
headers['Content-Length'] ||
-
headers['Transfer-Encoding']
-
[status, headers, body]
-
else
-
headers.delete('Content-Length')
-
headers['Transfer-Encoding'] = 'chunked'
-
[status, headers, Body.new(body)]
-
end
-
end
-
end
-
end
-
2
require 'rack/utils'
-
-
2
module Rack
-
-
# Middleware that enables conditional GET using If-None-Match and
-
# If-Modified-Since. The application should set either or both of the
-
# Last-Modified or Etag response headers according to RFC 2616. When
-
# either of the conditions is met, the response body is set to be zero
-
# length and the response status is set to 304 Not Modified.
-
#
-
# Applications that defer response body generation until the body's each
-
# message is received will avoid response body generation completely when
-
# a conditional GET matches.
-
#
-
# Adapted from Michael Klishin's Merb implementation:
-
# http://github.com/wycats/merb-core/tree/master/lib/merb-core/rack/middleware/conditional_get.rb
-
2
class ConditionalGet
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
case env['REQUEST_METHOD']
-
when "GET", "HEAD"
-
status, headers, body = @app.call(env)
-
headers = Utils::HeaderHash.new(headers)
-
if status == 200 && fresh?(env, headers)
-
status = 304
-
headers.delete('Content-Type')
-
headers.delete('Content-Length')
-
body = []
-
end
-
[status, headers, body]
-
else
-
@app.call(env)
-
end
-
end
-
-
2
private
-
-
2
def fresh?(env, headers)
-
modified_since = env['HTTP_IF_MODIFIED_SINCE']
-
none_match = env['HTTP_IF_NONE_MATCH']
-
-
return false unless modified_since || none_match
-
-
success = true
-
success &&= modified_since?(to_rfc2822(modified_since), headers) if modified_since
-
success &&= etag_matches?(none_match, headers) if none_match
-
success
-
end
-
-
2
def etag_matches?(none_match, headers)
-
etag = headers['ETag'] and etag == none_match
-
end
-
-
2
def modified_since?(modified_since, headers)
-
last_modified = to_rfc2822(headers['Last-Modified']) and
-
modified_since and
-
modified_since >= last_modified
-
end
-
-
2
def to_rfc2822(since)
-
Time.rfc2822(since) rescue nil
-
end
-
end
-
end
-
2
require 'digest/md5'
-
-
2
module Rack
-
# Automatically sets the ETag header on all String bodies.
-
#
-
# The ETag header is skipped if ETag or Last-Modified headers are sent or if
-
# a sendfile body (body.responds_to :to_path) is given (since such cases
-
# should be handled by apache/nginx).
-
#
-
# On initialization, you can pass two parameters: a Cache-Control directive
-
# used when Etag is absent and a directive when it is present. The first
-
# defaults to nil, while the second defaults to "max-age=0, private, must-revalidate"
-
2
class ETag
-
2
DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate".freeze
-
-
2
def initialize(app, no_cache_control = nil, cache_control = DEFAULT_CACHE_CONTROL)
-
2
@app = app
-
2
@cache_control = cache_control
-
2
@no_cache_control = no_cache_control
-
end
-
-
2
def call(env)
-
status, headers, body = @app.call(env)
-
-
if etag_status?(status) && etag_body?(body) && !skip_caching?(headers)
-
digest, body = digest_body(body)
-
headers['ETag'] = %("#{digest}") if digest
-
end
-
-
unless headers['Cache-Control']
-
if digest
-
headers['Cache-Control'] = @cache_control if @cache_control
-
else
-
headers['Cache-Control'] = @no_cache_control if @no_cache_control
-
end
-
end
-
-
[status, headers, body]
-
end
-
-
2
private
-
-
2
def etag_status?(status)
-
status == 200 || status == 201
-
end
-
-
2
def etag_body?(body)
-
!body.respond_to?(:to_path)
-
end
-
-
2
def skip_caching?(headers)
-
(headers['Cache-Control'] && headers['Cache-Control'].include?('no-cache')) ||
-
headers.key?('ETag') || headers.key?('Last-Modified')
-
end
-
-
2
def digest_body(body)
-
parts = []
-
body.each { |part| parts << part }
-
string_body = parts.join
-
digest = Digest::MD5.hexdigest(string_body) unless string_body.empty?
-
[digest, parts]
-
end
-
end
-
end
-
2
require 'time'
-
2
require 'rack/utils'
-
2
require 'rack/mime'
-
-
2
module Rack
-
# Rack::File serves files below the +root+ directory given, according to the
-
# path info of the Rack request.
-
# e.g. when Rack::File.new("/etc") is used, you can access 'passwd' file
-
# as http://localhost:9292/passwd
-
#
-
# Handlers can detect if bodies are a Rack::File, and use mechanisms
-
# like sendfile on the +path+.
-
-
2
class File
-
2
SEPS = Regexp.union(*[::File::SEPARATOR, ::File::ALT_SEPARATOR].compact)
-
2
ALLOWED_VERBS = %w[GET HEAD]
-
-
2
attr_accessor :root
-
2
attr_accessor :path
-
2
attr_accessor :cache_control
-
-
2
alias :to_path :path
-
-
2
def initialize(root, headers={})
-
2
@root = root
-
# Allow a cache_control string for backwards compatibility
-
2
if headers.instance_of? String
-
warn \
-
"Rack::File headers parameter replaces cache_control after Rack 1.5."
-
@headers = { 'Cache-Control' => headers }
-
else
-
2
@headers = headers
-
end
-
end
-
-
2
def call(env)
-
dup._call(env)
-
end
-
-
2
F = ::File
-
-
2
def _call(env)
-
unless ALLOWED_VERBS.include? env["REQUEST_METHOD"]
-
return fail(405, "Method Not Allowed")
-
end
-
-
@path_info = Utils.unescape(env["PATH_INFO"])
-
parts = @path_info.split SEPS
-
-
clean = []
-
-
parts.each do |part|
-
next if part.empty? || part == '.'
-
part == '..' ? clean.pop : clean << part
-
end
-
-
@path = F.join(@root, *clean)
-
-
available = begin
-
F.file?(@path) && F.readable?(@path)
-
rescue SystemCallError
-
false
-
end
-
-
if available
-
serving(env)
-
else
-
fail(404, "File not found: #{@path_info}")
-
end
-
end
-
-
2
def serving(env)
-
last_modified = F.mtime(@path).httpdate
-
return [304, {}, []] if env['HTTP_IF_MODIFIED_SINCE'] == last_modified
-
response = [
-
200,
-
{
-
"Last-Modified" => last_modified,
-
"Content-Type" => Mime.mime_type(F.extname(@path), 'text/plain')
-
},
-
env["REQUEST_METHOD"] == "HEAD" ? [] : self
-
]
-
-
# Set custom headers
-
@headers.each { |field, content| response[1][field] = content } if @headers
-
-
# NOTE:
-
# We check via File::size? whether this file provides size info
-
# via stat (e.g. /proc files often don't), otherwise we have to
-
# figure it out by reading the whole file into memory.
-
size = F.size?(@path) || Utils.bytesize(F.read(@path))
-
-
ranges = Rack::Utils.byte_ranges(env, size)
-
if ranges.nil? || ranges.length > 1
-
# No ranges, or multiple ranges (which we don't support):
-
# TODO: Support multiple byte-ranges
-
response[0] = 200
-
@range = 0..size-1
-
elsif ranges.empty?
-
# Unsatisfiable. Return error, and file size:
-
response = fail(416, "Byte range unsatisfiable")
-
response[1]["Content-Range"] = "bytes */#{size}"
-
return response
-
else
-
# Partial content:
-
@range = ranges[0]
-
response[0] = 206
-
response[1]["Content-Range"] = "bytes #{@range.begin}-#{@range.end}/#{size}"
-
size = @range.end - @range.begin + 1
-
end
-
-
response[1]["Content-Length"] = size.to_s
-
response
-
end
-
-
2
def each
-
F.open(@path, "rb") do |file|
-
file.seek(@range.begin)
-
remaining_len = @range.end-@range.begin+1
-
while remaining_len > 0
-
part = file.read([8192, remaining_len].min)
-
break unless part
-
remaining_len -= part.length
-
-
yield part
-
end
-
end
-
end
-
-
2
private
-
-
2
def fail(status, body)
-
body += "\n"
-
[
-
status,
-
{
-
"Content-Type" => "text/plain",
-
"Content-Length" => body.size.to_s,
-
"X-Cascade" => "pass"
-
},
-
[body]
-
]
-
end
-
-
end
-
end
-
2
require 'rack/utils'
-
-
2
module Rack
-
# Rack::Lint validates your application and the requests and
-
# responses according to the Rack spec.
-
-
2
class Lint
-
2
def initialize(app)
-
@app = app
-
@content_length = nil
-
end
-
-
# :stopdoc:
-
-
2
class LintError < RuntimeError; end
-
2
module Assertion
-
2
def assert(message, &block)
-
unless block.call
-
raise LintError, message
-
end
-
end
-
end
-
2
include Assertion
-
-
## This specification aims to formalize the Rack protocol. You
-
## can (and should) use Rack::Lint to enforce it.
-
##
-
## When you develop middleware, be sure to add a Lint before and
-
## after to catch all mistakes.
-
-
## = Rack applications
-
-
## A Rack application is a Ruby object (not a class) that
-
## responds to +call+.
-
2
def call(env=nil)
-
dup._call(env)
-
end
-
-
2
def _call(env)
-
## It takes exactly one argument, the *environment*
-
assert("No env given") { env }
-
check_env env
-
-
env['rack.input'] = InputWrapper.new(env['rack.input'])
-
env['rack.errors'] = ErrorWrapper.new(env['rack.errors'])
-
-
## and returns an Array of exactly three values:
-
status, headers, @body = @app.call(env)
-
## The *status*,
-
check_status status
-
## the *headers*,
-
check_headers headers
-
## and the *body*.
-
check_content_type status, headers
-
check_content_length status, headers
-
@head_request = env["REQUEST_METHOD"] == "HEAD"
-
[status, headers, self]
-
end
-
-
## == The Environment
-
2
def check_env(env)
-
## The environment must be an instance of Hash that includes
-
## CGI-like headers. The application is free to modify the
-
## environment.
-
assert("env #{env.inspect} is not a Hash, but #{env.class}") {
-
env.kind_of? Hash
-
}
-
-
##
-
## The environment is required to include these variables
-
## (adopted from PEP333), except when they'd be empty, but see
-
## below.
-
-
## <tt>REQUEST_METHOD</tt>:: The HTTP request method, such as
-
## "GET" or "POST". This cannot ever
-
## be an empty string, and so is
-
## always required.
-
-
## <tt>SCRIPT_NAME</tt>:: The initial portion of the request
-
## URL's "path" that corresponds to the
-
## application object, so that the
-
## application knows its virtual
-
## "location". This may be an empty
-
## string, if the application corresponds
-
## to the "root" of the server.
-
-
## <tt>PATH_INFO</tt>:: The remainder of the request URL's
-
## "path", designating the virtual
-
## "location" of the request's target
-
## within the application. This may be an
-
## empty string, if the request URL targets
-
## the application root and does not have a
-
## trailing slash. This value may be
-
## percent-encoded when I originating from
-
## a URL.
-
-
## <tt>QUERY_STRING</tt>:: The portion of the request URL that
-
## follows the <tt>?</tt>, if any. May be
-
## empty, but is always required!
-
-
## <tt>SERVER_NAME</tt>, <tt>SERVER_PORT</tt>:: When combined with <tt>SCRIPT_NAME</tt> and <tt>PATH_INFO</tt>, these variables can be used to complete the URL. Note, however, that <tt>HTTP_HOST</tt>, if present, should be used in preference to <tt>SERVER_NAME</tt> for reconstructing the request URL. <tt>SERVER_NAME</tt> and <tt>SERVER_PORT</tt> can never be empty strings, and so are always required.
-
-
## <tt>HTTP_</tt> Variables:: Variables corresponding to the
-
## client-supplied HTTP request
-
## headers (i.e., variables whose
-
## names begin with <tt>HTTP_</tt>). The
-
## presence or absence of these
-
## variables should correspond with
-
## the presence or absence of the
-
## appropriate HTTP header in the
-
## request.
-
-
## In addition to this, the Rack environment must include these
-
## Rack-specific variables:
-
-
## <tt>rack.version</tt>:: The Array [1,1], representing this version of Rack.
-
## <tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the request URL.
-
## <tt>rack.input</tt>:: See below, the input stream.
-
## <tt>rack.errors</tt>:: See below, the error stream.
-
## <tt>rack.multithread</tt>:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise.
-
## <tt>rack.multiprocess</tt>:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise.
-
## <tt>rack.run_once</tt>:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar).
-
##
-
-
## Additional environment specifications have approved to
-
## standardized middleware APIs. None of these are required to
-
## be implemented by the server.
-
-
## <tt>rack.session</tt>:: A hash like interface for storing request session data.
-
## The store must implement:
-
if session = env['rack.session']
-
## store(key, value) (aliased as []=);
-
assert("session #{session.inspect} must respond to store and []=") {
-
session.respond_to?(:store) && session.respond_to?(:[]=)
-
}
-
-
## fetch(key, default = nil) (aliased as []);
-
assert("session #{session.inspect} must respond to fetch and []") {
-
session.respond_to?(:fetch) && session.respond_to?(:[])
-
}
-
-
## delete(key);
-
assert("session #{session.inspect} must respond to delete") {
-
session.respond_to?(:delete)
-
}
-
-
## clear;
-
assert("session #{session.inspect} must respond to clear") {
-
session.respond_to?(:clear)
-
}
-
end
-
-
## <tt>rack.logger</tt>:: A common object interface for logging messages.
-
## The object must implement:
-
if logger = env['rack.logger']
-
## info(message, &block)
-
assert("logger #{logger.inspect} must respond to info") {
-
logger.respond_to?(:info)
-
}
-
-
## debug(message, &block)
-
assert("logger #{logger.inspect} must respond to debug") {
-
logger.respond_to?(:debug)
-
}
-
-
## warn(message, &block)
-
assert("logger #{logger.inspect} must respond to warn") {
-
logger.respond_to?(:warn)
-
}
-
-
## error(message, &block)
-
assert("logger #{logger.inspect} must respond to error") {
-
logger.respond_to?(:error)
-
}
-
-
## fatal(message, &block)
-
assert("logger #{logger.inspect} must respond to fatal") {
-
logger.respond_to?(:fatal)
-
}
-
end
-
-
## The server or the application can store their own data in the
-
## environment, too. The keys must contain at least one dot,
-
## and should be prefixed uniquely. The prefix <tt>rack.</tt>
-
## is reserved for use with the Rack core distribution and other
-
## accepted specifications and must not be used otherwise.
-
##
-
-
%w[REQUEST_METHOD SERVER_NAME SERVER_PORT
-
QUERY_STRING
-
rack.version rack.input rack.errors
-
rack.multithread rack.multiprocess rack.run_once].each { |header|
-
assert("env missing required key #{header}") { env.include? header }
-
}
-
-
## The environment must not contain the keys
-
## <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>
-
## (use the versions without <tt>HTTP_</tt>).
-
%w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header|
-
assert("env contains #{header}, must use #{header[5,-1]}") {
-
not env.include? header
-
}
-
}
-
-
## The CGI keys (named without a period) must have String values.
-
env.each { |key, value|
-
next if key.include? "." # Skip extensions
-
assert("env variable #{key} has non-string value #{value.inspect}") {
-
value.kind_of? String
-
}
-
}
-
-
##
-
## There are the following restrictions:
-
-
## * <tt>rack.version</tt> must be an array of Integers.
-
assert("rack.version must be an Array, was #{env["rack.version"].class}") {
-
env["rack.version"].kind_of? Array
-
}
-
## * <tt>rack.url_scheme</tt> must either be +http+ or +https+.
-
assert("rack.url_scheme unknown: #{env["rack.url_scheme"].inspect}") {
-
%w[http https].include? env["rack.url_scheme"]
-
}
-
-
## * There must be a valid input stream in <tt>rack.input</tt>.
-
check_input env["rack.input"]
-
## * There must be a valid error stream in <tt>rack.errors</tt>.
-
check_error env["rack.errors"]
-
-
## * The <tt>REQUEST_METHOD</tt> must be a valid token.
-
assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD"]}") {
-
env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
-
}
-
-
## * The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt>
-
assert("SCRIPT_NAME must start with /") {
-
!env.include?("SCRIPT_NAME") ||
-
env["SCRIPT_NAME"] == "" ||
-
env["SCRIPT_NAME"] =~ /\A\//
-
}
-
## * The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt>
-
assert("PATH_INFO must start with /") {
-
!env.include?("PATH_INFO") ||
-
env["PATH_INFO"] == "" ||
-
env["PATH_INFO"] =~ /\A\//
-
}
-
## * The <tt>CONTENT_LENGTH</tt>, if given, must consist of digits only.
-
assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") {
-
!env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/
-
}
-
-
## * One of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be
-
## set. <tt>PATH_INFO</tt> should be <tt>/</tt> if
-
## <tt>SCRIPT_NAME</tt> is empty.
-
assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") {
-
env["SCRIPT_NAME"] || env["PATH_INFO"]
-
}
-
## <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, but instead be empty.
-
assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") {
-
env["SCRIPT_NAME"] != "/"
-
}
-
end
-
-
## === The Input Stream
-
##
-
## The input stream is an IO-like object which contains the raw HTTP
-
## POST data.
-
2
def check_input(input)
-
## When applicable, its external encoding must be "ASCII-8BIT" and it
-
## must be opened in binary mode, for Ruby 1.9 compatibility.
-
assert("rack.input #{input} does not have ASCII-8BIT as its external encoding") {
-
input.external_encoding.name == "ASCII-8BIT"
-
} if input.respond_to?(:external_encoding)
-
assert("rack.input #{input} is not opened in binary mode") {
-
input.binmode?
-
} if input.respond_to?(:binmode?)
-
-
## The input stream must respond to +gets+, +each+, +read+ and +rewind+.
-
[:gets, :each, :read, :rewind].each { |method|
-
assert("rack.input #{input} does not respond to ##{method}") {
-
input.respond_to? method
-
}
-
}
-
end
-
-
2
class InputWrapper
-
2
include Assertion
-
-
2
def initialize(input)
-
@input = input
-
end
-
-
## * +gets+ must be called without arguments and return a string,
-
## or +nil+ on EOF.
-
2
def gets(*args)
-
assert("rack.input#gets called with arguments") { args.size == 0 }
-
v = @input.gets
-
assert("rack.input#gets didn't return a String") {
-
v.nil? or v.kind_of? String
-
}
-
v
-
end
-
-
## * +read+ behaves like IO#read. Its signature is <tt>read([length, [buffer]])</tt>.
-
## If given, +length+ must be a non-negative Integer (>= 0) or +nil+, and +buffer+ must
-
## be a String and may not be nil. If +length+ is given and not nil, then this method
-
## reads at most +length+ bytes from the input stream. If +length+ is not given or nil,
-
## then this method reads all data until EOF.
-
## When EOF is reached, this method returns nil if +length+ is given and not nil, or ""
-
## if +length+ is not given or is nil.
-
## If +buffer+ is given, then the read data will be placed into +buffer+ instead of a
-
## newly created String object.
-
2
def read(*args)
-
assert("rack.input#read called with too many arguments") {
-
args.size <= 2
-
}
-
if args.size >= 1
-
assert("rack.input#read called with non-integer and non-nil length") {
-
args.first.kind_of?(Integer) || args.first.nil?
-
}
-
assert("rack.input#read called with a negative length") {
-
args.first.nil? || args.first >= 0
-
}
-
end
-
if args.size >= 2
-
assert("rack.input#read called with non-String buffer") {
-
args[1].kind_of?(String)
-
}
-
end
-
-
v = @input.read(*args)
-
-
assert("rack.input#read didn't return nil or a String") {
-
v.nil? or v.kind_of? String
-
}
-
if args[0].nil?
-
assert("rack.input#read(nil) returned nil on EOF") {
-
!v.nil?
-
}
-
end
-
-
v
-
end
-
-
## * +each+ must be called without arguments and only yield Strings.
-
2
def each(*args)
-
assert("rack.input#each called with arguments") { args.size == 0 }
-
@input.each { |line|
-
assert("rack.input#each didn't yield a String") {
-
line.kind_of? String
-
}
-
yield line
-
}
-
end
-
-
## * +rewind+ must be called without arguments. It rewinds the input
-
## stream back to the beginning. It must not raise Errno::ESPIPE:
-
## that is, it may not be a pipe or a socket. Therefore, handler
-
## developers must buffer the input data into some rewindable object
-
## if the underlying input stream is not rewindable.
-
2
def rewind(*args)
-
assert("rack.input#rewind called with arguments") { args.size == 0 }
-
assert("rack.input#rewind raised Errno::ESPIPE") {
-
begin
-
@input.rewind
-
true
-
rescue Errno::ESPIPE
-
false
-
end
-
}
-
end
-
-
## * +close+ must never be called on the input stream.
-
2
def close(*args)
-
assert("rack.input#close must not be called") { false }
-
end
-
end
-
-
## === The Error Stream
-
2
def check_error(error)
-
## The error stream must respond to +puts+, +write+ and +flush+.
-
[:puts, :write, :flush].each { |method|
-
assert("rack.error #{error} does not respond to ##{method}") {
-
error.respond_to? method
-
}
-
}
-
end
-
-
2
class ErrorWrapper
-
2
include Assertion
-
-
2
def initialize(error)
-
@error = error
-
end
-
-
## * +puts+ must be called with a single argument that responds to +to_s+.
-
2
def puts(str)
-
@error.puts str
-
end
-
-
## * +write+ must be called with a single argument that is a String.
-
2
def write(str)
-
assert("rack.errors#write not called with a String") { str.kind_of? String }
-
@error.write str
-
end
-
-
## * +flush+ must be called without arguments and must be called
-
## in order to make the error appear for sure.
-
2
def flush
-
@error.flush
-
end
-
-
## * +close+ must never be called on the error stream.
-
2
def close(*args)
-
assert("rack.errors#close must not be called") { false }
-
end
-
end
-
-
## == The Response
-
-
## === The Status
-
2
def check_status(status)
-
## This is an HTTP status. When parsed as integer (+to_i+), it must be
-
## greater than or equal to 100.
-
assert("Status must be >=100 seen as integer") { status.to_i >= 100 }
-
end
-
-
## === The Headers
-
2
def check_headers(header)
-
## The header must respond to +each+, and yield values of key and value.
-
assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") {
-
header.respond_to? :each
-
}
-
header.each { |key, value|
-
## The header keys must be Strings.
-
assert("header key must be a string, was #{key.class}") {
-
key.kind_of? String
-
}
-
## The header must not contain a +Status+ key,
-
assert("header must not contain Status") { key.downcase != "status" }
-
## contain keys with <tt>:</tt> or newlines in their name,
-
assert("header names must not contain : or \\n") { key !~ /[:\n]/ }
-
## contain keys names that end in <tt>-</tt> or <tt>_</tt>,
-
assert("header names must not end in - or _") { key !~ /[-_]\z/ }
-
## but only contain keys that consist of
-
## letters, digits, <tt>_</tt> or <tt>-</tt> and start with a letter.
-
assert("invalid header name: #{key}") { key =~ /\A[a-zA-Z][a-zA-Z0-9_-]*\z/ }
-
-
## The values of the header must be Strings,
-
assert("a header value must be a String, but the value of " +
-
"'#{key}' is a #{value.class}") { value.kind_of? String }
-
## consisting of lines (for multiple header values, e.g. multiple
-
## <tt>Set-Cookie</tt> values) seperated by "\n".
-
value.split("\n").each { |item|
-
## The lines must not contain characters below 037.
-
assert("invalid header value #{key}: #{item.inspect}") {
-
item !~ /[\000-\037]/
-
}
-
}
-
}
-
end
-
-
## === The Content-Type
-
2
def check_content_type(status, headers)
-
headers.each { |key, value|
-
## There must be a <tt>Content-Type</tt>, except when the
-
## +Status+ is 1xx, 204, 205 or 304, in which case there must be none
-
## given.
-
if key.downcase == "content-type"
-
assert("Content-Type header found in #{status} response, not allowed") {
-
not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
-
}
-
return
-
end
-
}
-
assert("No Content-Type header found") {
-
Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
-
}
-
end
-
-
## === The Content-Length
-
2
def check_content_length(status, headers)
-
headers.each { |key, value|
-
if key.downcase == 'content-length'
-
## There must not be a <tt>Content-Length</tt> header when the
-
## +Status+ is 1xx, 204, 205 or 304.
-
assert("Content-Length header found in #{status} response, not allowed") {
-
not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i
-
}
-
@content_length = value
-
end
-
}
-
end
-
-
2
def verify_content_length(bytes)
-
if @head_request
-
assert("Response body was given for HEAD request, but should be empty") {
-
bytes == 0
-
}
-
elsif @content_length
-
assert("Content-Length header was #{@content_length}, but should be #{bytes}") {
-
@content_length == bytes.to_s
-
}
-
end
-
end
-
-
## === The Body
-
2
def each
-
@closed = false
-
bytes = 0
-
-
## The Body must respond to +each+
-
assert("Response body must respond to each") do
-
@body.respond_to?(:each)
-
end
-
-
@body.each { |part|
-
## and must only yield String values.
-
assert("Body yielded non-string value #{part.inspect}") {
-
part.kind_of? String
-
}
-
bytes += Rack::Utils.bytesize(part)
-
yield part
-
}
-
verify_content_length(bytes)
-
-
##
-
## The Body itself should not be an instance of String, as this will
-
## break in Ruby 1.9.
-
##
-
## If the Body responds to +close+, it will be called after iteration. If
-
## the body is replaced by a middleware after action, the original body
-
## must be closed first, if it repsonds to close.
-
# XXX howto: assert("Body has not been closed") { @closed }
-
-
-
##
-
## If the Body responds to +to_path+, it must return a String
-
## identifying the location of a file whose contents are identical
-
## to that produced by calling +each+; this may be used by the
-
## server as an alternative, possibly more efficient way to
-
## transport the response.
-
-
if @body.respond_to?(:to_path)
-
assert("The file identified by body.to_path does not exist") {
-
::File.exist? @body.to_path
-
}
-
end
-
-
##
-
## The Body commonly is an Array of Strings, the application
-
## instance itself, or a File-like object.
-
end
-
-
2
def close
-
@closed = true
-
@body.close if @body.respond_to?(:close)
-
end
-
-
# :startdoc:
-
-
end
-
end
-
-
## == Thanks
-
## Some parts of this specification are adopted from PEP333: Python
-
## Web Server Gateway Interface
-
## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank
-
## everyone involved in that effort.
-
2
require 'thread'
-
2
require 'rack/body_proxy'
-
-
2
module Rack
-
2
class Lock
-
2
FLAG = 'rack.multithread'.freeze
-
-
2
def initialize(app, mutex = Mutex.new)
-
2
@app, @mutex = app, mutex
-
end
-
-
2
def call(env)
-
old, env[FLAG] = env[FLAG], false
-
@mutex.lock
-
response = @app.call(env)
-
body = BodyProxy.new(response[2]) { @mutex.unlock }
-
response[2] = body
-
response
-
ensure
-
@mutex.unlock unless body
-
env[FLAG] = old
-
end
-
end
-
end
-
2
module Rack
-
2
class MethodOverride
-
2
HTTP_METHODS = %w(GET HEAD PUT POST DELETE OPTIONS PATCH)
-
-
2
METHOD_OVERRIDE_PARAM_KEY = "_method".freeze
-
2
HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE".freeze
-
-
2
def initialize(app)
-
2
@app = app
-
end
-
-
2
def call(env)
-
if env["REQUEST_METHOD"] == "POST"
-
method = method_override(env)
-
if HTTP_METHODS.include?(method)
-
env["rack.methodoverride.original_method"] = env["REQUEST_METHOD"]
-
env["REQUEST_METHOD"] = method
-
end
-
end
-
-
@app.call(env)
-
end
-
-
2
def method_override(env)
-
req = Request.new(env)
-
method = req.POST[METHOD_OVERRIDE_PARAM_KEY] ||
-
env[HTTP_METHOD_OVERRIDE_HEADER]
-
method.to_s.upcase
-
rescue EOFError
-
""
-
end
-
end
-
end
-
2
module Rack
-
2
module Mime
-
# Returns String with mime type if found, otherwise use +fallback+.
-
# +ext+ should be filename extension in the '.ext' format that
-
# File.extname(file) returns.
-
# +fallback+ may be any object
-
#
-
# Also see the documentation for MIME_TYPES
-
#
-
# Usage:
-
# Rack::Mime.mime_type('.foo')
-
#
-
# This is a shortcut for:
-
# Rack::Mime::MIME_TYPES.fetch('.foo', 'application/octet-stream')
-
-
2
def mime_type(ext, fallback='application/octet-stream')
-
MIME_TYPES.fetch(ext.to_s.downcase, fallback)
-
end
-
2
module_function :mime_type
-
-
# List of most common mime-types, selected various sources
-
# according to their usefulness in a webserving scope for Ruby
-
# users.
-
#
-
# To amend this list with your local mime.types list you can use:
-
#
-
# require 'webrick/httputils'
-
# list = WEBrick::HTTPUtils.load_mime_types('/etc/mime.types')
-
# Rack::Mime::MIME_TYPES.merge!(list)
-
#
-
# N.B. On Ubuntu the mime.types file does not include the leading period, so
-
# users may need to modify the data before merging into the hash.
-
#
-
# To add the list mongrel provides, use:
-
#
-
# require 'mongrel/handlers'
-
# Rack::Mime::MIME_TYPES.merge!(Mongrel::DirHandler::MIME_TYPES)
-
-
2
MIME_TYPES = {
-
".123" => "application/vnd.lotus-1-2-3",
-
".3dml" => "text/vnd.in3d.3dml",
-
".3g2" => "video/3gpp2",
-
".3gp" => "video/3gpp",
-
".a" => "application/octet-stream",
-
".acc" => "application/vnd.americandynamics.acc",
-
".ace" => "application/x-ace-compressed",
-
".acu" => "application/vnd.acucobol",
-
".aep" => "application/vnd.audiograph",
-
".afp" => "application/vnd.ibm.modcap",
-
".ai" => "application/postscript",
-
".aif" => "audio/x-aiff",
-
".aiff" => "audio/x-aiff",
-
".ami" => "application/vnd.amiga.ami",
-
".appcache" => "text/cache-manifest",
-
".apr" => "application/vnd.lotus-approach",
-
".asc" => "application/pgp-signature",
-
".asf" => "video/x-ms-asf",
-
".asm" => "text/x-asm",
-
".aso" => "application/vnd.accpac.simply.aso",
-
".asx" => "video/x-ms-asf",
-
".atc" => "application/vnd.acucorp",
-
".atom" => "application/atom+xml",
-
".atomcat" => "application/atomcat+xml",
-
".atomsvc" => "application/atomsvc+xml",
-
".atx" => "application/vnd.antix.game-component",
-
".au" => "audio/basic",
-
".avi" => "video/x-msvideo",
-
".bat" => "application/x-msdownload",
-
".bcpio" => "application/x-bcpio",
-
".bdm" => "application/vnd.syncml.dm+wbxml",
-
".bh2" => "application/vnd.fujitsu.oasysprs",
-
".bin" => "application/octet-stream",
-
".bmi" => "application/vnd.bmi",
-
".bmp" => "image/bmp",
-
".box" => "application/vnd.previewsystems.box",
-
".btif" => "image/prs.btif",
-
".bz" => "application/x-bzip",
-
".bz2" => "application/x-bzip2",
-
".c" => "text/x-c",
-
".c4g" => "application/vnd.clonk.c4group",
-
".cab" => "application/vnd.ms-cab-compressed",
-
".cc" => "text/x-c",
-
".ccxml" => "application/ccxml+xml",
-
".cdbcmsg" => "application/vnd.contact.cmsg",
-
".cdkey" => "application/vnd.mediastation.cdkey",
-
".cdx" => "chemical/x-cdx",
-
".cdxml" => "application/vnd.chemdraw+xml",
-
".cdy" => "application/vnd.cinderella",
-
".cer" => "application/pkix-cert",
-
".cgm" => "image/cgm",
-
".chat" => "application/x-chat",
-
".chm" => "application/vnd.ms-htmlhelp",
-
".chrt" => "application/vnd.kde.kchart",
-
".cif" => "chemical/x-cif",
-
".cii" => "application/vnd.anser-web-certificate-issue-initiation",
-
".cil" => "application/vnd.ms-artgalry",
-
".cla" => "application/vnd.claymore",
-
".class" => "application/octet-stream",
-
".clkk" => "application/vnd.crick.clicker.keyboard",
-
".clkp" => "application/vnd.crick.clicker.palette",
-
".clkt" => "application/vnd.crick.clicker.template",
-
".clkw" => "application/vnd.crick.clicker.wordbank",
-
".clkx" => "application/vnd.crick.clicker",
-
".clp" => "application/x-msclip",
-
".cmc" => "application/vnd.cosmocaller",
-
".cmdf" => "chemical/x-cmdf",
-
".cml" => "chemical/x-cml",
-
".cmp" => "application/vnd.yellowriver-custom-menu",
-
".cmx" => "image/x-cmx",
-
".com" => "application/x-msdownload",
-
".conf" => "text/plain",
-
".cpio" => "application/x-cpio",
-
".cpp" => "text/x-c",
-
".cpt" => "application/mac-compactpro",
-
".crd" => "application/x-mscardfile",
-
".crl" => "application/pkix-crl",
-
".crt" => "application/x-x509-ca-cert",
-
".csh" => "application/x-csh",
-
".csml" => "chemical/x-csml",
-
".csp" => "application/vnd.commonspace",
-
".css" => "text/css",
-
".csv" => "text/csv",
-
".curl" => "application/vnd.curl",
-
".cww" => "application/prs.cww",
-
".cxx" => "text/x-c",
-
".daf" => "application/vnd.mobius.daf",
-
".davmount" => "application/davmount+xml",
-
".dcr" => "application/x-director",
-
".dd2" => "application/vnd.oma.dd2+xml",
-
".ddd" => "application/vnd.fujixerox.ddd",
-
".deb" => "application/x-debian-package",
-
".der" => "application/x-x509-ca-cert",
-
".dfac" => "application/vnd.dreamfactory",
-
".diff" => "text/x-diff",
-
".dis" => "application/vnd.mobius.dis",
-
".djv" => "image/vnd.djvu",
-
".djvu" => "image/vnd.djvu",
-
".dll" => "application/x-msdownload",
-
".dmg" => "application/octet-stream",
-
".dna" => "application/vnd.dna",
-
".doc" => "application/msword",
-
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
-
".dot" => "application/msword",
-
".dp" => "application/vnd.osgi.dp",
-
".dpg" => "application/vnd.dpgraph",
-
".dsc" => "text/prs.lines.tag",
-
".dtd" => "application/xml-dtd",
-
".dts" => "audio/vnd.dts",
-
".dtshd" => "audio/vnd.dts.hd",
-
".dv" => "video/x-dv",
-
".dvi" => "application/x-dvi",
-
".dwf" => "model/vnd.dwf",
-
".dwg" => "image/vnd.dwg",
-
".dxf" => "image/vnd.dxf",
-
".dxp" => "application/vnd.spotfire.dxp",
-
".ear" => "application/java-archive",
-
".ecelp4800" => "audio/vnd.nuera.ecelp4800",
-
".ecelp7470" => "audio/vnd.nuera.ecelp7470",
-
".ecelp9600" => "audio/vnd.nuera.ecelp9600",
-
".ecma" => "application/ecmascript",
-
".edm" => "application/vnd.novadigm.edm",
-
".edx" => "application/vnd.novadigm.edx",
-
".efif" => "application/vnd.picsel",
-
".ei6" => "application/vnd.pg.osasli",
-
".eml" => "message/rfc822",
-
".eol" => "audio/vnd.digital-winds",
-
".eot" => "application/vnd.ms-fontobject",
-
".eps" => "application/postscript",
-
".es3" => "application/vnd.eszigno3+xml",
-
".esf" => "application/vnd.epson.esf",
-
".etx" => "text/x-setext",
-
".exe" => "application/x-msdownload",
-
".ext" => "application/vnd.novadigm.ext",
-
".ez" => "application/andrew-inset",
-
".ez2" => "application/vnd.ezpix-album",
-
".ez3" => "application/vnd.ezpix-package",
-
".f" => "text/x-fortran",
-
".f77" => "text/x-fortran",
-
".f90" => "text/x-fortran",
-
".fbs" => "image/vnd.fastbidsheet",
-
".fdf" => "application/vnd.fdf",
-
".fe_launch" => "application/vnd.denovo.fcselayout-link",
-
".fg5" => "application/vnd.fujitsu.oasysgp",
-
".fli" => "video/x-fli",
-
".flo" => "application/vnd.micrografx.flo",
-
".flv" => "video/x-flv",
-
".flw" => "application/vnd.kde.kivio",
-
".flx" => "text/vnd.fmi.flexstor",
-
".fly" => "text/vnd.fly",
-
".fm" => "application/vnd.framemaker",
-
".fnc" => "application/vnd.frogans.fnc",
-
".for" => "text/x-fortran",
-
".fpx" => "image/vnd.fpx",
-
".fsc" => "application/vnd.fsc.weblaunch",
-
".fst" => "image/vnd.fst",
-
".ftc" => "application/vnd.fluxtime.clip",
-
".fti" => "application/vnd.anser-web-funds-transfer-initiation",
-
".fvt" => "video/vnd.fvt",
-
".fzs" => "application/vnd.fuzzysheet",
-
".g3" => "image/g3fax",
-
".gac" => "application/vnd.groove-account",
-
".gdl" => "model/vnd.gdl",
-
".gem" => "application/octet-stream",
-
".gemspec" => "text/x-script.ruby",
-
".ghf" => "application/vnd.groove-help",
-
".gif" => "image/gif",
-
".gim" => "application/vnd.groove-identity-message",
-
".gmx" => "application/vnd.gmx",
-
".gph" => "application/vnd.flographit",
-
".gqf" => "application/vnd.grafeq",
-
".gram" => "application/srgs",
-
".grv" => "application/vnd.groove-injector",
-
".grxml" => "application/srgs+xml",
-
".gtar" => "application/x-gtar",
-
".gtm" => "application/vnd.groove-tool-message",
-
".gtw" => "model/vnd.gtw",
-
".gv" => "text/vnd.graphviz",
-
".gz" => "application/x-gzip",
-
".h" => "text/x-c",
-
".h261" => "video/h261",
-
".h263" => "video/h263",
-
".h264" => "video/h264",
-
".hbci" => "application/vnd.hbci",
-
".hdf" => "application/x-hdf",
-
".hh" => "text/x-c",
-
".hlp" => "application/winhlp",
-
".hpgl" => "application/vnd.hp-hpgl",
-
".hpid" => "application/vnd.hp-hpid",
-
".hps" => "application/vnd.hp-hps",
-
".hqx" => "application/mac-binhex40",
-
".htc" => "text/x-component",
-
".htke" => "application/vnd.kenameaapp",
-
".htm" => "text/html",
-
".html" => "text/html",
-
".hvd" => "application/vnd.yamaha.hv-dic",
-
".hvp" => "application/vnd.yamaha.hv-voice",
-
".hvs" => "application/vnd.yamaha.hv-script",
-
".icc" => "application/vnd.iccprofile",
-
".ice" => "x-conference/x-cooltalk",
-
".ico" => "image/vnd.microsoft.icon",
-
".ics" => "text/calendar",
-
".ief" => "image/ief",
-
".ifb" => "text/calendar",
-
".ifm" => "application/vnd.shana.informed.formdata",
-
".igl" => "application/vnd.igloader",
-
".igs" => "model/iges",
-
".igx" => "application/vnd.micrografx.igx",
-
".iif" => "application/vnd.shana.informed.interchange",
-
".imp" => "application/vnd.accpac.simply.imp",
-
".ims" => "application/vnd.ms-ims",
-
".ipk" => "application/vnd.shana.informed.package",
-
".irm" => "application/vnd.ibm.rights-management",
-
".irp" => "application/vnd.irepository.package+xml",
-
".iso" => "application/octet-stream",
-
".itp" => "application/vnd.shana.informed.formtemplate",
-
".ivp" => "application/vnd.immervision-ivp",
-
".ivu" => "application/vnd.immervision-ivu",
-
".jad" => "text/vnd.sun.j2me.app-descriptor",
-
".jam" => "application/vnd.jam",
-
".jar" => "application/java-archive",
-
".java" => "text/x-java-source",
-
".jisp" => "application/vnd.jisp",
-
".jlt" => "application/vnd.hp-jlyt",
-
".jnlp" => "application/x-java-jnlp-file",
-
".joda" => "application/vnd.joost.joda-archive",
-
".jp2" => "image/jp2",
-
".jpeg" => "image/jpeg",
-
".jpg" => "image/jpeg",
-
".jpgv" => "video/jpeg",
-
".jpm" => "video/jpm",
-
".js" => "application/javascript",
-
".json" => "application/json",
-
".karbon" => "application/vnd.kde.karbon",
-
".kfo" => "application/vnd.kde.kformula",
-
".kia" => "application/vnd.kidspiration",
-
".kml" => "application/vnd.google-earth.kml+xml",
-
".kmz" => "application/vnd.google-earth.kmz",
-
".kne" => "application/vnd.kinar",
-
".kon" => "application/vnd.kde.kontour",
-
".kpr" => "application/vnd.kde.kpresenter",
-
".ksp" => "application/vnd.kde.kspread",
-
".ktz" => "application/vnd.kahootz",
-
".kwd" => "application/vnd.kde.kword",
-
".latex" => "application/x-latex",
-
".lbd" => "application/vnd.llamagraphics.life-balance.desktop",
-
".lbe" => "application/vnd.llamagraphics.life-balance.exchange+xml",
-
".les" => "application/vnd.hhe.lesson-player",
-
".link66" => "application/vnd.route66.link66+xml",
-
".log" => "text/plain",
-
".lostxml" => "application/lost+xml",
-
".lrm" => "application/vnd.ms-lrm",
-
".ltf" => "application/vnd.frogans.ltf",
-
".lvp" => "audio/vnd.lucent.voice",
-
".lwp" => "application/vnd.lotus-wordpro",
-
".m3u" => "audio/x-mpegurl",
-
".m4a" => "audio/mp4a-latm",
-
".m4v" => "video/mp4",
-
".ma" => "application/mathematica",
-
".mag" => "application/vnd.ecowin.chart",
-
".man" => "text/troff",
-
".manifest" => "text/cache-manifest",
-
".mathml" => "application/mathml+xml",
-
".mbk" => "application/vnd.mobius.mbk",
-
".mbox" => "application/mbox",
-
".mc1" => "application/vnd.medcalcdata",
-
".mcd" => "application/vnd.mcd",
-
".mdb" => "application/x-msaccess",
-
".mdi" => "image/vnd.ms-modi",
-
".mdoc" => "text/troff",
-
".me" => "text/troff",
-
".mfm" => "application/vnd.mfmp",
-
".mgz" => "application/vnd.proteus.magazine",
-
".mid" => "audio/midi",
-
".midi" => "audio/midi",
-
".mif" => "application/vnd.mif",
-
".mime" => "message/rfc822",
-
".mj2" => "video/mj2",
-
".mlp" => "application/vnd.dolby.mlp",
-
".mmd" => "application/vnd.chipnuts.karaoke-mmd",
-
".mmf" => "application/vnd.smaf",
-
".mml" => "application/mathml+xml",
-
".mmr" => "image/vnd.fujixerox.edmics-mmr",
-
".mng" => "video/x-mng",
-
".mny" => "application/x-msmoney",
-
".mov" => "video/quicktime",
-
".movie" => "video/x-sgi-movie",
-
".mp3" => "audio/mpeg",
-
".mp4" => "video/mp4",
-
".mp4a" => "audio/mp4",
-
".mp4s" => "application/mp4",
-
".mp4v" => "video/mp4",
-
".mpc" => "application/vnd.mophun.certificate",
-
".mpeg" => "video/mpeg",
-
".mpg" => "video/mpeg",
-
".mpga" => "audio/mpeg",
-
".mpkg" => "application/vnd.apple.installer+xml",
-
".mpm" => "application/vnd.blueice.multipass",
-
".mpn" => "application/vnd.mophun.application",
-
".mpp" => "application/vnd.ms-project",
-
".mpy" => "application/vnd.ibm.minipay",
-
".mqy" => "application/vnd.mobius.mqy",
-
".mrc" => "application/marc",
-
".ms" => "text/troff",
-
".mscml" => "application/mediaservercontrol+xml",
-
".mseq" => "application/vnd.mseq",
-
".msf" => "application/vnd.epson.msf",
-
".msh" => "model/mesh",
-
".msi" => "application/x-msdownload",
-
".msl" => "application/vnd.mobius.msl",
-
".msty" => "application/vnd.muvee.style",
-
".mts" => "model/vnd.mts",
-
".mus" => "application/vnd.musician",
-
".mvb" => "application/x-msmediaview",
-
".mwf" => "application/vnd.mfer",
-
".mxf" => "application/mxf",
-
".mxl" => "application/vnd.recordare.musicxml",
-
".mxml" => "application/xv+xml",
-
".mxs" => "application/vnd.triscape.mxs",
-
".mxu" => "video/vnd.mpegurl",
-
".n" => "application/vnd.nokia.n-gage.symbian.install",
-
".nc" => "application/x-netcdf",
-
".ngdat" => "application/vnd.nokia.n-gage.data",
-
".nlu" => "application/vnd.neurolanguage.nlu",
-
".nml" => "application/vnd.enliven",
-
".nnd" => "application/vnd.noblenet-directory",
-
".nns" => "application/vnd.noblenet-sealer",
-
".nnw" => "application/vnd.noblenet-web",
-
".npx" => "image/vnd.net-fpx",
-
".nsf" => "application/vnd.lotus-notes",
-
".oa2" => "application/vnd.fujitsu.oasys2",
-
".oa3" => "application/vnd.fujitsu.oasys3",
-
".oas" => "application/vnd.fujitsu.oasys",
-
".obd" => "application/x-msbinder",
-
".oda" => "application/oda",
-
".odc" => "application/vnd.oasis.opendocument.chart",
-
".odf" => "application/vnd.oasis.opendocument.formula",
-
".odg" => "application/vnd.oasis.opendocument.graphics",
-
".odi" => "application/vnd.oasis.opendocument.image",
-
".odp" => "application/vnd.oasis.opendocument.presentation",
-
".ods" => "application/vnd.oasis.opendocument.spreadsheet",
-
".odt" => "application/vnd.oasis.opendocument.text",
-
".oga" => "audio/ogg",
-
".ogg" => "application/ogg",
-
".ogv" => "video/ogg",
-
".ogx" => "application/ogg",
-
".org" => "application/vnd.lotus-organizer",
-
".otc" => "application/vnd.oasis.opendocument.chart-template",
-
".otf" => "application/vnd.oasis.opendocument.formula-template",
-
".otg" => "application/vnd.oasis.opendocument.graphics-template",
-
".oth" => "application/vnd.oasis.opendocument.text-web",
-
".oti" => "application/vnd.oasis.opendocument.image-template",
-
".otm" => "application/vnd.oasis.opendocument.text-master",
-
".ots" => "application/vnd.oasis.opendocument.spreadsheet-template",
-
".ott" => "application/vnd.oasis.opendocument.text-template",
-
".oxt" => "application/vnd.openofficeorg.extension",
-
".p" => "text/x-pascal",
-
".p10" => "application/pkcs10",
-
".p12" => "application/x-pkcs12",
-
".p7b" => "application/x-pkcs7-certificates",
-
".p7m" => "application/pkcs7-mime",
-
".p7r" => "application/x-pkcs7-certreqresp",
-
".p7s" => "application/pkcs7-signature",
-
".pas" => "text/x-pascal",
-
".pbd" => "application/vnd.powerbuilder6",
-
".pbm" => "image/x-portable-bitmap",
-
".pcl" => "application/vnd.hp-pcl",
-
".pclxl" => "application/vnd.hp-pclxl",
-
".pcx" => "image/x-pcx",
-
".pdb" => "chemical/x-pdb",
-
".pdf" => "application/pdf",
-
".pem" => "application/x-x509-ca-cert",
-
".pfr" => "application/font-tdpfr",
-
".pgm" => "image/x-portable-graymap",
-
".pgn" => "application/x-chess-pgn",
-
".pgp" => "application/pgp-encrypted",
-
".pic" => "image/x-pict",
-
".pict" => "image/pict",
-
".pkg" => "application/octet-stream",
-
".pki" => "application/pkixcmp",
-
".pkipath" => "application/pkix-pkipath",
-
".pl" => "text/x-script.perl",
-
".plb" => "application/vnd.3gpp.pic-bw-large",
-
".plc" => "application/vnd.mobius.plc",
-
".plf" => "application/vnd.pocketlearn",
-
".pls" => "application/pls+xml",
-
".pm" => "text/x-script.perl-module",
-
".pml" => "application/vnd.ctc-posml",
-
".png" => "image/png",
-
".pnm" => "image/x-portable-anymap",
-
".pntg" => "image/x-macpaint",
-
".portpkg" => "application/vnd.macports.portpkg",
-
".ppd" => "application/vnd.cups-ppd",
-
".ppm" => "image/x-portable-pixmap",
-
".pps" => "application/vnd.ms-powerpoint",
-
".ppt" => "application/vnd.ms-powerpoint",
-
".prc" => "application/vnd.palm",
-
".pre" => "application/vnd.lotus-freelance",
-
".prf" => "application/pics-rules",
-
".ps" => "application/postscript",
-
".psb" => "application/vnd.3gpp.pic-bw-small",
-
".psd" => "image/vnd.adobe.photoshop",
-
".ptid" => "application/vnd.pvi.ptid1",
-
".pub" => "application/x-mspublisher",
-
".pvb" => "application/vnd.3gpp.pic-bw-var",
-
".pwn" => "application/vnd.3m.post-it-notes",
-
".py" => "text/x-script.python",
-
".pya" => "audio/vnd.ms-playready.media.pya",
-
".pyv" => "video/vnd.ms-playready.media.pyv",
-
".qam" => "application/vnd.epson.quickanime",
-
".qbo" => "application/vnd.intu.qbo",
-
".qfx" => "application/vnd.intu.qfx",
-
".qps" => "application/vnd.publishare-delta-tree",
-
".qt" => "video/quicktime",
-
".qtif" => "image/x-quicktime",
-
".qxd" => "application/vnd.quark.quarkxpress",
-
".ra" => "audio/x-pn-realaudio",
-
".rake" => "text/x-script.ruby",
-
".ram" => "audio/x-pn-realaudio",
-
".rar" => "application/x-rar-compressed",
-
".ras" => "image/x-cmu-raster",
-
".rb" => "text/x-script.ruby",
-
".rcprofile" => "application/vnd.ipunplugged.rcprofile",
-
".rdf" => "application/rdf+xml",
-
".rdz" => "application/vnd.data-vision.rdz",
-
".rep" => "application/vnd.businessobjects",
-
".rgb" => "image/x-rgb",
-
".rif" => "application/reginfo+xml",
-
".rl" => "application/resource-lists+xml",
-
".rlc" => "image/vnd.fujixerox.edmics-rlc",
-
".rld" => "application/resource-lists-diff+xml",
-
".rm" => "application/vnd.rn-realmedia",
-
".rmp" => "audio/x-pn-realaudio-plugin",
-
".rms" => "application/vnd.jcp.javame.midlet-rms",
-
".rnc" => "application/relax-ng-compact-syntax",
-
".roff" => "text/troff",
-
".rpm" => "application/x-redhat-package-manager",
-
".rpss" => "application/vnd.nokia.radio-presets",
-
".rpst" => "application/vnd.nokia.radio-preset",
-
".rq" => "application/sparql-query",
-
".rs" => "application/rls-services+xml",
-
".rsd" => "application/rsd+xml",
-
".rss" => "application/rss+xml",
-
".rtf" => "application/rtf",
-
".rtx" => "text/richtext",
-
".ru" => "text/x-script.ruby",
-
".s" => "text/x-asm",
-
".saf" => "application/vnd.yamaha.smaf-audio",
-
".sbml" => "application/sbml+xml",
-
".sc" => "application/vnd.ibm.secure-container",
-
".scd" => "application/x-msschedule",
-
".scm" => "application/vnd.lotus-screencam",
-
".scq" => "application/scvp-cv-request",
-
".scs" => "application/scvp-cv-response",
-
".sdkm" => "application/vnd.solent.sdkm+xml",
-
".sdp" => "application/sdp",
-
".see" => "application/vnd.seemail",
-
".sema" => "application/vnd.sema",
-
".semd" => "application/vnd.semd",
-
".semf" => "application/vnd.semf",
-
".setpay" => "application/set-payment-initiation",
-
".setreg" => "application/set-registration-initiation",
-
".sfd" => "application/vnd.hydrostatix.sof-data",
-
".sfs" => "application/vnd.spotfire.sfs",
-
".sgm" => "text/sgml",
-
".sgml" => "text/sgml",
-
".sh" => "application/x-sh",
-
".shar" => "application/x-shar",
-
".shf" => "application/shf+xml",
-
".sig" => "application/pgp-signature",
-
".sit" => "application/x-stuffit",
-
".sitx" => "application/x-stuffitx",
-
".skp" => "application/vnd.koan",
-
".slt" => "application/vnd.epson.salt",
-
".smi" => "application/smil+xml",
-
".snd" => "audio/basic",
-
".so" => "application/octet-stream",
-
".spf" => "application/vnd.yamaha.smaf-phrase",
-
".spl" => "application/x-futuresplash",
-
".spot" => "text/vnd.in3d.spot",
-
".spp" => "application/scvp-vp-response",
-
".spq" => "application/scvp-vp-request",
-
".src" => "application/x-wais-source",
-
".srx" => "application/sparql-results+xml",
-
".sse" => "application/vnd.kodak-descriptor",
-
".ssf" => "application/vnd.epson.ssf",
-
".ssml" => "application/ssml+xml",
-
".stf" => "application/vnd.wt.stf",
-
".stk" => "application/hyperstudio",
-
".str" => "application/vnd.pg.format",
-
".sus" => "application/vnd.sus-calendar",
-
".sv4cpio" => "application/x-sv4cpio",
-
".sv4crc" => "application/x-sv4crc",
-
".svd" => "application/vnd.svd",
-
".svg" => "image/svg+xml",
-
".svgz" => "image/svg+xml",
-
".swf" => "application/x-shockwave-flash",
-
".swi" => "application/vnd.arastra.swi",
-
".t" => "text/troff",
-
".tao" => "application/vnd.tao.intent-module-archive",
-
".tar" => "application/x-tar",
-
".tbz" => "application/x-bzip-compressed-tar",
-
".tcap" => "application/vnd.3gpp2.tcap",
-
".tcl" => "application/x-tcl",
-
".tex" => "application/x-tex",
-
".texi" => "application/x-texinfo",
-
".texinfo" => "application/x-texinfo",
-
".text" => "text/plain",
-
".tif" => "image/tiff",
-
".tiff" => "image/tiff",
-
".tmo" => "application/vnd.tmobile-livetv",
-
".torrent" => "application/x-bittorrent",
-
".tpl" => "application/vnd.groove-tool-template",
-
".tpt" => "application/vnd.trid.tpt",
-
".tr" => "text/troff",
-
".tra" => "application/vnd.trueapp",
-
".trm" => "application/x-msterminal",
-
".tsv" => "text/tab-separated-values",
-
".ttf" => "application/octet-stream",
-
".twd" => "application/vnd.simtech-mindmapper",
-
".txd" => "application/vnd.genomatix.tuxedo",
-
".txf" => "application/vnd.mobius.txf",
-
".txt" => "text/plain",
-
".ufd" => "application/vnd.ufdl",
-
".umj" => "application/vnd.umajin",
-
".unityweb" => "application/vnd.unity",
-
".uoml" => "application/vnd.uoml+xml",
-
".uri" => "text/uri-list",
-
".ustar" => "application/x-ustar",
-
".utz" => "application/vnd.uiq.theme",
-
".uu" => "text/x-uuencode",
-
".vcd" => "application/x-cdlink",
-
".vcf" => "text/x-vcard",
-
".vcg" => "application/vnd.groove-vcard",
-
".vcs" => "text/x-vcalendar",
-
".vcx" => "application/vnd.vcx",
-
".vis" => "application/vnd.visionary",
-
".viv" => "video/vnd.vivo",
-
".vrml" => "model/vrml",
-
".vsd" => "application/vnd.visio",
-
".vsf" => "application/vnd.vsf",
-
".vtu" => "model/vnd.vtu",
-
".vxml" => "application/voicexml+xml",
-
".war" => "application/java-archive",
-
".wav" => "audio/x-wav",
-
".wax" => "audio/x-ms-wax",
-
".wbmp" => "image/vnd.wap.wbmp",
-
".wbs" => "application/vnd.criticaltools.wbs+xml",
-
".wbxml" => "application/vnd.wap.wbxml",
-
".webm" => "video/webm",
-
".wm" => "video/x-ms-wm",
-
".wma" => "audio/x-ms-wma",
-
".wmd" => "application/x-ms-wmd",
-
".wmf" => "application/x-msmetafile",
-
".wml" => "text/vnd.wap.wml",
-
".wmlc" => "application/vnd.wap.wmlc",
-
".wmls" => "text/vnd.wap.wmlscript",
-
".wmlsc" => "application/vnd.wap.wmlscriptc",
-
".wmv" => "video/x-ms-wmv",
-
".wmx" => "video/x-ms-wmx",
-
".wmz" => "application/x-ms-wmz",
-
".woff" => "application/font-woff",
-
".wpd" => "application/vnd.wordperfect",
-
".wpl" => "application/vnd.ms-wpl",
-
".wps" => "application/vnd.ms-works",
-
".wqd" => "application/vnd.wqd",
-
".wri" => "application/x-mswrite",
-
".wrl" => "model/vrml",
-
".wsdl" => "application/wsdl+xml",
-
".wspolicy" => "application/wspolicy+xml",
-
".wtb" => "application/vnd.webturbo",
-
".wvx" => "video/x-ms-wvx",
-
".x3d" => "application/vnd.hzn-3d-crossword",
-
".xar" => "application/vnd.xara",
-
".xbd" => "application/vnd.fujixerox.docuworks.binder",
-
".xbm" => "image/x-xbitmap",
-
".xdm" => "application/vnd.syncml.dm+xml",
-
".xdp" => "application/vnd.adobe.xdp+xml",
-
".xdw" => "application/vnd.fujixerox.docuworks",
-
".xenc" => "application/xenc+xml",
-
".xer" => "application/patch-ops-error+xml",
-
".xfdf" => "application/vnd.adobe.xfdf",
-
".xfdl" => "application/vnd.xfdl",
-
".xhtml" => "application/xhtml+xml",
-
".xif" => "image/vnd.xiff",
-
".xls" => "application/vnd.ms-excel",
-
".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
-
".xml" => "application/xml",
-
".xo" => "application/vnd.olpc-sugar",
-
".xop" => "application/xop+xml",
-
".xpm" => "image/x-xpixmap",
-
".xpr" => "application/vnd.is-xpr",
-
".xps" => "application/vnd.ms-xpsdocument",
-
".xpw" => "application/vnd.intercon.formnet",
-
".xsl" => "application/xml",
-
".xslt" => "application/xslt+xml",
-
".xsm" => "application/vnd.syncml+xml",
-
".xspf" => "application/xspf+xml",
-
".xul" => "application/vnd.mozilla.xul+xml",
-
".xwd" => "image/x-xwindowdump",
-
".xyz" => "chemical/x-xyz",
-
".yaml" => "text/yaml",
-
".yml" => "text/yaml",
-
".zaz" => "application/vnd.zzazz.deck+xml",
-
".zip" => "application/zip",
-
".zmm" => "application/vnd.handheld-entertainment+xml",
-
}
-
end
-
end
-
2
require 'uri'
-
2
require 'stringio'
-
2
require 'rack'
-
2
require 'rack/lint'
-
2
require 'rack/utils'
-
2
require 'rack/response'
-
-
2
module Rack
-
# Rack::MockRequest helps testing your Rack application without
-
# actually using HTTP.
-
#
-
# After performing a request on a URL with get/post/put/patch/delete, it
-
# returns a MockResponse with useful helper methods for effective
-
# testing.
-
#
-
# You can pass a hash with additional configuration to the
-
# get/post/put/patch/delete.
-
# <tt>:input</tt>:: A String or IO-like to be used as rack.input.
-
# <tt>:fatal</tt>:: Raise a FatalWarning if the app writes to rack.errors.
-
# <tt>:lint</tt>:: If true, wrap the application in a Rack::Lint.
-
-
2
class MockRequest
-
2
class FatalWarning < RuntimeError
-
end
-
-
2
class FatalWarner
-
2
def puts(warning)
-
raise FatalWarning, warning
-
end
-
-
2
def write(warning)
-
raise FatalWarning, warning
-
end
-
-
2
def flush
-
end
-
-
2
def string
-
""
-
end
-
end
-
-
2
DEFAULT_ENV = {
-
"rack.version" => Rack::VERSION,
-
"rack.input" => StringIO.new,
-
"rack.errors" => StringIO.new,
-
"rack.multithread" => true,
-
"rack.multiprocess" => true,
-
"rack.run_once" => false,
-
}
-
-
2
def initialize(app)
-
@app = app
-
end
-
-
2
def get(uri, opts={}) request("GET", uri, opts) end
-
2
def post(uri, opts={}) request("POST", uri, opts) end
-
2
def put(uri, opts={}) request("PUT", uri, opts) end
-
2
def patch(uri, opts={}) request("PATCH", uri, opts) end
-
2
def delete(uri, opts={}) request("DELETE", uri, opts) end
-
2
def head(uri, opts={}) request("HEAD", uri, opts) end
-
-
2
def request(method="GET", uri="", opts={})
-
env = self.class.env_for(uri, opts.merge(:method => method))
-
-
if opts[:lint]
-
app = Rack::Lint.new(@app)
-
else
-
app = @app
-
end
-
-
errors = env["rack.errors"]
-
status, headers, body = app.call(env)
-
MockResponse.new(status, headers, body, errors)
-
ensure
-
body.close if body.respond_to?(:close)
-
end
-
-
# Return the Rack environment used for a request to +uri+.
-
2
def self.env_for(uri="", opts={})
-
2
uri = URI(uri)
-
2
uri.path = "/#{uri.path}" unless uri.path[0] == ?/
-
-
2
env = DEFAULT_ENV.dup
-
-
2
env["REQUEST_METHOD"] = opts[:method] ? opts[:method].to_s.upcase : "GET"
-
2
env["SERVER_NAME"] = uri.host || "example.org"
-
2
env["SERVER_PORT"] = uri.port ? uri.port.to_s : "80"
-
2
env["QUERY_STRING"] = uri.query.to_s
-
2
env["PATH_INFO"] = (!uri.path || uri.path.empty?) ? "/" : uri.path
-
2
env["rack.url_scheme"] = uri.scheme || "http"
-
2
env["HTTPS"] = env["rack.url_scheme"] == "https" ? "on" : "off"
-
-
2
env["SCRIPT_NAME"] = opts[:script_name] || ""
-
-
2
if opts[:fatal]
-
env["rack.errors"] = FatalWarner.new
-
else
-
2
env["rack.errors"] = StringIO.new
-
end
-
-
2
if params = opts[:params]
-
if env["REQUEST_METHOD"] == "GET"
-
params = Utils.parse_nested_query(params) if params.is_a?(String)
-
params.update(Utils.parse_nested_query(env["QUERY_STRING"]))
-
env["QUERY_STRING"] = Utils.build_nested_query(params)
-
elsif !opts.has_key?(:input)
-
opts["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
-
if params.is_a?(Hash)
-
if data = Utils::Multipart.build_multipart(params)
-
opts[:input] = data
-
opts["CONTENT_LENGTH"] ||= data.length.to_s
-
opts["CONTENT_TYPE"] = "multipart/form-data; boundary=#{Utils::Multipart::MULTIPART_BOUNDARY}"
-
else
-
opts[:input] = Utils.build_nested_query(params)
-
end
-
else
-
opts[:input] = params
-
end
-
end
-
end
-
-
2
empty_str = ""
-
2
empty_str.force_encoding("ASCII-8BIT") if empty_str.respond_to? :force_encoding
-
2
opts[:input] ||= empty_str
-
2
if String === opts[:input]
-
2
rack_input = StringIO.new(opts[:input])
-
else
-
rack_input = opts[:input]
-
end
-
-
2
rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding)
-
2
env['rack.input'] = rack_input
-
-
2
env["CONTENT_LENGTH"] ||= env["rack.input"].length.to_s
-
-
2
opts.each { |field, value|
-
2
env[field] = value if String === field
-
}
-
-
2
env
-
end
-
end
-
-
# Rack::MockResponse provides useful helpers for testing your apps.
-
# Usually, you don't create the MockResponse on your own, but use
-
# MockRequest.
-
-
2
class MockResponse < Rack::Response
-
# Headers
-
2
attr_reader :original_headers
-
-
# Errors
-
2
attr_accessor :errors
-
-
2
def initialize(status, headers, body, errors=StringIO.new(""))
-
@original_headers = headers
-
@errors = errors.string if errors.respond_to?(:string)
-
@body_string = nil
-
-
super(body, status, headers)
-
end
-
-
2
def =~(other)
-
body =~ other
-
end
-
-
2
def match(other)
-
body.match other
-
end
-
-
2
def body
-
# FIXME: apparently users of MockResponse expect the return value of
-
# MockResponse#body to be a string. However, the real response object
-
# returns the body as a list.
-
#
-
# See spec_showstatus.rb:
-
#
-
# should "not replace existing messages" do
-
# ...
-
# res.body.should == "foo!"
-
# end
-
super.join
-
end
-
-
2
def empty?
-
[201, 204, 205, 304].include? status
-
end
-
end
-
end
-
2
module Rack
-
# A multipart form data parser, adapted from IOWA.
-
#
-
# Usually, Rack::Request#POST takes care of calling this.
-
2
module Multipart
-
2
autoload :UploadedFile, 'rack/multipart/uploaded_file'
-
2
autoload :Parser, 'rack/multipart/parser'
-
2
autoload :Generator, 'rack/multipart/generator'
-
-
2
EOL = "\r\n"
-
2
MULTIPART_BOUNDARY = "AaB03x"
-
2
MULTIPART = %r|\Amultipart/.*boundary=\"?([^\";,]+)\"?|n
-
2
TOKEN = /[^\s()<>,;:\\"\/\[\]?=]+/
-
2
CONDISP = /Content-Disposition:\s*#{TOKEN}\s*/i
-
2
DISPPARM = /;\s*(#{TOKEN})=("(?:\\"|[^"])*"|#{TOKEN})/
-
2
RFC2183 = /^#{CONDISP}(#{DISPPARM})+$/i
-
2
BROKEN_QUOTED = /^#{CONDISP}.*;\sfilename="(.*?)"(?:\s*$|\s*;\s*#{TOKEN}=)/i
-
2
BROKEN_UNQUOTED = /^#{CONDISP}.*;\sfilename=(#{TOKEN})/i
-
2
MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{EOL}/ni
-
2
MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*\s+name="?([^\";]*)"?/ni
-
2
MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{EOL}]*)/ni
-
-
2
class << self
-
2
def parse_multipart(env)
-
Parser.new(env).parse
-
end
-
-
2
def build_multipart(params, first = true)
-
Generator.new(params, first).dump
-
end
-
end
-
-
end
-
end
-
2
require 'rack/utils'
-
-
2
module Rack
-
# Rack::Request provides a convenient interface to a Rack
-
# environment. It is stateless, the environment +env+ passed to the
-
# constructor will be directly modified.
-
#
-
# req = Rack::Request.new(env)
-
# req.post?
-
# req.params["data"]
-
#
-
# The environment hash passed will store a reference to the Request object
-
# instantiated so that it will only instantiate if an instance of the Request
-
# object doesn't already exist.
-
-
2
class Request
-
# The environment of the request.
-
2
attr_reader :env
-
-
2
def initialize(env)
-
75
@env = env
-
end
-
-
2
def body; @env["rack.input"] end
-
11
def script_name; @env["SCRIPT_NAME"].to_s end
-
11
def path_info; @env["PATH_INFO"].to_s end
-
2
def request_method; @env["REQUEST_METHOD"] end
-
11
def query_string; @env["QUERY_STRING"].to_s end
-
2
def content_length; @env['CONTENT_LENGTH'] end
-
-
2
def content_type
-
content_type = @env['CONTENT_TYPE']
-
content_type.nil? || content_type.empty? ? nil : content_type
-
end
-
-
47
def session; @env['rack.session'] ||= {} end
-
2
def session_options; @env['rack.session.options'] ||= {} end
-
2
def logger; @env['rack.logger'] end
-
-
# The media type (type/subtype) portion of the CONTENT_TYPE header
-
# without any media type parameters. e.g., when CONTENT_TYPE is
-
# "text/plain;charset=utf-8", the media-type is "text/plain".
-
#
-
# For more information on the use of media types in HTTP, see:
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
-
2
def media_type
-
content_type && content_type.split(/\s*[;,]\s*/, 2).first.downcase
-
end
-
-
# The media type parameters provided in CONTENT_TYPE as a Hash, or
-
# an empty Hash if no CONTENT_TYPE or media-type parameters were
-
# provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8",
-
# this method responds with the following Hash:
-
# { 'charset' => 'utf-8' }
-
2
def media_type_params
-
return {} if content_type.nil?
-
Hash[*content_type.split(/\s*[;,]\s*/)[1..-1].
-
collect { |s| s.split('=', 2) }.
-
map { |k,v| [k.downcase, v] }.flatten]
-
end
-
-
# The character set of the request body if a "charset" media type
-
# parameter was given, or nil if no "charset" was specified. Note
-
# that, per RFC2616, text/* media types that specify no explicit
-
# charset are to be considered ISO-8859-1.
-
2
def content_charset
-
media_type_params['charset']
-
end
-
-
2
def scheme
-
19
if @env['HTTPS'] == 'on'
-
'https'
-
19
elsif @env['HTTP_X_FORWARDED_SSL'] == 'on'
-
'https'
-
19
elsif @env['HTTP_X_FORWARDED_SCHEME']
-
@env['HTTP_X_FORWARDED_SCHEME']
-
19
elsif @env['HTTP_X_FORWARDED_PROTO']
-
@env['HTTP_X_FORWARDED_PROTO'].split(',')[0]
-
else
-
19
@env["rack.url_scheme"]
-
end
-
end
-
-
2
def ssl?
-
19
scheme == 'https'
-
end
-
-
2
def host_with_port
-
if forwarded = @env["HTTP_X_FORWARDED_HOST"]
-
forwarded.split(/,\s?/).last
-
else
-
@env['HTTP_HOST'] || "#{@env['SERVER_NAME'] || @env['SERVER_ADDR']}:#{@env['SERVER_PORT']}"
-
end
-
end
-
-
2
def port
-
if port = host_with_port.split(/:/)[1]
-
port.to_i
-
elsif port = @env['HTTP_X_FORWARDED_PORT']
-
port.to_i
-
elsif ssl?
-
443
-
elsif @env.has_key?("HTTP_X_FORWARDED_HOST")
-
80
-
else
-
@env["SERVER_PORT"].to_i
-
end
-
end
-
-
2
def host
-
# Remove port number.
-
host_with_port.to_s.gsub(/:\d+\z/, '')
-
end
-
-
2
def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end
-
2
def path_info=(s); @env["PATH_INFO"] = s.to_s end
-
-
-
# Checks the HTTP request method (or verb) to see if it was of type DELETE
-
2
def delete?; request_method == "DELETE" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type GET
-
2
def get?; request_method == "GET" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type HEAD
-
2
def head?; request_method == "HEAD" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type OPTIONS
-
2
def options?; request_method == "OPTIONS" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type PATCH
-
2
def patch?; request_method == "PATCH" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type POST
-
2
def post?; request_method == "POST" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type PUT
-
2
def put?; request_method == "PUT" end
-
-
# Checks the HTTP request method (or verb) to see if it was of type TRACE
-
2
def trace?; request_method == "TRACE" end
-
-
-
# The set of form-data media-types. Requests that do not indicate
-
# one of the media types presents in this list will not be eligible
-
# for form-data / param parsing.
-
2
FORM_DATA_MEDIA_TYPES = [
-
'application/x-www-form-urlencoded',
-
'multipart/form-data'
-
]
-
-
# The set of media-types. Requests that do not indicate
-
# one of the media types presents in this list will not be eligible
-
# for param parsing like soap attachments or generic multiparts
-
2
PARSEABLE_DATA_MEDIA_TYPES = [
-
'multipart/related',
-
'multipart/mixed'
-
]
-
-
# Determine whether the request body contains form-data by checking
-
# the request Content-Type for one of the media-types:
-
# "application/x-www-form-urlencoded" or "multipart/form-data". The
-
# list of form-data media types can be modified through the
-
# +FORM_DATA_MEDIA_TYPES+ array.
-
#
-
# A request body is also assumed to contain form-data when no
-
# Content-Type header is provided and the request_method is POST.
-
2
def form_data?
-
type = media_type
-
meth = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']
-
(meth == 'POST' && type.nil?) || FORM_DATA_MEDIA_TYPES.include?(type)
-
end
-
-
# Determine whether the request body contains data by checking
-
# the request media_type against registered parse-data media-types
-
2
def parseable_data?
-
9
PARSEABLE_DATA_MEDIA_TYPES.include?(media_type)
-
end
-
-
# Returns the data received in the query string.
-
2
def GET
-
if @env["rack.request.query_string"] == query_string
-
@env["rack.request.query_hash"]
-
else
-
@env["rack.request.query_string"] = query_string
-
@env["rack.request.query_hash"] = parse_query(query_string)
-
end
-
end
-
-
# Returns the data received in the request body.
-
#
-
# This method support both application/x-www-form-urlencoded and
-
# multipart/form-data.
-
2
def POST
-
9
if @env["rack.input"].nil?
-
raise "Missing rack.input"
-
9
elsif @env["rack.request.form_input"].eql? @env["rack.input"]
-
@env["rack.request.form_hash"]
-
9
elsif form_data? || parseable_data?
-
@env["rack.request.form_input"] = @env["rack.input"]
-
unless @env["rack.request.form_hash"] = parse_multipart(env)
-
form_vars = @env["rack.input"].read
-
-
# Fix for Safari Ajax postings that always append \0
-
# form_vars.sub!(/\0\z/, '') # performance replacement:
-
form_vars.slice!(-1) if form_vars[-1] == ?\0
-
-
@env["rack.request.form_vars"] = form_vars
-
@env["rack.request.form_hash"] = parse_query(form_vars)
-
-
@env["rack.input"].rewind
-
end
-
@env["rack.request.form_hash"]
-
else
-
9
{}
-
end
-
end
-
-
# The union of GET and POST data.
-
2
def params
-
@params ||= self.GET.merge(self.POST)
-
rescue EOFError
-
self.GET
-
end
-
-
# shortcut for request.params[key]
-
2
def [](key)
-
params[key.to_s]
-
end
-
-
# shortcut for request.params[key] = value
-
2
def []=(key, value)
-
params[key.to_s] = value
-
end
-
-
# like Hash#values_at
-
2
def values_at(*keys)
-
keys.map{|key| params[key] }
-
end
-
-
# the referer of the client
-
2
def referer
-
@env['HTTP_REFERER']
-
end
-
2
alias referrer referer
-
-
2
def user_agent
-
@env['HTTP_USER_AGENT']
-
end
-
-
2
def cookies
-
10
hash = @env["rack.request.cookie_hash"] ||= {}
-
10
string = @env["HTTP_COOKIE"]
-
-
10
return hash if string == @env["rack.request.cookie_string"]
-
hash.clear
-
-
# According to RFC 2109:
-
# If multiple cookies satisfy the criteria above, they are ordered in
-
# the Cookie header such that those with more specific Path attributes
-
# precede those with less specific. Ordering with respect to other
-
# attributes (e.g., Domain) is unspecified.
-
cookies = Utils.parse_query(string, ';,') { |s| Rack::Utils.unescape(s) rescue s }
-
cookies.each { |k,v| hash[k] = Array === v ? v.first : v }
-
@env["rack.request.cookie_string"] = string
-
hash
-
end
-
-
2
def xhr?
-
@env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
-
end
-
-
2
def base_url
-
url = scheme + "://"
-
url << host
-
-
if scheme == "https" && port != 443 ||
-
scheme == "http" && port != 80
-
url << ":#{port}"
-
end
-
-
url
-
end
-
-
# Tries to return a remake of the original request URL as a string.
-
2
def url
-
base_url + fullpath
-
end
-
-
2
def path
-
9
script_name + path_info
-
end
-
-
2
def fullpath
-
9
query_string.empty? ? path : "#{path}?#{query_string}"
-
end
-
-
2
def accept_encoding
-
@env["HTTP_ACCEPT_ENCODING"].to_s.split(/\s*,\s*/).map do |part|
-
encoding, parameters = part.split(/\s*;\s*/, 2)
-
quality = 1.0
-
if parameters and /\Aq=([\d.]+)/ =~ parameters
-
quality = $1.to_f
-
end
-
[encoding, quality]
-
end
-
end
-
-
2
def trusted_proxy?(ip)
-
ip =~ /^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\.|^::1$|^fd[0-9a-f]{2}:.+|^localhost$/i
-
end
-
-
2
def ip
-
remote_addrs = @env['REMOTE_ADDR'] ? @env['REMOTE_ADDR'].split(/[,\s]+/) : []
-
remote_addrs.reject! { |addr| trusted_proxy?(addr) }
-
-
return remote_addrs.first if remote_addrs.any?
-
-
forwarded_ips = @env['HTTP_X_FORWARDED_FOR'] ? @env['HTTP_X_FORWARDED_FOR'].strip.split(/[,\s]+/) : []
-
-
if client_ip = @env['HTTP_CLIENT_IP']
-
# If forwarded_ips doesn't include the client_ip, it might be an
-
# ip spoofing attempt, so we ignore HTTP_CLIENT_IP
-
return client_ip if forwarded_ips.include?(client_ip)
-
end
-
-
return forwarded_ips.reject { |ip| trusted_proxy?(ip) }.last || @env["REMOTE_ADDR"]
-
end
-
-
2
protected
-
2
def parse_query(qs)
-
Utils.parse_nested_query(qs)
-
end
-
-
2
def parse_multipart(env)
-
Rack::Multipart.parse_multipart(env)
-
end
-
end
-
end
-
2
require 'rack/request'
-
2
require 'rack/utils'
-
2
require 'time'
-
-
2
module Rack
-
# Rack::Response provides a convenient interface to create a Rack
-
# response.
-
#
-
# It allows setting of headers and cookies, and provides useful
-
# defaults (a OK response containing HTML).
-
#
-
# You can use Response#write to iteratively generate your response,
-
# but note that this is buffered by Rack::Response until you call
-
# +finish+. +finish+ however can take a block inside which calls to
-
# +write+ are synchronous with the Rack response.
-
#
-
# Your application's +call+ should end returning Response#finish.
-
-
2
class Response
-
2
attr_accessor :length
-
-
2
def initialize(body=[], status=200, header={})
-
@status = status.to_i
-
@header = Utils::HeaderHash.new("Content-Type" => "text/html").
-
merge(header)
-
-
@chunked = "chunked" == @header['Transfer-Encoding']
-
@writer = lambda { |x| @body << x }
-
@block = nil
-
@length = 0
-
-
@body = []
-
-
if body.respond_to? :to_str
-
write body.to_str
-
elsif body.respond_to?(:each)
-
body.each { |part|
-
write part.to_s
-
}
-
else
-
raise TypeError, "stringable or iterable required"
-
end
-
-
yield self if block_given?
-
end
-
-
2
attr_reader :header
-
2
attr_accessor :status, :body
-
-
2
def [](key)
-
header[key]
-
end
-
-
2
def []=(key, value)
-
header[key] = value
-
end
-
-
2
def set_cookie(key, value)
-
Utils.set_cookie_header!(header, key, value)
-
end
-
-
2
def delete_cookie(key, value={})
-
Utils.delete_cookie_header!(header, key, value)
-
end
-
-
2
def redirect(target, status=302)
-
self.status = status
-
self["Location"] = target
-
end
-
-
2
def finish(&block)
-
@block = block
-
-
if [204, 205, 304].include?(status.to_i)
-
header.delete "Content-Type"
-
header.delete "Content-Length"
-
close
-
[status.to_i, header, []]
-
else
-
[status.to_i, header, BodyProxy.new(self){}]
-
end
-
end
-
2
alias to_a finish # For *response
-
2
alias to_ary finish # For implicit-splat on Ruby 1.9.2
-
-
2
def each(&callback)
-
@body.each(&callback)
-
@writer = callback
-
@block.call(self) if @block
-
end
-
-
# Append to body and update Content-Length.
-
#
-
# NOTE: Do not mix #write and direct #body access!
-
#
-
2
def write(str)
-
s = str.to_s
-
@length += Rack::Utils.bytesize(s) unless @chunked
-
@writer.call s
-
-
header["Content-Length"] = @length.to_s unless @chunked
-
str
-
end
-
-
2
def close
-
body.close if body.respond_to?(:close)
-
end
-
-
2
def empty?
-
@block == nil && @body.empty?
-
end
-
-
2
alias headers header
-
-
2
module Helpers
-
2
def invalid?; status < 100 || status >= 600; end
-
-
2
def informational?; status >= 100 && status < 200; end
-
8
def successful?; status >= 200 && status < 300; end
-
2
def redirection?; status >= 300 && status < 400; end
-
2
def client_error?; status >= 400 && status < 500; end
-
2
def server_error?; status >= 500 && status < 600; end
-
-
2
def ok?; status == 200; end
-
2
def bad_request?; status == 400; end
-
2
def forbidden?; status == 403; end
-
2
def not_found?; status == 404; end
-
2
def method_not_allowed?; status == 405; end
-
2
def unprocessable?; status == 422; end
-
-
2
def redirect?; [301, 302, 303, 307].include? status; end
-
-
# Headers
-
2
attr_reader :headers, :original_headers
-
-
2
def include?(header)
-
!!headers[header]
-
end
-
-
2
def content_type
-
headers["Content-Type"]
-
end
-
-
2
def content_length
-
cl = headers["Content-Length"]
-
cl ? cl.to_i : cl
-
end
-
-
2
def location
-
headers["Location"]
-
end
-
end
-
-
2
include Helpers
-
end
-
end
-
2
module Rack
-
# Sets an "X-Runtime" response header, indicating the response
-
# time of the request, in seconds
-
#
-
# You can put it right before the application to see the processing
-
# time, or before all the other middlewares to include time for them,
-
# too.
-
2
class Runtime
-
2
def initialize(app, name = nil)
-
2
@app = app
-
2
@header_name = "X-Runtime"
-
2
@header_name << "-#{name}" if name
-
end
-
-
2
def call(env)
-
start_time = Time.now
-
status, headers, body = @app.call(env)
-
request_time = Time.now - start_time
-
-
if !headers.has_key?(@header_name)
-
headers[@header_name] = "%0.6f" % request_time
-
end
-
-
[status, headers, body]
-
end
-
end
-
end
-
# AUTHOR: blink <blinketje@gmail.com>; blink#ruby-lang@irc.freenode.net
-
# bugrep: Andreas Zehnder
-
-
2
require 'time'
-
2
require 'rack/request'
-
2
require 'rack/response'
-
2
begin
-
2
require 'securerandom'
-
rescue LoadError
-
# We just won't get securerandom
-
end
-
-
2
module Rack
-
-
2
module Session
-
-
2
module Abstract
-
2
ENV_SESSION_KEY = 'rack.session'.freeze
-
2
ENV_SESSION_OPTIONS_KEY = 'rack.session.options'.freeze
-
-
# Thin wrapper around Hash that allows us to lazily load session id into session_options.
-
-
2
class OptionsHash < Hash #:nodoc:
-
2
def initialize(by, env, default_options)
-
@by = by
-
@env = env
-
@session_id_loaded = false
-
merge!(default_options)
-
end
-
-
2
def [](key)
-
load_session_id! if key == :id && session_id_not_loaded?
-
super
-
end
-
-
2
private
-
-
2
def session_id_not_loaded?
-
!(@session_id_loaded || key?(:id))
-
end
-
-
2
def load_session_id!
-
self[:id] = @by.send(:extract_session_id, @env)
-
@session_id_loaded = true
-
end
-
end
-
-
# SessionHash is responsible to lazily load the session from store.
-
-
2
class SessionHash < Hash
-
2
def initialize(by, env)
-
75
super()
-
75
@by = by
-
75
@env = env
-
75
@loaded = false
-
end
-
-
2
def [](key)
-
36
load_for_read!
-
36
super(key.to_s)
-
end
-
-
2
def has_key?(key)
-
load_for_read!
-
super(key.to_s)
-
end
-
2
alias :key? :has_key?
-
2
alias :include? :has_key?
-
-
2
def []=(key, value)
-
9
load_for_write!
-
9
super(key.to_s, value)
-
end
-
-
2
def clear
-
load_for_write!
-
super
-
end
-
-
2
def to_hash
-
load_for_read!
-
h = {}.replace(self)
-
h.delete_if { |k,v| v.nil? }
-
h
-
end
-
-
2
def update(hash)
-
load_for_write!
-
super(stringify_keys(hash))
-
end
-
-
2
def delete(key)
-
load_for_write!
-
super(key.to_s)
-
end
-
-
2
def inspect
-
if loaded?
-
super
-
else
-
"#<#{self.class}:0x#{self.object_id.to_s(16)} not yet loaded>"
-
end
-
end
-
-
2
def exists?
-
return @exists if instance_variable_defined?(:@exists)
-
@exists = @by.send(:session_exists?, @env)
-
end
-
-
2
def loaded?
-
45
@loaded
-
end
-
-
2
def empty?
-
load_for_read!
-
super
-
end
-
-
2
def merge!(hash)
-
load_for_write!
-
super
-
end
-
-
2
private
-
-
2
def load_for_read!
-
36
load! if !loaded? && exists?
-
end
-
-
2
def load_for_write!
-
9
load! unless loaded?
-
end
-
-
2
def load!
-
id, session = @by.send(:load_session, @env)
-
@env[ENV_SESSION_OPTIONS_KEY][:id] = id
-
replace(stringify_keys(session))
-
@loaded = true
-
end
-
-
2
def stringify_keys(other)
-
hash = {}
-
other.each do |key, value|
-
hash[key.to_s] = value
-
end
-
hash
-
end
-
end
-
-
# ID sets up a basic framework for implementing an id based sessioning
-
# service. Cookies sent to the client for maintaining sessions will only
-
# contain an id reference. Only #get_session and #set_session are
-
# required to be overwritten.
-
#
-
# All parameters are optional.
-
# * :key determines the name of the cookie, by default it is
-
# 'rack.session'
-
# * :path, :domain, :expire_after, :secure, and :httponly set the related
-
# cookie options as by Rack::Response#add_cookie
-
# * :skip will not a set a cookie in the response nor update the session state
-
# * :defer will not set a cookie in the response but still update the session
-
# state if it is used with a backend
-
# * :renew (implementation dependent) will prompt the generation of a new
-
# session id, and migration of data to be referenced at the new id. If
-
# :defer is set, it will be overridden and the cookie will be set.
-
# * :sidbits sets the number of bits in length that a generated session
-
# id will be.
-
#
-
# These options can be set on a per request basis, at the location of
-
# env['rack.session.options']. Additionally the id of the session can be
-
# found within the options hash at the key :id. It is highly not
-
# recommended to change its value.
-
#
-
# Is Rack::Utils::Context compatible.
-
#
-
# Not included by default; you must require 'rack/session/abstract/id'
-
# to use.
-
-
2
class ID
-
2
DEFAULT_OPTIONS = {
-
:key => 'rack.session',
-
:path => '/',
-
:domain => nil,
-
:expire_after => nil,
-
:secure => false,
-
:httponly => true,
-
:defer => false,
-
:renew => false,
-
:sidbits => 128,
-
:cookie_only => true,
-
2
:secure_random => (::SecureRandom rescue false)
-
}
-
-
2
attr_reader :key, :default_options
-
-
2
def initialize(app, options={})
-
2
@app = app
-
2
@default_options = self.class::DEFAULT_OPTIONS.merge(options)
-
2
@key = @default_options.delete(:key)
-
2
@cookie_only = @default_options.delete(:cookie_only)
-
2
initialize_sid
-
end
-
-
2
def call(env)
-
context(env)
-
end
-
-
2
def context(env, app=@app)
-
prepare_session(env)
-
status, headers, body = app.call(env)
-
commit_session(env, status, headers, body)
-
end
-
-
2
private
-
-
2
def initialize_sid
-
@sidbits = @default_options[:sidbits]
-
@sid_secure = @default_options[:secure_random]
-
@sid_length = @sidbits / 4
-
end
-
-
# Generate a new session id using Ruby #rand. The size of the
-
# session id is controlled by the :sidbits option.
-
# Monkey patch this to use custom methods for session id generation.
-
-
2
def generate_sid(secure = @sid_secure)
-
if secure
-
SecureRandom.hex(@sid_length)
-
else
-
"%0#{@sid_length}x" % Kernel.rand(2**@sidbits - 1)
-
end
-
rescue NotImplementedError
-
generate_sid(false)
-
end
-
-
# Sets the lazy session at 'rack.session' and places options and session
-
# metadata into 'rack.session.options'.
-
-
2
def prepare_session(env)
-
session_was = env[ENV_SESSION_KEY]
-
env[ENV_SESSION_KEY] = SessionHash.new(self, env)
-
env[ENV_SESSION_OPTIONS_KEY] = OptionsHash.new(self, env, @default_options)
-
env[ENV_SESSION_KEY].merge! session_was if session_was
-
end
-
-
# Extracts the session id from provided cookies and passes it and the
-
# environment to #get_session.
-
-
2
def load_session(env)
-
sid = current_session_id(env)
-
sid, session = get_session(env, sid)
-
[sid, session || {}]
-
end
-
-
# Extract session id from request object.
-
-
2
def extract_session_id(env)
-
request = Rack::Request.new(env)
-
sid = request.cookies[@key]
-
sid ||= request.params[@key] unless @cookie_only
-
sid
-
end
-
-
# Returns the current session id from the OptionsHash.
-
-
2
def current_session_id(env)
-
env[ENV_SESSION_OPTIONS_KEY][:id]
-
end
-
-
# Check if the session exists or not.
-
-
2
def session_exists?(env)
-
value = current_session_id(env)
-
value && !value.empty?
-
end
-
-
# Session should be commited if it was loaded, any of specific options like :renew, :drop
-
# or :expire_after was given and the security permissions match. Skips if skip is given.
-
-
2
def commit_session?(env, session, options)
-
if options[:skip]
-
false
-
else
-
has_session = loaded_session?(session) || forced_session_update?(session, options)
-
has_session && security_matches?(env, options)
-
end
-
end
-
-
2
def loaded_session?(session)
-
!session.is_a?(SessionHash) || session.loaded?
-
end
-
-
2
def forced_session_update?(session, options)
-
force_options?(options) && session && !session.empty?
-
end
-
-
2
def force_options?(options)
-
options.values_at(:renew, :drop, :defer, :expire_after).any?
-
end
-
-
2
def security_matches?(env, options)
-
return true unless options[:secure]
-
request = Rack::Request.new(env)
-
request.ssl?
-
end
-
-
# Acquires the session from the environment and the session id from
-
# the session options and passes them to #set_session. If successful
-
# and the :defer option is not true, a cookie will be added to the
-
# response with the session's id.
-
-
2
def commit_session(env, status, headers, body)
-
session = env['rack.session']
-
options = env['rack.session.options']
-
-
if options[:drop] || options[:renew]
-
session_id = destroy_session(env, options[:id] || generate_sid, options)
-
return [status, headers, body] unless session_id
-
end
-
-
return [status, headers, body] unless commit_session?(env, session, options)
-
-
session.send(:load!) unless loaded_session?(session)
-
session = session.to_hash
-
session_id ||= options[:id] || generate_sid
-
-
if not data = set_session(env, session_id, session, options)
-
env["rack.errors"].puts("Warning! #{self.class.name} failed to save session. Content dropped.")
-
elsif options[:defer] and not options[:renew]
-
env["rack.errors"].puts("Defering cookie for #{session_id}") if $VERBOSE
-
else
-
cookie = Hash.new
-
cookie[:value] = data
-
cookie[:expires] = Time.now + options[:expire_after] if options[:expire_after]
-
set_cookie(env, headers, cookie.merge!(options))
-
end
-
-
[status, headers, body]
-
end
-
-
# Sets the cookie back to the client with session id. We skip the cookie
-
# setting if the value didn't change (sid is the same) or expires was given.
-
-
2
def set_cookie(env, headers, cookie)
-
request = Rack::Request.new(env)
-
if request.cookies[@key] != cookie[:value] || cookie[:expires]
-
Utils.set_cookie_header!(headers, @key, cookie)
-
end
-
end
-
-
# All thread safety and session retrival proceedures should occur here.
-
# Should return [session_id, session].
-
# If nil is provided as the session id, generation of a new valid id
-
# should occur within.
-
-
2
def get_session(env, sid)
-
raise '#get_session not implemented.'
-
end
-
-
# All thread safety and session storage proceedures should occur here.
-
# Should return true or false dependant on whether or not the session
-
# was saved or not.
-
-
2
def set_session(env, sid, session, options)
-
raise '#set_session not implemented.'
-
end
-
-
# All thread safety and session destroy proceedures should occur here.
-
# Should return a new session id or nil if options[:drop]
-
-
2
def destroy_session(env, sid, options)
-
raise '#destroy_session not implemented'
-
end
-
end
-
end
-
end
-
end
-
2
require 'openssl'
-
2
require 'rack/request'
-
2
require 'rack/response'
-
2
require 'rack/session/abstract/id'
-
-
2
module Rack
-
-
2
module Session
-
-
# Rack::Session::Cookie provides simple cookie based session management.
-
# By default, the session is a Ruby Hash stored as base64 encoded marshalled
-
# data set to :key (default: rack.session). The object that encodes the
-
# session data is configurable and must respond to +encode+ and +decode+.
-
# Both methods must take a string and return a string.
-
#
-
# When the secret key is set, cookie data is checked for data integrity.
-
# The old secret key is also accepted and allows graceful secret rotation.
-
#
-
# Example:
-
#
-
# use Rack::Session::Cookie, :key => 'rack.session',
-
# :domain => 'foo.com',
-
# :path => '/',
-
# :expire_after => 2592000,
-
# :secret => 'change_me',
-
# :old_secret => 'also_change_me'
-
#
-
# All parameters are optional.
-
#
-
# Example of a cookie with no encoding:
-
#
-
# Rack::Session::Cookie.new(application, {
-
# :coder => Rack::Session::Cookie::Identity.new
-
# })
-
#
-
# Example of a cookie with custom encoding:
-
#
-
# Rack::Session::Cookie.new(application, {
-
# :coder => Class.new {
-
# def encode(str); str.reverse; end
-
# def decode(str); str.reverse; end
-
# }.new
-
# })
-
#
-
-
2
class Cookie < Abstract::ID
-
# Encode session cookies as Base64
-
2
class Base64
-
2
def encode(str)
-
[str].pack('m')
-
end
-
-
2
def decode(str)
-
str.unpack('m').first
-
end
-
-
# Encode session cookies as Marshaled Base64 data
-
2
class Marshal < Base64
-
2
def encode(str)
-
super(::Marshal.dump(str))
-
end
-
-
2
def decode(str)
-
::Marshal.load(super(str)) rescue nil
-
end
-
end
-
end
-
-
# Use no encoding for session cookies
-
2
class Identity
-
2
def encode(str); str; end
-
2
def decode(str); str; end
-
end
-
-
# Reverse string encoding. (trollface)
-
2
class Reverse
-
2
def encode(str); str.reverse; end
-
2
def decode(str); str.reverse; end
-
end
-
-
2
attr_reader :coder
-
-
2
def initialize(app, options={})
-
2
@secrets = options.values_at(:secret, :old_secret).compact
-
warn <<-MSG unless @secrets.size >= 1
-
SECURITY WARNING: No secret option provided to Rack::Session::Cookie.
-
This poses a security threat. It is strongly recommended that you
-
provide a secret to prevent exploits that may be possible from crafted
-
cookies. This will not be supported in future versions of Rack, and
-
future versions will even invalidate your existing user cookies.
-
-
Called from: #{caller[0]}.
-
2
MSG
-
2
@coder = options[:coder] ||= Base64::Marshal.new
-
2
super(app, options.merge!(:cookie_only => true))
-
end
-
-
2
private
-
-
2
def load_session(env)
-
data = unpacked_cookie_data(env)
-
data = persistent_session_id!(data)
-
[data["session_id"], data]
-
end
-
-
2
def extract_session_id(env)
-
unpacked_cookie_data(env)["session_id"]
-
end
-
-
2
def unpacked_cookie_data(env)
-
env["rack.session.unpacked_cookie_data"] ||= begin
-
request = Rack::Request.new(env)
-
session_data = request.cookies[@key]
-
-
if @secrets.size > 0 && session_data
-
session_data, digest = session_data.split("--")
-
-
if session_data && digest
-
ok = @secrets.any? do |secret|
-
secret && Rack::Utils.secure_compare(digest, generate_hmac(session_data, secret))
-
end
-
end
-
-
session_data = nil unless ok
-
end
-
-
coder.decode(session_data) || {}
-
end
-
end
-
-
2
def persistent_session_id!(data, sid=nil)
-
data ||= {}
-
data["session_id"] ||= sid || generate_sid
-
data
-
end
-
-
# Overwrite set cookie to bypass content equality and always stream the cookie.
-
-
2
def set_cookie(env, headers, cookie)
-
Utils.set_cookie_header!(headers, @key, cookie)
-
end
-
-
2
def set_session(env, session_id, session, options)
-
session = session.merge("session_id" => session_id)
-
session_data = coder.encode(session)
-
-
if @secrets.first
-
session_data = "#{session_data}--#{generate_hmac(session_data, @secrets.first)}"
-
end
-
-
if session_data.size > (4096 - @key.size)
-
env["rack.errors"].puts("Warning! Rack::Session::Cookie data size exceeds 4K.")
-
nil
-
else
-
session_data
-
end
-
end
-
-
2
def destroy_session(env, session_id, options)
-
# Nothing to do here, data is in the client
-
generate_sid unless options[:drop]
-
end
-
-
2
def generate_hmac(data, secret)
-
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, data)
-
end
-
-
end
-
end
-
end
-
# -*- encoding: binary -*-
-
2
require 'fileutils'
-
2
require 'set'
-
2
require 'tempfile'
-
2
require 'rack/multipart'
-
-
8
major, minor, patch = RUBY_VERSION.split('.').map { |v| v.to_i }
-
-
2
if major == 1 && minor < 9
-
require 'rack/backports/uri/common_18'
-
elsif major == 1 && minor == 9 && patch == 2 && RUBY_PATCHLEVEL <= 320 && RUBY_ENGINE != 'jruby'
-
require 'rack/backports/uri/common_192'
-
elsif major == 1 && minor == 9 && patch == 3 && RUBY_PATCHLEVEL < 125
-
2
require 'rack/backports/uri/common_193'
-
else
-
require 'uri/common'
-
end
-
-
2
module Rack
-
# Rack::Utils contains a grab-bag of useful methods for writing web
-
# applications adopted from all kinds of Ruby libraries.
-
-
2
module Utils
-
# URI escapes. (CGI style space to +)
-
2
def escape(s)
-
URI.encode_www_form_component(s)
-
end
-
2
module_function :escape
-
-
# Like URI escaping, but with %20 instead of +. Strictly speaking this is
-
# true URI escaping.
-
2
def escape_path(s)
-
escape(s).gsub('+', '%20')
-
end
-
2
module_function :escape_path
-
-
# Unescapes a URI escaped string with +encoding+. +encoding+ will be the
-
# target encoding of the string returned, and it defaults to UTF-8
-
2
if defined?(::Encoding)
-
2
def unescape(s, encoding = Encoding::UTF_8)
-
URI.decode_www_form_component(s, encoding)
-
end
-
else
-
def unescape(s, encoding = nil)
-
URI.decode_www_form_component(s, encoding)
-
end
-
end
-
2
module_function :unescape
-
-
2
DEFAULT_SEP = /[&;] */n
-
-
2
class << self
-
2
attr_accessor :key_space_limit
-
end
-
-
# The default number of bytes to allow parameter keys to take up.
-
# This helps prevent a rogue client from flooding a Request.
-
2
self.key_space_limit = 65536
-
-
# Stolen from Mongrel, with some small modifications:
-
# Parses a query string by breaking it up at the '&'
-
# and ';' characters. You can also use this to parse
-
# cookies by changing the characters used in the second
-
# parameter (which defaults to '&;').
-
2
def parse_query(qs, d = nil, &unescaper)
-
unescaper ||= method(:unescape)
-
-
params = KeySpaceConstrainedParams.new
-
-
(qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
-
next if p.empty?
-
k, v = p.split('=', 2).map(&unescaper)
-
next unless k || v
-
-
if cur = params[k]
-
if cur.class == Array
-
params[k] << v
-
else
-
params[k] = [cur, v]
-
end
-
else
-
params[k] = v
-
end
-
end
-
-
return params.to_params_hash
-
end
-
2
module_function :parse_query
-
-
2
def parse_nested_query(qs, d = nil)
-
params = KeySpaceConstrainedParams.new
-
-
(qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
-
k, v = p.split('=', 2).map { |s| unescape(s) }
-
-
normalize_params(params, k, v)
-
end
-
-
return params.to_params_hash
-
end
-
2
module_function :parse_nested_query
-
-
2
def normalize_params(params, name, v = nil)
-
name =~ %r(\A[\[\]]*([^\[\]]+)\]*)
-
k = $1 || ''
-
after = $' || ''
-
-
return if k.empty?
-
-
if after == ""
-
params[k] = v
-
elsif after == "[]"
-
params[k] ||= []
-
raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
-
params[k] << v
-
elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$)
-
child_key = $1
-
params[k] ||= []
-
raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array)
-
if params_hash_type?(params[k].last) && !params[k].last.key?(child_key)
-
normalize_params(params[k].last, child_key, v)
-
else
-
params[k] << normalize_params(params.class.new, child_key, v)
-
end
-
else
-
params[k] ||= params.class.new
-
raise TypeError, "expected Hash (got #{params[k].class.name}) for param `#{k}'" unless params_hash_type?(params[k])
-
params[k] = normalize_params(params[k], after, v)
-
end
-
-
return params
-
end
-
2
module_function :normalize_params
-
-
2
def params_hash_type?(obj)
-
obj.kind_of?(KeySpaceConstrainedParams) || obj.kind_of?(Hash)
-
end
-
2
module_function :params_hash_type?
-
-
2
def build_query(params)
-
params.map { |k, v|
-
if v.class == Array
-
build_query(v.map { |x| [k, x] })
-
else
-
v.nil? ? escape(k) : "#{escape(k)}=#{escape(v)}"
-
end
-
}.join("&")
-
end
-
2
module_function :build_query
-
-
2
def build_nested_query(value, prefix = nil)
-
case value
-
when Array
-
value.map { |v|
-
build_nested_query(v, "#{prefix}[]")
-
}.join("&")
-
when Hash
-
value.map { |k, v|
-
build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
-
}.join("&")
-
when String
-
raise ArgumentError, "value must be a Hash" if prefix.nil?
-
"#{prefix}=#{escape(value)}"
-
else
-
prefix
-
end
-
end
-
2
module_function :build_nested_query
-
-
2
ESCAPE_HTML = {
-
"&" => "&",
-
"<" => "<",
-
">" => ">",
-
"'" => "'",
-
'"' => """,
-
"/" => "/"
-
}
-
2
if //.respond_to?(:encoding)
-
2
ESCAPE_HTML_PATTERN = Regexp.union(*ESCAPE_HTML.keys)
-
else
-
# On 1.8, there is a kcode = 'u' bug that allows for XSS otherwhise
-
# TODO doesn't apply to jruby, so a better condition above might be preferable?
-
ESCAPE_HTML_PATTERN = /#{Regexp.union(*ESCAPE_HTML.keys)}/n
-
end
-
-
# Escape ampersands, brackets and quotes to their HTML/XML entities.
-
2
def escape_html(string)
-
string.to_s.gsub(ESCAPE_HTML_PATTERN){|c| ESCAPE_HTML[c] }
-
end
-
2
module_function :escape_html
-
-
2
def select_best_encoding(available_encodings, accept_encoding)
-
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
-
-
expanded_accept_encoding =
-
accept_encoding.map { |m, q|
-
if m == "*"
-
(available_encodings - accept_encoding.map { |m2, _| m2 }).map { |m2| [m2, q] }
-
else
-
[[m, q]]
-
end
-
}.inject([]) { |mem, list|
-
mem + list
-
}
-
-
encoding_candidates = expanded_accept_encoding.sort_by { |_, q| -q }.map { |m, _| m }
-
-
unless encoding_candidates.include?("identity")
-
encoding_candidates.push("identity")
-
end
-
-
expanded_accept_encoding.find_all { |m, q|
-
q == 0.0
-
}.each { |m, _|
-
encoding_candidates.delete(m)
-
}
-
-
return (encoding_candidates & available_encodings)[0]
-
end
-
2
module_function :select_best_encoding
-
-
2
def set_cookie_header!(header, key, value)
-
case value
-
when Hash
-
domain = "; domain=" + value[:domain] if value[:domain]
-
path = "; path=" + value[:path] if value[:path]
-
# According to RFC 2109, we need dashes here.
-
# N.B.: cgi.rb uses spaces...
-
expires = "; expires=" +
-
rfc2822(value[:expires].clone.gmtime) if value[:expires]
-
secure = "; secure" if value[:secure]
-
httponly = "; HttpOnly" if value[:httponly]
-
value = value[:value]
-
end
-
value = [value] unless Array === value
-
cookie = escape(key) + "=" +
-
value.map { |v| escape v }.join("&") +
-
"#{domain}#{path}#{expires}#{secure}#{httponly}"
-
-
case header["Set-Cookie"]
-
when nil, ''
-
header["Set-Cookie"] = cookie
-
when String
-
header["Set-Cookie"] = [header["Set-Cookie"], cookie].join("\n")
-
when Array
-
header["Set-Cookie"] = (header["Set-Cookie"] + [cookie]).join("\n")
-
end
-
-
nil
-
end
-
2
module_function :set_cookie_header!
-
-
2
def delete_cookie_header!(header, key, value = {})
-
case header["Set-Cookie"]
-
when nil, ''
-
cookies = []
-
when String
-
cookies = header["Set-Cookie"].split("\n")
-
when Array
-
cookies = header["Set-Cookie"]
-
end
-
-
cookies.reject! { |cookie|
-
if value[:domain]
-
cookie =~ /\A#{escape(key)}=.*domain=#{value[:domain]}/
-
elsif value[:path]
-
cookie =~ /\A#{escape(key)}=.*path=#{value[:path]}/
-
else
-
cookie =~ /\A#{escape(key)}=/
-
end
-
}
-
-
header["Set-Cookie"] = cookies.join("\n")
-
-
set_cookie_header!(header, key,
-
{:value => '', :path => nil, :domain => nil,
-
:expires => Time.at(0) }.merge(value))
-
-
nil
-
end
-
2
module_function :delete_cookie_header!
-
-
# Return the bytesize of String; uses String#size under Ruby 1.8 and
-
# String#bytesize under 1.9.
-
2
if ''.respond_to?(:bytesize)
-
2
def bytesize(string)
-
string.bytesize
-
end
-
else
-
def bytesize(string)
-
string.size
-
end
-
end
-
2
module_function :bytesize
-
-
# Modified version of stdlib time.rb Time#rfc2822 to use '%d-%b-%Y' instead
-
# of '% %b %Y'.
-
# It assumes that the time is in GMT to comply to the RFC 2109.
-
#
-
# NOTE: I'm not sure the RFC says it requires GMT, but is ambigous enough
-
# that I'm certain someone implemented only that option.
-
# Do not use %a and %b from Time.strptime, it would use localized names for
-
# weekday and month.
-
#
-
2
def rfc2822(time)
-
wday = Time::RFC2822_DAY_NAME[time.wday]
-
mon = Time::RFC2822_MONTH_NAME[time.mon - 1]
-
time.strftime("#{wday}, %d-#{mon}-%Y %H:%M:%S GMT")
-
end
-
2
module_function :rfc2822
-
-
# Parses the "Range:" header, if present, into an array of Range objects.
-
# Returns nil if the header is missing or syntactically invalid.
-
# Returns an empty array if none of the ranges are satisfiable.
-
2
def byte_ranges(env, size)
-
# See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35>
-
http_range = env['HTTP_RANGE']
-
return nil unless http_range && http_range =~ /bytes=([^;]+)/
-
ranges = []
-
$1.split(/,\s*/).each do |range_spec|
-
return nil unless range_spec =~ /(\d*)-(\d*)/
-
r0,r1 = $1, $2
-
if r0.empty?
-
return nil if r1.empty?
-
# suffix-byte-range-spec, represents trailing suffix of file
-
r0 = size - r1.to_i
-
r0 = 0 if r0 < 0
-
r1 = size - 1
-
else
-
r0 = r0.to_i
-
if r1.empty?
-
r1 = size - 1
-
else
-
r1 = r1.to_i
-
return nil if r1 < r0 # backwards range is syntactically invalid
-
r1 = size-1 if r1 >= size
-
end
-
end
-
ranges << (r0..r1) if r0 <= r1
-
end
-
ranges
-
end
-
2
module_function :byte_ranges
-
-
# Constant time string comparison.
-
2
def secure_compare(a, b)
-
return false unless bytesize(a) == bytesize(b)
-
-
l = a.unpack("C*")
-
-
r, i = 0, -1
-
b.each_byte { |v| r |= v ^ l[i+=1] }
-
r == 0
-
end
-
2
module_function :secure_compare
-
-
# Context allows the use of a compatible middleware at different points
-
# in a request handling stack. A compatible middleware must define
-
# #context which should take the arguments env and app. The first of which
-
# would be the request environment. The second of which would be the rack
-
# application that the request would be forwarded to.
-
2
class Context
-
2
attr_reader :for, :app
-
-
2
def initialize(app_f, app_r)
-
raise 'running context does not respond to #context' unless app_f.respond_to? :context
-
@for, @app = app_f, app_r
-
end
-
-
2
def call(env)
-
@for.context(env, @app)
-
end
-
-
2
def recontext(app)
-
self.class.new(@for, app)
-
end
-
-
2
def context(env, app=@app)
-
recontext(app).call(env)
-
end
-
end
-
-
# A case-insensitive Hash that preserves the original case of a
-
# header when set.
-
2
class HeaderHash < Hash
-
2
def self.new(hash={})
-
HeaderHash === hash ? hash : super(hash)
-
end
-
-
2
def initialize(hash={})
-
super()
-
@names = {}
-
hash.each { |k, v| self[k] = v }
-
end
-
-
2
def each
-
super do |k, v|
-
yield(k, v.respond_to?(:to_ary) ? v.to_ary.join("\n") : v)
-
end
-
end
-
-
2
def to_hash
-
hash = {}
-
each { |k,v| hash[k] = v }
-
hash
-
end
-
-
2
def [](k)
-
super(k) || super(@names[k.downcase])
-
end
-
-
2
def []=(k, v)
-
canonical = k.downcase
-
delete k if @names[canonical] && @names[canonical] != k # .delete is expensive, don't invoke it unless necessary
-
@names[k] = @names[canonical] = k
-
super k, v
-
end
-
-
2
def delete(k)
-
canonical = k.downcase
-
result = super @names.delete(canonical)
-
@names.delete_if { |name,| name.downcase == canonical }
-
result
-
end
-
-
2
def include?(k)
-
@names.include?(k) || @names.include?(k.downcase)
-
end
-
-
2
alias_method :has_key?, :include?
-
2
alias_method :member?, :include?
-
2
alias_method :key?, :include?
-
-
2
def merge!(other)
-
other.each { |k, v| self[k] = v }
-
self
-
end
-
-
2
def merge(other)
-
hash = dup
-
hash.merge! other
-
end
-
-
2
def replace(other)
-
clear
-
other.each { |k, v| self[k] = v }
-
self
-
end
-
end
-
-
2
class KeySpaceConstrainedParams
-
2
def initialize(limit = Utils.key_space_limit)
-
@limit = limit
-
@size = 0
-
@params = {}
-
end
-
-
2
def [](key)
-
@params[key]
-
end
-
-
2
def []=(key, value)
-
@size += key.size if key && !@params.key?(key)
-
raise RangeError, 'exceeded available parameter key space' if @size > @limit
-
@params[key] = value
-
end
-
-
2
def key?(key)
-
@params.key?(key)
-
end
-
-
2
def to_params_hash
-
hash = @params
-
hash.keys.each do |key|
-
value = hash[key]
-
if value.kind_of?(self.class)
-
hash[key] = value.to_params_hash
-
elsif value.kind_of?(Array)
-
value.map! {|x| x.kind_of?(self.class) ? x.to_params_hash : x}
-
end
-
end
-
hash
-
end
-
end
-
-
# Every standard HTTP code mapped to the appropriate message.
-
# Generated with:
-
# curl -s http://www.iana.org/assignments/http-status-codes | \
-
# ruby -ane 'm = /^(\d{3}) +(\S[^\[(]+)/.match($_) and
-
# puts " #{m[1]} => \x27#{m[2].strip}x27,"'
-
2
HTTP_STATUS_CODES = {
-
100 => 'Continue',
-
101 => 'Switching Protocols',
-
102 => 'Processing',
-
200 => 'OK',
-
201 => 'Created',
-
202 => 'Accepted',
-
203 => 'Non-Authoritative Information',
-
204 => 'No Content',
-
205 => 'Reset Content',
-
206 => 'Partial Content',
-
207 => 'Multi-Status',
-
226 => 'IM Used',
-
300 => 'Multiple Choices',
-
301 => 'Moved Permanently',
-
302 => 'Found',
-
303 => 'See Other',
-
304 => 'Not Modified',
-
305 => 'Use Proxy',
-
306 => 'Reserved',
-
307 => 'Temporary Redirect',
-
400 => 'Bad Request',
-
401 => 'Unauthorized',
-
402 => 'Payment Required',
-
403 => 'Forbidden',
-
404 => 'Not Found',
-
405 => 'Method Not Allowed',
-
406 => 'Not Acceptable',
-
407 => 'Proxy Authentication Required',
-
408 => 'Request Timeout',
-
409 => 'Conflict',
-
410 => 'Gone',
-
411 => 'Length Required',
-
412 => 'Precondition Failed',
-
413 => 'Request Entity Too Large',
-
414 => 'Request-URI Too Long',
-
415 => 'Unsupported Media Type',
-
416 => 'Requested Range Not Satisfiable',
-
417 => 'Expectation Failed',
-
418 => "I'm a Teapot",
-
422 => 'Unprocessable Entity',
-
423 => 'Locked',
-
424 => 'Failed Dependency',
-
426 => 'Upgrade Required',
-
500 => 'Internal Server Error',
-
501 => 'Not Implemented',
-
502 => 'Bad Gateway',
-
503 => 'Service Unavailable',
-
504 => 'Gateway Timeout',
-
505 => 'HTTP Version Not Supported',
-
506 => 'Variant Also Negotiates',
-
507 => 'Insufficient Storage',
-
510 => 'Not Extended',
-
}
-
-
# Responses with HTTP status codes that should not have an entity body
-
2
STATUS_WITH_NO_ENTITY_BODY = Set.new((100..199).to_a << 204 << 205 << 304)
-
-
2
SYMBOL_TO_STATUS_CODE = Hash[*HTTP_STATUS_CODES.map { |code, message|
-
104
[message.downcase.gsub(/\s|-/, '_').to_sym, code]
-
}.flatten]
-
-
2
def status_code(status)
-
84
if status.is_a?(Symbol)
-
SYMBOL_TO_STATUS_CODE[status] || 500
-
else
-
84
status.to_i
-
end
-
end
-
2
module_function :status_code
-
-
2
Multipart = Rack::Multipart
-
-
end
-
end
-
2
module Rack
-
-
2
class MockSession # :nodoc:
-
2
attr_writer :cookie_jar
-
2
attr_reader :default_host
-
-
2
def initialize(app, default_host = Rack::Test::DEFAULT_HOST)
-
@app = app
-
@after_request = []
-
@default_host = default_host
-
@last_request = nil
-
@last_response = nil
-
end
-
-
2
def after_request(&block)
-
@after_request << block
-
end
-
-
2
def clear_cookies
-
@cookie_jar = Rack::Test::CookieJar.new([], @default_host)
-
end
-
-
2
def set_cookie(cookie, uri = nil)
-
cookie_jar.merge(cookie, uri)
-
end
-
-
2
def request(uri, env)
-
env["HTTP_COOKIE"] ||= cookie_jar.for(uri)
-
@last_request = Rack::Request.new(env)
-
status, headers, body = @app.call(@last_request.env)
-
-
@last_response = MockResponse.new(status, headers, body, env["rack.errors"].flush)
-
body.close if body.respond_to?(:close)
-
-
cookie_jar.merge(last_response.headers["Set-Cookie"], uri)
-
-
@after_request.each { |hook| hook.call }
-
-
if @last_response.respond_to?(:finish)
-
@last_response.finish
-
else
-
@last_response
-
end
-
end
-
-
# Return the last request issued in the session. Raises an error if no
-
# requests have been sent yet.
-
2
def last_request
-
raise Rack::Test::Error.new("No request yet. Request a page first.") unless @last_request
-
@last_request
-
end
-
-
# Return the last response received in the session. Raises an error if
-
# no requests have been sent yet.
-
2
def last_response
-
raise Rack::Test::Error.new("No response yet. Request a page first.") unless @last_response
-
@last_response
-
end
-
-
2
def cookie_jar
-
@cookie_jar ||= Rack::Test::CookieJar.new([], @default_host)
-
end
-
-
end
-
-
end
-
2
require "uri"
-
2
require "rack"
-
2
require "rack/mock_session"
-
2
require "rack/test/cookie_jar"
-
2
require "rack/test/mock_digest_request"
-
2
require "rack/test/utils"
-
2
require "rack/test/methods"
-
2
require "rack/test/uploaded_file"
-
-
2
module Rack
-
2
module Test
-
2
VERSION = "0.6.2"
-
-
2
DEFAULT_HOST = "example.org"
-
2
MULTIPART_BOUNDARY = "----------XnJLe9ZIbbGUYtzPQJ16u1"
-
-
# The common base class for exceptions raised by Rack::Test
-
2
class Error < StandardError; end
-
-
# This class represents a series of requests issued to a Rack app, sharing
-
# a single cookie jar
-
#
-
# Rack::Test::Session's methods are most often called through Rack::Test::Methods,
-
# which will automatically build a session when it's first used.
-
2
class Session
-
2
extend Forwardable
-
2
include Rack::Test::Utils
-
-
2
def_delegators :@rack_mock_session, :clear_cookies, :set_cookie, :last_response, :last_request
-
-
# Creates a Rack::Test::Session for a given Rack app or Rack::MockSession.
-
#
-
# Note: Generally, you won't need to initialize a Rack::Test::Session directly.
-
# Instead, you should include Rack::Test::Methods into your testing context.
-
# (See README.rdoc for an example)
-
2
def initialize(mock_session)
-
@headers = {}
-
-
if mock_session.is_a?(MockSession)
-
@rack_mock_session = mock_session
-
else
-
@rack_mock_session = MockSession.new(mock_session)
-
end
-
-
@default_host = @rack_mock_session.default_host
-
end
-
-
# Issue a GET request for the given URI with the given params and Rack
-
# environment. Stores the issues request object in #last_request and
-
# the app's response in #last_response. Yield #last_response to a block
-
# if given.
-
#
-
# Example:
-
# get "/"
-
2
def get(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "GET", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a POST request for the given URI. See #get
-
#
-
# Example:
-
# post "/signup", "name" => "Bryan"
-
2
def post(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "POST", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a PUT request for the given URI. See #get
-
#
-
# Example:
-
# put "/"
-
2
def put(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "PUT", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a PATCH request for the given URI. See #get
-
#
-
# Example:
-
# patch "/"
-
2
def patch(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "PATCH", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a DELETE request for the given URI. See #get
-
#
-
# Example:
-
# delete "/"
-
2
def delete(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "DELETE", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue an OPTIONS request for the given URI. See #get
-
#
-
# Example:
-
# options "/"
-
2
def options(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "OPTIONS", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a HEAD request for the given URI. See #get
-
#
-
# Example:
-
# head "/"
-
2
def head(uri, params = {}, env = {}, &block)
-
env = env_for(uri, env.merge(:method => "HEAD", :params => params))
-
process_request(uri, env, &block)
-
end
-
-
# Issue a request to the Rack app for the given URI and optional Rack
-
# environment. Stores the issues request object in #last_request and
-
# the app's response in #last_response. Yield #last_response to a block
-
# if given.
-
#
-
# Example:
-
# request "/"
-
2
def request(uri, env = {}, &block)
-
env = env_for(uri, env)
-
process_request(uri, env, &block)
-
end
-
-
# Set a header to be included on all subsequent requests through the
-
# session. Use a value of nil to remove a previously configured header.
-
#
-
# In accordance with the Rack spec, headers will be included in the Rack
-
# environment hash in HTTP_USER_AGENT form.
-
#
-
# Example:
-
# header "User-Agent", "Firefox"
-
2
def header(name, value)
-
if value.nil?
-
@headers.delete(name)
-
else
-
@headers[name] = value
-
end
-
end
-
-
# Set the username and password for HTTP Basic authorization, to be
-
# included in subsequent requests in the HTTP_AUTHORIZATION header.
-
#
-
# Example:
-
# basic_authorize "bryan", "secret"
-
2
def basic_authorize(username, password)
-
encoded_login = ["#{username}:#{password}"].pack("m*")
-
header('Authorization', "Basic #{encoded_login}")
-
end
-
-
2
alias_method :authorize, :basic_authorize
-
-
# Set the username and password for HTTP Digest authorization, to be
-
# included in subsequent requests in the HTTP_AUTHORIZATION header.
-
#
-
# Example:
-
# digest_authorize "bryan", "secret"
-
2
def digest_authorize(username, password)
-
@digest_username = username
-
@digest_password = password
-
end
-
-
# Rack::Test will not follow any redirects automatically. This method
-
# will follow the redirect returned (including setting the Referer header
-
# on the new request) in the last response. If the last response was not
-
# a redirect, an error will be raised.
-
2
def follow_redirect!
-
unless last_response.redirect?
-
raise Error.new("Last response was not a redirect. Cannot follow_redirect!")
-
end
-
-
get(last_response["Location"], {}, { "HTTP_REFERER" => last_request.url })
-
end
-
-
2
private
-
-
2
def env_for(path, env)
-
uri = URI.parse(path)
-
uri.path = "/#{uri.path}" unless uri.path[0] == ?/
-
uri.host ||= @default_host
-
-
env = default_env.merge(env)
-
-
env["HTTP_HOST"] ||= [uri.host, (uri.port if uri.port != uri.default_port)].compact.join(":")
-
-
env.update("HTTPS" => "on") if URI::HTTPS === uri
-
env["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" if env[:xhr]
-
-
# TODO: Remove this after Rack 1.1 has been released.
-
# Stringifying and upcasing methods has be commit upstream
-
env["REQUEST_METHOD"] ||= env[:method] ? env[:method].to_s.upcase : "GET"
-
-
if env["REQUEST_METHOD"] == "GET"
-
# merge :params with the query string
-
if params = env[:params]
-
params = parse_nested_query(params) if params.is_a?(String)
-
params.update(parse_nested_query(uri.query))
-
uri.query = build_nested_query(params)
-
end
-
elsif !env.has_key?(:input)
-
env["CONTENT_TYPE"] ||= "application/x-www-form-urlencoded"
-
-
if env[:params].is_a?(Hash)
-
if data = build_multipart(env[:params])
-
env[:input] = data
-
env["CONTENT_LENGTH"] ||= data.length.to_s
-
env["CONTENT_TYPE"] = "multipart/form-data; boundary=#{MULTIPART_BOUNDARY}"
-
else
-
env[:input] = params_to_string(env[:params])
-
end
-
else
-
env[:input] = env[:params]
-
end
-
end
-
-
env.delete(:params)
-
-
if env.has_key?(:cookie)
-
set_cookie(env.delete(:cookie), uri)
-
end
-
-
Rack::MockRequest.env_for(uri.to_s, env)
-
end
-
-
2
def process_request(uri, env)
-
uri = URI.parse(uri)
-
uri.host ||= @default_host
-
-
@rack_mock_session.request(uri, env)
-
-
if retry_with_digest_auth?(env)
-
auth_env = env.merge({
-
"HTTP_AUTHORIZATION" => digest_auth_header,
-
"rack-test.digest_auth_retry" => true
-
})
-
auth_env.delete('rack.request')
-
process_request(uri.path, auth_env)
-
else
-
yield last_response if block_given?
-
-
last_response
-
end
-
end
-
-
2
def digest_auth_header
-
challenge = last_response["WWW-Authenticate"].split(" ", 2).last
-
params = Rack::Auth::Digest::Params.parse(challenge)
-
-
params.merge!({
-
"username" => @digest_username,
-
"nc" => "00000001",
-
"cnonce" => "nonsensenonce",
-
"uri" => last_request.fullpath,
-
"method" => last_request.env["REQUEST_METHOD"],
-
})
-
-
params["response"] = MockDigestRequest.new(params).response(@digest_password)
-
-
"Digest #{params}"
-
end
-
-
2
def retry_with_digest_auth?(env)
-
last_response.status == 401 &&
-
digest_auth_configured? &&
-
!env["rack-test.digest_auth_retry"]
-
end
-
-
2
def digest_auth_configured?
-
@digest_username
-
end
-
-
2
def default_env
-
{ "rack.test" => true, "REMOTE_ADDR" => "127.0.0.1" }.merge(headers_for_env)
-
end
-
-
2
def headers_for_env
-
converted_headers = {}
-
-
@headers.each do |name, value|
-
env_key = name.upcase.gsub("-", "_")
-
env_key = "HTTP_" + env_key unless "CONTENT_TYPE" == env_key
-
converted_headers[env_key] = value
-
end
-
-
converted_headers
-
end
-
-
2
def params_to_string(params)
-
case params
-
when Hash then build_nested_query(params)
-
when nil then ""
-
else params
-
end
-
end
-
-
end
-
-
2
def self.encoding_aware_strings?
-
defined?(Encoding) && "".respond_to?(:encode)
-
end
-
-
end
-
end
-
2
require "uri"
-
2
require "time"
-
-
2
module Rack
-
2
module Test
-
-
2
class Cookie # :nodoc:
-
2
include Rack::Utils
-
-
# :api: private
-
2
attr_reader :name, :value
-
-
# :api: private
-
2
def initialize(raw, uri = nil, default_host = DEFAULT_HOST)
-
@default_host = default_host
-
uri ||= default_uri
-
-
# separate the name / value pair from the cookie options
-
@name_value_raw, options = raw.split(/[;,] */n, 2)
-
-
@name, @value = parse_query(@name_value_raw, ';').to_a.first
-
@options = parse_query(options, ';')
-
-
@options["domain"] ||= (uri.host || default_host)
-
@options["path"] ||= uri.path.sub(/\/[^\/]*\Z/, "")
-
end
-
-
2
def replaces?(other)
-
[name.downcase, domain, path] == [other.name.downcase, other.domain, other.path]
-
end
-
-
# :api: private
-
2
def raw
-
@name_value_raw
-
end
-
-
# :api: private
-
2
def empty?
-
@value.nil? || @value.empty?
-
end
-
-
# :api: private
-
2
def domain
-
@options["domain"]
-
end
-
-
2
def secure?
-
@options.has_key?("secure")
-
end
-
-
# :api: private
-
2
def path
-
@options["path"].strip || "/"
-
end
-
-
# :api: private
-
2
def expires
-
Time.parse(@options["expires"]) if @options["expires"]
-
end
-
-
# :api: private
-
2
def expired?
-
expires && expires < Time.now
-
end
-
-
# :api: private
-
2
def valid?(uri)
-
uri ||= default_uri
-
-
if uri.host.nil?
-
uri.host = @default_host
-
end
-
-
real_domain = domain =~ /^\./ ? domain[1..-1] : domain
-
(!secure? || (secure? && uri.scheme == "https")) &&
-
uri.host =~ Regexp.new("#{Regexp.escape(real_domain)}$", Regexp::IGNORECASE) &&
-
uri.path =~ Regexp.new("^#{Regexp.escape(path)}")
-
end
-
-
# :api: private
-
2
def matches?(uri)
-
! expired? && valid?(uri)
-
end
-
-
# :api: private
-
2
def <=>(other)
-
# Orders the cookies from least specific to most
-
[name, path, domain.reverse] <=> [other.name, other.path, other.domain.reverse]
-
end
-
-
2
protected
-
-
2
def default_uri
-
URI.parse("//" + @default_host + "/")
-
end
-
-
end
-
-
2
class CookieJar # :nodoc:
-
-
# :api: private
-
2
def initialize(cookies = [], default_host = DEFAULT_HOST)
-
@default_host = default_host
-
@cookies = cookies
-
@cookies.sort!
-
end
-
-
2
def [](name)
-
cookies = hash_for(nil)
-
# TODO: Should be case insensitive
-
cookies[name] && cookies[name].value
-
end
-
-
2
def []=(name, value)
-
merge("#{name}=#{Rack::Utils.escape(value)}")
-
end
-
-
2
def delete(name)
-
@cookies.reject! do |cookie|
-
cookie.name == name
-
end
-
end
-
-
2
def merge(raw_cookies, uri = nil)
-
return unless raw_cookies
-
-
if raw_cookies.is_a? String
-
raw_cookies = raw_cookies.split("\n")
-
raw_cookies.reject!{|c| c.empty? }
-
end
-
-
raw_cookies.each do |raw_cookie|
-
cookie = Cookie.new(raw_cookie, uri, @default_host)
-
self << cookie if cookie.valid?(uri)
-
end
-
end
-
-
2
def <<(new_cookie)
-
@cookies.reject! do |existing_cookie|
-
new_cookie.replaces?(existing_cookie)
-
end
-
-
@cookies << new_cookie
-
@cookies.sort!
-
end
-
-
# :api: private
-
2
def for(uri)
-
hash_for(uri).values.map { |c| c.raw }.join(';')
-
end
-
-
2
def to_hash
-
cookies = {}
-
-
hash_for(nil).each do |name, cookie|
-
cookies[name] = cookie.value
-
end
-
-
return cookies
-
end
-
-
2
protected
-
-
2
def hash_for(uri = nil)
-
cookies = {}
-
-
# The cookies are sorted by most specific first. So, we loop through
-
# all the cookies in order and add it to a hash by cookie name if
-
# the cookie can be sent to the current URI. It's added to the hash
-
# so that when we are done, the cookies will be unique by name and
-
# we'll have grabbed the most specific to the URI.
-
@cookies.each do |cookie|
-
cookies[cookie.name] = cookie if !uri || cookie.matches?(uri)
-
end
-
-
return cookies
-
end
-
-
end
-
-
end
-
end
-
2
require "forwardable"
-
-
2
module Rack
-
2
module Test
-
-
# This module serves as the primary integration point for using Rack::Test
-
# in a testing environment. It depends on an app method being defined in the
-
# same context, and provides the Rack::Test API methods (see Rack::Test::Session
-
# for their documentation).
-
#
-
# Example:
-
#
-
# class HomepageTest < Test::Unit::TestCase
-
# include Rack::Test::Methods
-
#
-
# def app
-
# MyApp.new
-
# end
-
# end
-
2
module Methods
-
2
extend Forwardable
-
-
2
def rack_mock_session(name = :default) # :nodoc:
-
return build_rack_mock_session unless name
-
-
@_rack_mock_sessions ||= {}
-
@_rack_mock_sessions[name] ||= build_rack_mock_session
-
end
-
-
2
def build_rack_mock_session # :nodoc:
-
Rack::MockSession.new(app)
-
end
-
-
2
def rack_test_session(name = :default) # :nodoc:
-
return build_rack_test_session(name) unless name
-
-
@_rack_test_sessions ||= {}
-
@_rack_test_sessions[name] ||= build_rack_test_session(name)
-
end
-
-
2
def build_rack_test_session(name) # :nodoc:
-
Rack::Test::Session.new(rack_mock_session(name))
-
end
-
-
2
def current_session # :nodoc:
-
rack_test_session(_current_session_names.last)
-
end
-
-
2
def with_session(name) # :nodoc:
-
_current_session_names.push(name)
-
yield rack_test_session(name)
-
_current_session_names.pop
-
end
-
-
2
def _current_session_names # :nodoc:
-
@_current_session_names ||= [:default]
-
end
-
-
2
METHODS = [
-
:request,
-
:get,
-
:post,
-
:put,
-
:patch,
-
:delete,
-
:options,
-
:head,
-
:follow_redirect!,
-
:header,
-
:set_cookie,
-
:clear_cookies,
-
:authorize,
-
:basic_authorize,
-
:digest_authorize,
-
:last_response,
-
:last_request
-
]
-
-
2
def_delegators :current_session, *METHODS
-
end
-
end
-
end
-
2
module Rack
-
2
module Test
-
-
2
class MockDigestRequest # :nodoc:
-
-
2
def initialize(params)
-
@params = params
-
end
-
-
2
def method_missing(sym)
-
if @params.has_key? k = sym.to_s
-
return @params[k]
-
end
-
-
super
-
end
-
-
2
def method
-
@params['method']
-
end
-
-
2
def response(password)
-
Rack::Auth::Digest::MD5.new(nil).send :digest, self, password
-
end
-
-
end
-
-
end
-
end
-
2
require "tempfile"
-
2
require "fileutils"
-
-
2
module Rack
-
2
module Test
-
-
# Wraps a Tempfile with a content type. Including one or more UploadedFile's
-
# in the params causes Rack::Test to build and issue a multipart request.
-
#
-
# Example:
-
# post "/photos", "file" => Rack::Test::UploadedFile.new("me.jpg", "image/jpeg")
-
2
class UploadedFile
-
-
# The filename, *not* including the path, of the "uploaded" file
-
2
attr_reader :original_filename
-
-
# The content type of the "uploaded" file
-
2
attr_accessor :content_type
-
-
2
def initialize(path, content_type = "text/plain", binary = false)
-
raise "#{path} file does not exist" unless ::File.exist?(path)
-
-
@content_type = content_type
-
@original_filename = ::File.basename(path)
-
-
@tempfile = Tempfile.new(@original_filename)
-
@tempfile.set_encoding(Encoding::BINARY) if @tempfile.respond_to?(:set_encoding)
-
@tempfile.binmode if binary
-
-
FileUtils.copy_file(path, @tempfile.path)
-
end
-
-
2
def path
-
@tempfile.path
-
end
-
-
2
alias_method :local_path, :path
-
-
2
def method_missing(method_name, *args, &block) #:nodoc:
-
@tempfile.__send__(method_name, *args, &block)
-
end
-
-
2
def respond_to?(method_name, include_private = false) #:nodoc:
-
@tempfile.respond_to?(method_name, include_private) || super
-
end
-
-
end
-
-
end
-
end
-
2
module Rack
-
2
module Test
-
-
2
module Utils # :nodoc:
-
2
include Rack::Utils
-
-
2
def build_nested_query(value, prefix = nil)
-
case value
-
when Array
-
value.map do |v|
-
unless unescape(prefix) =~ /\[\]$/
-
prefix = "#{prefix}[]"
-
end
-
build_nested_query(v, "#{prefix}")
-
end.join("&")
-
when Hash
-
value.map do |k, v|
-
build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k))
-
end.join("&")
-
when NilClass
-
prefix.to_s
-
else
-
"#{prefix}=#{escape(value)}"
-
end
-
end
-
-
2
module_function :build_nested_query
-
-
2
def build_multipart(params, first = true)
-
if first
-
unless params.is_a?(Hash)
-
raise ArgumentError, "value must be a Hash"
-
end
-
-
multipart = false
-
query = lambda { |value|
-
case value
-
when Array
-
value.each(&query)
-
when Hash
-
value.values.each(&query)
-
when UploadedFile
-
multipart = true
-
end
-
}
-
params.values.each(&query)
-
return nil unless multipart
-
end
-
-
flattened_params = Hash.new
-
-
params.each do |key, value|
-
k = first ? key.to_s : "[#{key}]"
-
-
case value
-
when Array
-
value.map do |v|
-
-
if (v.is_a?(Hash))
-
build_multipart(v, false).each { |subkey, subvalue|
-
flattened_params["#{k}[]#{subkey}"] = subvalue
-
}
-
else
-
flattened_params["#{k}[]"] = value
-
end
-
-
end
-
when Hash
-
build_multipart(value, false).each { |subkey, subvalue|
-
flattened_params[k + subkey] = subvalue
-
}
-
else
-
flattened_params[k] = value
-
end
-
end
-
-
if first
-
build_parts(flattened_params)
-
else
-
flattened_params
-
end
-
end
-
-
2
module_function :build_multipart
-
-
2
private
-
2
def build_parts(parameters)
-
parameters.map { |name, value|
-
if value.respond_to?(:original_filename)
-
build_file_part(name, value)
-
-
elsif value.is_a?(Array) and value.all? { |v| v.respond_to?(:original_filename) }
-
value.map do |v|
-
build_file_part(name, v)
-
end.join
-
-
else
-
primitive_part = build_primitive_part(name, value)
-
Rack::Test.encoding_aware_strings? ? primitive_part.force_encoding('BINARY') : primitive_part
-
end
-
-
}.join + "--#{MULTIPART_BOUNDARY}--\r"
-
end
-
-
2
def build_primitive_part(parameter_name, value)
-
unless value.is_a? Array
-
value = [value]
-
end
-
value.map do |v|
-
<<-EOF
-
--#{MULTIPART_BOUNDARY}\r
-
Content-Disposition: form-data; name="#{parameter_name}"\r
-
\r
-
#{v}\r
-
EOF
-
end.join
-
end
-
-
2
def build_file_part(parameter_name, uploaded_file)
-
::File.open(uploaded_file.path, "rb") do |physical_file|
-
physical_file.set_encoding(Encoding::BINARY) if physical_file.respond_to?(:set_encoding)
-
<<-EOF
-
--#{MULTIPART_BOUNDARY}\r
-
Content-Disposition: form-data; name="#{parameter_name}"; filename="#{escape(uploaded_file.original_filename)}"\r
-
Content-Type: #{uploaded_file.content_type}\r
-
Content-Length: #{::File.stat(uploaded_file.path).size}\r
-
\r
-
#{physical_file.read}\r
-
EOF
-
end
-
end
-
-
end
-
-
end
-
end
-
2
require "rails_erd"
-
2
require "active_support/ordered_options"
-
2
require "rails_erd/railtie" if defined? Rails
-
-
# Welcome to the API documentation of Rails ERD. If you wish to extend or
-
# customise the output that is generated by Rails ERD, you have come to the
-
# right place.
-
#
-
# == Creating custom output
-
#
-
# If you want to create your own kind of diagrams, or some other output, a
-
# good starting point is the RailsERD::Diagram class. It can serve as the base
-
# of your output generation code.
-
#
-
# == Options
-
#
-
# Rails ERD provides several options that allow you to customise the
-
# generation of the diagram and the domain model itself. For an overview of
-
# all options available in Rails ERD, see README.rdoc.
-
#
-
# You can specify the option on the command line if you use Rails ERD with
-
# Rake:
-
#
-
# % rake erd orientation=vertical title='My model diagram'
-
#
-
# When using Rails ERD from within Ruby, you can set the options on the
-
# RailsERD namespace module:
-
#
-
# RailsERD.options.orientation = :vertical
-
# RailsERD.options.title = "My model diagram"
-
2
module RailsERD
-
2
class << self
-
# Access to default options. Any instance of RailsERD::Domain and
-
# RailsERD::Diagram will use these options unless overridden.
-
2
attr_accessor :options
-
end
-
-
2
module Inspectable # @private :nodoc:
-
2
def inspection_attributes(*attributes)
-
attribute_inspection = attributes.collect { |attribute|
-
" @#{attribute}=\#{[Symbol, String].include?(#{attribute}.class) ? #{attribute}.inspect : #{attribute}}"
-
}.join
-
class_eval <<-RUBY
-
def inspect
-
"#<\#{self.class}:0x%.14x#{attribute_inspection}>" % (object_id << 1)
-
end
-
RUBY
-
end
-
end
-
-
2
self.options = ActiveSupport::OrderedOptions[
-
:attributes, :content,
-
:disconnected, true,
-
:filename, "erd",
-
:filetype, :pdf,
-
:indirect, true,
-
:inheritance, false,
-
:markup, true,
-
:notation, :simple,
-
:orientation, :horizontal,
-
:polymorphism, false,
-
:warn, true,
-
:title, true,
-
:exclude, nil,
-
:only, nil
-
]
-
end
-
2
module RailsERD
-
# Rails ERD integrates with Rails 3. If you add it to your +Gemfile+, you
-
# will gain a Rake task called +erd+, which you can use to generate diagrams
-
# of your domain model.
-
2
class Railtie < Rails::Railtie
-
2
rake_tasks do
-
load "rails_erd/tasks.rake"
-
end
-
end
-
end
-
2
require 'rails/ruby_version_check'
-
-
2
require 'pathname'
-
-
2
require 'active_support'
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'active_support/core_ext/array/extract_options'
-
2
require 'active_support/core_ext/logger'
-
-
2
require 'rails/application'
-
2
require 'rails/version'
-
-
2
require 'active_support/railtie'
-
2
require 'action_dispatch/railtie'
-
-
# For Ruby 1.8, this initialization sets $KCODE to 'u' to enable the
-
# multibyte safe operations. Plugin authors supporting other encodings
-
# should override this behavior and set the relevant +default_charset+
-
# on ActionController::Base.
-
#
-
# For Ruby 1.9, UTF-8 is the default internal and external encoding.
-
2
if RUBY_VERSION < '1.9'
-
$KCODE='u'
-
else
-
2
silence_warnings do
-
2
Encoding.default_external = Encoding::UTF_8
-
2
Encoding.default_internal = Encoding::UTF_8
-
end
-
end
-
-
2
module Rails
-
2
autoload :Info, 'rails/info'
-
2
autoload :InfoController, 'rails/info_controller'
-
-
2
class << self
-
2
def application
-
263
@@application ||= nil
-
end
-
-
2
def application=(application)
-
2
@@application = application
-
end
-
-
# The Configuration instance used to configure the Rails environment
-
2
def configuration
-
application.config
-
end
-
-
2
def initialize!
-
application.initialize!
-
end
-
-
2
def initialized?
-
@@initialized || false
-
end
-
-
2
def initialized=(initialized)
-
@@initialized ||= initialized
-
end
-
-
2
def logger
-
15
@@logger ||= nil
-
end
-
-
2
def logger=(logger)
-
2
@@logger = logger
-
end
-
-
2
def backtrace_cleaner
-
@@backtrace_cleaner ||= begin
-
# Relies on Active Support, so we have to lazy load to postpone definition until AS has been loaded
-
1
require 'rails/backtrace_cleaner'
-
1
Rails::BacktraceCleaner.new
-
1
end
-
end
-
-
2
def root
-
13
application && application.config.root
-
end
-
-
2
def env
-
34
@_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
-
end
-
-
2
def env=(environment)
-
@_env = ActiveSupport::StringInquirer.new(environment)
-
end
-
-
2
def cache
-
RAILS_CACHE
-
end
-
-
# Returns all rails groups for loading based on:
-
#
-
# * The Rails environment;
-
# * The environment variable RAILS_GROUPS;
-
# * The optional envs given as argument and the hash with group dependencies;
-
#
-
# == Examples
-
#
-
# groups :assets => [:development, :test]
-
#
-
# # Returns
-
# # => [:default, :development, :assets] for Rails.env == "development"
-
# # => [:default, :production] for Rails.env == "production"
-
#
-
2
def groups(*groups)
-
hash = groups.extract_options!
-
env = Rails.env
-
groups.unshift(:default, env)
-
groups.concat ENV["RAILS_GROUPS"].to_s.split(",")
-
groups.concat hash.map { |k,v| k if v.map(&:to_s).include?(env) }
-
groups.compact!
-
groups.uniq!
-
groups
-
end
-
-
2
def version
-
2
VERSION::STRING
-
end
-
-
2
def public_path
-
4
application && application.paths["public"].first
-
end
-
end
-
end
-
2
require "rails"
-
-
%w(
-
active_record
-
2
action_controller
-
action_mailer
-
active_resource
-
rails/test_unit
-
sprockets
-
).each do |framework|
-
12
begin
-
12
require "#{framework}/railtie"
-
rescue LoadError
-
end
-
end
-
2
require 'active_support/core_ext/hash/reverse_merge'
-
2
require 'fileutils'
-
2
require 'rails/plugin'
-
2
require 'rails/engine'
-
-
2
module Rails
-
# In Rails 3.0, a Rails::Application object was introduced which is nothing more than
-
# an Engine but with the responsibility of coordinating the whole boot process.
-
#
-
# == Initialization
-
#
-
# Rails::Application is responsible for executing all railties, engines and plugin
-
# initializers. It also executes some bootstrap initializers (check
-
# Rails::Application::Bootstrap) and finishing initializers, after all the others
-
# are executed (check Rails::Application::Finisher).
-
#
-
# == Configuration
-
#
-
# Besides providing the same configuration as Rails::Engine and Rails::Railtie,
-
# the application object has several specific configurations, for example
-
# "allow_concurrency", "cache_classes", "consider_all_requests_local", "filter_parameters",
-
# "logger", "reload_plugins" and so forth.
-
#
-
# Check Rails::Application::Configuration to see them all.
-
#
-
# == Routes
-
#
-
# The application object is also responsible for holding the routes and reloading routes
-
# whenever the files change in development.
-
#
-
# == Middlewares
-
#
-
# The Application is also responsible for building the middleware stack.
-
#
-
# == Booting process
-
#
-
# The application is also responsible for setting up and executing the booting
-
# process. From the moment you require "config/application.rb" in your app,
-
# the booting process goes like this:
-
#
-
# 1) require "config/boot.rb" to setup load paths
-
# 2) require railties and engines
-
# 3) Define Rails.application as "class MyApp::Application < Rails::Application"
-
# 4) Run config.before_configuration callbacks
-
# 5) Load config/environments/ENV.rb
-
# 6) Run config.before_initialize callbacks
-
# 7) Run Railtie#initializer defined by railties, engines and application.
-
# One by one, each engine sets up its load paths, routes and runs its config/initializers/* files.
-
# 9) Custom Railtie#initializers added by railties, engines and applications are executed
-
# 10) Build the middleware stack and run to_prepare callbacks
-
# 11) Run config.before_eager_load and eager_load if cache classes is true
-
# 12) Run config.after_initialize callbacks
-
#
-
2
class Application < Engine
-
2
autoload :Bootstrap, 'rails/application/bootstrap'
-
2
autoload :Configuration, 'rails/application/configuration'
-
2
autoload :Finisher, 'rails/application/finisher'
-
2
autoload :Railties, 'rails/application/railties'
-
2
autoload :RoutesReloader, 'rails/application/routes_reloader'
-
-
2
class << self
-
2
def inherited(base)
-
2
raise "You cannot have more than one Rails::Application" if Rails.application
-
2
super
-
2
Rails.application = base.instance
-
2
Rails.application.add_lib_to_load_path!
-
2
ActiveSupport.run_load_hooks(:before_configuration, base.instance)
-
end
-
end
-
-
2
attr_accessor :assets, :sandbox
-
2
alias_method :sandbox?, :sandbox
-
2
attr_reader :reloaders
-
-
2
delegate :default_url_options, :default_url_options=, :to => :routes
-
-
2
def initialize
-
2
super
-
2
@initialized = false
-
2
@reloaders = []
-
end
-
-
# This method is called just after an application inherits from Rails::Application,
-
# allowing the developer to load classes in lib and use them during application
-
# configuration.
-
#
-
# class MyApplication < Rails::Application
-
# require "my_backend" # in lib/my_backend
-
# config.i18n.backend = MyBackend
-
# end
-
#
-
# Notice this method takes into consideration the default root path. So if you
-
# are changing config.root inside your application definition or having a custom
-
# Rails application, you will need to add lib to $LOAD_PATH on your own in case
-
# you need to load files in lib/ during the application configuration as well.
-
2
def add_lib_to_load_path! #:nodoc:
-
2
path = config.root.join('lib').to_s
-
2
$LOAD_PATH.unshift(path) if File.exists?(path)
-
end
-
-
2
def require_environment! #:nodoc:
-
environment = paths["config/environment"].existent.first
-
require environment if environment
-
end
-
-
# Reload application routes regardless if they changed or not.
-
2
def reload_routes!
-
routes_reloader.reload!
-
end
-
-
2
def routes_reloader #:nodoc:
-
6
@routes_reloader ||= RoutesReloader.new
-
end
-
-
# Returns an array of file paths appended with a hash of directories-extensions
-
# suitable for ActiveSupport::FileUpdateChecker API.
-
2
def watchable_args
-
2
files = []
-
2
files.concat config.watchable_files
-
-
2
dirs = {}
-
2
dirs.merge! config.watchable_dirs
-
2
ActiveSupport::Dependencies.autoload_paths.each do |path|
-
14
dirs[path.to_s] = [:rb]
-
end
-
-
2
[files, dirs]
-
end
-
-
# Initialize the application passing the given group. By default, the
-
# group is :default but sprockets precompilation passes group equals
-
# to assets if initialize_on_precompile is false to avoid booting the
-
# whole app.
-
2
def initialize!(group=:default) #:nodoc:
-
2
raise "Application has been already initialized." if @initialized
-
2
run_initializers(group, self)
-
2
@initialized = true
-
2
self
-
end
-
-
# Load the application and its railties tasks and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.rake_tasks</tt> for more info.
-
2
def load_tasks(app=self)
-
initialize_tasks
-
super
-
self
-
end
-
-
# Load the application console and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.console</tt> for more info.
-
2
def load_console(app=self)
-
initialize_console
-
super
-
self
-
end
-
-
# Load the application runner and invoke the registered hooks.
-
# Check <tt>Rails::Railtie.runner</tt> for more info.
-
2
def load_runner(app=self)
-
initialize_runner
-
super
-
self
-
end
-
-
# Rails.application.env_config stores some of the Rails initial environment parameters.
-
# Currently stores:
-
#
-
# * "action_dispatch.parameter_filter" => config.filter_parameters,
-
# * "action_dispatch.secret_token" => config.secret_token,
-
# * "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
-
# * "action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
-
# * "action_dispatch.logger" => Rails.logger,
-
# * "action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner
-
#
-
# These parameters will be used by middlewares and engines to configure themselves.
-
#
-
2
def env_config
-
@app_env_config ||= super.merge({
-
"action_dispatch.parameter_filter" => config.filter_parameters,
-
"action_dispatch.secret_token" => config.secret_token,
-
"action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
-
"action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
-
"action_dispatch.logger" => Rails.logger,
-
"action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner
-
75
})
-
end
-
-
# Returns the ordered railties for this application considering railties_order.
-
2
def ordered_railties #:nodoc:
-
@ordered_railties ||= begin
-
2
order = config.railties_order.map do |railtie|
-
2
if railtie == :main_app
-
self
-
elsif railtie.respond_to?(:instance)
-
railtie.instance
-
else
-
2
railtie
-
end
-
end
-
-
2
all = (railties.all - order)
-
2
all.push(self) unless (all + order).include?(self)
-
2
order.push(:all) unless order.include?(:all)
-
-
2
index = order.index(:all)
-
2
order[index] = all
-
2
order.reverse.flatten
-
2
end
-
end
-
-
2
def initializers #:nodoc:
-
Bootstrap.initializers_for(self) +
-
super +
-
2
Finisher.initializers_for(self)
-
end
-
-
2
def config #:nodoc:
-
358
@config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd))
-
end
-
-
2
def to_app
-
self
-
end
-
-
2
def helpers_paths #:nodoc:
-
29
config.helpers_paths
-
end
-
-
2
def call(env)
-
env["ORIGINAL_FULLPATH"] = build_original_fullpath(env)
-
super(env)
-
end
-
-
2
protected
-
-
2
alias :build_middleware_stack :app
-
-
2
def reload_dependencies?
-
config.reload_classes_only_on_change != true || reloaders.map(&:updated?).any?
-
end
-
-
2
def default_middleware_stack
-
2
require 'action_controller/railtie'
-
-
2
ActionDispatch::MiddlewareStack.new.tap do |middleware|
-
2
if rack_cache = config.action_controller.perform_caching && config.action_dispatch.rack_cache
-
require "action_dispatch/http/rack_cache"
-
middleware.use ::Rack::Cache, rack_cache
-
end
-
-
2
if config.force_ssl
-
require "rack/ssl"
-
middleware.use ::Rack::SSL, config.ssl_options
-
end
-
-
2
if config.serve_static_assets
-
2
middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
-
end
-
-
2
middleware.use ::Rack::Lock unless config.allow_concurrency
-
2
middleware.use ::Rack::Runtime
-
2
middleware.use ::Rack::MethodOverride
-
2
middleware.use ::ActionDispatch::RequestId
-
2
middleware.use ::Rails::Rack::Logger, config.log_tags # must come after Rack::MethodOverride to properly log overridden methods
-
2
middleware.use ::ActionDispatch::ShowExceptions, config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path)
-
2
middleware.use ::ActionDispatch::DebugExceptions
-
2
middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
-
-
2
if config.action_dispatch.x_sendfile_header.present?
-
middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
-
end
-
-
2
unless config.cache_classes
-
app = self
-
middleware.use ::ActionDispatch::Reloader, lambda { app.reload_dependencies? }
-
end
-
-
2
middleware.use ::ActionDispatch::Callbacks
-
2
middleware.use ::ActionDispatch::Cookies
-
-
2
if config.session_store
-
2
if config.force_ssl && !config.session_options.key?(:secure)
-
config.session_options[:secure] = true
-
end
-
2
middleware.use config.session_store, config.session_options
-
2
middleware.use ::ActionDispatch::Flash
-
end
-
-
2
middleware.use ::ActionDispatch::ParamsParser
-
2
middleware.use ::ActionDispatch::Head
-
2
middleware.use ::Rack::ConditionalGet
-
2
middleware.use ::Rack::ETag, "no-cache"
-
-
2
if config.action_dispatch.best_standards_support
-
2
middleware.use ::ActionDispatch::BestStandardsSupport, config.action_dispatch.best_standards_support
-
end
-
end
-
end
-
-
2
def initialize_tasks #:nodoc:
-
self.class.rake_tasks do
-
require "rails/tasks"
-
task :environment do
-
$rails_rake_task = true
-
require_environment!
-
end
-
end
-
end
-
-
2
def initialize_console #:nodoc:
-
require "pp"
-
require "rails/console/app"
-
require "rails/console/helpers"
-
end
-
-
2
def initialize_runner #:nodoc:
-
end
-
-
2
def build_original_fullpath(env)
-
path_info = env["PATH_INFO"]
-
query_string = env["QUERY_STRING"]
-
script_name = env["SCRIPT_NAME"]
-
-
if query_string.present?
-
"#{script_name}#{path_info}?#{query_string}"
-
else
-
"#{script_name}#{path_info}"
-
end
-
end
-
end
-
end
-
2
require "active_support/notifications"
-
2
require "active_support/dependencies"
-
2
require "active_support/descendants_tracker"
-
-
2
module Rails
-
2
class Application
-
2
module Bootstrap
-
2
include Initializable
-
-
2
initializer :load_environment_hook, :group => :all do end
-
-
2
initializer :load_active_support, :group => :all do
-
2
require "active_support/all" unless config.active_support.bare
-
end
-
-
# Preload all frameworks specified by the Configuration#frameworks.
-
# Used by Passenger to ensure everything's loaded before forking and
-
# to avoid autoload race conditions in JRuby.
-
2
initializer :preload_frameworks, :group => :all do
-
2
ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks
-
end
-
-
# Initialize the logger early in the stack in case we need to log some deprecation.
-
2
initializer :initialize_logger, :group => :all do
-
2
Rails.logger ||= config.logger || begin
-
2
path = config.paths["log"].first
-
2
unless File.exist? File.dirname path
-
FileUtils.mkdir_p File.dirname path
-
end
-
-
2
f = File.open path, 'a'
-
2
f.binmode
-
2
f.sync = true # make sure every write flushes
-
-
2
logger = ActiveSupport::TaggedLogging.new(
-
ActiveSupport::BufferedLogger.new(f)
-
)
-
2
logger.level = ActiveSupport::BufferedLogger.const_get(config.log_level.to_s.upcase)
-
2
logger
-
rescue StandardError
-
logger = ActiveSupport::TaggedLogging.new(ActiveSupport::BufferedLogger.new(STDERR))
-
logger.level = ActiveSupport::BufferedLogger::WARN
-
logger.warn(
-
"Rails Error: Unable to access log file. Please ensure that #{path} exists and is chmod 0666. " +
-
"The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
-
)
-
logger
-
end
-
end
-
-
# Initialize cache early in the stack so railties can make use of it.
-
2
initializer :initialize_cache, :group => :all do
-
2
unless defined?(RAILS_CACHE)
-
4
silence_warnings { Object.const_set "RAILS_CACHE", ActiveSupport::Cache.lookup_store(config.cache_store) }
-
-
2
if RAILS_CACHE.respond_to?(:middleware)
-
2
config.middleware.insert_before("Rack::Runtime", RAILS_CACHE.middleware)
-
end
-
end
-
end
-
-
# Sets the dependency loading mechanism.
-
# TODO: Remove files from the $" and always use require.
-
2
initializer :initialize_dependency_mechanism, :group => :all do
-
2
ActiveSupport::Dependencies.mechanism = config.cache_classes ? :require : :load
-
end
-
-
2
initializer :bootstrap_hook, :group => :all do |app|
-
2
ActiveSupport.run_load_hooks(:before_initialize, app)
-
end
-
end
-
end
-
end
-
2
require 'active_support/core_ext/string/encoding'
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'active_support/file_update_checker'
-
2
require 'rails/engine/configuration'
-
-
2
module Rails
-
2
class Application
-
2
class Configuration < ::Rails::Engine::Configuration
-
2
attr_accessor :allow_concurrency, :asset_host, :asset_path, :assets,
-
:cache_classes, :cache_store, :consider_all_requests_local,
-
:dependency_loading, :exceptions_app, :file_watcher, :filter_parameters,
-
:force_ssl, :helpers_paths, :logger, :log_tags, :preload_frameworks,
-
:railties_order, :relative_url_root, :reload_plugins, :secret_token,
-
:serve_static_assets, :ssl_options, :static_cache_control, :session_options,
-
:time_zone, :reload_classes_only_on_change, :whiny_nils
-
-
2
attr_writer :log_level
-
2
attr_reader :encoding
-
-
2
def initialize(*)
-
2
super
-
2
self.encoding = "utf-8"
-
2
@allow_concurrency = false
-
2
@consider_all_requests_local = false
-
2
@filter_parameters = []
-
2
@helpers_paths = []
-
2
@dependency_loading = true
-
2
@serve_static_assets = true
-
2
@static_cache_control = nil
-
2
@force_ssl = false
-
2
@ssl_options = {}
-
2
@session_store = :cookie_store
-
2
@session_options = {}
-
2
@time_zone = "UTC"
-
2
@log_level = nil
-
2
@middleware = app_middleware
-
2
@generators = app_generators
-
2
@cache_store = [ :file_store, "#{root}/tmp/cache/" ]
-
2
@railties_order = [:all]
-
2
@relative_url_root = ENV["RAILS_RELATIVE_URL_ROOT"]
-
2
@reload_classes_only_on_change = true
-
2
@file_watcher = ActiveSupport::FileUpdateChecker
-
2
@exceptions_app = nil
-
-
2
@assets = ActiveSupport::OrderedOptions.new
-
2
@assets.enabled = false
-
2
@assets.paths = []
-
2
@assets.precompile = [ Proc.new{ |path| !File.extname(path).in?(['.js', '.css']) },
-
/(?:\/|\\|\A)application\.(css|js)$/ ]
-
2
@assets.prefix = "/assets"
-
2
@assets.version = ''
-
2
@assets.debug = false
-
2
@assets.compile = true
-
2
@assets.digest = false
-
2
@assets.manifest = nil
-
2
@assets.cache_store = [ :file_store, "#{root}/tmp/cache/assets/" ]
-
2
@assets.js_compressor = nil
-
2
@assets.css_compressor = nil
-
2
@assets.initialize_on_precompile = true
-
2
@assets.logger = nil
-
end
-
-
2
def compiled_asset_path
-
"/"
-
end
-
-
2
def encoding=(value)
-
4
@encoding = value
-
4
if "ruby".encoding_aware?
-
4
silence_warnings do
-
4
Encoding.default_external = value
-
4
Encoding.default_internal = value
-
end
-
else
-
$KCODE = value
-
if $KCODE == "NONE"
-
raise "The value you specified for config.encoding is " \
-
"invalid. The possible values are UTF8, SJIS, or EUC"
-
end
-
end
-
end
-
-
2
def paths
-
@paths ||= begin
-
2
paths = super
-
2
paths.add "config/database", :with => "config/database.yml"
-
2
paths.add "config/environment", :with => "config/environment.rb"
-
2
paths.add "lib/templates"
-
2
paths.add "log", :with => "log/#{Rails.env}.log"
-
2
paths.add "public"
-
2
paths.add "public/javascripts"
-
2
paths.add "public/stylesheets"
-
2
paths.add "tmp"
-
2
paths
-
46
end
-
end
-
-
# Enable threaded mode. Allows concurrent requests to controller actions and
-
# multiple database connections. Also disables automatic dependency loading
-
# after boot, and disables reloading code on every request, as these are
-
# fundamentally incompatible with thread safety.
-
2
def threadsafe!
-
self.preload_frameworks = true
-
self.cache_classes = true
-
self.dependency_loading = false
-
self.allow_concurrency = true
-
self
-
end
-
-
# Loads and returns the contents of the #database_configuration_file. The
-
# contents of the file are processed via ERB before being sent through
-
# YAML::load.
-
2
def database_configuration
-
2
require 'erb'
-
2
YAML::load(ERB.new(IO.read(paths["config/database"].first)).result)
-
end
-
-
2
def log_level
-
2
@log_level ||= Rails.env.production? ? :info : :debug
-
end
-
-
2
def colorize_logging
-
@colorize_logging
-
end
-
-
2
def colorize_logging=(val)
-
@colorize_logging = val
-
ActiveSupport::LogSubscriber.colorize_logging = val
-
self.generators.colorize_logging = val
-
end
-
-
2
def session_store(*args)
-
6
if args.empty?
-
4
case @session_store
-
when :disabled
-
nil
-
when :active_record_store
-
ActiveRecord::SessionStore
-
when Symbol
-
4
ActionDispatch::Session.const_get(@session_store.to_s.camelize)
-
else
-
@session_store
-
end
-
else
-
2
@session_store = args.shift
-
2
@session_options = args.shift || {}
-
end
-
end
-
end
-
end
-
end
-
2
module Rails
-
2
class Application
-
2
module Finisher
-
2
include Initializable
-
-
2
initializer :add_generator_templates do
-
2
config.generators.templates.unshift(*paths["lib/templates"].existent)
-
end
-
-
2
initializer :ensure_autoload_once_paths_as_subset do
-
2
extra = ActiveSupport::Dependencies.autoload_once_paths -
-
ActiveSupport::Dependencies.autoload_paths
-
-
2
unless extra.empty?
-
abort <<-end_error
-
autoload_once_paths must be a subset of the autoload_paths.
-
Extra items in autoload_once_paths: #{extra * ','}
-
end_error
-
end
-
end
-
-
2
initializer :add_builtin_route do |app|
-
2
if Rails.env.development?
-
app.routes.append do
-
match '/rails/info/properties' => "rails/info#properties"
-
end
-
end
-
end
-
-
2
initializer :build_middleware_stack do
-
2
build_middleware_stack
-
end
-
-
2
initializer :define_main_app_helper do |app|
-
2
app.routes.define_mounted_helper(:main_app)
-
end
-
-
2
initializer :add_to_prepare_blocks do
-
2
config.to_prepare_blocks.each do |block|
-
2
ActionDispatch::Reloader.to_prepare(&block)
-
end
-
end
-
-
# This needs to happen before eager load so it happens
-
# in exactly the same point regardless of config.cache_classes
-
2
initializer :run_prepare_callbacks do
-
2
ActionDispatch::Reloader.prepare!
-
end
-
-
2
initializer :eager_load! do
-
2
if config.cache_classes && !(defined?($rails_rake_task) && $rails_rake_task)
-
2
ActiveSupport.run_load_hooks(:before_eager_load, self)
-
2
eager_load!
-
end
-
end
-
-
# All initialization is done, including eager loading in production
-
2
initializer :finisher_hook do
-
2
ActiveSupport.run_load_hooks(:after_initialize, self)
-
end
-
-
# Set app reload just after the finisher hook to ensure
-
# routes added in the hook are still loaded.
-
2
initializer :set_routes_reloader_hook do
-
2
reloader = routes_reloader
-
2
reloader.execute_if_updated
-
2
self.reloaders << reloader
-
2
ActionDispatch::Reloader.to_prepare { reloader.execute_if_updated }
-
end
-
-
# Set app reload just after the finisher hook to ensure
-
# paths added in the hook are still loaded.
-
2
initializer :set_clear_dependencies_hook, :group => :all do
-
2
callback = lambda do
-
ActiveSupport::DescendantsTracker.clear
-
ActiveSupport::Dependencies.clear
-
end
-
-
2
if config.reload_classes_only_on_change
-
2
reloader = config.file_watcher.new(*watchable_args, &callback)
-
2
self.reloaders << reloader
-
# We need to set a to_prepare callback regardless of the reloader result, i.e.
-
# models should be reloaded if any of the reloaders (i18n, routes) were updated.
-
2
ActionDispatch::Reloader.to_prepare(:prepend => true){ reloader.execute }
-
else
-
ActionDispatch::Reloader.to_cleanup(&callback)
-
end
-
end
-
-
# Disable dependency loading during request cycle
-
2
initializer :disable_dependency_loading do
-
2
if config.cache_classes && !config.dependency_loading
-
ActiveSupport::Dependencies.unhook!
-
end
-
end
-
end
-
end
-
end
-
2
require 'rails/engine/railties'
-
-
2
module Rails
-
2
class Application < Engine
-
2
class Railties < Rails::Engine::Railties
-
2
def all(&block)
-
4
@all ||= railties + engines + plugins
-
4
@all.each(&block) if block
-
4
@all
-
end
-
end
-
end
-
end
-
2
require "active_support/core_ext/module/delegation"
-
-
2
module Rails
-
2
class Application
-
2
class RoutesReloader
-
2
attr_reader :route_sets, :paths
-
2
delegate :execute_if_updated, :execute, :updated?, :to => :updater
-
-
2
def initialize
-
2
@paths = []
-
2
@route_sets = []
-
end
-
-
2
def reload!
-
2
clear!
-
2
load_paths
-
2
finalize!
-
ensure
-
2
revert
-
end
-
-
2
private
-
-
2
def updater
-
@updater ||= begin
-
4
updater = ActiveSupport::FileUpdateChecker.new(paths) { reload! }
-
2
updater.execute
-
2
updater
-
2
end
-
end
-
-
2
def clear!
-
2
route_sets.each do |routes|
-
2
routes.disable_clear_and_finalize = true
-
2
routes.clear!
-
end
-
end
-
-
2
def load_paths
-
4
paths.each { |path| load(path) }
-
end
-
-
2
def finalize!
-
2
route_sets.each do |routes|
-
4
ActiveSupport.on_load(:action_controller) { routes.finalize! }
-
end
-
end
-
-
2
def revert
-
2
route_sets.each do |routes|
-
2
routes.disable_clear_and_finalize = false
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/backtrace_cleaner'
-
-
1
module Rails
-
1
class BacktraceCleaner < ActiveSupport::BacktraceCleaner
-
1
APP_DIRS_PATTERN = /^\/?(app|config|lib|test)/
-
1
RENDER_TEMPLATE_PATTERN = /:in `_render_template_\w*'/
-
-
1
def initialize
-
1
super
-
1
add_filter { |line| line.sub("#{Rails.root}/", '') }
-
1
add_filter { |line| line.sub(RENDER_TEMPLATE_PATTERN, '') }
-
1
add_filter { |line| line.sub('./', '/') } # for tests
-
-
1
add_gem_filters
-
1
add_silencer { |line| line !~ APP_DIRS_PATTERN }
-
end
-
-
1
private
-
1
def add_gem_filters
-
1
return unless defined?(Gem)
-
-
3
gems_paths = (Gem.path + [Gem.default_dir]).uniq.map!{ |p| Regexp.escape(p) }
-
1
return if gems_paths.empty?
-
-
1
gems_regexp = %r{(#{gems_paths.join('|')})/gems/([^/]+)-([\w.]+)/(.*)}
-
1
add_filter { |line| line.sub(gems_regexp, '\2 (\3) \4') }
-
end
-
end
-
-
# For installing the BacktraceCleaner in the test/unit
-
1
module BacktraceFilterForTestUnit #:nodoc:
-
1
def self.included(klass)
-
klass.send :alias_method_chain, :filter_backtrace, :cleaning
-
end
-
-
1
def filter_backtrace_with_cleaning(backtrace, prefix=nil)
-
backtrace = filter_backtrace_without_cleaning(backtrace, prefix)
-
backtrace = backtrace.first.split("\n") if backtrace.size == 1
-
Rails.backtrace_cleaner.clean(backtrace)
-
end
-
end
-
end
-
2
require 'active_support/deprecation'
-
2
require 'active_support/ordered_options'
-
2
require 'active_support/core_ext/hash/deep_dup'
-
2
require 'rails/paths'
-
2
require 'rails/rack'
-
-
2
module Rails
-
2
module Configuration
-
2
class MiddlewareStackProxy #:nodoc:
-
2
def initialize
-
2
@operations = []
-
end
-
-
2
def insert_before(*args, &block)
-
2
@operations << [:insert_before, args, block]
-
end
-
-
2
alias :insert :insert_before
-
-
2
def insert_after(*args, &block)
-
4
@operations << [:insert_after, args, block]
-
end
-
-
2
def swap(*args, &block)
-
@operations << [:swap, args, block]
-
end
-
-
2
def use(*args, &block)
-
@operations << [:use, args, block]
-
end
-
-
2
def delete(*args, &block)
-
@operations << [:delete, args, block]
-
end
-
-
2
def merge_into(other)
-
2
@operations.each do |operation, args, block|
-
6
other.send(operation, *args, &block)
-
end
-
2
other
-
end
-
end
-
-
2
class Generators #:nodoc:
-
2
attr_accessor :aliases, :options, :templates, :fallbacks, :colorize_logging
-
2
attr_reader :hidden_namespaces
-
-
2
def initialize
-
2
@aliases = Hash.new { |h,k| h[k] = {} }
-
8
@options = Hash.new { |h,k| h[k] = {} }
-
2
@fallbacks = {}
-
2
@templates = []
-
2
@colorize_logging = true
-
2
@hidden_namespaces = []
-
end
-
-
2
def initialize_copy(source)
-
10
@aliases = @aliases.deep_dup
-
10
@options = @options.deep_dup
-
10
@fallbacks = @fallbacks.deep_dup
-
10
@templates = @templates.dup
-
end
-
-
2
def hide_namespace(namespace)
-
2
@hidden_namespaces << namespace
-
end
-
-
2
def method_missing(method, *args)
-
16
method = method.to_s.sub(/=$/, '').to_sym
-
-
16
return @options[method] if args.empty?
-
-
16
if method == :rails || args.first.is_a?(Hash)
-
namespace, configuration = method, args.shift
-
else
-
16
namespace, configuration = args.shift, args.shift
-
16
namespace = namespace.to_sym if namespace.respond_to?(:to_sym)
-
16
@options[:rails][method] = namespace
-
end
-
-
16
if configuration
-
4
aliases = configuration.delete(:aliases)
-
4
@aliases[namespace].merge!(aliases) if aliases
-
4
@options[namespace].merge!(configuration)
-
end
-
end
-
end
-
end
-
end
-
2
require 'rails/railtie'
-
2
require 'active_support/core_ext/module/delegation'
-
2
require 'pathname'
-
2
require 'rbconfig'
-
2
require 'rails/engine/railties'
-
-
2
module Rails
-
# <tt>Rails::Engine</tt> allows you to wrap a specific Rails application or subset of
-
# functionality and share it with other applications. Since Rails 3.0, every
-
# <tt>Rails::Application</tt> is just an engine, which allows for simple
-
# feature and application sharing.
-
#
-
# Any <tt>Rails::Engine</tt> is also a <tt>Rails::Railtie</tt>, so the same
-
# methods (like <tt>rake_tasks</tt> and +generators+) and configuration
-
# options that are available in railties can also be used in engines.
-
#
-
# == Creating an Engine
-
#
-
# In Rails versions prior to 3.0, your gems automatically behaved as engines, however,
-
# this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically
-
# behave as an engine, you have to specify an +Engine+ for it somewhere inside
-
# your plugin's +lib+ folder (similar to how we specify a +Railtie+):
-
#
-
# # lib/my_engine.rb
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# end
-
# end
-
#
-
# Then ensure that this file is loaded at the top of your <tt>config/application.rb</tt>
-
# (or in your +Gemfile+) and it will automatically load models, controllers and helpers
-
# inside +app+, load routes at <tt>config/routes.rb</tt>, load locales at
-
# <tt>config/locales/*</tt>, and load tasks at <tt>lib/tasks/*</tt>.
-
#
-
# == Configuration
-
#
-
# Besides the +Railtie+ configuration which is shared across the application, in a
-
# <tt>Rails::Engine</tt> you can access <tt>autoload_paths</tt>, <tt>eager_load_paths</tt>
-
# and <tt>autoload_once_paths</tt>, which, differently from a <tt>Railtie</tt>, are scoped to
-
# the current engine.
-
#
-
# Example:
-
#
-
# class MyEngine < Rails::Engine
-
# # Add a load path for this specific Engine
-
# config.autoload_paths << File.expand_path("../lib/some/path", __FILE__)
-
#
-
# initializer "my_engine.add_middleware" do |app|
-
# app.middleware.use MyEngine::Middleware
-
# end
-
# end
-
#
-
# == Generators
-
#
-
# You can set up generators for engines with <tt>config.generators</tt> method:
-
#
-
# class MyEngine < Rails::Engine
-
# config.generators do |g|
-
# g.orm :active_record
-
# g.template_engine :erb
-
# g.test_framework :test_unit
-
# end
-
# end
-
#
-
# You can also set generators for an application by using <tt>config.app_generators</tt>:
-
#
-
# class MyEngine < Rails::Engine
-
# # note that you can also pass block to app_generators in the same way you
-
# # can pass it to generators method
-
# config.app_generators.orm :datamapper
-
# end
-
#
-
# == Paths
-
#
-
# Since Rails 3.0, applications and engines have more flexible path configuration (as
-
# opposed to the previous hardcoded path configuration). This means that you are not
-
# required to place your controllers at <tt>app/controllers</tt>, but in any place
-
# which you find convenient.
-
#
-
# For example, let's suppose you want to place your controllers in <tt>lib/controllers</tt>.
-
# You can set that as an option:
-
#
-
# class MyEngine < Rails::Engine
-
# paths["app/controllers"] = "lib/controllers"
-
# end
-
#
-
# You can also have your controllers loaded from both <tt>app/controllers</tt> and
-
# <tt>lib/controllers</tt>:
-
#
-
# class MyEngine < Rails::Engine
-
# paths["app/controllers"] << "lib/controllers"
-
# end
-
#
-
# The available paths in an engine are:
-
#
-
# class MyEngine < Rails::Engine
-
# paths["app"] # => ["app"]
-
# paths["app/controllers"] # => ["app/controllers"]
-
# paths["app/helpers"] # => ["app/helpers"]
-
# paths["app/models"] # => ["app/models"]
-
# paths["app/views"] # => ["app/views"]
-
# paths["lib"] # => ["lib"]
-
# paths["lib/tasks"] # => ["lib/tasks"]
-
# paths["config"] # => ["config"]
-
# paths["config/initializers"] # => ["config/initializers"]
-
# paths["config/locales"] # => ["config/locales"]
-
# paths["config/routes"] # => ["config/routes.rb"]
-
# end
-
#
-
# The <tt>Application</tt> class adds a couple more paths to this set. And as in your
-
# <tt>Application</tt>, all folders under +app+ are automatically added to the load path.
-
# If you have an <tt>app/observers</tt> folder for example, it will be added by default.
-
#
-
# == Endpoint
-
#
-
# An engine can be also a rack application. It can be useful if you have a rack application that
-
# you would like to wrap with +Engine+ and provide some of the +Engine+'s features.
-
#
-
# To do that, use the +endpoint+ method:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# endpoint MyRackApplication
-
# end
-
# end
-
#
-
# Now you can mount your engine in application's routes just like that:
-
#
-
# MyRailsApp::Application.routes.draw do
-
# mount MyEngine::Engine => "/engine"
-
# end
-
#
-
# == Middleware stack
-
#
-
# As an engine can now be a rack endpoint, it can also have a middleware
-
# stack. The usage is exactly the same as in <tt>Application</tt>:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# middleware.use SomeMiddleware
-
# end
-
# end
-
#
-
# == Routes
-
#
-
# If you don't specify an endpoint, routes will be used as the default
-
# endpoint. You can use them just like you use an application's routes:
-
#
-
# # ENGINE/config/routes.rb
-
# MyEngine::Engine.routes.draw do
-
# match "/" => "posts#index"
-
# end
-
#
-
# == Mount priority
-
#
-
# Note that now there can be more than one router in your application, and it's better to avoid
-
# passing requests through many routers. Consider this situation:
-
#
-
# MyRailsApp::Application.routes.draw do
-
# mount MyEngine::Engine => "/blog"
-
# match "/blog/omg" => "main#omg"
-
# end
-
#
-
# +MyEngine+ is mounted at <tt>/blog</tt>, and <tt>/blog/omg</tt> points to application's
-
# controller. In such a situation, requests to <tt>/blog/omg</tt> will go through +MyEngine+,
-
# and if there is no such route in +Engine+'s routes, it will be dispatched to <tt>main#omg</tt>.
-
# It's much better to swap that:
-
#
-
# MyRailsApp::Application.routes.draw do
-
# match "/blog/omg" => "main#omg"
-
# mount MyEngine::Engine => "/blog"
-
# end
-
#
-
# Now, +Engine+ will get only requests that were not handled by +Application+.
-
#
-
# == Engine name
-
#
-
# There are some places where an Engine's name is used:
-
#
-
# * routes: when you mount an Engine with <tt>mount(MyEngine::Engine => '/my_engine')</tt>,
-
# it's used as default :as option
-
# * some of the rake tasks are based on engine name, e.g. <tt>my_engine:install:migrations</tt>,
-
# <tt>my_engine:install:assets</tt>
-
#
-
# Engine name is set by default based on class name. For <tt>MyEngine::Engine</tt> it will be
-
# <tt>my_engine_engine</tt>. You can change it manually using the <tt>engine_name</tt> method:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# engine_name "my_engine"
-
# end
-
# end
-
#
-
# == Isolated Engine
-
#
-
# Normally when you create controllers, helpers and models inside an engine, they are treated
-
# as if they were created inside the application itself. This means that all helpers and
-
# named routes from the application will be available to your engine's controllers as well.
-
#
-
# However, sometimes you want to isolate your engine from the application, especially if your engine
-
# has its own router. To do that, you simply need to call +isolate_namespace+. This method requires
-
# you to pass a module where all your controllers, helpers and models should be nested to:
-
#
-
# module MyEngine
-
# class Engine < Rails::Engine
-
# isolate_namespace MyEngine
-
# end
-
# end
-
#
-
# With such an engine, everything that is inside the +MyEngine+ module will be isolated from
-
# the application.
-
#
-
# Consider such controller:
-
#
-
# module MyEngine
-
# class FooController < ActionController::Base
-
# end
-
# end
-
#
-
# If an engine is marked as isolated, +FooController+ has access only to helpers from +Engine+ and
-
# <tt>url_helpers</tt> from <tt>MyEngine::Engine.routes</tt>.
-
#
-
# The next thing that changes in isolated engines is the behavior of routes. Normally, when you namespace
-
# your controllers, you also need to do namespace all your routes. With an isolated engine,
-
# the namespace is applied by default, so you can ignore it in routes:
-
#
-
# MyEngine::Engine.routes.draw do
-
# resources :articles
-
# end
-
#
-
# The routes above will automatically point to <tt>MyEngine::ApplicationController</tt>. Furthermore, you don't
-
# need to use longer url helpers like <tt>my_engine_articles_path</tt>. Instead, you should simply use
-
# <tt>articles_path</tt> as you would do with your application.
-
#
-
# To make that behavior consistent with other parts of the framework, an isolated engine also has influence on
-
# <tt>ActiveModel::Naming</tt>. When you use a namespaced model, like <tt>MyEngine::Article</tt>, it will normally
-
# use the prefix "my_engine". In an isolated engine, the prefix will be omitted in url helpers and
-
# form fields for convenience.
-
#
-
# polymorphic_url(MyEngine::Article.new) # => "articles_path"
-
#
-
# form_for(MyEngine::Article.new) do
-
# text_field :title # => <input type="text" name="article[title]" id="article_title" />
-
# end
-
#
-
# Additionally, an isolated engine will set its name according to namespace, so
-
# MyEngine::Engine.engine_name will be "my_engine". It will also set MyEngine.table_name_prefix
-
# to "my_engine_", changing the MyEngine::Article model to use the my_engine_articles table.
-
#
-
# == Using Engine's routes outside Engine
-
#
-
# Since you can now mount an engine inside application's routes, you do not have direct access to +Engine+'s
-
# <tt>url_helpers</tt> inside +Application+. When you mount an engine in an application's routes, a special helper is
-
# created to allow you to do that. Consider such a scenario:
-
#
-
# # config/routes.rb
-
# MyApplication::Application.routes.draw do
-
# mount MyEngine::Engine => "/my_engine", :as => "my_engine"
-
# match "/foo" => "foo#index"
-
# end
-
#
-
# Now, you can use the <tt>my_engine</tt> helper inside your application:
-
#
-
# class FooController < ApplicationController
-
# def index
-
# my_engine.root_url #=> /my_engine/
-
# end
-
# end
-
#
-
# There is also a <tt>main_app</tt> helper that gives you access to application's routes inside Engine:
-
#
-
# module MyEngine
-
# class BarController
-
# def index
-
# main_app.foo_path #=> /foo
-
# end
-
# end
-
# end
-
#
-
# Note that the <tt>:as</tt> option given to mount takes the <tt>engine_name</tt> as default, so most of the time
-
# you can simply omit it.
-
#
-
# Finally, if you want to generate a url to an engine's route using
-
# <tt>polymorphic_url</tt>, you also need to pass the engine helper. Let's
-
# say that you want to create a form pointing to one of the engine's routes.
-
# All you need to do is pass the helper as the first element in array with
-
# attributes for url:
-
#
-
# form_for([my_engine, @user])
-
#
-
# This code will use <tt>my_engine.user_path(@user)</tt> to generate the proper route.
-
#
-
# == Isolated engine's helpers
-
#
-
# Sometimes you may want to isolate engine, but use helpers that are defined for it.
-
# If you want to share just a few specific helpers you can add them to application's
-
# helpers in ApplicationController:
-
#
-
# class ApplicationController < ActionController::Base
-
# helper MyEngine::SharedEngineHelper
-
# end
-
#
-
# If you want to include all of the engine's helpers, you can use #helpers method on an engine's
-
# instance:
-
#
-
# class ApplicationController < ActionController::Base
-
# helper MyEngine::Engine.helpers
-
# end
-
#
-
# It will include all of the helpers from engine's directory. Take into account that this does
-
# not include helpers defined in controllers with helper_method or other similar solutions,
-
# only helpers defined in the helpers directory will be included.
-
#
-
# == Migrations & seed data
-
#
-
# Engines can have their own migrations. The default path for migrations is exactly the same
-
# as in application: <tt>db/migrate</tt>
-
#
-
# To use engine's migrations in application you can use rake task, which copies them to
-
# application's dir:
-
#
-
# rake ENGINE_NAME:install:migrations
-
#
-
# Note that some of the migrations may be skipped if a migration with the same name already exists
-
# in application. In such a situation you must decide whether to leave that migration or rename the
-
# migration in the application and rerun copying migrations.
-
#
-
# If your engine has migrations, you may also want to prepare data for the database in
-
# the <tt>seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
-
#
-
# MyEngine::Engine.load_seed
-
#
-
# == Loading priority
-
#
-
# In order to change engine's priority you can use config.railties_order in main application.
-
# It will affect the priority of loading views, helpers, assets and all the other files
-
# related to engine or application.
-
#
-
# Example:
-
#
-
# # load Blog::Engine with highest priority, followed by application and other railties
-
# config.railties_order = [Blog::Engine, :main_app, :all]
-
#
-
2
class Engine < Railtie
-
2
autoload :Configuration, "rails/engine/configuration"
-
2
autoload :Railties, "rails/engine/railties"
-
-
2
def load_generators(app=self)
-
initialize_generators
-
railties.all { |r| r.load_generators(app) }
-
Rails::Generators.configure!(app.config.generators)
-
super
-
self
-
end
-
-
2
class << self
-
2
attr_accessor :called_from, :isolated
-
2
alias :isolated? :isolated
-
2
alias :engine_name :railtie_name
-
-
2
def inherited(base)
-
14
unless base.abstract_railtie?
-
10
base.called_from = begin
-
# Remove the line number from backtraces making sure we don't leave anything behind
-
250
call_stack = caller.map { |p| p.sub(/:\d+.*/, '') }
-
22
File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] })
-
end
-
end
-
-
14
super
-
end
-
-
2
def endpoint(endpoint = nil)
-
2
@endpoint ||= nil
-
2
@endpoint = endpoint if endpoint
-
2
@endpoint
-
end
-
-
2
def isolate_namespace(mod)
-
engine_name(generate_railtie_name(mod))
-
-
self.routes.default_scope = { :module => ActiveSupport::Inflector.underscore(mod.name) }
-
self.isolated = true
-
-
unless mod.respond_to?(:railtie_namespace)
-
name, railtie = engine_name, self
-
-
mod.singleton_class.instance_eval do
-
define_method(:railtie_namespace) { railtie }
-
-
unless mod.respond_to?(:table_name_prefix)
-
define_method(:table_name_prefix) { "#{name}_" }
-
end
-
-
unless mod.respond_to?(:use_relative_model_naming?)
-
class_eval "def use_relative_model_naming?; true; end", __FILE__, __LINE__
-
end
-
-
unless mod.respond_to?(:railtie_helpers_paths)
-
define_method(:railtie_helpers_paths) { railtie.helpers_paths }
-
end
-
-
unless mod.respond_to?(:railtie_routes_url_helpers)
-
define_method(:railtie_routes_url_helpers) { railtie.routes_url_helpers }
-
end
-
end
-
end
-
end
-
-
# Finds engine with given path
-
2
def find(path)
-
expanded_path = File.expand_path path.to_s
-
Rails::Engine::Railties.engines.find { |engine|
-
File.expand_path(engine.root.to_s) == expanded_path
-
}
-
end
-
end
-
-
2
delegate :middleware, :root, :paths, :to => :config
-
2
delegate :engine_name, :isolated?, :to => "self.class"
-
-
2
def load_tasks(app=self)
-
railties.all { |r| r.load_tasks(app) }
-
super
-
paths["lib/tasks"].existent.sort.each { |ext| load(ext) }
-
end
-
-
2
def load_console(app=self)
-
railties.all { |r| r.load_console(app) }
-
super
-
end
-
-
2
def load_runner(app=self)
-
railties.all { |r| r.load_runner(app) }
-
super
-
end
-
-
2
def eager_load!
-
10
railties.all(&:eager_load!)
-
-
10
config.eager_load_paths.each do |load_path|
-
14
matcher = /\A#{Regexp.escape(load_path)}\/(.*)\.rb\Z/
-
14
Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
-
102
require_dependency file.sub(matcher, '\1')
-
end
-
end
-
end
-
-
2
def railties
-
20
@railties ||= self.class::Railties.new(config)
-
end
-
-
2
def helpers
-
@helpers ||= begin
-
helpers = Module.new
-
all = ActionController::Base.all_helpers_from_path(helpers_paths)
-
ActionController::Base.modules_for_helpers(all).each do |mod|
-
helpers.send(:include, mod)
-
end
-
helpers
-
end
-
end
-
-
2
def helpers_paths
-
paths["app/helpers"].existent
-
end
-
-
2
def routes_url_helpers
-
routes.url_helpers
-
end
-
-
2
def app
-
@app ||= begin
-
2
config.middleware = config.middleware.merge_into(default_middleware_stack)
-
2
config.middleware.build(endpoint)
-
2
end
-
end
-
-
2
def endpoint
-
2
self.class.endpoint || routes
-
end
-
-
2
def call(env)
-
app.call(env.merge!(env_config))
-
end
-
-
2
def env_config
-
@env_config ||= {
-
'action_dispatch.routes' => routes
-
1
}
-
end
-
-
2
def routes
-
94
@routes ||= ActionDispatch::Routing::RouteSet.new
-
94
@routes.append(&Proc.new) if block_given?
-
94
@routes
-
end
-
-
2
def ordered_railties
-
8
railties.all + [self]
-
end
-
-
2
def initializers
-
10
initializers = []
-
10
ordered_railties.each do |r|
-
50
if r == self
-
10
initializers += super
-
else
-
40
initializers += r.initializers
-
end
-
end
-
10
initializers
-
end
-
-
2
def config
-
164
@config ||= Engine::Configuration.new(find_root_with_flag("lib"))
-
end
-
-
# Load data from db/seeds.rb file. It can be used in to load engines'
-
# seeds, e.g.:
-
#
-
# Blog::Engine.load_seed
-
2
def load_seed
-
seed_file = paths["db/seeds"].existent.first
-
load(seed_file) if seed_file
-
end
-
-
# Add configured load paths to ruby load paths and remove duplicates.
-
2
initializer :set_load_path, :before => :bootstrap_hook do
-
10
_all_load_paths.reverse_each do |path|
-
32
$LOAD_PATH.unshift(path) if File.directory?(path)
-
end
-
10
$LOAD_PATH.uniq!
-
end
-
-
# Set the paths from which Rails will automatically load source files,
-
# and the load_once paths.
-
#
-
# This needs to be an initializer, since it needs to run once
-
# per engine and get the engine as a block parameter
-
2
initializer :set_autoload_paths, :before => :bootstrap_hook do |app|
-
10
ActiveSupport::Dependencies.autoload_paths.unshift(*_all_autoload_paths)
-
10
ActiveSupport::Dependencies.autoload_once_paths.unshift(*_all_autoload_once_paths)
-
-
# Freeze so future modifications will fail rather than do nothing mysteriously
-
10
config.autoload_paths.freeze
-
10
config.eager_load_paths.freeze
-
10
config.autoload_once_paths.freeze
-
end
-
-
2
initializer :add_routing_paths do |app|
-
10
paths = self.paths["config/routes"].existent
-
-
10
if routes? || paths.any?
-
2
app.routes_reloader.paths.unshift(*paths)
-
2
app.routes_reloader.route_sets << routes
-
end
-
end
-
-
# I18n load paths are a special case since the ones added
-
# later have higher priority.
-
2
initializer :add_locales do
-
10
config.i18n.railties_load_path.concat(paths["config/locales"].existent)
-
end
-
-
2
initializer :add_view_paths do
-
10
views = paths["app/views"].existent
-
10
unless views.empty?
-
8
ActiveSupport.on_load(:action_controller){ prepend_view_path(views) }
-
8
ActiveSupport.on_load(:action_mailer){ prepend_view_path(views) }
-
end
-
end
-
-
2
initializer :load_environment_config, :before => :load_environment_hook, :group => :all do
-
10
environment = paths["config/environments"].existent.first
-
10
require environment if environment
-
end
-
-
2
initializer :append_assets_path, :group => :all do |app|
-
10
app.config.assets.paths.unshift(*paths["vendor/assets"].existent_directories)
-
10
app.config.assets.paths.unshift(*paths["lib/assets"].existent_directories)
-
10
app.config.assets.paths.unshift(*paths["app/assets"].existent_directories)
-
end
-
-
2
initializer :prepend_helpers_path do |app|
-
10
if !isolated? || (app == self)
-
10
app.config.helpers_paths.unshift(*paths["app/helpers"].existent)
-
end
-
end
-
-
2
initializer :load_config_initializers do
-
10
config.paths["config/initializers"].existent.sort.each do |initializer|
-
16
load(initializer)
-
end
-
end
-
-
2
initializer :engines_blank_point do
-
# We need this initializer so all extra initializers added in engines are
-
# consistently executed after all the initializers above across all engines.
-
end
-
-
2
rake_tasks do
-
next if self.is_a?(Rails::Application)
-
next unless has_migrations?
-
-
namespace railtie_name do
-
namespace :install do
-
desc "Copy migrations from #{railtie_name} to application"
-
task :migrations do
-
ENV["FROM"] = railtie_name
-
Rake::Task["railties:install:migrations"].invoke
-
end
-
end
-
end
-
end
-
-
2
protected
-
-
2
def initialize_generators
-
require "rails/generators"
-
end
-
-
2
def routes?
-
10
defined?(@routes)
-
end
-
-
2
def has_migrations?
-
paths["db/migrate"].existent.any?
-
end
-
-
2
def find_root_with_flag(flag, default=nil)
-
10
root_path = self.class.called_from
-
-
10
while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
-
26
parent = File.dirname(root_path)
-
26
root_path = parent != root_path && parent
-
end
-
-
10
root = File.exist?("#{root_path}/#{flag}") ? root_path : default
-
10
raise "Could not find root path for #{self}" unless root
-
-
10
RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ?
-
10
Pathname.new(root).expand_path : Pathname.new(root).realpath
-
end
-
-
2
def default_middleware_stack
-
ActionDispatch::MiddlewareStack.new
-
end
-
-
2
def _all_autoload_once_paths
-
10
config.autoload_once_paths
-
end
-
-
2
def _all_autoload_paths
-
20
@_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq
-
end
-
-
2
def _all_load_paths
-
10
@_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq
-
end
-
end
-
end
-
2
require 'rails/railtie/configuration'
-
-
2
module Rails
-
2
class Engine
-
2
class Configuration < ::Rails::Railtie::Configuration
-
2
attr_reader :root
-
2
attr_writer :middleware, :eager_load_paths, :autoload_once_paths, :autoload_paths
-
2
attr_accessor :plugins
-
-
2
def initialize(root=nil)
-
10
super()
-
10
@root = root
-
10
@generators = app_generators.dup
-
end
-
-
# Returns the middleware stack for the engine.
-
2
def middleware
-
6
@middleware ||= Rails::Configuration::MiddlewareStackProxy.new
-
end
-
-
# Holds generators configuration:
-
#
-
# config.generators do |g|
-
# g.orm :datamapper, :migration => true
-
# g.template_engine :haml
-
# g.test_framework :rspec
-
# end
-
#
-
# If you want to disable color in console, do:
-
#
-
# config.generators.colorize_logging = false
-
#
-
2
def generators #:nodoc:
-
4
@generators ||= Rails::Configuration::Generators.new
-
4
yield(@generators) if block_given?
-
4
@generators
-
end
-
-
2
def paths
-
@paths ||= begin
-
10
paths = Rails::Paths::Root.new(@root)
-
10
paths.add "app", :eager_load => true, :glob => "*"
-
10
paths.add "app/assets", :glob => "*"
-
10
paths.add "app/controllers", :eager_load => true
-
10
paths.add "app/helpers", :eager_load => true
-
10
paths.add "app/models", :eager_load => true
-
10
paths.add "app/mailers", :eager_load => true
-
10
paths.add "app/views"
-
10
paths.add "lib", :load_path => true
-
10
paths.add "lib/assets", :glob => "*"
-
10
paths.add "lib/tasks", :glob => "**/*.rake"
-
10
paths.add "config"
-
10
paths.add "config/environments", :glob => "#{Rails.env}.rb"
-
10
paths.add "config/initializers", :glob => "**/*.rb"
-
10
paths.add "config/locales", :glob => "*.{rb,yml}"
-
10
paths.add "config/routes", :with => "config/routes.rb"
-
10
paths.add "db"
-
10
paths.add "db/migrate"
-
10
paths.add "db/seeds", :with => "db/seeds.rb"
-
10
paths.add "vendor", :load_path => true
-
10
paths.add "vendor/assets", :glob => "*"
-
10
paths.add "vendor/plugins"
-
10
paths
-
114
end
-
end
-
-
2
def root=(value)
-
@root = paths.path = Pathname.new(value).expand_path
-
end
-
-
2
def eager_load_paths
-
30
@eager_load_paths ||= paths.eager_load
-
end
-
-
2
def autoload_once_paths
-
30
@autoload_once_paths ||= paths.autoload_once
-
end
-
-
2
def autoload_paths
-
20
@autoload_paths ||= paths.autoload_paths
-
end
-
end
-
end
-
end
-
2
module Rails
-
2
class Engine < Railtie
-
2
class Railties
-
# TODO Write tests for this behavior extracted from Application
-
2
def initialize(config)
-
10
@config = config
-
end
-
-
2
def all(&block)
-
16
@all ||= plugins
-
16
@all.each(&block) if block
-
16
@all
-
end
-
-
2
def plugins
-
@plugins ||= begin
-
20
plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym }
-
10
Plugin.all(plugin_names, @config.paths["vendor/plugins"].existent)
-
10
end
-
end
-
-
2
def self.railties
-
2
@railties ||= ::Rails::Railtie.subclasses.map(&:instance)
-
end
-
-
2
def self.engines
-
2
@engines ||= ::Rails::Engine.subclasses.map(&:instance)
-
end
-
-
2
delegate :railties, :engines, :to => "self.class"
-
end
-
end
-
end
-
2
require 'tsort'
-
-
2
module Rails
-
2
module Initializable
-
2
def self.included(base)
-
6
base.extend ClassMethods
-
end
-
-
2
class Initializer
-
2
attr_reader :name, :block
-
-
2
def initialize(name, context, options, &block)
-
350
options[:group] ||= :default
-
350
@name, @context, @options, @block = name, context, options, block
-
end
-
-
2
def before
-
22472
@options[:before]
-
end
-
-
2
def after
-
22432
@options[:after]
-
end
-
-
2
def belongs_to?(group)
-
212
@options[:group] == group || @options[:group] == :all
-
end
-
-
2
def run(*args)
-
212
@context.instance_exec(*args, &block)
-
end
-
-
2
def bind(context)
-
212
return self if @context
-
212
Initializer.new(@name, context, @options, &block)
-
end
-
end
-
-
2
class Collection < Array
-
2
include TSort
-
-
2
alias :tsort_each_node :each
-
2
def tsort_each_child(initializer, &block)
-
22684
select { |i| i.before == initializer.name || i.name == initializer.after }.each(&block)
-
end
-
-
2
def +(other)
-
104
Collection.new(to_a + other.to_a)
-
end
-
end
-
-
2
def run_initializers(group=:default, *args)
-
2
return if instance_variable_defined?(:@ran)
-
2
initializers.tsort.each do |initializer|
-
212
initializer.run(*args) if initializer.belongs_to?(group)
-
end
-
2
@ran = true
-
end
-
-
2
def initializers
-
42
@initializers ||= self.class.initializers_for(self)
-
end
-
-
2
module ClassMethods
-
2
def initializers
-
578
@initializers ||= Collection.new
-
end
-
-
2
def initializers_chain
-
46
initializers = Collection.new
-
46
ancestors.reverse_each do |klass|
-
482
next unless klass.respond_to?(:initializers)
-
100
initializers = initializers + klass.initializers
-
end
-
46
initializers
-
end
-
-
2
def initializers_for(binding)
-
258
Collection.new(initializers_chain.map { |i| i.bind(binding) })
-
end
-
-
2
def initializer(name, opts = {}, &blk)
-
138
raise ArgumentError, "A block must be passed when defining an initializer" unless blk
-
526
opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] }
-
138
initializers << Initializer.new(name, nil, opts, &blk)
-
end
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module Rails
-
2
module Paths
-
# This object is an extended hash that behaves as root of the <tt>Rails::Paths</tt> system.
-
# It allows you to collect information about how you want to structure your application
-
# paths by a Hash like API. It requires you to give a physical path on initialization.
-
#
-
# root = Root.new "/rails"
-
# root.add "app/controllers", :eager_load => true
-
#
-
# The command above creates a new root object and add "app/controllers" as a path.
-
# This means we can get a +Rails::Paths::Path+ object back like below:
-
#
-
# path = root["app/controllers"]
-
# path.eager_load? # => true
-
# path.is_a?(Rails::Paths::Path) # => true
-
#
-
# The +Path+ object is simply an array and allows you to easily add extra paths:
-
#
-
# path.is_a?(Array) # => true
-
# path.inspect # => ["app/controllers"]
-
#
-
# path << "lib/controllers"
-
# path.inspect # => ["app/controllers", "lib/controllers"]
-
#
-
# Notice that when you add a path using +add+, the path object created already
-
# contains the path with the same path value given to +add+. In some situations,
-
# you may not want this behavior, so you can give :with as option.
-
#
-
# root.add "config/routes", :with => "config/routes.rb"
-
# root["config/routes"].inspect # => ["config/routes.rb"]
-
#
-
# The +add+ method accepts the following options as arguments:
-
# eager_load, autoload, autoload_once and glob.
-
#
-
# Finally, the +Path+ object also provides a few helpers:
-
#
-
# root = Root.new "/rails"
-
# root.add "app/controllers"
-
#
-
# root["app/controllers"].expanded # => ["/rails/app/controllers"]
-
# root["app/controllers"].existent # => ["/rails/app/controllers"]
-
#
-
# Check the <tt>Rails::Paths::Path</tt> documentation for more information.
-
2
class Root < ::Hash
-
2
attr_accessor :path
-
-
2
def initialize(path)
-
10
raise "Argument should be a String of the physical root path" if path.is_a?(Array)
-
10
@current = nil
-
10
@path = path
-
10
@root = self
-
10
super()
-
end
-
-
2
def []=(path, value)
-
226
value = Path.new(self, path, value) unless value.is_a?(Path)
-
226
super(path, value)
-
end
-
-
2
def add(path, options={})
-
226
with = options[:with] || path
-
226
self[path] = Path.new(self, path, with, options)
-
end
-
-
2
def all_paths
-
80
values.tap { |v| v.uniq! }
-
end
-
-
2
def autoload_once
-
10
filter_by(:autoload_once?)
-
end
-
-
2
def eager_load
-
10
filter_by(:eager_load?)
-
end
-
-
2
def autoload_paths
-
10
filter_by(:autoload?)
-
end
-
-
2
def load_paths
-
10
filter_by(:load_path?)
-
end
-
-
2
protected
-
-
2
def filter_by(constraint)
-
40
all = []
-
40
all_paths.each do |path|
-
904
if path.send(constraint)
-
70
paths = path.existent
-
172
paths -= path.children.map { |p| p.send(constraint) ? [] : p.existent }.flatten
-
70
all.concat(paths)
-
end
-
end
-
40
all.uniq!
-
40
all
-
end
-
end
-
-
2
class Path < Array
-
2
attr_reader :path
-
2
attr_accessor :glob
-
-
2
def initialize(root, current, *paths)
-
226
options = paths.last.is_a?(::Hash) ? paths.pop : {}
-
226
super(paths.flatten)
-
-
226
@current = current
-
226
@root = root
-
226
@glob = options[:glob]
-
-
226
options[:autoload_once] ? autoload_once! : skip_autoload_once!
-
226
options[:eager_load] ? eager_load! : skip_eager_load!
-
226
options[:autoload] ? autoload! : skip_autoload!
-
226
options[:load_path] ? load_path! : skip_load_path!
-
end
-
-
2
def children
-
1652
keys = @root.keys.select { |k| k.include?(@current) }
-
70
keys.delete(@current)
-
70
@root.values_at(*keys.sort)
-
end
-
-
2
def first
-
24
expanded.first
-
end
-
-
2
def last
-
expanded.last
-
end
-
-
2
%w(autoload_once eager_load autoload load_path).each do |m|
-
8
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{m}! # def eager_load!
-
@#{m} = true # @eager_load = true
-
end # end
-
#
-
def skip_#{m}! # def skip_eager_load!
-
@#{m} = false # @eager_load = false
-
end # end
-
#
-
def #{m}? # def eager_load?
-
@#{m} # @eager_load
-
end # end
-
RUBY
-
end
-
-
# Expands all paths against the root and return all unique values.
-
2
def expanded
-
258
raise "You need to set a path root" unless @root.path
-
258
result = []
-
-
258
each do |p|
-
258
path = File.expand_path(p, @root.path)
-
-
258
if @glob
-
110
if File.directory? path
-
44
result.concat expand_dir(path, @glob)
-
else
-
# FIXME: I think we can remove this branch, but I'm not sure.
-
# Say the filesystem has this file:
-
#
-
# /tmp/foobar
-
#
-
# and someone adds this path:
-
#
-
# /tmp/foo
-
#
-
# with a glob of "*", then this function will return
-
#
-
# /tmp/foobar
-
#
-
# We need to figure out if that is desired behavior.
-
66
result.concat expand_file(path, @glob)
-
end
-
else
-
148
result << path
-
end
-
end
-
-
258
result.uniq!
-
258
result
-
end
-
-
# Returns all expanded paths but only if they exist in the filesystem.
-
2
def existent
-
402
expanded.select { |f| File.exists?(f) }
-
end
-
-
2
def existent_directories
-
56
expanded.select { |d| File.directory?(d) }
-
end
-
-
2
alias to_a expanded
-
-
2
private
-
2
def expand_file(path, glob)
-
66
Dir[File.join(path, glob)].sort
-
end
-
-
2
def expand_dir(path, glob)
-
44
Dir.chdir(path) do
-
144
Dir.glob(@glob).map { |file| File.join path, file }.sort
-
end
-
end
-
end
-
end
-
end
-
2
require 'rails/engine'
-
2
require 'active_support/core_ext/array/conversions'
-
-
2
module Rails
-
# Rails::Plugin is nothing more than a Rails::Engine, but since it's loaded too late
-
# in the boot process, it does not have the same configuration powers as a bare
-
# Rails::Engine.
-
#
-
# Opposite to Rails::Railtie and Rails::Engine, you are not supposed to inherit from
-
# Rails::Plugin. Rails::Plugin is automatically configured to be an engine by simply
-
# placing inside vendor/plugins. Since this is done automatically, you actually cannot
-
# declare a Rails::Engine inside your Plugin, otherwise it would cause the same files
-
# to be loaded twice. This means that if you want to ship an Engine as gem it cannot
-
# be used as plugin and vice-versa.
-
#
-
# Besides this conceptual difference, the only difference between Rails::Engine and
-
# Rails::Plugin is that plugins automatically load the file "init.rb" at the plugin
-
# root during the boot process.
-
#
-
2
class Plugin < Engine
-
2
def self.global_plugins
-
@global_plugins ||= []
-
end
-
-
2
def self.inherited(base)
-
raise "You cannot inherit from Rails::Plugin"
-
end
-
-
2
def self.all(list, paths)
-
10
plugins = []
-
10
paths.each do |path|
-
2
Dir["#{path}/*"].each do |plugin_path|
-
plugin = new(plugin_path)
-
next unless list.include?(plugin.name) || list.include?(:all)
-
if global_plugins.include?(plugin.name)
-
warn "WARNING: plugin #{plugin.name} from #{path} was not loaded. Plugin with the same name has been already loaded."
-
next
-
end
-
global_plugins << plugin.name
-
plugins << plugin
-
end
-
end
-
-
10
plugins.sort_by do |p|
-
[list.index(p.name) || list.index(:all), p.name.to_s]
-
end
-
end
-
-
2
attr_reader :name, :path
-
-
2
def railtie_name
-
name.to_s
-
end
-
-
2
def initialize(root)
-
ActiveSupport::Deprecation.warn "You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released"
-
@name = File.basename(root).to_sym
-
config.root = root
-
end
-
-
2
def config
-
@config ||= Engine::Configuration.new
-
end
-
-
2
initializer :handle_lib_autoload, :before => :set_load_path do |app|
-
autoload = if app.config.reload_plugins
-
config.autoload_paths
-
else
-
config.autoload_once_paths
-
end
-
-
autoload.concat paths["lib"].existent
-
end
-
-
2
initializer :load_init_rb, :before => :load_config_initializers do |app|
-
init_rb = File.expand_path("init.rb", root)
-
if File.file?(init_rb)
-
# This double assignment is to prevent an "unused variable" warning on Ruby 1.9.3.
-
config = config = app.config
-
# TODO: think about evaling initrb in context of Engine (currently it's
-
# always evaled in context of Rails::Application)
-
eval(File.read(init_rb), binding, init_rb)
-
end
-
end
-
-
2
initializer :sanity_check_railties_collision do
-
if Engine.subclasses.map { |k| k.root.to_s }.include?(root.to_s)
-
raise "\"#{name}\" is a Railtie/Engine and cannot be installed as a plugin"
-
end
-
end
-
end
-
end
-
2
module Rails
-
2
module Rack
-
2
autoload :Debugger, "rails/rack/debugger"
-
2
autoload :Logger, "rails/rack/logger"
-
2
autoload :LogTailer, "rails/rack/log_tailer"
-
end
-
end
-
2
require 'active_support/core_ext/time/conversions'
-
2
require 'active_support/core_ext/object/blank'
-
-
2
module Rails
-
2
module Rack
-
# Sets log tags, logs the request, calls the app, and flushes the logs.
-
2
class Logger < ActiveSupport::LogSubscriber
-
2
def initialize(app, taggers = nil)
-
2
@app, @taggers = app, taggers || []
-
end
-
-
2
def call(env)
-
request = ActionDispatch::Request.new(env)
-
-
if Rails.logger.respond_to?(:tagged)
-
Rails.logger.tagged(compute_tags(request)) { call_app(request, env) }
-
else
-
call_app(request, env)
-
end
-
end
-
-
2
protected
-
-
2
def call_app(request, env)
-
# Put some space between requests in development logs.
-
if Rails.env.development?
-
Rails.logger.info ''
-
Rails.logger.info ''
-
end
-
-
Rails.logger.info started_request_message(request)
-
@app.call(env)
-
ensure
-
ActiveSupport::LogSubscriber.flush_all!
-
end
-
-
# Started GET "/session/new" for 127.0.0.1 at 2012-09-26 14:51:42 -0700
-
2
def started_request_message(request)
-
'Started %s "%s" for %s at %s' % [
-
request.request_method,
-
request.filtered_path,
-
request.ip,
-
Time.now.to_default_s ]
-
end
-
-
2
def compute_tags(request)
-
@taggers.collect do |tag|
-
case tag
-
when Proc
-
tag.call(request)
-
when Symbol
-
request.send(tag)
-
else
-
tag
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'rails/initializable'
-
2
require 'rails/configuration'
-
2
require 'active_support/inflector'
-
2
require 'active_support/core_ext/module/introspection'
-
2
require 'active_support/core_ext/module/delegation'
-
-
2
module Rails
-
# Railtie is the core of the Rails framework and provides several hooks to extend
-
# Rails and/or modify the initialization process.
-
#
-
# Every major component of Rails (Action Mailer, Action Controller,
-
# Action View, Active Record and Active Resource) is a Railtie. Each of
-
# them is responsible for their own initialization. This makes Rails itself
-
# absent of any component hooks, allowing other components to be used in
-
# place of any of the Rails defaults.
-
#
-
# Developing a Rails extension does _not_ require any implementation of
-
# Railtie, but if you need to interact with the Rails framework during
-
# or after boot, then Railtie is needed.
-
#
-
# For example, an extension doing any of the following would require Railtie:
-
#
-
# * creating initializers
-
# * configuring a Rails framework for the application, like setting a generator
-
# * adding config.* keys to the environment
-
# * setting up a subscriber with ActiveSupport::Notifications
-
# * adding rake tasks
-
#
-
# == Creating your Railtie
-
#
-
# To extend Rails using Railtie, create a Railtie class which inherits
-
# from Rails::Railtie within your extension's namespace. This class must be
-
# loaded during the Rails boot process.
-
#
-
# The following example demonstrates an extension which can be used with or without Rails.
-
#
-
# # lib/my_gem/railtie.rb
-
# module MyGem
-
# class Railtie < Rails::Railtie
-
# end
-
# end
-
#
-
# # lib/my_gem.rb
-
# require 'my_gem/railtie' if defined?(Rails)
-
#
-
# == Initializers
-
#
-
# To add an initialization step from your Railtie to Rails boot process, you just need
-
# to create an initializer block:
-
#
-
# class MyRailtie < Rails::Railtie
-
# initializer "my_railtie.configure_rails_initialization" do
-
# # some initialization behavior
-
# end
-
# end
-
#
-
# If specified, the block can also receive the application object, in case you
-
# need to access some application specific configuration, like middleware:
-
#
-
# class MyRailtie < Rails::Railtie
-
# initializer "my_railtie.configure_rails_initialization" do |app|
-
# app.middleware.use MyRailtie::Middleware
-
# end
-
# end
-
#
-
# Finally, you can also pass :before and :after as option to initializer, in case
-
# you want to couple it with a specific step in the initialization process.
-
#
-
# == Configuration
-
#
-
# Inside the Railtie class, you can access a config object which contains configuration
-
# shared by all railties and the application:
-
#
-
# class MyRailtie < Rails::Railtie
-
# # Customize the ORM
-
# config.app_generators.orm :my_railtie_orm
-
#
-
# # Add a to_prepare block which is executed once in production
-
# # and before each request in development
-
# config.to_prepare do
-
# MyRailtie.setup!
-
# end
-
# end
-
#
-
# == Loading rake tasks and generators
-
#
-
# If your railtie has rake tasks, you can tell Rails to load them through the method
-
# rake_tasks:
-
#
-
# class MyRailtie < Rails::Railtie
-
# rake_tasks do
-
# load "path/to/my_railtie.tasks"
-
# end
-
# end
-
#
-
# By default, Rails load generators from your load path. However, if you want to place
-
# your generators at a different location, you can specify in your Railtie a block which
-
# will load them during normal generators lookup:
-
#
-
# class MyRailtie < Rails::Railtie
-
# generators do
-
# require "path/to/my_railtie_generator"
-
# end
-
# end
-
#
-
# == Application, Plugin and Engine
-
#
-
# A Rails::Engine is nothing more than a Railtie with some initializers already set.
-
# And since Rails::Application and Rails::Plugin are engines, the same configuration
-
# described here can be used in all three.
-
#
-
# Be sure to look at the documentation of those specific classes for more information.
-
#
-
2
class Railtie
-
2
autoload :Configurable, "rails/railtie/configurable"
-
2
autoload :Configuration, "rails/railtie/configuration"
-
-
2
include Initializable
-
-
2
ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Plugin Rails::Engine Rails::Application)
-
-
2
class << self
-
2
private :new
-
-
2
def subclasses
-
46
@subclasses ||= []
-
end
-
-
2
def inherited(base)
-
48
unless base.abstract_railtie?
-
42
base.send(:include, Railtie::Configurable)
-
42
subclasses << base
-
end
-
end
-
-
2
def rake_tasks(&blk)
-
12
@rake_tasks ||= []
-
12
@rake_tasks << blk if blk
-
12
@rake_tasks
-
end
-
-
2
def console(&blk)
-
2
@load_console ||= []
-
2
@load_console << blk if blk
-
2
@load_console
-
end
-
-
2
def runner(&blk)
-
2
@load_runner ||= []
-
2
@load_runner << blk if blk
-
2
@load_runner
-
end
-
-
2
def generators(&blk)
-
@generators ||= []
-
@generators << blk if blk
-
@generators
-
end
-
-
2
def abstract_railtie?
-
62
ABSTRACT_RAILTIES.include?(name)
-
end
-
-
2
def railtie_name(name = nil)
-
@railtie_name = name.to_s if name
-
@railtie_name ||= generate_railtie_name(self.name)
-
end
-
-
2
protected
-
2
def generate_railtie_name(class_or_module)
-
ActiveSupport::Inflector.underscore(class_or_module).gsub("/", "_")
-
end
-
end
-
-
2
delegate :railtie_name, :to => "self.class"
-
-
2
def config
-
132
@config ||= Railtie::Configuration.new
-
end
-
-
2
def eager_load!
-
end
-
-
2
def load_console(app=self)
-
self.class.console.each { |block| block.call(app) }
-
end
-
-
2
def load_runner(app=self)
-
self.class.runner.each { |block| block.call(app) }
-
end
-
-
2
def load_tasks(app=self)
-
extend Rake::DSL if defined? Rake::DSL
-
self.class.rake_tasks.each { |block| self.instance_exec(app, &block) }
-
-
# load also tasks from all superclasses
-
klass = self.class.superclass
-
while klass.respond_to?(:rake_tasks)
-
klass.rake_tasks.each { |t| self.instance_exec(app, &t) }
-
klass = klass.superclass
-
end
-
end
-
-
2
def load_generators(app=self)
-
self.class.generators.each { |block| block.call(app) }
-
end
-
-
2
def railtie_namespace
-
@railtie_namespace ||= self.class.parents.detect { |n| n.respond_to?(:railtie_namespace) }
-
end
-
end
-
end
-
2
require 'active_support/concern'
-
-
2
module Rails
-
2
class Railtie
-
2
module Configurable
-
2
extend ActiveSupport::Concern
-
-
2
module ClassMethods
-
2
delegate :config, :to => :instance
-
-
2
def inherited(base)
-
raise "You cannot inherit from a #{self.superclass.name} child"
-
end
-
-
2
def instance
-
196
@instance ||= new
-
end
-
-
2
def respond_to?(*args)
-
42
super || instance.respond_to?(*args)
-
end
-
-
2
def configure(&block)
-
2
class_eval(&block)
-
end
-
-
2
protected
-
-
2
def method_missing(*args, &block)
-
4
instance.send(*args, &block)
-
end
-
end
-
end
-
end
-
end
-
2
require 'rails/configuration'
-
-
2
module Rails
-
2
class Railtie
-
2
class Configuration
-
2
def initialize
-
38
@@options ||= {}
-
end
-
-
# Add files that should be watched for change.
-
2
def watchable_files
-
4
@@watchable_files ||= []
-
end
-
-
# Add directories that should be watched for change.
-
# The key of the hashes should be directories and the values should
-
# be an array of extensions to match in each directory.
-
2
def watchable_dirs
-
2
@@watchable_dirs ||= {}
-
end
-
-
# This allows you to modify the application's middlewares from Engines.
-
#
-
# All operations you run on the app_middleware will be replayed on the
-
# application once it is defined and the default_middlewares are
-
# created
-
2
def app_middleware
-
6
@@app_middleware ||= Rails::Configuration::MiddlewareStackProxy.new
-
end
-
-
# This allows you to modify application's generators from Railties.
-
#
-
# Values set on app_generators will become defaults for application, unless
-
# application overwrites them.
-
2
def app_generators
-
24
@@app_generators ||= Rails::Configuration::Generators.new
-
24
yield(@@app_generators) if block_given?
-
24
@@app_generators
-
end
-
-
# First configurable block to run. Called before any initializers are run.
-
2
def before_configuration(&block)
-
2
ActiveSupport.on_load(:before_configuration, :yield => true, &block)
-
end
-
-
# Third configurable block to run. Does not run if config.cache_classes
-
# set to false.
-
2
def before_eager_load(&block)
-
2
ActiveSupport.on_load(:before_eager_load, :yield => true, &block)
-
end
-
-
# Second configurable block to run. Called before frameworks initialize.
-
2
def before_initialize(&block)
-
4
ActiveSupport.on_load(:before_initialize, :yield => true, &block)
-
end
-
-
# Last configurable block to run. Called after frameworks initialize.
-
2
def after_initialize(&block)
-
8
ActiveSupport.on_load(:after_initialize, :yield => true, &block)
-
end
-
-
# Array of callbacks defined by #to_prepare.
-
2
def to_prepare_blocks
-
4
@@to_prepare_blocks ||= []
-
end
-
-
# Defines generic callbacks to run before #after_initialize. Useful for
-
# Rails::Railtie subclasses.
-
2
def to_prepare(&blk)
-
2
to_prepare_blocks << blk if blk
-
end
-
-
2
def respond_to?(name)
-
super || @@options.key?(name.to_sym)
-
end
-
-
2
private
-
-
2
def method_missing(name, *args, &blk)
-
191
if name.to_s =~ /=$/
-
20
@@options[$`.to_sym] = args.first
-
171
elsif @@options.key?(name)
-
171
@@options[name]
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
2
if RUBY_VERSION < '1.8.7'
-
desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
-
abort <<-end_message
-
-
Rails 3 requires Ruby 1.8.7 or >= 1.9.2.
-
-
You're running
-
#{desc}
-
-
Please upgrade to continue.
-
-
end_message
-
elsif RUBY_VERSION > '1.9' and RUBY_VERSION < '1.9.2'
-
$stderr.puts <<-end_message
-
-
Rails 3 doesn't officially support Ruby 1.9.1 since recent stable
-
releases have segfaulted the test suite. Please upgrade to Ruby 1.9.2 or later.
-
-
You're running
-
#{RUBY_DESCRIPTION}
-
-
end_message
-
end
-
# Make double-sure the RAILS_ENV is not set to production,
-
# so fixtures aren't loaded into that environment
-
2
abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production?
-
-
2
require 'test/unit'
-
2
require 'active_support/test_case'
-
2
require 'action_controller/test_case'
-
2
require 'action_dispatch/testing/integration'
-
-
2
if defined?(Test::Unit::Util::BacktraceFilter) && ENV['BACKTRACE'].nil?
-
require 'rails/backtrace_cleaner'
-
Test::Unit::Util::BacktraceFilter.module_eval { include Rails::BacktraceFilterForTestUnit }
-
end
-
-
2
if defined?(MiniTest)
-
# Enable turn if it is available
-
2
begin
-
2
require 'turn'
-
-
Turn.config do |c|
-
c.natural = true
-
end
-
rescue LoadError
-
end
-
end
-
-
2
if defined?(ActiveRecord::Base)
-
2
require 'active_record/test_case'
-
-
2
class ActiveSupport::TestCase
-
2
include ActiveRecord::TestFixtures
-
2
self.fixture_path = "#{Rails.root}/test/fixtures/"
-
-
2
setup do
-
145
ActiveRecord::IdentityMap.clear
-
end
-
end
-
-
2
ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
-
-
2
def create_fixtures(*table_names, &block)
-
Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block)
-
end
-
end
-
-
2
class ActionController::TestCase
-
2
setup do
-
75
@routes = Rails.application.routes
-
end
-
end
-
-
2
class ActionDispatch::IntegrationTest
-
2
setup do
-
@routes = Rails.application.routes
-
end
-
end
-
2
module Rails
-
2
class TestUnitRailtie < Rails::Railtie
-
2
config.app_generators do |c|
-
2
c.test_framework :test_unit, :fixture => true,
-
:fixture_replacement => nil
-
-
2
c.integration_tool :test_unit
-
2
c.performance_tool :test_unit
-
end
-
-
2
rake_tasks do
-
load "rails/test_unit/testing.rake"
-
end
-
end
-
end
-
2
module Rails
-
2
module VERSION #:nodoc:
-
2
MAJOR = 3
-
2
MINOR = 2
-
2
TINY = 16
-
2
PRE = nil
-
-
2
STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
-
end
-
end
-
2
module Ref
-
2
require File.join(File.dirname(__FILE__), "ref", "abstract_reference_value_map.rb")
-
2
require File.join(File.dirname(__FILE__), "ref", "abstract_reference_key_map.rb")
-
2
require File.join(File.dirname(__FILE__), "ref", "reference.rb")
-
2
require File.join(File.dirname(__FILE__), "ref", "reference_queue.rb")
-
2
require File.join(File.dirname(__FILE__), "ref", "safe_monitor.rb")
-
-
# Set the best implementation for weak references based on the runtime.
-
2
if defined?(RUBY_PLATFORM) && RUBY_PLATFORM == 'java'
-
# Use native Java references
-
begin
-
$LOAD_PATH.unshift(File.dirname(__FILE__))
-
require 'org/jruby/ext/ref/references'
-
ensure
-
$LOAD_PATH.shift if $LOAD_PATH.first == File.dirname(__FILE__)
-
end
-
else
-
2
require File.join(File.dirname(__FILE__), "ref", "soft_reference.rb")
-
2
if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'ironruby'
-
# IronRuby has it's own implementation of weak references.
-
require File.join(File.dirname(__FILE__), "ref", "weak_reference", "iron_ruby.rb")
-
elsif defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx'
-
# If using Rubinius set the implementation to use WeakRef since it is very efficient and using finalizers is not.
-
require File.join(File.dirname(__FILE__), "ref", "weak_reference", "weak_ref.rb")
-
elsif defined?(::ObjectSpace::WeakMap)
-
# Ruby 2.0 has a working implementation of weakref.rb backed by the new ObjectSpace::WeakMap
-
require File.join(File.dirname(__FILE__), "ref", "weak_reference", "weak_ref.rb")
-
elsif defined?(::ObjectSpace._id2ref)
-
# If ObjectSpace can lookup objects from their object_id, then use the pure ruby implementation.
-
2
require File.join(File.dirname(__FILE__), "ref", "weak_reference", "pure_ruby.rb")
-
else
-
# Otherwise, wrap the standard library WeakRef class
-
require File.join(File.dirname(__FILE__), "ref", "weak_reference", "weak_ref.rb")
-
end
-
end
-
-
2
require File.join(File.dirname(__FILE__), "ref", "soft_key_map.rb")
-
2
require File.join(File.dirname(__FILE__), "ref", "soft_value_map.rb")
-
2
require File.join(File.dirname(__FILE__), "ref", "strong_reference.rb")
-
2
require File.join(File.dirname(__FILE__), "ref", "weak_key_map.rb")
-
2
require File.join(File.dirname(__FILE__), "ref", "weak_value_map.rb")
-
-
# Used for testing
-
2
autoload :Mock, File.join(File.dirname(__FILE__), "ref", "mock.rb")
-
end
-
2
module Ref
-
# Abstract base class for WeakKeyMap and SoftKeyMap.
-
#
-
# The classes behave similar to Hashes, but the keys in the map are not strong references
-
# and can be reclaimed by the garbage collector at any time. When a key is reclaimed, the
-
# map entry will be removed.
-
2
class AbstractReferenceKeyMap
-
2
class << self
-
2
def reference_class=(klass) #:nodoc:
-
4
@reference_class = klass
-
end
-
-
2
def reference_class #:nodoc:
-
raise NotImplementedError.new("#{name} is an abstract class and cannot be instantiated") unless @reference_class
-
@reference_class
-
end
-
end
-
-
# Create a new map. Values added to the hash will be cleaned up by the garbage
-
# collector if there are no other reference except in the map.
-
2
def initialize
-
@values = {}
-
@references_to_keys_map = {}
-
@lock = SafeMonitor.new
-
@reference_cleanup = lambda{|object_id| remove_reference_to(object_id)}
-
end
-
-
# Get a value from the map by key. If the value has been reclaimed by the garbage
-
# collector, this will return nil.
-
2
def [](key)
-
rkey = ref_key(key)
-
@values[rkey] if rkey
-
end
-
-
# Add a key/value to the map.
-
2
def []=(key, value)
-
ObjectSpace.define_finalizer(key, @reference_cleanup)
-
@lock.synchronize do
-
@references_to_keys_map[key.__id__] = self.class.reference_class.new(key)
-
@values[key.__id__] = value
-
end
-
end
-
-
# Remove the value associated with the key from the map.
-
2
def delete(key)
-
rkey = ref_key(key)
-
if rkey
-
@references_to_keys_map.delete(rkey)
-
@values.delete(rkey)
-
else
-
nil
-
end
-
end
-
-
# Get an array of keys that have not yet been garbage collected.
-
2
def keys
-
@values.keys.collect{|rkey| @references_to_keys_map[rkey].object}.compact
-
end
-
-
# Turn the map into an arry of [key, value] entries.
-
2
def to_a
-
array = []
-
each{|k,v| array << [k, v]}
-
array
-
end
-
-
# Iterate through all the key/value pairs in the map that have not been reclaimed
-
# by the garbage collector.
-
2
def each
-
@references_to_keys_map.each do |rkey, ref|
-
key = ref.object
-
yield(key, @values[rkey]) if key
-
end
-
end
-
-
# Clear the map of all key/value pairs.
-
2
def clear
-
@lock.synchronize do
-
@values.clear
-
@references_to_keys_map.clear
-
end
-
end
-
-
# Merge the values from another hash into this map.
-
2
def merge!(other_hash)
-
other_hash.each do |key, value|
-
self[key] = value
-
end
-
end
-
-
2
def inspect
-
live_entries = {}
-
each do |key, value|
-
live_entries[key] = value
-
end
-
live_entries.inspect
-
end
-
-
2
private
-
-
2
def ref_key (key)
-
ref = @references_to_keys_map[key.__id__]
-
if ref && ref.object
-
ref.referenced_object_id
-
else
-
nil
-
end
-
end
-
-
2
def remove_reference_to(object_id)
-
@lock.synchronize do
-
@references_to_keys_map.delete(object_id)
-
@values.delete(object_id)
-
end
-
end
-
end
-
end
-
2
module Ref
-
# Abstract base class for WeakValueMap and SoftValueMap.
-
#
-
# The classes behave similar to Hashes, but the values in the map are not strong references
-
# and can be reclaimed by the garbage collector at any time. When a value is reclaimed, the
-
# map entry will be removed.
-
2
class AbstractReferenceValueMap
-
2
class << self
-
2
def reference_class=(klass) #:nodoc:
-
4
@reference_class = klass
-
end
-
-
2
def reference_class #:nodoc:
-
720
raise NotImplementedError.new("#{name} is an abstract class and cannot be instantiated") unless @reference_class
-
720
@reference_class
-
end
-
end
-
-
# Create a new map. Values added to the map will be cleaned up by the garbage
-
# collector if there are no other reference except in the map.
-
2
def initialize
-
6
@references = {}
-
6
@references_to_keys_map = {}
-
6
@lock = SafeMonitor.new
-
372
@reference_cleanup = lambda{|object_id| remove_reference_to(object_id)}
-
end
-
-
# Get a value from the map by key. If the value has been reclaimed by the garbage
-
# collector, this will return nil.
-
2
def [](key)
-
1090
ref = @references[key]
-
1090
value = ref.object if ref
-
1090
value
-
end
-
-
# Add a key/value to the map.
-
2
def []=(key, value)
-
720
ObjectSpace.define_finalizer(value, @reference_cleanup)
-
720
key = key.dup if key.is_a?(String)
-
720
@lock.synchronize do
-
720
@references[key] = self.class.reference_class.new(value)
-
720
keys_for_id = @references_to_keys_map[value.__id__]
-
720
unless keys_for_id
-
720
keys_for_id = []
-
720
@references_to_keys_map[value.__id__] = keys_for_id
-
end
-
720
keys_for_id << key
-
end
-
720
value
-
end
-
-
# Remove the entry associated with the key from the map.
-
2
def delete(key)
-
ref = @references.delete(key)
-
if ref
-
keys_to_id = @references_to_keys_map[ref.referenced_object_id]
-
if keys_to_id
-
keys_to_id.delete(key)
-
@references_to_keys_map.delete(ref.referenced_object_id) if keys_to_id.empty?
-
end
-
ref.object
-
else
-
nil
-
end
-
end
-
-
# Get the list of all values that have not yet been garbage collected.
-
2
def values
-
vals = []
-
each{|k,v| vals << v}
-
vals
-
end
-
-
# Turn the map into an arry of [key, value] entries
-
2
def to_a
-
array = []
-
each{|k,v| array << [k, v]}
-
array
-
end
-
-
# Iterate through all the key/value pairs in the map that have not been reclaimed
-
# by the garbage collector.
-
2
def each
-
@references.each do |key, ref|
-
value = ref.object
-
yield(key, value) if value
-
end
-
end
-
-
# Clear the map of all key/value pairs.
-
2
def clear
-
@lock.synchronize do
-
@references.clear
-
@references_to_keys_map.clear
-
end
-
end
-
-
# Merge the values from another hash into this map.
-
2
def merge!(other_hash)
-
other_hash.each do |key, value|
-
self[key] = value
-
end
-
end
-
-
2
def inspect
-
live_entries = {}
-
each do |key, value|
-
live_entries[key] = value
-
end
-
live_entries.inspect
-
end
-
-
2
private
-
-
2
def remove_reference_to(object_id)
-
366
@lock.synchronize do
-
366
keys = @references_to_keys_map[object_id]
-
366
if keys
-
366
keys.each do |key|
-
366
@references.delete(key)
-
end
-
366
@references_to_keys_map.delete(object_id)
-
end
-
end
-
end
-
end
-
end
-
2
module Ref
-
# This class serves as a generic reference mechanism to other objects. The
-
# actual reference can be either a WeakReference, SoftReference, or StrongReference.
-
2
class Reference
-
# The object id of the object being referenced.
-
2
attr_reader :referenced_object_id
-
-
# Create a new reference to an object.
-
2
def initialize(obj)
-
raise NotImplementedError.new("cannot instantiate a generic reference")
-
end
-
-
# Get the referenced object. This could be nil if the reference
-
# is a WeakReference or a SoftReference and the object has been reclaimed by the garbage collector.
-
2
def object
-
raise NotImplementedError
-
end
-
-
2
def inspect
-
obj = object
-
"<##{self.class.name}: #{obj ? obj.inspect : "##{referenced_object_id} (not accessible)"}>"
-
end
-
end
-
end
-
2
module Ref
-
# This class provides a simple thread safe container to hold a reference queue. Instances
-
# of WeakReference can be added to the queue and as the objects pointed to by those references
-
# are cleaned up by the garbage collector, the references will be added to the queue.
-
#
-
# The reason for using a reference queue is that it tends to be more efficient than adding
-
# individual finalizers to objects and the cleanup code can be handled by a thread outside
-
# of garbage collection.
-
#
-
# In general, you should create your own subclass of WeakReference that contains the logic
-
# needed to complete the cleanup. The object pointed to will have already been cleaned up
-
# and the reference cannot maintain a reference to the object.
-
#
-
# === Example usage:
-
#
-
# class MyRef < Ref::WeakReference
-
# def cleanup
-
# # Do something...
-
# end
-
# end
-
#
-
# queue = Ref::ReferenceQueue.new
-
# ref = MyRef.new(Object.new)
-
# queue.monitor(ref)
-
# queue.shift # = nil
-
# ObjectSpace.garbage_collect
-
# r = queue.shift # = ref
-
# r.cleanup
-
2
class ReferenceQueue
-
2
def initialize
-
@queue = []
-
@references = {}
-
@lock = SafeMonitor.new
-
@finalizer = lambda do |object_id|
-
@lock.synchronize do
-
ref = @references.delete(object_id)
-
@queue.push(ref) if ref
-
end
-
end
-
end
-
-
# Monitor a reference. When the object the reference points to is garbage collected,
-
# the reference will be added to the queue.
-
2
def monitor(reference)
-
obj = reference.object
-
if obj
-
@lock.synchronize do
-
@references[reference.referenced_object_id] = reference
-
end
-
ObjectSpace.define_finalizer(obj, @finalizer)
-
else
-
push(reference)
-
end
-
end
-
-
# Add a reference to the queue.
-
2
def push(reference)
-
if reference
-
@lock.synchronize do
-
@queue.push(reference)
-
end
-
end
-
end
-
-
# Pull the last reference off the queue. Returns +nil+ if their are no references.
-
2
def pop
-
@lock.synchronize do
-
@queue.pop
-
end
-
end
-
-
# Pull the next reference off the queue. Returns +nil+ if there are no references.
-
2
def shift
-
@lock.synchronize do
-
@queue.shift
-
end
-
end
-
-
# Return +true+ if the queue is empty.
-
2
def empty?
-
@queue.empty?
-
end
-
-
# Get the current size of the queue.
-
2
def size
-
@queue.size
-
end
-
end
-
end
-
2
begin
-
2
require 'thread'
-
rescue LoadError
-
# Threads not available. Monitor will do nothing.
-
end
-
-
2
module Ref
-
# The Monitor class in Ruby 1.8 has some bugs and also threads may not be available on all
-
# runtimes. This class provides a simple, safe re-entrant mutex as an alternative.
-
2
class SafeMonitor
-
2
def initialize
-
10
@owner = nil
-
10
@count = 0
-
10
@mutex = defined?(Mutex) ? Mutex.new : nil
-
end
-
-
# Acquire an exclusive lock.
-
2
def lock
-
2531
if @mutex
-
2531
if @owner != Thread.current.object_id
-
2531
@mutex.lock
-
2531
@owner = Thread.current.object_id
-
end
-
2531
@count += 1
-
end
-
2531
true
-
end
-
-
# Release the exclusive lock.
-
2
def unlock
-
2531
if @mutex
-
2531
if @owner == Thread.current.object_id
-
2531
@count -= 1
-
2531
if @count == 0
-
2531
@owner = nil
-
2531
@mutex.unlock
-
end
-
end
-
end
-
end
-
-
# Run a block of code with an exclusive lock.
-
2
def synchronize
-
2531
lock
-
2531
yield
-
ensure
-
2531
unlock
-
end
-
end
-
end
-
2
module Ref
-
# Implementation of a map in which only softly referenced keys are kept to the map values.
-
# This allows the garbage collector to reclaim these objects if the only reference to them
-
# is the soft reference in the map.
-
#
-
# This is often useful for cache implementations since the map can be allowed to grow
-
# without bound and the garbage collector can be relied on to clean it up as necessary.
-
# One must be careful, though, when accessing entries since they can be collected at
-
# any time until there is a strong reference to the key.
-
#
-
# === Example usage:
-
#
-
# cache = Ref::SoftKeyMap.new
-
# obj = MyObject.find_by_whatever
-
# obj_info = Service.lookup_object_info(obj)
-
# cache[obj] = Service.lookup_object_info(obj)
-
# cache[obj] # The values looked up from the service
-
# obj = nil
-
# ObjectSpace.garbage_collect
-
# cache.keys # empty array since the keys and values have been reclaimed
-
#
-
# See AbstractReferenceKeyMap for details.
-
2
class SoftKeyMap < AbstractReferenceKeyMap
-
2
self.reference_class = SoftReference
-
end
-
end
-
2
module Ref
-
# A SoftReference represents a reference to an object that is not seen by
-
# the tracing phase of the garbage collector. This allows the referenced
-
# object to be garbage collected as if nothing is referring to it.
-
#
-
# A SoftReference differs from a WeakReference in that the garbage collector
-
# is not so eager to reclaim soft references so they should persist longer.
-
#
-
# === Example usage:
-
#
-
# foo = Object.new
-
# ref = Ref::SoftReference.new(foo)
-
# ref.object # should be foo
-
# ObjectSpace.garbage_collect
-
# ref.object # should be foo
-
# ObjectSpace.garbage_collect
-
# ObjectSpace.garbage_collect
-
# ref.object # should be nil
-
2
class SoftReference < Reference
-
2
@@strong_references = [{}]
-
2
@@gc_flag_set = false
-
-
# Number of garbage collection cycles after an object is used before a reference to it can be reclaimed.
-
2
MIN_GC_CYCLES = 10
-
-
2
@@lock = SafeMonitor.new
-
-
2
@@finalizer = lambda do |object_id|
-
@@lock.synchronize do
-
while @@strong_references.size >= MIN_GC_CYCLES do
-
@@strong_references.shift
-
end
-
@@strong_references.push({}) if @@strong_references.size < MIN_GC_CYCLES
-
@@gc_flag_set = false
-
end
-
end
-
-
# Create a new soft reference to an object.
-
2
def initialize(obj)
-
@referenced_object_id = obj.__id__
-
@weak_reference = WeakReference.new(obj)
-
add_strong_reference(obj)
-
end
-
-
# Get the referenced object. If the object has been reclaimed by the
-
# garbage collector, then this will return nil.
-
2
def object
-
obj = @weak_reference.object
-
# add a temporary strong reference each time the object is referenced.
-
add_strong_reference(obj) if obj
-
obj
-
end
-
-
2
private
-
# Create a strong reference to the object. This reference will live
-
# for three passes of the garbage collector.
-
2
def add_strong_reference(obj) #:nodoc:
-
@@lock.synchronize do
-
@@strong_references.last[obj] = true
-
unless @@gc_flag_set
-
@@gc_flag_set = true
-
ObjectSpace.define_finalizer(Object.new, @@finalizer)
-
end
-
end
-
end
-
end
-
end
-
2
module Ref
-
# Implementation of a map in which soft references are kept to the map values.
-
# This allows the garbage collector to reclaim these objects if the
-
# only reference to them is the soft reference in the map.
-
#
-
# This is often useful for cache implementations since the map can be allowed to grow
-
# without bound and the garbage collector can be relied on to clean it up as necessary.
-
# One must be careful, though, when accessing entries since the values can be collected
-
# at any time until there is a strong reference to them.
-
#
-
# === Example usage:
-
#
-
# cache = Ref::SoftValueMap.new
-
# foo = "foo"
-
# cache["strong"] = foo # add a value with a strong reference
-
# cache["soft"] = "bar" # add a value without a strong reference
-
# cache["strong"] # "foo"
-
# cache["soft"] # "bar"
-
# ObjectSpace.garbage_collect
-
# ObjectSpace.garbage_collect
-
# cache["strong"] # "foo"
-
# cache["soft"] # nil
-
#
-
# See AbstractReferenceValueMap for details.
-
2
class SoftValueMap < AbstractReferenceValueMap
-
2
self.reference_class = SoftReference
-
end
-
end
-
2
module Ref
-
# This implementation of Reference holds a strong reference to an object. The
-
# referenced object will not be garbage collected as long as the strong reference
-
# exists.
-
2
class StrongReference < Reference
-
# Create a new strong reference to an object.
-
2
def initialize(obj)
-
@obj = obj
-
@referenced_object_id = obj.__id__
-
end
-
-
# Get the referenced object.
-
2
def object
-
@obj
-
end
-
end
-
end
-
2
module Ref
-
# Implementation of a map in which only weakly referenced keys are kept to the map values.
-
# This allows the garbage collector to reclaim these objects if the only reference to them
-
# is the weak reference in the map.
-
#
-
# This is often useful for cache implementations since the map can be allowed to grow
-
# without bound and the garbage collector can be relied on to clean it up as necessary.
-
# One must be careful, though, when accessing entries since they can be collected at
-
# any time until there is a strong reference to the key.
-
#
-
# === Example usage:
-
#
-
# cache = Ref::WeakKeyMap.new
-
# obj = MyObject.find_by_whatever
-
# obj_info = Service.lookup_object_info(obj)
-
# cache[obj] = Service.lookup_object_info(obj)
-
# cache[obj] # The values looked up from the service
-
# obj = nil
-
# ObjectSpace.garbage_collect
-
# cache.keys # empty array since the keys and values have been reclaimed
-
#
-
# See AbstractReferenceKeyMap for details.
-
2
class WeakKeyMap < AbstractReferenceKeyMap
-
2
self.reference_class = WeakReference
-
end
-
end
-
2
module Ref
-
# This is a pure ruby implementation of a weak reference. It is much more
-
# efficient than the WeakRef implementation bundled in MRI 1.8 and 1.9
-
# subclass Delegator which is very heavy to instantiate and utilizes a
-
# because it does not fair amount of memory under Ruby 1.8.
-
2
class WeakReference < Reference
-
-
2
class ReferencePointer
-
2
def initialize(object)
-
1080
@referenced_object_id = object.__id__
-
1080
add_backreference(object)
-
end
-
-
2
def cleanup
-
365
obj = ObjectSpace._id2ref(@referenced_object_id) rescue nil
-
365
remove_backreference(obj) if obj
-
end
-
-
2
def object
-
1302
obj = ObjectSpace._id2ref(@referenced_object_id)
-
1302
obj if verify_backreferences(obj)
-
rescue RangeError
-
nil
-
end
-
-
2
private
-
# Verify that the object is the same one originally set for the weak reference.
-
2
def verify_backreferences(obj) #:nodoc:
-
1302
return nil unless supports_backreference?(obj)
-
1302
backreferences = obj.instance_variable_get(:@__weak_backreferences__) if obj.instance_variable_defined?(:@__weak_backreferences__)
-
1302
backreferences && backreferences.include?(object_id)
-
end
-
-
# Add a backreference to the object.
-
2
def add_backreference(obj) #:nodoc:
-
1080
return unless supports_backreference?(obj)
-
1080
backreferences = obj.instance_variable_get(:@__weak_backreferences__) if obj.instance_variable_defined?(:@__weak_backreferences__)
-
1080
unless backreferences
-
834
backreferences = []
-
834
obj.instance_variable_set(:@__weak_backreferences__, backreferences)
-
end
-
1080
backreferences << object_id
-
end
-
-
# Remove backreferences from the object.
-
2
def remove_backreference(obj) #:nodoc:
-
29
return unless supports_backreference?(obj)
-
29
backreferences = obj.instance_variable_get(:@__weak_backreferences__) if obj.instance_variable_defined?(:@__weak_backreferences__)
-
29
if backreferences
-
backreferences.dup.delete(object_id)
-
obj.send(:remove_instance_variable, :@__weak_backreferences__) if backreferences.empty?
-
end
-
end
-
-
2
def supports_backreference?(obj)
-
2411
obj.respond_to?(:instance_variable_get) && obj.respond_to?(:instance_variable_defined?)
-
rescue NoMethodError
-
false
-
end
-
end
-
-
2
@@weak_references = {}
-
2
@@lock = SafeMonitor.new
-
-
# Finalizer that cleans up weak references when references are destroyed.
-
2
@@reference_finalizer = lambda do |object_id|
-
365
@@lock.synchronize do
-
365
reference_pointer = @@weak_references.delete(object_id)
-
365
reference_pointer.cleanup if reference_pointer
-
end
-
end
-
-
# Create a new weak reference to an object. The existence of the weak reference
-
# will not prevent the garbage collector from reclaiming the referenced object.
-
2
def initialize(obj) #:nodoc:
-
1080
@referenced_object_id = obj.__id__
-
1080
@@lock.synchronize do
-
1080
@reference_pointer = ReferencePointer.new(obj)
-
1080
@@weak_references[self.object_id] = @reference_pointer
-
end
-
1080
ObjectSpace.define_finalizer(self, @@reference_finalizer)
-
end
-
-
# Get the reference object. If the object has already been garbage collected,
-
# then this method will return nil.
-
2
def object #:nodoc:
-
1302
if @reference_pointer
-
1302
obj = @reference_pointer.object
-
1302
unless obj
-
@@lock.synchronize do
-
@@weak_references.delete(object_id)
-
@reference_pointer.cleanup
-
@reference_pointer = nil
-
end
-
end
-
1302
obj
-
end
-
end
-
end
-
end
-
2
module Ref
-
# Implementation of a map in which weak references are kept to the map values.
-
# This allows the garbage collector to reclaim these objects if the
-
# only reference to them is the weak reference in the map.
-
#
-
# This is often useful for cache implementations since the map can be allowed to grow
-
# without bound and the garbage collector can be relied on to clean it up as necessary.
-
# One must be careful, though, when accessing entries since the values can be collected
-
# at any time until there is a strong reference to them.
-
#
-
# === Example usage:
-
#
-
# cache = Ref::WeakValueMap.new
-
# foo = "foo"
-
# cache["strong"] = foo # add a value with a strong reference
-
# cache["weak"] = "bar" # add a value without a strong reference
-
# cache["strong"] # "foo"
-
# cache["weak"] # "bar"
-
# ObjectSpace.garbage_collect
-
# cache["strong"] # "foo"
-
# cache["weak"] # nil
-
#
-
# See AbstractReferenceValueMap for details.
-
2
class WeakValueMap < AbstractReferenceValueMap
-
2
self.reference_class = WeakReference
-
end
-
end
-
2
dir = File.dirname(__FILE__)
-
2
$LOAD_PATH.unshift dir unless $LOAD_PATH.include?(dir)
-
-
# This is necessary to set so that the Haml code that tries to load Sass
-
# knows that Sass is indeed loading,
-
# even if there's some crazy autoload stuff going on.
-
2
SASS_BEGUN_TO_LOAD = true unless defined?(SASS_BEGUN_TO_LOAD)
-
-
2
require 'sass/version'
-
-
# The module that contains everything Sass-related:
-
#
-
# * {Sass::Engine} is the class used to render Sass/SCSS within Ruby code.
-
# * {Sass::Plugin} is interfaces with web frameworks (Rails and Merb in particular).
-
# * {Sass::SyntaxError} is raised when Sass encounters an error.
-
# * {Sass::CSS} handles conversion of CSS to Sass.
-
#
-
# Also see the {file:SASS_REFERENCE.md full Sass reference}.
-
2
module Sass
-
# The global load paths for Sass files. This is meant for plugins and
-
# libraries to register the paths to their Sass stylesheets to that they may
-
# be `@imported`. This load path is used by every instance of [Sass::Engine].
-
# They are lower-precedence than any load paths passed in via the
-
# {file:SASS_REFERENCE.md#load_paths-option `:load_paths` option}.
-
#
-
# If the `SASS_PATH` environment variable is set,
-
# the initial value of `load_paths` will be initialized based on that.
-
# The variable should be a colon-separated list of path names
-
# (semicolon-separated on Windows).
-
#
-
# Note that files on the global load path are never compiled to CSS
-
# themselves, even if they aren't partials. They exist only to be imported.
-
#
-
# @example
-
# Sass.load_paths << File.dirname(__FILE__ + '/sass')
-
# @return [Array<String, Pathname, Sass::Importers::Base>]
-
2
def self.load_paths
-
@load_paths ||= ENV['SASS_PATH'] ?
-
ENV['SASS_PATH'].split(Sass::Util.windows? ? ';' : ':') : []
-
end
-
-
# Compile a Sass or SCSS string to CSS.
-
# Defaults to SCSS.
-
#
-
# @param contents [String] The contents of the Sass file.
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
2
def self.compile(contents, options = {})
-
options[:syntax] ||= :scss
-
Engine.new(contents, options).to_css
-
end
-
-
# Compile a file on disk to CSS.
-
#
-
# @param filename [String] The path to the Sass, SCSS, or CSS file on disk.
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
#
-
# @overload compile_file(filename, options = {})
-
# Return the compiled CSS rather than writing it to a file.
-
#
-
# @return [String] The compiled CSS.
-
#
-
# @overload compile_file(filename, css_filename, options = {})
-
# Write the compiled CSS to a file.
-
#
-
# @param css_filename [String] The location to which to write the compiled CSS.
-
2
def self.compile_file(filename, *args)
-
options = args.last.is_a?(Hash) ? args.pop : {}
-
css_filename = args.shift
-
result = Sass::Engine.for_file(filename, options).render
-
if css_filename
-
options[:css_filename] ||= css_filename
-
open(css_filename,"w") {|css_file| css_file.write(result)}
-
nil
-
else
-
result
-
end
-
end
-
end
-
-
2
require 'sass/logger'
-
2
require 'sass/util'
-
-
2
require 'sass/engine'
-
2
require 'sass/plugin' if defined?(Merb::Plugins)
-
2
require 'sass/railtie'
-
2
require 'stringio'
-
-
2
module Sass
-
# Sass cache stores are in charge of storing cached information,
-
# especially parse trees for Sass documents.
-
#
-
# User-created importers must inherit from {CacheStores::Base}.
-
2
module CacheStores
-
end
-
end
-
-
2
require 'sass/cache_stores/base'
-
2
require 'sass/cache_stores/filesystem'
-
2
require 'sass/cache_stores/memory'
-
2
require 'sass/cache_stores/chain'
-
2
module Sass
-
2
module CacheStores
-
# An abstract base class for backends for the Sass cache.
-
# Any key-value store can act as such a backend;
-
# it just needs to implement the
-
# \{#_store} and \{#_retrieve} methods.
-
#
-
# To use a cache store with Sass,
-
# use the {file:SASS_REFERENCE.md#cache_store-option `:cache_store` option}.
-
#
-
# @abstract
-
2
class Base
-
# Store cached contents for later retrieval
-
# Must be implemented by all CacheStore subclasses
-
#
-
# Note: cache contents contain binary data.
-
#
-
# @param key [String] The key to store the contents under
-
# @param version [String] The current sass version.
-
# Cached contents must not be retrieved across different versions of sass.
-
# @param sha [String] The sha of the sass source.
-
# Cached contents must not be retrieved if the sha has changed.
-
# @param contents [String] The contents to store.
-
2
def _store(key, version, sha, contents)
-
raise "#{self.class} must implement #_store."
-
end
-
-
# Retrieved cached contents.
-
# Must be implemented by all subclasses.
-
#
-
# Note: if the key exists but the sha or version have changed,
-
# then the key may be deleted by the cache store, if it wants to do so.
-
#
-
# @param key [String] The key to retrieve
-
# @param version [String] The current sass version.
-
# Cached contents must not be retrieved across different versions of sass.
-
# @param sha [String] The sha of the sass source.
-
# Cached contents must not be retrieved if the sha has changed.
-
# @return [String] The contents that were previously stored.
-
# @return [NilClass] when the cache key is not found or the version or sha have changed.
-
2
def _retrieve(key, version, sha)
-
raise "#{self.class} must implement #_retrieve."
-
end
-
-
# Store a {Sass::Tree::RootNode}.
-
#
-
# @param key [String] The key to store it under.
-
# @param sha [String] The checksum for the contents that are being stored.
-
# @param obj [Object] The object to cache.
-
2
def store(key, sha, root)
-
_store(key, Sass::VERSION, sha, Marshal.dump(root))
-
rescue TypeError, LoadError => e
-
Sass::Util.sass_warn "Warning. Error encountered while saving cache #{path_to(key)}: #{e}"
-
nil
-
end
-
-
# Retrieve a {Sass::Tree::RootNode}.
-
#
-
# @param key [String] The key the root element was stored under.
-
# @param sha [String] The checksum of the root element's content.
-
# @return [Object] The cached object.
-
2
def retrieve(key, sha)
-
contents = _retrieve(key, Sass::VERSION, sha)
-
Marshal.load(contents) if contents
-
rescue EOFError, TypeError, ArgumentError, LoadError => e
-
Sass::Util.sass_warn "Warning. Error encountered while reading cache #{path_to(key)}: #{e}"
-
nil
-
end
-
-
# Return the key for the sass file.
-
#
-
# The `(sass_dirname, sass_basename)` pair
-
# should uniquely identify the Sass document,
-
# but otherwise there are no restrictions on their content.
-
#
-
# @param sass_dirname [String]
-
# The fully-expanded location of the Sass file.
-
# This corresponds to the directory name on a filesystem.
-
# @param sass_basename [String] The name of the Sass file that is being referenced.
-
# This corresponds to the basename on a filesystem.
-
2
def key(sass_dirname, sass_basename)
-
dir = Digest::SHA1.hexdigest(sass_dirname)
-
filename = "#{sass_basename}c"
-
"#{dir}/#{filename}"
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module CacheStores
-
# A meta-cache that chains multiple caches together.
-
# Specifically:
-
#
-
# * All `#store`s are passed to all caches.
-
# * `#retrieve`s are passed to each cache until one has a hit.
-
# * When one cache has a hit, the value is `#store`d in all earlier caches.
-
2
class Chain < Base
-
# Create a new cache chaining the given caches.
-
#
-
# @param caches [Array<Sass::CacheStores::Base>] The caches to chain.
-
2
def initialize(*caches)
-
@caches = caches
-
end
-
-
# @see Base#store
-
2
def store(key, sha, obj)
-
@caches.each {|c| c.store(key, sha, obj)}
-
end
-
-
# @see Base#retrieve
-
2
def retrieve(key, sha)
-
@caches.each_with_index do |c, i|
-
next unless obj = c.retrieve(key, sha)
-
@caches[0...i].each {|prev| prev.store(key, sha, obj)}
-
return obj
-
end
-
nil
-
end
-
end
-
end
-
end
-
2
require 'fileutils'
-
-
2
module Sass
-
2
module CacheStores
-
# A backend for the Sass cache using the filesystem.
-
2
class Filesystem < Base
-
# The directory where the cached files will be stored.
-
#
-
# @return [String]
-
2
attr_accessor :cache_location
-
-
# @param cache_location [String] see \{#cache\_location}
-
2
def initialize(cache_location)
-
@cache_location = cache_location
-
end
-
-
# @see Base#\_retrieve
-
2
def _retrieve(key, version, sha)
-
return unless File.readable?(path_to(key))
-
File.open(path_to(key), "rb") do |f|
-
if f.readline("\n").strip == version && f.readline("\n").strip == sha
-
return f.read
-
end
-
end
-
File.unlink path_to(key)
-
nil
-
rescue EOFError, TypeError, ArgumentError => e
-
Sass::Util.sass_warn "Warning. Error encountered while reading cache #{path_to(key)}: #{e}"
-
end
-
-
# @see Base#\_store
-
2
def _store(key, version, sha, contents)
-
# return unless File.writable?(File.dirname(@cache_location))
-
# return if File.exists?(@cache_location) && !File.writable?(@cache_location)
-
compiled_filename = path_to(key)
-
# return if File.exists?(File.dirname(compiled_filename)) && !File.writable?(File.dirname(compiled_filename))
-
# return if File.exists?(compiled_filename) && !File.writable?(compiled_filename)
-
FileUtils.mkdir_p(File.dirname(compiled_filename))
-
Sass::Util.atomic_create_and_write_file(compiled_filename) do |f|
-
f.puts(version)
-
f.puts(sha)
-
f.write(contents)
-
end
-
rescue Errno::EACCES
-
#pass
-
end
-
-
2
private
-
-
# Returns the path to a file for the given key.
-
#
-
# @param key [String]
-
# @return [String] The path to the cache file.
-
2
def path_to(key)
-
key = key.gsub(/[<>:\\|?*%]/) {|c| "%%%03d" % Sass::Util.ord(c)}
-
File.join(cache_location, key)
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module CacheStores
-
# A backend for the Sass cache using in-process memory.
-
2
class Memory < Base
-
# Since the {Memory} store is stored in the Sass tree's options hash,
-
# when the options get serialized as part of serializing the tree,
-
# you get crazy exponential growth in the size of the cached objects
-
# unless you don't dump the cache.
-
#
-
# @private
-
2
def _dump(depth)
-
""
-
end
-
-
# If we deserialize this class, just make a new empty one.
-
#
-
# @private
-
2
def self._load(repr)
-
Memory.new
-
end
-
-
# Create a new, empty cache store.
-
2
def initialize
-
@contents = {}
-
end
-
-
# @see Base#retrieve
-
2
def retrieve(key, sha)
-
if @contents.has_key?(key)
-
return unless @contents[key][:sha] == sha
-
obj = @contents[key][:obj]
-
obj.respond_to?(:deep_copy) ? obj.deep_copy : obj.dup
-
end
-
end
-
-
# @see Base#store
-
2
def store(key, sha, obj)
-
@contents[key] = {:sha => sha, :obj => obj}
-
end
-
-
# Destructively clear the cache.
-
2
def reset!
-
@contents = {}
-
end
-
end
-
end
-
end
-
2
require 'set'
-
2
require 'digest/sha1'
-
2
require 'sass/cache_stores'
-
2
require 'sass/tree/node'
-
2
require 'sass/tree/root_node'
-
2
require 'sass/tree/rule_node'
-
2
require 'sass/tree/comment_node'
-
2
require 'sass/tree/prop_node'
-
2
require 'sass/tree/directive_node'
-
2
require 'sass/tree/media_node'
-
2
require 'sass/tree/supports_node'
-
2
require 'sass/tree/css_import_node'
-
2
require 'sass/tree/variable_node'
-
2
require 'sass/tree/mixin_def_node'
-
2
require 'sass/tree/mixin_node'
-
2
require 'sass/tree/trace_node'
-
2
require 'sass/tree/content_node'
-
2
require 'sass/tree/function_node'
-
2
require 'sass/tree/return_node'
-
2
require 'sass/tree/extend_node'
-
2
require 'sass/tree/if_node'
-
2
require 'sass/tree/while_node'
-
2
require 'sass/tree/for_node'
-
2
require 'sass/tree/each_node'
-
2
require 'sass/tree/debug_node'
-
2
require 'sass/tree/warn_node'
-
2
require 'sass/tree/import_node'
-
2
require 'sass/tree/charset_node'
-
2
require 'sass/tree/visitors/base'
-
2
require 'sass/tree/visitors/perform'
-
2
require 'sass/tree/visitors/cssize'
-
2
require 'sass/tree/visitors/extend'
-
2
require 'sass/tree/visitors/convert'
-
2
require 'sass/tree/visitors/to_css'
-
2
require 'sass/tree/visitors/deep_copy'
-
2
require 'sass/tree/visitors/set_options'
-
2
require 'sass/tree/visitors/check_nesting'
-
2
require 'sass/selector'
-
2
require 'sass/environment'
-
2
require 'sass/script'
-
2
require 'sass/scss'
-
2
require 'sass/error'
-
2
require 'sass/importers'
-
2
require 'sass/shared'
-
2
require 'sass/media'
-
2
require 'sass/supports'
-
-
2
module Sass
-
-
# A Sass mixin or function.
-
#
-
# `name`: `String`
-
# : The name of the mixin/function.
-
#
-
# `args`: `Array<(Script::Node, Script::Node)>`
-
# : The arguments for the mixin/function.
-
# Each element is a tuple containing the variable node of the argument
-
# and the parse tree for the default value of the argument.
-
#
-
# `splat`: `Script::Node?`
-
# : The variable node of the splat argument for this callable, or null.
-
#
-
# `environment`: {Sass::Environment}
-
# : The environment in which the mixin/function was defined.
-
# This is captured so that the mixin/function can have access
-
# to local variables defined in its scope.
-
#
-
# `tree`: `Array<Tree::Node>`
-
# : The parse tree for the mixin/function.
-
#
-
# `has_content`: `Boolean`
-
# : Whether the callable accepts a content block.
-
#
-
# `type`: `String`
-
# : The user-friendly name of the type of the callable.
-
2
Callable = Struct.new(:name, :args, :splat, :environment, :tree, :has_content, :type)
-
-
# This class handles the parsing and compilation of the Sass template.
-
# Example usage:
-
#
-
# template = File.load('stylesheets/sassy.sass')
-
# sass_engine = Sass::Engine.new(template)
-
# output = sass_engine.render
-
# puts output
-
2
class Engine
-
2
include Sass::Util
-
-
# A line of Sass code.
-
#
-
# `text`: `String`
-
# : The text in the line, without any whitespace at the beginning or end.
-
#
-
# `tabs`: `Fixnum`
-
# : The level of indentation of the line.
-
#
-
# `index`: `Fixnum`
-
# : The line number in the original document.
-
#
-
# `offset`: `Fixnum`
-
# : The number of bytes in on the line that the text begins.
-
# This ends up being the number of bytes of leading whitespace.
-
#
-
# `filename`: `String`
-
# : The name of the file in which this line appeared.
-
#
-
# `children`: `Array<Line>`
-
# : The lines nested below this one.
-
#
-
# `comment_tab_str`: `String?`
-
# : The prefix indentation for this comment, if it is a comment.
-
2
class Line < Struct.new(:text, :tabs, :index, :offset, :filename, :children, :comment_tab_str)
-
2
def comment?
-
text[0] == COMMENT_CHAR && (text[1] == SASS_COMMENT_CHAR || text[1] == CSS_COMMENT_CHAR)
-
end
-
end
-
-
# The character that begins a CSS property.
-
2
PROPERTY_CHAR = ?:
-
-
# The character that designates the beginning of a comment,
-
# either Sass or CSS.
-
2
COMMENT_CHAR = ?/
-
-
# The character that follows the general COMMENT_CHAR and designates a Sass comment,
-
# which is not output as a CSS comment.
-
2
SASS_COMMENT_CHAR = ?/
-
-
# The character that indicates that a comment allows interpolation
-
# and should be preserved even in `:compressed` mode.
-
2
SASS_LOUD_COMMENT_CHAR = ?!
-
-
# The character that follows the general COMMENT_CHAR and designates a CSS comment,
-
# which is embedded in the CSS document.
-
2
CSS_COMMENT_CHAR = ?*
-
-
# The character used to denote a compiler directive.
-
2
DIRECTIVE_CHAR = ?@
-
-
# Designates a non-parsed rule.
-
2
ESCAPE_CHAR = ?\\
-
-
# Designates block as mixin definition rather than CSS rules to output
-
2
MIXIN_DEFINITION_CHAR = ?=
-
-
# Includes named mixin declared using MIXIN_DEFINITION_CHAR
-
2
MIXIN_INCLUDE_CHAR = ?+
-
-
# The regex that matches and extracts data from
-
# properties of the form `:name prop`.
-
2
PROPERTY_OLD = /^:([^\s=:"]+)\s*(?:\s+|$)(.*)/
-
-
# The default options for Sass::Engine.
-
# @api public
-
2
DEFAULT_OPTIONS = {
-
:style => :nested,
-
:load_paths => ['.'],
-
:cache => true,
-
:cache_location => './.sass-cache',
-
:syntax => :sass,
-
:filesystem_importer => Sass::Importers::Filesystem
-
}.freeze
-
-
# Converts a Sass options hash into a standard form, filling in
-
# default values and resolving aliases.
-
#
-
# @param options [{Symbol => Object}] The options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
# @return [{Symbol => Object}] The normalized options hash.
-
# @private
-
2
def self.normalize_options(options)
-
options = DEFAULT_OPTIONS.merge(options.reject {|k, v| v.nil?})
-
-
# If the `:filename` option is passed in without an importer,
-
# assume it's using the default filesystem importer.
-
options[:importer] ||= options[:filesystem_importer].new(".") if options[:filename]
-
-
# Tracks the original filename of the top-level Sass file
-
options[:original_filename] ||= options[:filename]
-
-
options[:cache_store] ||= Sass::CacheStores::Chain.new(
-
Sass::CacheStores::Memory.new, Sass::CacheStores::Filesystem.new(options[:cache_location]))
-
# Support both, because the docs said one and the other actually worked
-
# for quite a long time.
-
options[:line_comments] ||= options[:line_numbers]
-
-
options[:load_paths] = (options[:load_paths] + Sass.load_paths).map do |p|
-
next p unless p.is_a?(String) || (defined?(Pathname) && p.is_a?(Pathname))
-
options[:filesystem_importer].new(p.to_s)
-
end
-
-
# Backwards compatibility
-
options[:property_syntax] ||= options[:attribute_syntax]
-
case options[:property_syntax]
-
when :alternate; options[:property_syntax] = :new
-
when :normal; options[:property_syntax] = :old
-
end
-
-
options
-
end
-
-
# Returns the {Sass::Engine} for the given file.
-
# This is preferable to Sass::Engine.new when reading from a file
-
# because it properly sets up the Engine's metadata,
-
# enables parse-tree caching,
-
# and infers the syntax from the filename.
-
#
-
# @param filename [String] The path to the Sass or SCSS file
-
# @param options [{Symbol => Object}] The options hash;
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
# @return [Sass::Engine] The Engine for the given Sass or SCSS file.
-
# @raise [Sass::SyntaxError] if there's an error in the document.
-
2
def self.for_file(filename, options)
-
had_syntax = options[:syntax]
-
-
if had_syntax
-
# Use what was explicitly specificed
-
elsif filename =~ /\.scss$/
-
options.merge!(:syntax => :scss)
-
elsif filename =~ /\.sass$/
-
options.merge!(:syntax => :sass)
-
end
-
-
Sass::Engine.new(File.read(filename), options.merge(:filename => filename))
-
end
-
-
# The options for the Sass engine.
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
#
-
# @return [{Symbol => Object}]
-
2
attr_reader :options
-
-
# Creates a new Engine. Note that Engine should only be used directly
-
# when compiling in-memory Sass code.
-
# If you're compiling a single Sass file from the filesystem,
-
# use \{Sass::Engine.for\_file}.
-
# If you're compiling multiple files from the filesystem,
-
# use {Sass::Plugin}.
-
#
-
# @param template [String] The Sass template.
-
# This template can be encoded using any encoding
-
# that can be converted to Unicode.
-
# If the template contains an `@charset` declaration,
-
# that overrides the Ruby encoding
-
# (see {file:SASS_REFERENCE.md#encodings the encoding documentation})
-
# @param options [{Symbol => Object}] An options hash.
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
# @see {Sass::Engine.for_file}
-
# @see {Sass::Plugin}
-
2
def initialize(template, options={})
-
@options = self.class.normalize_options(options)
-
@template = template
-
end
-
-
# Render the template to CSS.
-
#
-
# @return [String] The CSS
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
2
def render
-
return _render unless @options[:quiet]
-
Sass::Util.silence_sass_warnings {_render}
-
end
-
2
alias_method :to_css, :render
-
-
# Parses the document into its parse tree. Memoized.
-
#
-
# @return [Sass::Tree::Node] The root of the parse tree.
-
# @raise [Sass::SyntaxError] if there's an error in the document
-
2
def to_tree
-
@tree ||= @options[:quiet] ?
-
Sass::Util.silence_sass_warnings {_to_tree} :
-
_to_tree
-
end
-
-
# Returns the original encoding of the document,
-
# or `nil` under Ruby 1.8.
-
#
-
# @return [Encoding, nil]
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
2
def source_encoding
-
check_encoding!
-
@original_encoding
-
end
-
-
# Gets a set of all the documents
-
# that are (transitive) dependencies of this document,
-
# not including the document itself.
-
#
-
# @return [[Sass::Engine]] The dependency documents.
-
2
def dependencies
-
_dependencies(Set.new, engines = Set.new)
-
Sass::Util.array_minus(engines, [self])
-
end
-
-
# Helper for \{#dependencies}.
-
#
-
# @private
-
2
def _dependencies(seen, engines)
-
return if seen.include?(key = [@options[:filename], @options[:importer]])
-
seen << key
-
engines << self
-
to_tree.grep(Tree::ImportNode) do |n|
-
next if n.css_import?
-
n.imported_file._dependencies(seen, engines)
-
end
-
end
-
-
2
private
-
-
2
def _render
-
rendered = _to_tree.render
-
return rendered if ruby1_8?
-
begin
-
# Try to convert the result to the original encoding,
-
# but if that doesn't work fall back on UTF-8
-
rendered = rendered.encode(source_encoding)
-
rescue EncodingError
-
end
-
rendered.gsub(Regexp.new('\A@charset "(.*?)"'.encode(source_encoding)),
-
"@charset \"#{source_encoding.name}\"".encode(source_encoding))
-
end
-
-
2
def _to_tree
-
if (@options[:cache] || @options[:read_cache]) &&
-
@options[:filename] && @options[:importer]
-
key = sassc_key
-
sha = Digest::SHA1.hexdigest(@template)
-
-
if root = @options[:cache_store].retrieve(key, sha)
-
root.options = @options
-
return root
-
end
-
end
-
-
check_encoding!
-
-
if @options[:syntax] == :scss
-
root = Sass::SCSS::Parser.new(@template, @options[:filename]).parse
-
else
-
root = Tree::RootNode.new(@template)
-
append_children(root, tree(tabulate(@template)).first, true)
-
end
-
-
root.options = @options
-
if @options[:cache] && key && sha
-
begin
-
old_options = root.options
-
root.options = {}
-
@options[:cache_store].store(key, sha, root)
-
ensure
-
root.options = old_options
-
end
-
end
-
root
-
rescue SyntaxError => e
-
e.modify_backtrace(:filename => @options[:filename], :line => @line)
-
e.sass_template = @template
-
raise e
-
end
-
-
2
def sassc_key
-
@options[:cache_store].key(*@options[:importer].key(@options[:filename], @options))
-
end
-
-
2
def check_encoding!
-
return if @checked_encoding
-
@checked_encoding = true
-
@template, @original_encoding = check_sass_encoding(@template) do |msg, line|
-
raise Sass::SyntaxError.new(msg, :line => line)
-
end
-
end
-
-
2
def tabulate(string)
-
tab_str = nil
-
comment_tab_str = nil
-
first = true
-
lines = []
-
string.gsub(/\r\n|\r|\n/, "\n").scan(/^[^\n]*?$/).each_with_index do |line, index|
-
index += (@options[:line] || 1)
-
if line.strip.empty?
-
lines.last.text << "\n" if lines.last && lines.last.comment?
-
next
-
end
-
-
line_tab_str = line[/^\s*/]
-
unless line_tab_str.empty?
-
if tab_str.nil?
-
comment_tab_str ||= line_tab_str
-
next if try_comment(line, lines.last, "", comment_tab_str, index)
-
comment_tab_str = nil
-
end
-
-
tab_str ||= line_tab_str
-
-
raise SyntaxError.new("Indenting at the beginning of the document is illegal.",
-
:line => index) if first
-
-
raise SyntaxError.new("Indentation can't use both tabs and spaces.",
-
:line => index) if tab_str.include?(?\s) && tab_str.include?(?\t)
-
end
-
first &&= !tab_str.nil?
-
if tab_str.nil?
-
lines << Line.new(line.strip, 0, index, 0, @options[:filename], [])
-
next
-
end
-
-
comment_tab_str ||= line_tab_str
-
if try_comment(line, lines.last, tab_str * lines.last.tabs, comment_tab_str, index)
-
next
-
else
-
comment_tab_str = nil
-
end
-
-
line_tabs = line_tab_str.scan(tab_str).size
-
if tab_str * line_tabs != line_tab_str
-
message = <<END.strip.gsub("\n", ' ')
-
Inconsistent indentation: #{Sass::Shared.human_indentation line_tab_str, true} used for indentation,
-
but the rest of the document was indented using #{Sass::Shared.human_indentation tab_str}.
-
END
-
raise SyntaxError.new(message, :line => index)
-
end
-
-
lines << Line.new(line.strip, line_tabs, index, tab_str.size, @options[:filename], [])
-
end
-
lines
-
end
-
-
2
def try_comment(line, last, tab_str, comment_tab_str, index)
-
return unless last && last.comment?
-
# Nested comment stuff must be at least one whitespace char deeper
-
# than the normal indentation
-
return unless line =~ /^#{tab_str}\s/
-
unless line =~ /^(?:#{comment_tab_str})(.*)$/
-
raise SyntaxError.new(<<MSG.strip.gsub("\n", " "), :line => index)
-
Inconsistent indentation:
-
previous line was indented by #{Sass::Shared.human_indentation comment_tab_str},
-
but this line was indented by #{Sass::Shared.human_indentation line[/^\s*/]}.
-
MSG
-
end
-
-
last.comment_tab_str ||= comment_tab_str
-
last.text << "\n" << line
-
true
-
end
-
-
2
def tree(arr, i = 0)
-
return [], i if arr[i].nil?
-
-
base = arr[i].tabs
-
nodes = []
-
while (line = arr[i]) && line.tabs >= base
-
if line.tabs > base
-
raise SyntaxError.new("The line was indented #{line.tabs - base} levels deeper than the previous line.",
-
:line => line.index) if line.tabs > base + 1
-
-
nodes.last.children, i = tree(arr, i)
-
else
-
nodes << line
-
i += 1
-
end
-
end
-
return nodes, i
-
end
-
-
2
def build_tree(parent, line, root = false)
-
@line = line.index
-
node_or_nodes = parse_line(parent, line, root)
-
-
Array(node_or_nodes).each do |node|
-
# Node is a symbol if it's non-outputting, like a variable assignment
-
next unless node.is_a? Tree::Node
-
-
node.line = line.index
-
node.filename = line.filename
-
-
append_children(node, line.children, false)
-
end
-
-
node_or_nodes
-
end
-
-
2
def append_children(parent, children, root)
-
continued_rule = nil
-
continued_comment = nil
-
children.each do |line|
-
child = build_tree(parent, line, root)
-
-
if child.is_a?(Tree::RuleNode)
-
if child.continued? && child.children.empty?
-
if continued_rule
-
continued_rule.add_rules child
-
else
-
continued_rule = child
-
end
-
next
-
elsif continued_rule
-
continued_rule.add_rules child
-
continued_rule.children = child.children
-
continued_rule, child = nil, continued_rule
-
end
-
elsif continued_rule
-
continued_rule = nil
-
end
-
-
if child.is_a?(Tree::CommentNode) && child.type == :silent
-
if continued_comment &&
-
child.line == continued_comment.line +
-
continued_comment.lines + 1
-
continued_comment.value += ["\n"] + child.value
-
next
-
end
-
-
continued_comment = child
-
end
-
-
check_for_no_children(child)
-
validate_and_append_child(parent, child, line, root)
-
end
-
-
parent
-
end
-
-
2
def validate_and_append_child(parent, child, line, root)
-
case child
-
when Array
-
child.each {|c| validate_and_append_child(parent, c, line, root)}
-
when Tree::Node
-
parent << child
-
end
-
end
-
-
2
def check_for_no_children(node)
-
return unless node.is_a?(Tree::RuleNode) && node.children.empty?
-
Sass::Util.sass_warn(<<WARNING.strip)
-
WARNING on line #{node.line}#{" of #{node.filename}" if node.filename}:
-
This selector doesn't have any properties and will not be rendered.
-
WARNING
-
end
-
-
2
def parse_line(parent, line, root)
-
case line.text[0]
-
when PROPERTY_CHAR
-
if line.text[1] == PROPERTY_CHAR ||
-
(@options[:property_syntax] == :new &&
-
line.text =~ PROPERTY_OLD && $2.empty?)
-
# Support CSS3-style pseudo-elements,
-
# which begin with ::,
-
# as well as pseudo-classes
-
# if we're using the new property syntax
-
Tree::RuleNode.new(parse_interp(line.text))
-
else
-
name, value = line.text.scan(PROPERTY_OLD)[0]
-
raise SyntaxError.new("Invalid property: \"#{line.text}\".",
-
:line => @line) if name.nil? || value.nil?
-
parse_property(name, parse_interp(name), value, :old, line)
-
end
-
when ?$
-
parse_variable(line)
-
when COMMENT_CHAR
-
parse_comment(line)
-
when DIRECTIVE_CHAR
-
parse_directive(parent, line, root)
-
when ESCAPE_CHAR
-
Tree::RuleNode.new(parse_interp(line.text[1..-1]))
-
when MIXIN_DEFINITION_CHAR
-
parse_mixin_definition(line)
-
when MIXIN_INCLUDE_CHAR
-
if line.text[1].nil? || line.text[1] == ?\s
-
Tree::RuleNode.new(parse_interp(line.text))
-
else
-
parse_mixin_include(line, root)
-
end
-
else
-
parse_property_or_rule(line)
-
end
-
end
-
-
2
def parse_property_or_rule(line)
-
scanner = Sass::Util::MultibyteStringScanner.new(line.text)
-
hack_char = scanner.scan(/[:\*\.]|\#(?!\{)/)
-
parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @line)
-
-
unless res = parser.parse_interp_ident
-
return Tree::RuleNode.new(parse_interp(line.text))
-
end
-
res.unshift(hack_char) if hack_char
-
if comment = scanner.scan(Sass::SCSS::RX::COMMENT)
-
res << comment
-
end
-
-
name = line.text[0...scanner.pos]
-
if scanner.scan(/\s*:(?:\s|$)/)
-
parse_property(name, res, scanner.rest, :new, line)
-
else
-
res.pop if comment
-
Tree::RuleNode.new(res + parse_interp(scanner.rest))
-
end
-
end
-
-
2
def parse_property(name, parsed_name, value, prop, line)
-
if value.strip.empty?
-
expr = Sass::Script::String.new("")
-
else
-
expr = parse_script(value, :offset => line.offset + line.text.index(value))
-
end
-
node = Tree::PropNode.new(parse_interp(name), expr, prop)
-
if value.strip.empty? && line.children.empty?
-
raise SyntaxError.new(
-
"Invalid property: \"#{node.declaration}\" (no value)." +
-
node.pseudo_class_selector_message)
-
end
-
-
node
-
end
-
-
2
def parse_variable(line)
-
name, value, default = line.text.scan(Script::MATCH)[0]
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath variable declarations.",
-
:line => @line + 1) unless line.children.empty?
-
raise SyntaxError.new("Invalid variable: \"#{line.text}\".",
-
:line => @line) unless name && value
-
-
expr = parse_script(value, :offset => line.offset + line.text.index(value))
-
-
Tree::VariableNode.new(name, expr, default)
-
end
-
-
2
def parse_comment(line)
-
if line.text[1] == CSS_COMMENT_CHAR || line.text[1] == SASS_COMMENT_CHAR
-
silent = line.text[1] == SASS_COMMENT_CHAR
-
loud = !silent && line.text[2] == SASS_LOUD_COMMENT_CHAR
-
if silent
-
value = [line.text]
-
else
-
value = self.class.parse_interp(line.text, line.index, line.offset, :filename => @filename)
-
end
-
value = with_extracted_values(value) do |str|
-
str = str.gsub(/^#{line.comment_tab_str}/m, '')[2..-1] # get rid of // or /*
-
format_comment_text(str, silent)
-
end
-
type = if silent then :silent elsif loud then :loud else :normal end
-
Tree::CommentNode.new(value, type)
-
else
-
Tree::RuleNode.new(parse_interp(line.text))
-
end
-
end
-
-
2
def parse_directive(parent, line, root)
-
directive, whitespace, value = line.text[1..-1].split(/(\s+)/, 2)
-
offset = directive.size + whitespace.size + 1 if whitespace
-
-
# If value begins with url( or ",
-
# it's a CSS @import rule and we don't want to touch it.
-
case directive
-
when 'import'
-
parse_import(line, value, offset)
-
when 'mixin'
-
parse_mixin_definition(line)
-
when 'content'
-
parse_content_directive(line)
-
when 'include'
-
parse_mixin_include(line, root)
-
when 'function'
-
parse_function(line, root)
-
when 'for'
-
parse_for(line, root, value)
-
when 'each'
-
parse_each(line, root, value)
-
when 'else'
-
parse_else(parent, line, value)
-
when 'while'
-
raise SyntaxError.new("Invalid while directive '@while': expected expression.") unless value
-
Tree::WhileNode.new(parse_script(value, :offset => offset))
-
when 'if'
-
raise SyntaxError.new("Invalid if directive '@if': expected expression.") unless value
-
Tree::IfNode.new(parse_script(value, :offset => offset))
-
when 'debug'
-
raise SyntaxError.new("Invalid debug directive '@debug': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath debug directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::DebugNode.new(parse_script(value, :offset => offset))
-
when 'extend'
-
raise SyntaxError.new("Invalid extend directive '@extend': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath extend directives.",
-
:line => @line + 1) unless line.children.empty?
-
optional = !!value.gsub!(/\s+#{Sass::SCSS::RX::OPTIONAL}$/, '')
-
offset = line.offset + line.text.index(value).to_i
-
Tree::ExtendNode.new(parse_interp(value, offset), optional)
-
when 'warn'
-
raise SyntaxError.new("Invalid warn directive '@warn': expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath warn directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::WarnNode.new(parse_script(value, :offset => offset))
-
when 'return'
-
raise SyntaxError.new("Invalid @return: expected expression.") unless value
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath return directives.",
-
:line => @line + 1) unless line.children.empty?
-
offset = line.offset + line.text.index(value).to_i
-
Tree::ReturnNode.new(parse_script(value, :offset => offset))
-
when 'charset'
-
name = value && value[/\A(["'])(.*)\1\Z/, 2] #"
-
raise SyntaxError.new("Invalid charset directive '@charset': expected string.") unless name
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath charset directives.",
-
:line => @line + 1) unless line.children.empty?
-
Tree::CharsetNode.new(name)
-
when 'media'
-
parser = Sass::SCSS::Parser.new(value, @options[:filename], @line)
-
Tree::MediaNode.new(parser.parse_media_query_list.to_a)
-
else
-
unprefixed_directive = directive.gsub(/^-[a-z0-9]+-/i, '')
-
if unprefixed_directive == 'supports'
-
parser = Sass::SCSS::Parser.new(value, @options[:filename], @line)
-
return Tree::SupportsNode.new(directive, parser.parse_supports_condition)
-
end
-
-
Tree::DirectiveNode.new(
-
value.nil? ? ["@#{directive}"] : ["@#{directive} "] + parse_interp(value, offset))
-
end
-
end
-
-
2
def parse_for(line, root, text)
-
var, from_expr, to_name, to_expr = text.scan(/^([^\s]+)\s+from\s+(.+)\s+(to|through)\s+(.+)$/).first
-
-
if var.nil? # scan failed, try to figure out why for error message
-
if text !~ /^[^\s]+/
-
expected = "variable name"
-
elsif text !~ /^[^\s]+\s+from\s+.+/
-
expected = "'from <expr>'"
-
else
-
expected = "'to <expr>' or 'through <expr>'"
-
end
-
raise SyntaxError.new("Invalid for directive '@for #{text}': expected #{expected}.")
-
end
-
raise SyntaxError.new("Invalid variable \"#{var}\".") unless var =~ Script::VALIDATE
-
-
var = var[1..-1]
-
parsed_from = parse_script(from_expr, :offset => line.offset + line.text.index(from_expr))
-
parsed_to = parse_script(to_expr, :offset => line.offset + line.text.index(to_expr))
-
Tree::ForNode.new(var, parsed_from, parsed_to, to_name == 'to')
-
end
-
-
2
def parse_each(line, root, text)
-
var, list_expr = text.scan(/^([^\s]+)\s+in\s+(.+)$/).first
-
-
if var.nil? # scan failed, try to figure out why for error message
-
if text !~ /^[^\s]+/
-
expected = "variable name"
-
elsif text !~ /^[^\s]+\s+from\s+.+/
-
expected = "'in <expr>'"
-
end
-
raise SyntaxError.new("Invalid for directive '@each #{text}': expected #{expected}.")
-
end
-
raise SyntaxError.new("Invalid variable \"#{var}\".") unless var =~ Script::VALIDATE
-
-
var = var[1..-1]
-
parsed_list = parse_script(list_expr, :offset => line.offset + line.text.index(list_expr))
-
Tree::EachNode.new(var, parsed_list)
-
end
-
-
2
def parse_else(parent, line, text)
-
previous = parent.children.last
-
raise SyntaxError.new("@else must come after @if.") unless previous.is_a?(Tree::IfNode)
-
-
if text
-
if text !~ /^if\s+(.+)/
-
raise SyntaxError.new("Invalid else directive '@else #{text}': expected 'if <expr>'.")
-
end
-
expr = parse_script($1, :offset => line.offset + line.text.index($1))
-
end
-
-
node = Tree::IfNode.new(expr)
-
append_children(node, line.children, false)
-
previous.add_else node
-
nil
-
end
-
-
2
def parse_import(line, value, offset)
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath import directives.",
-
:line => @line + 1) unless line.children.empty?
-
-
scanner = Sass::Util::MultibyteStringScanner.new(value)
-
values = []
-
-
loop do
-
unless node = parse_import_arg(scanner, offset + scanner.pos)
-
raise SyntaxError.new("Invalid @import: expected file to import, was #{scanner.rest.inspect}",
-
:line => @line)
-
end
-
values << node
-
break unless scanner.scan(/,\s*/)
-
end
-
-
if scanner.scan(/;/)
-
raise SyntaxError.new("Invalid @import: expected end of line, was \";\".",
-
:line => @line)
-
end
-
-
return values
-
end
-
-
2
def parse_import_arg(scanner, offset)
-
return if scanner.eos?
-
-
if scanner.match?(/url\(/i)
-
script_parser = Sass::Script::Parser.new(scanner, @line, offset, @options)
-
str = script_parser.parse_string
-
media_parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @line)
-
media = media_parser.parse_media_query_list
-
return Tree::CssImportNode.new(str, media.to_a)
-
end
-
-
unless str = scanner.scan(Sass::SCSS::RX::STRING)
-
return Tree::ImportNode.new(scanner.scan(/[^,;]+/))
-
end
-
-
val = scanner[1] || scanner[2]
-
scanner.scan(/\s*/)
-
if !scanner.match?(/[,;]|$/)
-
media_parser = Sass::SCSS::Parser.new(scanner, @options[:filename], @line)
-
media = media_parser.parse_media_query_list
-
Tree::CssImportNode.new(str || uri, media.to_a)
-
elsif val =~ /^(https?:)?\/\//
-
Tree::CssImportNode.new("url(#{val})")
-
else
-
Tree::ImportNode.new(val)
-
end
-
end
-
-
2
MIXIN_DEF_RE = /^(?:=|@mixin)\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
-
2
def parse_mixin_definition(line)
-
name, arg_string = line.text.scan(MIXIN_DEF_RE).first
-
raise SyntaxError.new("Invalid mixin \"#{line.text[1..-1]}\".") if name.nil?
-
-
offset = line.offset + line.text.size - arg_string.size
-
args, splat = Script::Parser.new(arg_string.strip, @line, offset, @options).
-
parse_mixin_definition_arglist
-
Tree::MixinDefNode.new(name, args, splat)
-
end
-
-
2
CONTENT_RE = /^@content\s*(.+)?$/
-
2
def parse_content_directive(line)
-
trailing = line.text.scan(CONTENT_RE).first.first
-
raise SyntaxError.new("Invalid content directive. Trailing characters found: \"#{trailing}\".") unless trailing.nil?
-
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath @content directives.",
-
:line => line.index + 1) unless line.children.empty?
-
Tree::ContentNode.new
-
end
-
-
2
MIXIN_INCLUDE_RE = /^(?:\+|@include)\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
-
2
def parse_mixin_include(line, root)
-
name, arg_string = line.text.scan(MIXIN_INCLUDE_RE).first
-
raise SyntaxError.new("Invalid mixin include \"#{line.text}\".") if name.nil?
-
-
offset = line.offset + line.text.size - arg_string.size
-
args, keywords, splat = Script::Parser.new(arg_string.strip, @line, offset, @options).
-
parse_mixin_include_arglist
-
Tree::MixinNode.new(name, args, keywords, splat)
-
end
-
-
2
FUNCTION_RE = /^@function\s*(#{Sass::SCSS::RX::IDENT})(.*)$/
-
2
def parse_function(line, root)
-
name, arg_string = line.text.scan(FUNCTION_RE).first
-
raise SyntaxError.new("Invalid function definition \"#{line.text}\".") if name.nil?
-
-
offset = line.offset + line.text.size - arg_string.size
-
args, splat = Script::Parser.new(arg_string.strip, @line, offset, @options).
-
parse_function_definition_arglist
-
Tree::FunctionNode.new(name, args, splat)
-
end
-
-
2
def parse_script(script, options = {})
-
line = options[:line] || @line
-
offset = options[:offset] || 0
-
Script.parse(script, line, offset, @options)
-
end
-
-
2
def format_comment_text(text, silent)
-
content = text.split("\n")
-
-
if content.first && content.first.strip.empty?
-
removed_first = true
-
content.shift
-
end
-
-
return silent ? "//" : "/* */" if content.empty?
-
content.last.gsub!(%r{ ?\*/ *$}, '')
-
content.map! {|l| l.gsub!(/^\*( ?)/, '\1') || (l.empty? ? "" : " ") + l}
-
content.first.gsub!(/^ /, '') unless removed_first
-
if silent
-
"//" + content.join("\n//")
-
else
-
# The #gsub fixes the case of a trailing */
-
"/*" + content.join("\n *").gsub(/ \*\Z/, '') + " */"
-
end
-
end
-
-
2
def parse_interp(text, offset = 0)
-
self.class.parse_interp(text, @line, offset, :filename => @filename)
-
end
-
-
# It's important that this have strings (at least)
-
# at the beginning, the end, and between each Script::Node.
-
#
-
# @private
-
2
def self.parse_interp(text, line, offset, options)
-
res = []
-
rest = Sass::Shared.handle_interpolation text do |scan|
-
escapes = scan[2].size
-
res << scan.matched[0...-2 - escapes]
-
if escapes % 2 == 1
-
res << "\\" * (escapes - 1) << '#{'
-
else
-
res << "\\" * [0, escapes - 1].max
-
res << Script::Parser.new(
-
scan, line, offset + scan.pos - scan.matched_size, options).
-
parse_interpolated
-
end
-
end
-
res << rest
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module Sass
-
# The lexical environment for SassScript.
-
# This keeps track of variable, mixin, and function definitions.
-
#
-
# A new environment is created for each level of Sass nesting.
-
# This allows variables to be lexically scoped.
-
# The new environment refers to the environment in the upper scope,
-
# so it has access to variables defined in enclosing scopes,
-
# but new variables are defined locally.
-
#
-
# Environment also keeps track of the {Engine} options
-
# so that they can be made available to {Sass::Script::Functions}.
-
2
class Environment
-
# The enclosing environment,
-
# or nil if this is the global environment.
-
#
-
# @return [Environment]
-
2
attr_reader :parent
-
2
attr_reader :options
-
2
attr_writer :caller
-
2
attr_writer :content
-
-
# @param options [{Symbol => Object}] The options hash. See
-
# {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
# @param parent [Environment] See \{#parent}
-
2
def initialize(parent = nil, options = nil)
-
@parent = parent
-
@options = options || (parent && parent.options) || {}
-
end
-
-
# The environment of the caller of this environment's mixin or function.
-
# @return {Environment?}
-
2
def caller
-
@caller || (@parent && @parent.caller)
-
end
-
-
# The content passed to this environmnet. This is naturally only set
-
# for mixin body environments with content passed in.
-
# @return {Environment?}
-
2
def content
-
@content || (@parent && @parent.content)
-
end
-
-
2
private
-
-
2
class << self
-
2
private
-
2
UNDERSCORE, DASH = '_', '-'
-
-
# Note: when updating this,
-
# update sass/yard/inherited_hash.rb as well.
-
2
def inherited_hash(name)
-
6
class_eval <<RUBY, __FILE__, __LINE__ + 1
-
def #{name}(name)
-
_#{name}(name.tr(UNDERSCORE, DASH))
-
end
-
-
def _#{name}(name)
-
(@#{name}s && @#{name}s[name]) || @parent && @parent._#{name}(name)
-
end
-
protected :_#{name}
-
-
def set_#{name}(name, value)
-
name = name.tr(UNDERSCORE, DASH)
-
@#{name}s[name] = value unless try_set_#{name}(name, value)
-
end
-
-
def try_set_#{name}(name, value)
-
@#{name}s ||= {}
-
if @#{name}s.include?(name)
-
@#{name}s[name] = value
-
true
-
elsif @parent
-
@parent.try_set_#{name}(name, value)
-
else
-
false
-
end
-
end
-
protected :try_set_#{name}
-
-
def set_local_#{name}(name, value)
-
@#{name}s ||= {}
-
@#{name}s[name.tr(UNDERSCORE, DASH)] = value
-
end
-
RUBY
-
end
-
end
-
-
# variable
-
# Script::Literal
-
2
inherited_hash :var
-
# mixin
-
# Sass::Callable
-
2
inherited_hash :mixin
-
# function
-
# Sass::Callable
-
2
inherited_hash :function
-
end
-
end
-
2
module Sass
-
# An exception class that keeps track of
-
# the line of the Sass template it was raised on
-
# and the Sass file that was being parsed (if applicable).
-
#
-
# All Sass errors are raised as {Sass::SyntaxError}s.
-
#
-
# When dealing with SyntaxErrors,
-
# it's important to provide filename and line number information.
-
# This will be used in various error reports to users, including backtraces;
-
# see \{#sass\_backtrace} for details.
-
#
-
# Some of this information is usually provided as part of the constructor.
-
# New backtrace entries can be added with \{#add\_backtrace},
-
# which is called when an exception is raised between files (e.g. with `@import`).
-
#
-
# Often, a chunk of code will all have similar backtrace information -
-
# the same filename or even line.
-
# It may also be useful to have a default line number set.
-
# In those situations, the default values can be used
-
# by omitting the information on the original exception,
-
# and then calling \{#modify\_backtrace} in a wrapper `rescue`.
-
# When doing this, be sure that all exceptions ultimately end up
-
# with the information filled in.
-
2
class SyntaxError < StandardError
-
# The backtrace of the error within Sass files.
-
# This is an array of hashes containing information for a single entry.
-
# The hashes have the following keys:
-
#
-
# `:filename`
-
# : The name of the file in which the exception was raised,
-
# or `nil` if no filename is available.
-
#
-
# `:mixin`
-
# : The name of the mixin in which the exception was raised,
-
# or `nil` if it wasn't raised in a mixin.
-
#
-
# `:line`
-
# : The line of the file on which the error occurred. Never nil.
-
#
-
# This information is also included in standard backtrace format
-
# in the output of \{#backtrace}.
-
#
-
# @return [Aray<{Symbol => Object>}]
-
2
attr_accessor :sass_backtrace
-
-
# The text of the template where this error was raised.
-
#
-
# @return [String]
-
2
attr_accessor :sass_template
-
-
# @param msg [String] The error message
-
# @param attrs [{Symbol => Object}] The information in the backtrace entry.
-
# See \{#sass\_backtrace}
-
2
def initialize(msg, attrs = {})
-
@message = msg
-
@sass_backtrace = []
-
add_backtrace(attrs)
-
end
-
-
# The name of the file in which the exception was raised.
-
# This could be `nil` if no filename is available.
-
#
-
# @return [String, nil]
-
2
def sass_filename
-
sass_backtrace.first[:filename]
-
end
-
-
# The name of the mixin in which the error occurred.
-
# This could be `nil` if the error occurred outside a mixin.
-
#
-
# @return [Fixnum]
-
2
def sass_mixin
-
sass_backtrace.first[:mixin]
-
end
-
-
# The line of the Sass template on which the error occurred.
-
#
-
# @return [Fixnum]
-
2
def sass_line
-
sass_backtrace.first[:line]
-
end
-
-
# Adds an entry to the exception's Sass backtrace.
-
#
-
# @param attrs [{Symbol => Object}] The information in the backtrace entry.
-
# See \{#sass\_backtrace}
-
2
def add_backtrace(attrs)
-
sass_backtrace << attrs.reject {|k, v| v.nil?}
-
end
-
-
# Modify the top Sass backtrace entries
-
# (that is, the most deeply nested ones)
-
# to have the given attributes.
-
#
-
# Specifically, this goes through the backtrace entries
-
# from most deeply nested to least,
-
# setting the given attributes for each entry.
-
# If an entry already has one of the given attributes set,
-
# the pre-existing attribute takes precedence
-
# and is not used for less deeply-nested entries
-
# (even if they don't have that attribute set).
-
#
-
# @param attrs [{Symbol => Object}] The information to add to the backtrace entry.
-
# See \{#sass\_backtrace}
-
2
def modify_backtrace(attrs)
-
attrs = attrs.reject {|k, v| v.nil?}
-
# Move backwards through the backtrace
-
(0...sass_backtrace.size).to_a.reverse.each do |i|
-
entry = sass_backtrace[i]
-
sass_backtrace[i] = attrs.merge(entry)
-
attrs.reject! {|k, v| entry.include?(k)}
-
break if attrs.empty?
-
end
-
end
-
-
# @return [String] The error message
-
2
def to_s
-
@message
-
end
-
-
# Returns the standard exception backtrace,
-
# including the Sass backtrace.
-
#
-
# @return [Array<String>]
-
2
def backtrace
-
return nil if super.nil?
-
return super if sass_backtrace.all? {|h| h.empty?}
-
sass_backtrace.map do |h|
-
"#{h[:filename] || "(sass)"}:#{h[:line]}" +
-
(h[:mixin] ? ":in `#{h[:mixin]}'" : "")
-
end + super
-
end
-
-
# Returns a string representation of the Sass backtrace.
-
#
-
# @param default_filename [String] The filename to use for unknown files
-
# @see #sass_backtrace
-
# @return [String]
-
2
def sass_backtrace_str(default_filename = "an unknown file")
-
lines = self.message.split("\n")
-
msg = lines[0] + lines[1..-1].
-
map {|l| "\n" + (" " * "Syntax error: ".size) + l}.join
-
"Syntax error: #{msg}" +
-
Sass::Util.enum_with_index(sass_backtrace).map do |entry, i|
-
"\n #{i == 0 ? "on" : "from"} line #{entry[:line]}" +
-
" of #{entry[:filename] || default_filename}" +
-
(entry[:mixin] ? ", in `#{entry[:mixin]}'" : "")
-
end.join
-
end
-
-
2
class << self
-
# Returns an error report for an exception in CSS format.
-
#
-
# @param e [Exception]
-
# @param options [{Symbol => Object}] The options passed to {Sass::Engine#initialize}
-
# @return [String] The error report
-
# @raise [Exception] `e`, if the
-
# {file:SASS_REFERENCE.md#full_exception-option `:full_exception`} option
-
# is set to false.
-
2
def exception_to_css(e, options)
-
raise e unless options[:full_exception]
-
-
header = header_string(e, options)
-
-
<<END
-
/*
-
#{header.gsub("*/", "*\\/")}
-
-
Backtrace:\n#{e.backtrace.join("\n").gsub("*/", "*\\/")}
-
*/
-
body:before {
-
white-space: pre;
-
font-family: monospace;
-
content: "#{header.gsub('"', '\"').gsub("\n", '\\A ')}"; }
-
END
-
end
-
-
2
private
-
-
2
def header_string(e, options)
-
unless e.is_a?(Sass::SyntaxError) && e.sass_line && e.sass_template
-
return "#{e.class}: #{e.message}"
-
end
-
-
line_offset = options[:line] || 1
-
line_num = e.sass_line + 1 - line_offset
-
min = [line_num - 6, 0].max
-
section = e.sass_template.rstrip.split("\n")[min ... line_num + 5]
-
return e.sass_backtrace_str if section.nil? || section.empty?
-
-
e.sass_backtrace_str + "\n\n" + Sass::Util.enum_with_index(section).
-
map {|line, i| "#{line_offset + min + i}: #{line}"}.join("\n")
-
end
-
end
-
end
-
-
# The class for Sass errors that are raised due to invalid unit conversions
-
# in SassScript.
-
2
class UnitConversionError < SyntaxError; end
-
end
-
2
module Sass
-
# Sass importers are in charge of taking paths passed to `@import`
-
# and finding the appropriate Sass code for those paths.
-
# By default, this code is always loaded from the filesystem,
-
# but importers could be added to load from a database or over HTTP.
-
#
-
# Each importer is in charge of a single load path
-
# (or whatever the corresponding notion is for the backend).
-
# Importers can be placed in the {file:SASS_REFERENCE.md#load_paths-option `:load_paths` array}
-
# alongside normal filesystem paths.
-
#
-
# When resolving an `@import`, Sass will go through the load paths
-
# looking for an importer that successfully imports the path.
-
# Once one is found, the imported file is used.
-
#
-
# User-created importers must inherit from {Importers::Base}.
-
2
module Importers
-
end
-
end
-
-
2
require 'sass/importers/base'
-
2
require 'sass/importers/filesystem'
-
2
module Sass
-
2
module Importers
-
# The abstract base class for Sass importers.
-
# All importers should inherit from this.
-
#
-
# At the most basic level, an importer is given a string
-
# and must return a {Sass::Engine} containing some Sass code.
-
# This string can be interpreted however the importer wants;
-
# however, subclasses are encouraged to use the URI format
-
# for pathnames.
-
#
-
# Importers that have some notion of "relative imports"
-
# should take a single load path in their constructor,
-
# and interpret paths as relative to that.
-
# They should also implement the \{#find\_relative} method.
-
#
-
# Importers should be serializable via `Marshal.dump`.
-
# In addition to the standard `_dump` and `_load` methods,
-
# importers can define `_before_dump`, `_after_dump`, `_around_dump`,
-
# and `_after_load` methods as per {Sass::Util#dump} and {Sass::Util#load}.
-
#
-
# @abstract
-
2
class Base
-
-
# Find a Sass file relative to another file.
-
# Importers without a notion of "relative paths"
-
# should just return nil here.
-
#
-
# If the importer does have a notion of "relative paths",
-
# it should ignore its load path during this method.
-
#
-
# See \{#find} for important information on how this method should behave.
-
#
-
# The `:filename` option passed to the returned {Sass::Engine}
-
# should be of a format that could be passed to \{#find}.
-
#
-
# @param uri [String] The URI to import. This is not necessarily relative,
-
# but this method should only return true if it is.
-
# @param base [String] The base filename. If `uri` is relative,
-
# it should be interpreted as relative to `base`.
-
# `base` is guaranteed to be in a format importable by this importer.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` that's currently being resolved.
-
# @return [Sass::Engine, nil] An Engine containing the imported file,
-
# or nil if it couldn't be found or was in the wrong format.
-
2
def find_relative(uri, base, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Find a Sass file, if it exists.
-
#
-
# This is the primary entry point of the Importer.
-
# It corresponds directly to an `@import` statement in Sass.
-
# It should do three basic things:
-
#
-
# * Determine if the URI is in this importer's format.
-
# If not, return nil.
-
# * Determine if the file indicated by the URI actually exists and is readable.
-
# If not, return nil.
-
# * Read the file and place the contents in a {Sass::Engine}.
-
# Return that engine.
-
#
-
# If this importer's format allows for file extensions,
-
# it should treat them the same way as the default {Filesystem} importer.
-
# If the URI explicitly has a `.sass` or `.scss` filename,
-
# the importer should look for that exact file
-
# and import it as the syntax indicated.
-
# If it doesn't exist, the importer should return nil.
-
#
-
# If the URI doesn't have either of these extensions,
-
# the importer should look for files with the extensions.
-
# If no such files exist, it should return nil.
-
#
-
# The {Sass::Engine} to be returned should be passed `options`,
-
# with a few modifications. `:syntax` should be set appropriately,
-
# `:filename` should be set to `uri`,
-
# and `:importer` should be set to this importer.
-
#
-
# @param uri [String] The URI to import.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` that's currently being resolved.
-
# This is safe for subclasses to modify destructively.
-
# Callers should only pass in a value they don't mind being destructively modified.
-
# @return [Sass::Engine, nil] An Engine containing the imported file,
-
# or nil if it couldn't be found or was in the wrong format.
-
2
def find(uri, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Returns the time the given Sass file was last modified.
-
#
-
# If the given file has been deleted or the time can't be accessed
-
# for some other reason, this should return nil.
-
#
-
# @param uri [String] The URI of the file to check.
-
# Comes from a `:filename` option set on an engine returned by this importer.
-
# @param options [{Symbol => Objet}] Options for the Sass file
-
# containing the `@import` currently being checked.
-
# @return [Time, nil]
-
2
def mtime(uri, options)
-
Sass::Util.abstract(self)
-
end
-
-
# Get the cache key pair for the given Sass URI.
-
# The URI need not be checked for validity.
-
#
-
# The only strict requirement is that the returned pair of strings
-
# uniquely identify the file at the given URI.
-
# However, the first component generally corresponds roughly to the directory,
-
# and the second to the basename, of the URI.
-
#
-
# Note that keys must be unique *across importers*.
-
# Thus it's probably a good idea to include the importer name
-
# at the beginning of the first component.
-
#
-
# @param uri [String] A URI known to be valid for this importer.
-
# @param options [{Symbol => Object}] Options for the Sass file
-
# containing the `@import` currently being checked.
-
# @return [(String, String)] The key pair which uniquely identifies
-
# the file at the given URI.
-
2
def key(uri, options)
-
Sass::Util.abstract(self)
-
end
-
-
# A string representation of the importer.
-
# Should be overridden by subclasses.
-
#
-
# This is used to help debugging,
-
# and should usually just show the load path encapsulated by this importer.
-
#
-
# @return [String]
-
2
def to_s
-
Sass::Util.abstract(self)
-
end
-
end
-
end
-
end
-
-
-
2
require 'pathname'
-
2
require 'set'
-
-
2
module Sass
-
2
module Importers
-
# The default importer, used for any strings found in the load path.
-
# Simply loads Sass files from the filesystem using the default logic.
-
2
class Filesystem < Base
-
-
2
attr_accessor :root
-
-
# Creates a new filesystem importer that imports files relative to a given path.
-
#
-
# @param root [String] The root path.
-
# This importer will import files relative to this path.
-
2
def initialize(root)
-
@root = File.expand_path(root)
-
@same_name_warnings = Set.new
-
end
-
-
# @see Base#find_relative
-
2
def find_relative(name, base, options)
-
_find(File.dirname(base), name, options)
-
end
-
-
# @see Base#find
-
2
def find(name, options)
-
_find(@root, name, options)
-
end
-
-
# @see Base#mtime
-
2
def mtime(name, options)
-
file, _ = Sass::Util.destructure(find_real_file(@root, name, options))
-
File.mtime(file) if file
-
rescue Errno::ENOENT
-
nil
-
end
-
-
# @see Base#key
-
2
def key(name, options)
-
[self.class.name + ":" + File.dirname(File.expand_path(name)),
-
File.basename(name)]
-
end
-
-
# @see Base#to_s
-
2
def to_s
-
@root
-
end
-
-
2
def hash
-
@root.hash
-
end
-
-
2
def eql?(other)
-
root.eql?(other.root)
-
end
-
-
2
protected
-
-
# If a full uri is passed, this removes the root from it
-
# otherwise returns the name unchanged
-
2
def remove_root(name)
-
if name.index(@root + "/") == 0
-
name[(@root.length + 1)..-1]
-
else
-
name
-
end
-
end
-
-
# A hash from file extensions to the syntaxes for those extensions.
-
# The syntaxes must be `:sass` or `:scss`.
-
#
-
# This can be overridden by subclasses that want normal filesystem importing
-
# with unusual extensions.
-
#
-
# @return [{String => Symbol}]
-
2
def extensions
-
{'sass' => :sass, 'scss' => :scss}
-
end
-
-
# Given an `@import`ed path, returns an array of possible
-
# on-disk filenames and their corresponding syntaxes for that path.
-
#
-
# @param name [String] The filename.
-
# @return [Array(String, Symbol)] An array of pairs.
-
# The first element of each pair is a filename to look for;
-
# the second element is the syntax that file would be in (`:sass` or `:scss`).
-
2
def possible_files(name)
-
name = escape_glob_characters(name)
-
dirname, basename, extname = split(name)
-
sorted_exts = extensions.sort
-
syntax = extensions[extname]
-
-
if syntax
-
ret = [["#{dirname}/{_,}#{basename}.#{extensions.invert[syntax]}", syntax]]
-
else
-
ret = sorted_exts.map {|ext, syn| ["#{dirname}/{_,}#{basename}.#{ext}", syn]}
-
end
-
-
# JRuby chokes when trying to import files from JARs when the path starts with './'.
-
ret.map {|f, s| [f.sub(%r{^\./}, ''), s]}
-
end
-
-
2
def escape_glob_characters(name)
-
name.gsub(/[\*\[\]\{\}\?]/) do |char|
-
"\\#{char}"
-
end
-
end
-
-
2
REDUNDANT_DIRECTORY = %r{#{Regexp.escape(File::SEPARATOR)}\.#{Regexp.escape(File::SEPARATOR)}}
-
# Given a base directory and an `@import`ed name,
-
# finds an existant file that matches the name.
-
#
-
# @param dir [String] The directory relative to which to search.
-
# @param name [String] The filename to search for.
-
# @return [(String, Symbol)] A filename-syntax pair.
-
2
def find_real_file(dir, name, options)
-
# on windows 'dir' can be in native File::ALT_SEPARATOR form
-
dir = dir.gsub(File::ALT_SEPARATOR, File::SEPARATOR) unless File::ALT_SEPARATOR.nil?
-
-
found = possible_files(remove_root(name)).map do |f, s|
-
path = (dir == "." || Pathname.new(f).absolute?) ? f : "#{escape_glob_characters(dir)}/#{f}"
-
Dir[path].map do |full_path|
-
full_path.gsub!(REDUNDANT_DIRECTORY, File::SEPARATOR)
-
[full_path, s]
-
end
-
end
-
found = Sass::Util.flatten(found, 1)
-
return if found.empty?
-
-
if found.size > 1 && !@same_name_warnings.include?(found.first.first)
-
found.each {|(f, _)| @same_name_warnings << f}
-
relative_to = Pathname.new(dir)
-
if options[:_line]
-
# If _line exists, we're here due to an actual import in an
-
# import_node and we want to print a warning for a user writing an
-
# ambiguous import.
-
candidates = found.map {|(f, _)| " " + Pathname.new(f).relative_path_from(relative_to).to_s}.join("\n")
-
Sass::Util.sass_warn <<WARNING
-
WARNING: On line #{options[:_line]}#{" of #{options[:filename]}" if options[:filename]}:
-
It's not clear which file to import for '@import "#{name}"'.
-
Candidates:
-
#{candidates}
-
For now I'll choose #{File.basename found.first.first}.
-
This will be an error in future versions of Sass.
-
WARNING
-
else
-
# Otherwise, we're here via StalenessChecker, and we want to print a
-
# warning for a user running `sass --watch` with two ambiguous files.
-
candidates = found.map {|(f, _)| " " + File.basename(f)}.join("\n")
-
Sass::Util.sass_warn <<WARNING
-
WARNING: In #{File.dirname(name)}:
-
There are multiple files that match the name "#{File.basename(name)}":
-
#{candidates}
-
WARNING
-
end
-
end
-
found.first
-
end
-
-
# Splits a filename into three parts, a directory part, a basename, and an extension
-
# Only the known extensions returned from the extensions method will be recognized as such.
-
2
def split(name)
-
extension = nil
-
dirname, basename = File.dirname(name), File.basename(name)
-
if basename =~ /^(.*)\.(#{extensions.keys.map{|e| Regexp.escape(e)}.join('|')})$/
-
basename = $1
-
extension = $2
-
end
-
[dirname, basename, extension]
-
end
-
-
2
private
-
-
2
def _find(dir, name, options)
-
full_filename, syntax = Sass::Util.destructure(find_real_file(dir, name, options))
-
return unless full_filename && File.readable?(full_filename)
-
-
options[:syntax] = syntax
-
options[:filename] = full_filename
-
options[:importer] = self
-
Sass::Engine.new(File.read(full_filename), options)
-
end
-
-
2
def join(base, path)
-
Pathname.new(base).join(path).to_s
-
end
-
end
-
end
-
end
-
2
module Sass::Logger
-
-
end
-
-
2
require "sass/logger/log_level"
-
2
require "sass/logger/base"
-
-
2
module Sass
-
-
2
class << self
-
2
attr_accessor :logger
-
end
-
-
2
self.logger = Sass::Logger::Base.new
-
end
-
2
require 'sass/logger/log_level'
-
-
2
class Sass::Logger::Base
-
-
2
include Sass::Logger::LogLevel
-
-
2
attr_accessor :log_level
-
2
attr_accessor :disabled
-
-
2
log_level :trace
-
2
log_level :debug
-
2
log_level :info
-
2
log_level :warn
-
2
log_level :error
-
-
2
def initialize(log_level = :debug)
-
4
self.log_level = log_level
-
end
-
-
2
def logging_level?(level)
-
!disabled && self.class.log_level?(level, log_level)
-
end
-
-
2
def log(level, message)
-
self._log(level, message) if logging_level?(level)
-
end
-
-
2
def _log(level, message)
-
Kernel::warn(message)
-
end
-
-
end
-
2
module Sass
-
2
module Logger
-
2
module LogLevel
-
-
2
def self.included(base)
-
2
base.extend(ClassMethods)
-
end
-
-
2
module ClassMethods
-
2
def inherited(subclass)
-
2
subclass.log_levels = subclass.superclass.log_levels.dup
-
end
-
-
2
def log_levels
-
22
@log_levels ||= {}
-
end
-
-
2
def log_levels=(levels)
-
2
@log_levels = levels
-
end
-
-
2
def log_level?(level, min_level)
-
log_levels[level] >= log_levels[min_level]
-
end
-
-
2
def log_level(name, options = {})
-
10
if options[:prepend]
-
level = log_levels.values.min
-
level = level.nil? ? 0 : level - 1
-
else
-
10
level = log_levels.values.max
-
10
level = level.nil? ? 0 : level + 1
-
end
-
10
log_levels.update(name => level)
-
10
define_logger(name)
-
end
-
-
2
def define_logger(name, options = {})
-
10
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{name}(message)
-
#{options.fetch(:to, :log)}(#{name.inspect}, message)
-
end
-
RUBY
-
end
-
end
-
-
end
-
end
-
end
-
# A namespace for the `@media` query parse tree.
-
2
module Sass::Media
-
# A comma-separated list of queries.
-
#
-
# media_query [ ',' S* media_query ]*
-
2
class QueryList
-
# The queries contained in this list.
-
#
-
# @return [Array<Query>]
-
2
attr_accessor :queries
-
-
# @param queries [Array<Query>] See \{#queries}
-
2
def initialize(queries)
-
@queries = queries
-
end
-
-
# Merges this query list with another. The returned query list
-
# queries for the intersection between the two inputs.
-
#
-
# Both query lists should be resolved.
-
#
-
# @param other [QueryList]
-
# @return [QueryList?] The merged list, or nil if there is no intersection.
-
2
def merge(other)
-
new_queries = queries.map {|q1| other.queries.map {|q2| q1.merge(q2)}}.flatten.compact
-
return if new_queries.empty?
-
QueryList.new(new_queries)
-
end
-
-
# Returns the CSS for the media query list.
-
#
-
# @return [String]
-
2
def to_css
-
queries.map {|q| q.to_css}.join(', ')
-
end
-
-
# Returns the Sass/SCSS code for the media query list.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
2
def to_src(options)
-
queries.map {|q| q.to_src(options)}.join(', ')
-
end
-
-
# Returns a representation of the query as an array of strings and
-
# potentially {Sass::Script::Node}s (if there's interpolation in it). When
-
# the interpolation is resolved and the strings are joined together, this
-
# will be the string representation of this query.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
def to_a
-
Sass::Util.intersperse(queries.map {|q| q.to_a}, ', ').flatten
-
end
-
-
# Returns a deep copy of this query list and all its children.
-
#
-
# @return [QueryList]
-
2
def deep_copy
-
QueryList.new(queries.map {|q| q.deep_copy})
-
end
-
end
-
-
# A single media query.
-
#
-
# [ [ONLY | NOT]? S* media_type S* | expression ] [ AND S* expression ]*
-
2
class Query
-
# The modifier for the query.
-
#
-
# When parsed as Sass code, this contains strings and SassScript nodes. When
-
# parsed as CSS, it contains a single string (accessible via
-
# \{#resolved_modifier}).
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :modifier
-
-
# The type of the query (e.g. `"screen"` or `"print"`).
-
#
-
# When parsed as Sass code, this contains strings and SassScript nodes. When
-
# parsed as CSS, it contains a single string (accessible via
-
# \{#resolved_type}).
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :type
-
-
# The trailing expressions in the query.
-
#
-
# When parsed as Sass code, each expression contains strings and SassScript
-
# nodes. When parsed as CSS, each one contains a single string.
-
#
-
# @return [Array<Array<String, Sass::Script::Node>>]
-
2
attr_accessor :expressions
-
-
# @param modifier [Array<String, Sass::Script::Node>] See \{#modifier}
-
# @param type [Array<String, Sass::Script::Node>] See \{#type}
-
# @param expressions [Array<Array<String, Sass::Script::Node>>] See \{#expressions}
-
2
def initialize(modifier, type, expressions)
-
@modifier = modifier
-
@type = type
-
@expressions = expressions
-
end
-
-
# See \{#modifier}.
-
# @return [String]
-
2
def resolved_modifier
-
# modifier should contain only a single string
-
modifier.first || ''
-
end
-
-
# See \{#type}.
-
# @return [String]
-
2
def resolved_type
-
# type should contain only a single string
-
type.first || ''
-
end
-
-
# Merges this query with another. The returned query queries for
-
# the intersection between the two inputs.
-
#
-
# Both queries should be resolved.
-
#
-
# @param other [Query]
-
# @return [Query?] The merged query, or nil if there is no intersection.
-
2
def merge(other)
-
m1, t1 = resolved_modifier.downcase, resolved_type.downcase
-
m2, t2 = other.resolved_modifier.downcase, other.resolved_type.downcase
-
t1 = t2 if t1.empty?
-
t2 = t1 if t2.empty?
-
if ((m1 == 'not') ^ (m2 == 'not'))
-
return if t1 == t2
-
type = m1 == 'not' ? t2 : t1
-
mod = m1 == 'not' ? m2 : m1
-
elsif m1 == 'not' && m2 == 'not'
-
# CSS has no way of representing "neither screen nor print"
-
return unless t1 == t2
-
type = t1
-
mod = 'not'
-
elsif t1 != t2
-
return
-
else # t1 == t2, neither m1 nor m2 are "not"
-
type = t1
-
mod = m1.empty? ? m2 : m1
-
end
-
return Query.new([mod], [type], other.expressions + expressions)
-
end
-
-
# Returns the CSS for the media query.
-
#
-
# @return [String]
-
2
def to_css
-
css = ''
-
css << resolved_modifier
-
css << ' ' unless resolved_modifier.empty?
-
css << resolved_type
-
css << ' and ' unless resolved_type.empty? || expressions.empty?
-
css << expressions.map do |e|
-
# It's possible for there to be script nodes in Expressions even when
-
# we're converting to CSS in the case where we parsed the document as
-
# CSS originally (as in css_test.rb).
-
e.map {|c| c.is_a?(Sass::Script::Node) ? c.to_sass : c.to_s}.join
-
end.join(' and ')
-
css
-
end
-
-
# Returns the Sass/SCSS code for the media query.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
2
def to_src(options)
-
src = ''
-
src << Sass::Media._interp_to_src(modifier, options)
-
src << ' ' unless modifier.empty?
-
src << Sass::Media._interp_to_src(type, options)
-
src << ' and ' unless type.empty? || expressions.empty?
-
src << expressions.map do |e|
-
Sass::Media._interp_to_src(e, options)
-
end.join(' and ')
-
src
-
end
-
-
# @see \{MediaQuery#to\_a}
-
2
def to_a
-
res = []
-
res += modifier
-
res << ' ' unless modifier.empty?
-
res += type
-
res << ' and ' unless type.empty? || expressions.empty?
-
res += Sass::Util.intersperse(expressions, ' and ').flatten
-
res
-
end
-
-
# Returns a deep copy of this query and all its children.
-
#
-
# @return [Query]
-
2
def deep_copy
-
Query.new(
-
modifier.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c},
-
type.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c},
-
expressions.map {|e| e.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c}})
-
end
-
end
-
-
# Converts an interpolation array to source.
-
#
-
# @param [Array<String, Sass::Script::Node>] The interpolation array to convert.
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
2
def self._interp_to_src(interp, options)
-
interp.map do |r|
-
next r if r.is_a?(String)
-
"\#{#{r.to_sass(options)}}"
-
end.join
-
end
-
end
-
# Rails 3.0.0.beta.2+, < 3.1
-
2
if defined?(ActiveSupport) && Sass::Util.has?(:public_method, ActiveSupport, :on_load) &&
-
!Sass::Util.ap_geq?('3.1.0.beta')
-
require 'sass/plugin/configuration'
-
ActiveSupport.on_load(:before_configuration) do
-
require 'sass'
-
require 'sass/plugin'
-
require 'sass/plugin/rails'
-
end
-
end
-
2
module Sass
-
# The root directory of the Sass source tree.
-
# This may be overridden by the package manager
-
# if the lib directory is separated from the main source tree.
-
# @api public
-
2
ROOT_DIR = File.expand_path(File.join(__FILE__, "../../.."))
-
end
-
2
require 'sass/script/node'
-
2
require 'sass/script/variable'
-
2
require 'sass/script/funcall'
-
2
require 'sass/script/operation'
-
2
require 'sass/script/literal'
-
2
require 'sass/script/parser'
-
-
2
module Sass
-
# SassScript is code that's embedded in Sass documents
-
# to allow for property values to be computed from variables.
-
#
-
# This module contains code that handles the parsing and evaluation of SassScript.
-
2
module Script
-
# The regular expression used to parse variables.
-
2
MATCH = /^\$(#{Sass::SCSS::RX::IDENT})\s*:\s*(.+?)(!(?i:default))?$/
-
-
# The regular expression used to validate variables without matching.
-
2
VALIDATE = /^\$#{Sass::SCSS::RX::IDENT}$/
-
-
# Parses a string of SassScript
-
#
-
# @param value [String] The SassScript
-
# @param line [Fixnum] The number of the line on which the SassScript appeared.
-
# Used for error reporting
-
# @param offset [Fixnum] The number of characters in on `line` that the SassScript started.
-
# Used for error reporting
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
# @return [Script::Node] The root node of the parse tree
-
2
def self.parse(value, line, offset, options = {})
-
Parser.parse(value, line, offset, options)
-
rescue Sass::SyntaxError => e
-
e.message << ": #{value.inspect}." if e.message == "SassScript error"
-
e.modify_backtrace(:line => line, :filename => options[:filename])
-
raise e
-
end
-
-
end
-
end
-
2
module Sass::Script
-
# A SassScript object representing a variable argument list. This works just
-
# like a normal list, but can also contain keyword arguments.
-
#
-
# The keyword arguments attached to this list are unused except when this is
-
# passed as a glob argument to a function or mixin.
-
2
class ArgList < List
-
# Whether \{#keywords} has been accessed. If so, we assume that all keywords
-
# were valid for the function that created this ArgList.
-
#
-
# @return [Boolean]
-
2
attr_accessor :keywords_accessed
-
-
# Creates a new argument list.
-
#
-
# @param value [Array<Literal>] See \{List#value}.
-
# @param keywords [Hash<String, Literal>] See \{#keywords}
-
# @param separator [String] See \{List#separator}.
-
2
def initialize(value, keywords, separator)
-
super(value, separator)
-
@keywords = keywords
-
end
-
-
# The keyword arguments attached to this list.
-
#
-
# @return [Hash<String, Literal>]
-
2
def keywords
-
@keywords_accessed = true
-
@keywords
-
end
-
-
# @see Node#children
-
2
def children
-
super + @keywords.values
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = super
-
node.instance_variable_set('@keywords',
-
Sass::Util.map_hash(@keywords) {|k, v| [k, v.deep_copy]})
-
node
-
end
-
-
2
protected
-
-
# @see Node#_perform
-
2
def _perform(environment)
-
self
-
end
-
end
-
end
-
2
require 'sass/script/literal'
-
-
2
module Sass::Script
-
# A SassScript object representing a boolean (true or false) value.
-
2
class Bool < Literal
-
# The Ruby value of the boolean.
-
#
-
# @return [Boolean]
-
2
attr_reader :value
-
2
alias_method :to_bool, :value
-
-
# @return [String] "true" or "false"
-
2
def to_s(opts = {})
-
@value.to_s
-
end
-
2
alias_method :to_sass, :to_s
-
end
-
end
-
2
require 'sass/script/literal'
-
-
2
module Sass::Script
-
# A SassScript object representing a CSS color.
-
#
-
# A color may be represented internally as RGBA, HSLA, or both.
-
# It's originally represented as whatever its input is;
-
# if it's created with RGB values, it's represented as RGBA,
-
# and if it's created with HSL values, it's represented as HSLA.
-
# Once a property is accessed that requires the other representation --
-
# for example, \{#red} for an HSL color --
-
# that component is calculated and cached.
-
#
-
# The alpha channel of a color is independent of its RGB or HSL representation.
-
# It's always stored, as 1 if nothing else is specified.
-
# If only the alpha channel is modified using \{#with},
-
# the cached RGB and HSL values are retained.
-
2
class Color < Literal
-
4
class << self; include Sass::Util; end
-
-
# A hash from color names to `[red, green, blue]` value arrays.
-
2
COLOR_NAMES = map_vals({
-
'aliceblue' => 0xf0f8ff,
-
'antiquewhite' => 0xfaebd7,
-
'aqua' => 0x00ffff,
-
'aquamarine' => 0x7fffd4,
-
'azure' => 0xf0ffff,
-
'beige' => 0xf5f5dc,
-
'bisque' => 0xffe4c4,
-
'black' => 0x000000,
-
'blanchedalmond' => 0xffebcd,
-
'blue' => 0x0000ff,
-
'blueviolet' => 0x8a2be2,
-
'brown' => 0xa52a2a,
-
'burlywood' => 0xdeb887,
-
'cadetblue' => 0x5f9ea0,
-
'chartreuse' => 0x7fff00,
-
'chocolate' => 0xd2691e,
-
'coral' => 0xff7f50,
-
'cornflowerblue' => 0x6495ed,
-
'cornsilk' => 0xfff8dc,
-
'crimson' => 0xdc143c,
-
'cyan' => 0x00ffff,
-
'darkblue' => 0x00008b,
-
'darkcyan' => 0x008b8b,
-
'darkgoldenrod' => 0xb8860b,
-
'darkgray' => 0xa9a9a9,
-
'darkgrey' => 0xa9a9a9,
-
'darkgreen' => 0x006400,
-
'darkkhaki' => 0xbdb76b,
-
'darkmagenta' => 0x8b008b,
-
'darkolivegreen' => 0x556b2f,
-
'darkorange' => 0xff8c00,
-
'darkorchid' => 0x9932cc,
-
'darkred' => 0x8b0000,
-
'darksalmon' => 0xe9967a,
-
'darkseagreen' => 0x8fbc8f,
-
'darkslateblue' => 0x483d8b,
-
'darkslategray' => 0x2f4f4f,
-
'darkslategrey' => 0x2f4f4f,
-
'darkturquoise' => 0x00ced1,
-
'darkviolet' => 0x9400d3,
-
'deeppink' => 0xff1493,
-
'deepskyblue' => 0x00bfff,
-
'dimgray' => 0x696969,
-
'dimgrey' => 0x696969,
-
'dodgerblue' => 0x1e90ff,
-
'firebrick' => 0xb22222,
-
'floralwhite' => 0xfffaf0,
-
'forestgreen' => 0x228b22,
-
'fuchsia' => 0xff00ff,
-
'gainsboro' => 0xdcdcdc,
-
'ghostwhite' => 0xf8f8ff,
-
'gold' => 0xffd700,
-
'goldenrod' => 0xdaa520,
-
'gray' => 0x808080,
-
'green' => 0x008000,
-
'greenyellow' => 0xadff2f,
-
'honeydew' => 0xf0fff0,
-
'hotpink' => 0xff69b4,
-
'indianred' => 0xcd5c5c,
-
'indigo' => 0x4b0082,
-
'ivory' => 0xfffff0,
-
'khaki' => 0xf0e68c,
-
'lavender' => 0xe6e6fa,
-
'lavenderblush' => 0xfff0f5,
-
'lawngreen' => 0x7cfc00,
-
'lemonchiffon' => 0xfffacd,
-
'lightblue' => 0xadd8e6,
-
'lightcoral' => 0xf08080,
-
'lightcyan' => 0xe0ffff,
-
'lightgoldenrodyellow' => 0xfafad2,
-
'lightgreen' => 0x90ee90,
-
'lightgray' => 0xd3d3d3,
-
'lightgrey' => 0xd3d3d3,
-
'lightpink' => 0xffb6c1,
-
'lightsalmon' => 0xffa07a,
-
'lightseagreen' => 0x20b2aa,
-
'lightskyblue' => 0x87cefa,
-
'lightslategray' => 0x778899,
-
'lightslategrey' => 0x778899,
-
'lightsteelblue' => 0xb0c4de,
-
'lightyellow' => 0xffffe0,
-
'lime' => 0x00ff00,
-
'limegreen' => 0x32cd32,
-
'linen' => 0xfaf0e6,
-
'magenta' => 0xff00ff,
-
'maroon' => 0x800000,
-
'mediumaquamarine' => 0x66cdaa,
-
'mediumblue' => 0x0000cd,
-
'mediumorchid' => 0xba55d3,
-
'mediumpurple' => 0x9370db,
-
'mediumseagreen' => 0x3cb371,
-
'mediumslateblue' => 0x7b68ee,
-
'mediumspringgreen' => 0x00fa9a,
-
'mediumturquoise' => 0x48d1cc,
-
'mediumvioletred' => 0xc71585,
-
'midnightblue' => 0x191970,
-
'mintcream' => 0xf5fffa,
-
'mistyrose' => 0xffe4e1,
-
'moccasin' => 0xffe4b5,
-
'navajowhite' => 0xffdead,
-
'navy' => 0x000080,
-
'oldlace' => 0xfdf5e6,
-
'olive' => 0x808000,
-
'olivedrab' => 0x6b8e23,
-
'orange' => 0xffa500,
-
'orangered' => 0xff4500,
-
'orchid' => 0xda70d6,
-
'palegoldenrod' => 0xeee8aa,
-
'palegreen' => 0x98fb98,
-
'paleturquoise' => 0xafeeee,
-
'palevioletred' => 0xdb7093,
-
'papayawhip' => 0xffefd5,
-
'peachpuff' => 0xffdab9,
-
'peru' => 0xcd853f,
-
'pink' => 0xffc0cb,
-
'plum' => 0xdda0dd,
-
'powderblue' => 0xb0e0e6,
-
'purple' => 0x800080,
-
'red' => 0xff0000,
-
'rosybrown' => 0xbc8f8f,
-
'royalblue' => 0x4169e1,
-
'saddlebrown' => 0x8b4513,
-
'salmon' => 0xfa8072,
-
'sandybrown' => 0xf4a460,
-
'seagreen' => 0x2e8b57,
-
'seashell' => 0xfff5ee,
-
'sienna' => 0xa0522d,
-
'silver' => 0xc0c0c0,
-
'skyblue' => 0x87ceeb,
-
'slateblue' => 0x6a5acd,
-
'slategray' => 0x708090,
-
'slategrey' => 0x708090,
-
'snow' => 0xfffafa,
-
'springgreen' => 0x00ff7f,
-
'steelblue' => 0x4682b4,
-
'tan' => 0xd2b48c,
-
'teal' => 0x008080,
-
'thistle' => 0xd8bfd8,
-
'tomato' => 0xff6347,
-
'turquoise' => 0x40e0d0,
-
'violet' => 0xee82ee,
-
'wheat' => 0xf5deb3,
-
'white' => 0xffffff,
-
'whitesmoke' => 0xf5f5f5,
-
'yellow' => 0xffff00,
-
'yellowgreen' => 0x9acd32
-
1168
}) {|color| (0..2).map {|n| color >> (n << 3) & 0xff}.reverse}
-
-
# A hash from `[red, green, blue]` value arrays to color names.
-
294
COLOR_NAMES_REVERSE = map_hash(hash_to_a(COLOR_NAMES)) {|k, v| [v, k]}
-
-
# Constructs an RGB or HSL color object,
-
# optionally with an alpha channel.
-
#
-
# The RGB values must be between 0 and 255.
-
# The saturation and lightness values must be between 0 and 100.
-
# The alpha value must be between 0 and 1.
-
#
-
# @raise [Sass::SyntaxError] if any color value isn't in the specified range
-
#
-
# @overload initialize(attrs)
-
# The attributes are specified as a hash.
-
# This hash must contain either `:hue`, `:saturation`, and `:value` keys,
-
# or `:red`, `:green`, and `:blue` keys.
-
# It cannot contain both HSL and RGB keys.
-
# It may also optionally contain an `:alpha` key.
-
#
-
# @param attrs [{Symbol => Numeric}] A hash of color attributes to values
-
# @raise [ArgumentError] if not enough attributes are specified,
-
# or both RGB and HSL attributes are specified
-
#
-
# @overload initialize(rgba)
-
# The attributes are specified as an array.
-
# This overload only supports RGB or RGBA colors.
-
#
-
# @param rgba [Array<Numeric>] A three- or four-element array
-
# of the red, green, blue, and optionally alpha values (respectively)
-
# of the color
-
# @raise [ArgumentError] if not enough attributes are specified
-
2
def initialize(attrs, allow_both_rgb_and_hsl = false)
-
super(nil)
-
-
if attrs.is_a?(Array)
-
unless (3..4).include?(attrs.size)
-
raise ArgumentError.new("Color.new(array) expects a three- or four-element array")
-
end
-
-
red, green, blue = attrs[0...3].map {|c| c.to_i}
-
@attrs = {:red => red, :green => green, :blue => blue}
-
@attrs[:alpha] = attrs[3] ? attrs[3].to_f : 1
-
else
-
attrs = attrs.reject {|k, v| v.nil?}
-
hsl = [:hue, :saturation, :lightness] & attrs.keys
-
rgb = [:red, :green, :blue] & attrs.keys
-
if !allow_both_rgb_and_hsl && !hsl.empty? && !rgb.empty?
-
raise ArgumentError.new("Color.new(hash) may not have both HSL and RGB keys specified")
-
elsif hsl.empty? && rgb.empty?
-
raise ArgumentError.new("Color.new(hash) must have either HSL or RGB keys specified")
-
elsif !hsl.empty? && hsl.size != 3
-
raise ArgumentError.new("Color.new(hash) must have all three HSL values specified")
-
elsif !rgb.empty? && rgb.size != 3
-
raise ArgumentError.new("Color.new(hash) must have all three RGB values specified")
-
end
-
-
@attrs = attrs
-
@attrs[:hue] %= 360 if @attrs[:hue]
-
@attrs[:alpha] ||= 1
-
end
-
-
[:red, :green, :blue].each do |k|
-
next if @attrs[k].nil?
-
@attrs[k] = @attrs[k].to_i
-
Sass::Util.check_range("#{k.to_s.capitalize} value", 0..255, @attrs[k])
-
end
-
-
[:saturation, :lightness].each do |k|
-
next if @attrs[k].nil?
-
value = Number.new(@attrs[k], ['%']) # Get correct unit for error messages
-
@attrs[k] = Sass::Util.check_range("#{k.to_s.capitalize}", 0..100, value, '%')
-
end
-
-
@attrs[:alpha] = Sass::Util.check_range("Alpha channel", 0..1, @attrs[:alpha])
-
end
-
-
# The red component of the color.
-
#
-
# @return [Fixnum]
-
2
def red
-
hsl_to_rgb!
-
@attrs[:red]
-
end
-
-
# The green component of the color.
-
#
-
# @return [Fixnum]
-
2
def green
-
hsl_to_rgb!
-
@attrs[:green]
-
end
-
-
# The blue component of the color.
-
#
-
# @return [Fixnum]
-
2
def blue
-
hsl_to_rgb!
-
@attrs[:blue]
-
end
-
-
# The hue component of the color.
-
#
-
# @return [Numeric]
-
2
def hue
-
rgb_to_hsl!
-
@attrs[:hue]
-
end
-
-
# The saturation component of the color.
-
#
-
# @return [Numeric]
-
2
def saturation
-
rgb_to_hsl!
-
@attrs[:saturation]
-
end
-
-
# The lightness component of the color.
-
#
-
# @return [Numeric]
-
2
def lightness
-
rgb_to_hsl!
-
@attrs[:lightness]
-
end
-
-
# The alpha channel (opacity) of the color.
-
# This is 1 unless otherwise defined.
-
#
-
# @return [Fixnum]
-
2
def alpha
-
@attrs[:alpha]
-
end
-
-
# Returns whether this color object is translucent;
-
# that is, whether the alpha channel is non-1.
-
#
-
# @return [Boolean]
-
2
def alpha?
-
alpha < 1
-
end
-
-
# Returns the red, green, and blue components of the color.
-
#
-
# @return [Array<Fixnum>] A frozen three-element array of the red, green, and blue
-
# values (respectively) of the color
-
2
def rgb
-
[red, green, blue].freeze
-
end
-
-
# Returns the hue, saturation, and lightness components of the color.
-
#
-
# @return [Array<Fixnum>] A frozen three-element array of the
-
# hue, saturation, and lightness values (respectively) of the color
-
2
def hsl
-
[hue, saturation, lightness].freeze
-
end
-
-
# The SassScript `==` operation.
-
# **Note that this returns a {Sass::Script::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Bool] True if this literal is the same as the other,
-
# false otherwise
-
2
def eq(other)
-
Sass::Script::Bool.new(
-
other.is_a?(Color) && rgb == other.rgb && alpha == other.alpha)
-
end
-
-
# Returns a copy of this color with one or more channels changed.
-
# RGB or HSL colors may be changed, but not both at once.
-
#
-
# For example:
-
#
-
# Color.new([10, 20, 30]).with(:blue => 40)
-
# #=> rgb(10, 40, 30)
-
# Color.new([126, 126, 126]).with(:red => 0, :green => 255)
-
# #=> rgb(0, 255, 126)
-
# Color.new([255, 0, 127]).with(:saturation => 60)
-
# #=> rgb(204, 51, 127)
-
# Color.new([1, 2, 3]).with(:alpha => 0.4)
-
# #=> rgba(1, 2, 3, 0.4)
-
#
-
# @param attrs [{Symbol => Numeric}]
-
# A map of channel names (`:red`, `:green`, `:blue`,
-
# `:hue`, `:saturation`, `:lightness`, or `:alpha`) to values
-
# @return [Color] The new Color object
-
# @raise [ArgumentError] if both RGB and HSL keys are specified
-
2
def with(attrs)
-
attrs = attrs.reject {|k, v| v.nil?}
-
hsl = !([:hue, :saturation, :lightness] & attrs.keys).empty?
-
rgb = !([:red, :green, :blue] & attrs.keys).empty?
-
if hsl && rgb
-
raise ArgumentError.new("Cannot specify HSL and RGB values for a color at the same time")
-
end
-
-
if hsl
-
[:hue, :saturation, :lightness].each {|k| attrs[k] ||= send(k)}
-
elsif rgb
-
[:red, :green, :blue].each {|k| attrs[k] ||= send(k)}
-
else
-
# If we're just changing the alpha channel,
-
# keep all the HSL/RGB stuff we've calculated
-
attrs = @attrs.merge(attrs)
-
end
-
attrs[:alpha] ||= alpha
-
-
Color.new(attrs, :allow_both_rgb_and_hsl)
-
end
-
-
# The SassScript `+` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Adds the number to each of the RGB color channels.
-
#
-
# {Color}
-
# : Adds each of the RGB color channels together.
-
#
-
# {Literal}
-
# : See {Literal#plus}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
2
def plus(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :+)
-
else
-
super
-
end
-
end
-
-
# The SassScript `-` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Subtracts the number from each of the RGB color channels.
-
#
-
# {Color}
-
# : Subtracts each of the other color's RGB color channels from this color's.
-
#
-
# {Literal}
-
# : See {Literal#minus}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
2
def minus(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :-)
-
else
-
super
-
end
-
end
-
-
# The SassScript `*` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Multiplies the number by each of the RGB color channels.
-
#
-
# {Color}
-
# : Multiplies each of the RGB color channels together.
-
#
-
# @param other [Number, Color] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
2
def times(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :*)
-
else
-
raise NoMethodError.new(nil, :times)
-
end
-
end
-
-
# The SassScript `/` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Divides each of the RGB color channels by the number.
-
#
-
# {Color}
-
# : Divides each of this color's RGB color channels by the other color's.
-
#
-
# {Literal}
-
# : See {Literal#div}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
2
def div(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :/)
-
else
-
super
-
end
-
end
-
-
# The SassScript `%` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Takes each of the RGB color channels module the number.
-
#
-
# {Color}
-
# : Takes each of this color's RGB color channels modulo the other color's.
-
#
-
# @param other [Number, Color] The right-hand side of the operator
-
# @return [Color] The resulting color
-
# @raise [Sass::SyntaxError] if `other` is a number with units
-
2
def mod(other)
-
if other.is_a?(Sass::Script::Number) || other.is_a?(Sass::Script::Color)
-
piecewise(other, :%)
-
else
-
raise NoMethodError.new(nil, :mod)
-
end
-
end
-
-
# Returns a string representation of the color.
-
# This is usually the color's hex value,
-
# but if the color has a name that's used instead.
-
#
-
# @return [String] The string representation
-
2
def to_s(opts = {})
-
return rgba_str if alpha?
-
return smallest if options[:style] == :compressed
-
return COLOR_NAMES_REVERSE[rgb] if COLOR_NAMES_REVERSE[rgb]
-
hex_str
-
end
-
2
alias_method :to_sass, :to_s
-
-
# Returns a string representation of the color.
-
#
-
# @return [String] The hex value
-
2
def inspect
-
alpha? ? rgba_str : hex_str
-
end
-
-
2
private
-
-
2
def smallest
-
small_hex_str = hex_str.gsub(/^#(.)\1(.)\2(.)\3$/, '#\1\2\3')
-
return small_hex_str unless (color = COLOR_NAMES_REVERSE[rgb]) &&
-
color.size <= small_hex_str.size
-
return color
-
end
-
-
2
def rgba_str
-
split = options[:style] == :compressed ? ',' : ', '
-
"rgba(#{rgb.join(split)}#{split}#{Number.round(alpha)})"
-
end
-
-
2
def hex_str
-
red, green, blue = rgb.map { |num| num.to_s(16).rjust(2, '0') }
-
"##{red}#{green}#{blue}"
-
end
-
-
2
def piecewise(other, operation)
-
other_num = other.is_a? Number
-
if other_num && !other.unitless?
-
raise Sass::SyntaxError.new("Cannot add a number with units (#{other}) to a color (#{self}).")
-
end
-
-
result = []
-
for i in (0...3)
-
res = rgb[i].send(operation, other_num ? other.value : other.rgb[i])
-
result[i] = [ [res, 255].min, 0 ].max
-
end
-
-
if !other_num && other.alpha != alpha
-
raise Sass::SyntaxError.new("Alpha channels must be equal: #{self} #{operation} #{other}")
-
end
-
-
with(:red => result[0], :green => result[1], :blue => result[2])
-
end
-
-
2
def hsl_to_rgb!
-
return if @attrs[:red] && @attrs[:blue] && @attrs[:green]
-
-
h = @attrs[:hue] / 360.0
-
s = @attrs[:saturation] / 100.0
-
l = @attrs[:lightness] / 100.0
-
-
# Algorithm from the CSS3 spec: http://www.w3.org/TR/css3-color/#hsl-color.
-
m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s
-
m1 = l * 2 - m2
-
@attrs[:red], @attrs[:green], @attrs[:blue] = [
-
hue_to_rgb(m1, m2, h + 1.0/3),
-
hue_to_rgb(m1, m2, h),
-
hue_to_rgb(m1, m2, h - 1.0/3)
-
].map {|c| (c * 0xff).round}
-
end
-
-
2
def hue_to_rgb(m1, m2, h)
-
h += 1 if h < 0
-
h -= 1 if h > 1
-
return m1 + (m2 - m1) * h * 6 if h * 6 < 1
-
return m2 if h * 2 < 1
-
return m1 + (m2 - m1) * (2.0/3 - h) * 6 if h * 3 < 2
-
return m1
-
end
-
-
2
def rgb_to_hsl!
-
return if @attrs[:hue] && @attrs[:saturation] && @attrs[:lightness]
-
r, g, b = [:red, :green, :blue].map {|k| @attrs[k] / 255.0}
-
-
# Algorithm from http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
max = [r, g, b].max
-
min = [r, g, b].min
-
d = max - min
-
-
h =
-
case max
-
when min; 0
-
when r; 60 * (g-b)/d
-
when g; 60 * (b-r)/d + 120
-
when b; 60 * (r-g)/d + 240
-
end
-
-
l = (max + min)/2.0
-
-
s =
-
if max == min
-
0
-
elsif l < 0.5
-
d/(2*l)
-
else
-
d/(2 - 2*l)
-
end
-
-
@attrs[:hue] = h % 360
-
@attrs[:saturation] = s * 100
-
@attrs[:lightness] = l * 100
-
end
-
end
-
end
-
2
module Sass
-
2
module Script
-
# This is a subclass of {Lexer} for use in parsing plain CSS properties.
-
#
-
# @see Sass::SCSS::CssParser
-
2
class CssLexer < Lexer
-
2
private
-
-
2
def token
-
important || super
-
end
-
-
2
def string(re, *args)
-
if re == :uri
-
return unless uri = scan(URI)
-
return [:string, Script::String.new(uri)]
-
end
-
-
return unless scan(STRING)
-
[:string, Script::String.new((@scanner[1] || @scanner[2]).gsub(/\\(['"])/, '\1'), :string)]
-
end
-
-
2
def important
-
return unless s = scan(IMPORTANT)
-
[:raw, s]
-
end
-
end
-
end
-
end
-
2
require 'sass/script'
-
2
require 'sass/script/css_lexer'
-
-
2
module Sass
-
2
module Script
-
# This is a subclass of {Parser} for use in parsing plain CSS properties.
-
#
-
# @see Sass::SCSS::CssParser
-
2
class CssParser < Parser
-
2
private
-
-
# @private
-
2
def lexer_class; CssLexer; end
-
-
# We need a production that only does /,
-
# since * and % aren't allowed in plain CSS
-
2
production :div, :unary_plus, :div
-
-
2
def string
-
return number unless tok = try_tok(:string)
-
return tok.value unless @lexer.peek && @lexer.peek.type == :begin_interpolation
-
end
-
-
# Short-circuit all the SassScript-only productions
-
2
alias_method :interpolation, :space
-
2
alias_method :or_expr, :div
-
2
alias_method :unary_div, :ident
-
2
alias_method :paren, :string
-
end
-
end
-
end
-
2
require 'sass/script/functions'
-
-
2
module Sass
-
2
module Script
-
# A SassScript parse node representing a function call.
-
#
-
# A function call either calls one of the functions in {Script::Functions},
-
# or if no function with the given name exists
-
# it returns a string representation of the function call.
-
2
class Funcall < Node
-
# The name of the function.
-
#
-
# @return [String]
-
2
attr_reader :name
-
-
# The arguments to the function.
-
#
-
# @return [Array<Script::Node>]
-
2
attr_reader :args
-
-
# The keyword arguments to the function.
-
#
-
# @return [{String => Script::Node}]
-
2
attr_reader :keywords
-
-
# The splat argument for this function, if one exists.
-
#
-
# @return [Script::Node?]
-
2
attr_accessor :splat
-
-
# @param name [String] See \{#name}
-
# @param args [Array<Script::Node>] See \{#args}
-
# @param splat [Script::Node] See \{#splat}
-
# @param keywords [{String => Script::Node}] See \{#keywords}
-
2
def initialize(name, args, keywords, splat)
-
@name = name
-
@args = args
-
@keywords = keywords
-
@splat = splat
-
super()
-
end
-
-
# @return [String] A string representation of the function call
-
2
def inspect
-
args = @args.map {|a| a.inspect}.join(', ')
-
keywords = Sass::Util.hash_to_a(@keywords).
-
map {|k, v| "$#{k}: #{v.inspect}"}.join(', ')
-
if self.splat
-
splat = (args.empty? && keywords.empty?) ? "" : ", "
-
splat = "#{splat}#{self.splat.inspect}..."
-
end
-
"#{name}(#{args}#{', ' unless args.empty? || keywords.empty?}#{keywords}#{splat})"
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
arg_to_sass = lambda do |arg|
-
sass = arg.to_sass(opts)
-
sass = "(#{sass})" if arg.is_a?(Sass::Script::List) && arg.separator == :comma
-
sass
-
end
-
-
args = @args.map(&arg_to_sass).join(', ')
-
keywords = Sass::Util.hash_to_a(@keywords).
-
map {|k, v| "$#{dasherize(k, opts)}: #{arg_to_sass[v]}"}.join(', ')
-
if self.splat
-
splat = (args.empty? && keywords.empty?) ? "" : ", "
-
splat = "#{splat}#{arg_to_sass[self.splat]}..."
-
end
-
"#{dasherize(name, opts)}(#{args}#{', ' unless args.empty? || keywords.empty?}#{keywords}#{splat})"
-
end
-
-
# Returns the arguments to the function.
-
#
-
# @return [Array<Node>]
-
# @see Node#children
-
2
def children
-
res = @args + @keywords.values
-
res << @splat if @splat
-
res
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = dup
-
node.instance_variable_set('@args', args.map {|a| a.deep_copy})
-
node.instance_variable_set('@keywords', Hash[keywords.map {|k, v| [k, v.deep_copy]}])
-
node
-
end
-
-
2
protected
-
-
# Evaluates the function call.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the function call
-
# @raise [Sass::SyntaxError] if the function call raises an ArgumentError
-
2
def _perform(environment)
-
args = @args.map {|a| a.perform(environment)}
-
splat = @splat.perform(environment) if @splat
-
if fn = environment.function(@name)
-
keywords = Sass::Util.map_hash(@keywords) {|k, v| [k, v.perform(environment)]}
-
return without_original(perform_sass_fn(fn, args, keywords, splat))
-
end
-
-
ruby_name = @name.tr('-', '_')
-
args = construct_ruby_args(ruby_name, args, splat, environment)
-
-
unless Functions.callable?(ruby_name)
-
without_original(opts(to_literal(args)))
-
else
-
without_original(opts(Functions::EvaluationContext.new(environment.options).
-
send(ruby_name, *args)))
-
end
-
rescue ArgumentError => e
-
message = e.message
-
-
# If this is a legitimate Ruby-raised argument error, re-raise it.
-
# Otherwise, it's an error in the user's stylesheet, so wrap it.
-
if Sass::Util.rbx?
-
# Rubinius has a different error report string than vanilla Ruby. It
-
# also doesn't put the actual method for which the argument error was
-
# thrown in the backtrace, nor does it include `send`, so we look for
-
# `_perform`.
-
if e.message =~ /^method '([^']+)': given (\d+), expected (\d+)/
-
error_name, given, expected = $1, $2, $3
-
raise e if error_name != ruby_name || e.backtrace[0] !~ /:in `_perform'$/
-
message = "wrong number of arguments (#{given} for #{expected})"
-
end
-
elsif Sass::Util.jruby?
-
if Sass::Util.jruby1_6?
-
should_maybe_raise = e.message =~ /^wrong number of arguments \((\d+) for (\d+)\)/ &&
-
# The one case where JRuby does include the Ruby name of the function
-
# is manually-thrown ArgumentErrors, which are indistinguishable from
-
# legitimate ArgumentErrors. We treat both of these as
-
# Sass::SyntaxErrors even though it can hide Ruby errors.
-
e.backtrace[0] !~ /:in `(block in )?#{ruby_name}'$/
-
else
-
should_maybe_raise = e.message =~ /^wrong number of arguments calling `[^`]+` \((\d+) for (\d+)\)/
-
given, expected = $1, $2
-
end
-
-
if should_maybe_raise
-
# JRuby 1.7 includes __send__ before send and _perform.
-
trace = e.backtrace.dup
-
raise e if !Sass::Util.jruby1_6? && trace.shift !~ /:in `__send__'$/
-
-
# JRuby (as of 1.7.2) doesn't put the actual method
-
# for which the argument error was thrown in the backtrace, so we
-
# detect whether our send threw an argument error.
-
if !(trace[0] =~ /:in `send'$/ && trace[1] =~ /:in `_perform'$/)
-
raise e
-
elsif !Sass::Util.jruby1_6?
-
# JRuby 1.7 doesn't use standard formatting for its ArgumentErrors.
-
message = "wrong number of arguments (#{given} for #{expected})"
-
end
-
end
-
elsif e.message =~ /^wrong number of arguments \(\d+ for \d+\)/ &&
-
e.backtrace[0] !~ /:in `(block in )?#{ruby_name}'$/
-
raise e
-
end
-
raise Sass::SyntaxError.new("#{message} for `#{name}'")
-
end
-
-
# This method is factored out from `_perform` so that compass can override
-
# it with a cross-browser implementation for functions that require vendor prefixes
-
# in the generated css.
-
2
def to_literal(args)
-
Script::String.new("#{name}(#{args.join(', ')})")
-
end
-
-
2
private
-
-
2
def without_original(value)
-
return value unless value.is_a?(Number)
-
value = value.dup
-
value.original = nil
-
return value
-
end
-
-
2
def construct_ruby_args(name, args, splat, environment)
-
args += splat.to_a if splat
-
-
# If variable arguments were passed, there won't be any explicit keywords.
-
if splat.is_a?(Sass::Script::ArgList)
-
kwargs_size = splat.keywords.size
-
splat.keywords_accessed = false
-
else
-
kwargs_size = @keywords.size
-
end
-
-
unless signature = Functions.signature(name.to_sym, args.size, kwargs_size)
-
return args if @keywords.empty?
-
raise Sass::SyntaxError.new("Function #{name} doesn't support keyword arguments")
-
end
-
keywords = splat.is_a?(Sass::Script::ArgList) ? splat.keywords :
-
Sass::Util.map_hash(@keywords) {|k, v| [k, v.perform(environment)]}
-
-
# If the user passes more non-keyword args than the function expects,
-
# but it does expect keyword args, Ruby's arg handling won't raise an error.
-
# Since we don't want to make functions think about this,
-
# we'll handle it for them here.
-
if signature.var_kwargs && !signature.var_args && args.size > signature.args.size
-
raise Sass::SyntaxError.new(
-
"#{args[signature.args.size].inspect} is not a keyword argument for `#{name}'")
-
elsif keywords.empty?
-
return args
-
end
-
-
args = args + signature.args[args.size..-1].map do |argname|
-
if keywords.has_key?(argname)
-
keywords.delete(argname)
-
else
-
raise Sass::SyntaxError.new("Function #{name} requires an argument named $#{argname}")
-
end
-
end
-
-
if keywords.size > 0
-
if signature.var_kwargs
-
args << keywords
-
else
-
argname = keywords.keys.sort.first
-
if signature.args.include?(argname)
-
raise Sass::SyntaxError.new("Function #{name} was passed argument $#{argname} both by position and by name")
-
else
-
raise Sass::SyntaxError.new("Function #{name} doesn't have an argument named $#{argname}")
-
end
-
end
-
end
-
-
args
-
end
-
-
2
def perform_sass_fn(function, args, keywords, splat)
-
Sass::Tree::Visitors::Perform.perform_arguments(function, args, keywords, splat) do |env|
-
val = catch :_sass_return do
-
function.tree.each {|c| Sass::Tree::Visitors::Perform.visit(c, env)}
-
raise Sass::SyntaxError.new("Function #{@name} finished without @return")
-
end
-
val
-
end
-
end
-
end
-
end
-
end
-
2
module Sass::Script
-
# Methods in this module are accessible from the SassScript context.
-
# For example, you can write
-
#
-
# $color: hsl(120deg, 100%, 50%)
-
#
-
# and it will call {Sass::Script::Functions#hsl}.
-
#
-
# The following functions are provided:
-
#
-
# *Note: These functions are described in more detail below.*
-
#
-
# ## RGB Functions
-
#
-
# \{#rgb rgb($red, $green, $blue)}
-
# : Creates a {Color} from red, green, and blue values.
-
#
-
# \{#rgba rgba($red, $green, $blue, $alpha)}
-
# : Creates a {Color} from red, green, blue, and alpha values.
-
#
-
# \{#red red($color)}
-
# : Gets the red component of a color.
-
#
-
# \{#green green($color)}
-
# : Gets the green component of a color.
-
#
-
# \{#blue blue($color)}
-
# : Gets the blue component of a color.
-
#
-
# \{#mix mix($color-1, $color-2, \[$weight\])}
-
# : Mixes two colors together.
-
#
-
# ## HSL Functions
-
#
-
# \{#hsl hsl($hue, $saturation, $lightness)}
-
# : Creates a {Color} from hue, saturation, and lightness values.
-
#
-
# \{#hsla hsla($hue, $saturation, $lightness, $alpha)}
-
# : Creates a {Color} from hue, saturation, lightness, and alpha
-
# values.
-
#
-
# \{#hue hue($color)}
-
# : Gets the hue component of a color.
-
#
-
# \{#saturation saturation($color)}
-
# : Gets the saturation component of a color.
-
#
-
# \{#lightness lightness($color)}
-
# : Gets the lightness component of a color.
-
#
-
# \{#adjust_hue adjust-hue($color, $degrees)}
-
# : Changes the hue of a color.
-
#
-
# \{#lighten lighten($color, $amount)}
-
# : Makes a color lighter.
-
#
-
# \{#darken darken($color, $amount)}
-
# : Makes a color darker.
-
#
-
# \{#saturate saturate($color, $amount)}
-
# : Makes a color more saturated.
-
#
-
# \{#desaturate desaturate($color, $amount)}
-
# : Makes a color less saturated.
-
#
-
# \{#grayscale grayscale($color)}
-
# : Converts a color to grayscale.
-
#
-
# \{#complement complement($color)}
-
# : Returns the complement of a color.
-
#
-
# \{#invert invert($color)}
-
# : Returns the inverse of a color.
-
#
-
# ## Opacity Functions
-
#
-
# \{#alpha alpha($color)} / \{#opacity opacity($color)}
-
# : Gets the alpha component (opacity) of a color.
-
#
-
# \{#rgba rgba($color, $alpha)}
-
# : Changes the alpha component for a color.
-
#
-
# \{#opacify opacify($color, $amount)} / \{#fade_in fade-in($color, $amount)}
-
# : Makes a color more opaque.
-
#
-
# \{#transparentize transparentize($color, $amount)} / \{#fade_out fade-out($color, $amount)}
-
# : Makes a color more transparent.
-
#
-
# ## Other Color Functions
-
#
-
# \{#adjust_color adjust-color($color, \[$red\], \[$green\], \[$blue\], \[$hue\], \[$saturation\], \[$lightness\], \[$alpha\])}
-
# : Increases or decreases one or more components of a color.
-
#
-
# \{#scale_color scale-color($color, \[$red\], \[$green\], \[$blue\], \[$saturation\], \[$lightness\], \[$alpha\])}
-
# : Fluidly scales one or more properties of a color.
-
#
-
# \{#change_color change-color($color, \[$red\], \[$green\], \[$blue\], \[$hue\], \[$saturation\], \[$lightness\], \[$alpha\])}
-
# : Changes one or more properties of a color.
-
#
-
# \{#ie_hex_str ie-hex-str($color)}
-
# : Converts a color into the format understood by IE filters.
-
#
-
# ## String Functions
-
#
-
# \{#unquote unquote($string)}
-
# : Removes quotes from a string.
-
#
-
# \{#quote quote($string)}
-
# : Adds quotes to a string.
-
#
-
# ## Number Functions
-
#
-
# \{#percentage percentage($value)}
-
# : Converts a unitless number to a percentage.
-
#
-
# \{#round round($value)}
-
# : Rounds a number to the nearest whole number.
-
#
-
# \{#ceil ceil($value)}
-
# : Rounds a number up to the next whole number.
-
#
-
# \{#floor floor($value)}
-
# : Rounds a number down to the previous whole number.
-
#
-
# \{#abs abs($value)}
-
# : Returns the absolute value of a number.
-
#
-
# \{#min min($numbers...)\}
-
# : Finds the minimum of several numbers.
-
#
-
# \{#max max($numbers...)\}
-
# : Finds the maximum of several numbers.
-
#
-
# ## List Functions {#list-functions}
-
#
-
# \{#length length($list)}
-
# : Returns the length of a list.
-
#
-
# \{#nth nth($list, $n)}
-
# : Returns a specific item in a list.
-
#
-
# \{#join join($list1, $list2, \[$separator\])}
-
# : Joins together two lists into one.
-
#
-
# \{#append append($list1, $val, \[$separator\])}
-
# : Appends a single value onto the end of a list.
-
#
-
# \{#zip zip($lists...)}
-
# : Combines several lists into a single multidimensional list.
-
#
-
# \{#index index($list, $value)}
-
# : Returns the position of a value within a list.
-
#
-
# ## Introspection Functions
-
#
-
# \{#type_of type-of($value)}
-
# : Returns the type of a value.
-
#
-
# \{#unit unit($number)}
-
# : Returns the unit(s) associated with a number.
-
#
-
# \{#unitless unitless($number)}
-
# : Returns whether a number has units.
-
#
-
# \{#comparable comparable($number-1, $number-2)}
-
# : Returns whether two numbers can be added, subtracted, or compared.
-
#
-
# ## Miscellaneous Functions
-
#
-
# \{#if if($condition, $if-true, $if-false)}
-
# : Returns one of two values, depending on whether or not `$condition` is
-
# true.
-
#
-
# ## Adding Custom Functions
-
#
-
# New Sass functions can be added by adding Ruby methods to this module.
-
# For example:
-
#
-
# module Sass::Script::Functions
-
# def reverse(string)
-
# assert_type string, :String
-
# Sass::Script::String.new(string.value.reverse)
-
# end
-
# declare :reverse, :args => [:string]
-
# end
-
#
-
# Calling {declare} tells Sass the argument names for your function.
-
# If omitted, the function will still work, but will not be able to accept keyword arguments.
-
# {declare} can also allow your function to take arbitrary keyword arguments.
-
#
-
# There are a few things to keep in mind when modifying this module.
-
# First of all, the arguments passed are {Sass::Script::Literal} objects.
-
# Literal objects are also expected to be returned.
-
# This means that Ruby values must be unwrapped and wrapped.
-
#
-
# Most Literal objects support the {Sass::Script::Literal#value value} accessor
-
# for getting their Ruby values.
-
# Color objects, though, must be accessed using {Sass::Script::Color#rgb rgb},
-
# {Sass::Script::Color#red red}, {Sass::Script::Color#blue green}, or {Sass::Script::Color#blue blue}.
-
#
-
# Second, making Ruby functions accessible from Sass introduces the temptation
-
# to do things like database access within stylesheets.
-
# This is generally a bad idea;
-
# since Sass files are by default only compiled once,
-
# dynamic code is not a great fit.
-
#
-
# If you really, really need to compile Sass on each request,
-
# first make sure you have adequate caching set up.
-
# Then you can use {Sass::Engine} to render the code,
-
# using the {file:SASS_REFERENCE.md#custom-option `options` parameter}
-
# to pass in data that {EvaluationContext#options can be accessed}
-
# from your Sass functions.
-
#
-
# Within one of the functions in this module,
-
# methods of {EvaluationContext} can be used.
-
#
-
# ### Caveats
-
#
-
# When creating new {Literal} objects within functions,
-
# be aware that it's not safe to call {Literal#to_s #to_s}
-
# (or other methods that use the string representation)
-
# on those objects without first setting {Node#options= the #options attribute}.
-
2
module Functions
-
2
@signatures = {}
-
-
# A class representing a Sass function signature.
-
#
-
# @attr args [Array<Symbol>] The names of the arguments to the function.
-
# @attr var_args [Boolean] Whether the function takes a variable number of arguments.
-
# @attr var_kwargs [Boolean] Whether the function takes an arbitrary set of keyword arguments.
-
2
Signature = Struct.new(:args, :var_args, :var_kwargs)
-
-
# Declare a Sass signature for a Ruby-defined function.
-
# This includes the names of the arguments,
-
# whether the function takes a variable number of arguments,
-
# and whether the function takes an arbitrary set of keyword arguments.
-
#
-
# It's not necessary to declare a signature for a function.
-
# However, without a signature it won't support keyword arguments.
-
#
-
# A single function can have multiple signatures declared
-
# as long as each one takes a different number of arguments.
-
# It's also possible to declare multiple signatures
-
# that all take the same number of arguments,
-
# but none of them but the first will be used
-
# unless the user uses keyword arguments.
-
#
-
# @example
-
# declare :rgba, [:hex, :alpha]
-
# declare :rgba, [:red, :green, :blue, :alpha]
-
# declare :accepts_anything, [], :var_args => true, :var_kwargs => true
-
# declare :some_func, [:foo, :bar, :baz], :var_kwargs => true
-
#
-
# @param method_name [Symbol] The name of the method
-
# whose signature is being declared.
-
# @param args [Array<Symbol>] The names of the arguments for the function signature.
-
# @option options :var_args [Boolean] (false)
-
# Whether the function accepts a variable number of (unnamed) arguments
-
# in addition to the named arguments.
-
# @option options :var_kwargs [Boolean] (false)
-
# Whether the function accepts other keyword arguments
-
# in addition to those in `:args`.
-
# If this is true, the Ruby function will be passed a hash from strings
-
# to {Sass::Script::Literal}s as the last argument.
-
# In addition, if this is true and `:var_args` is not,
-
# Sass will ensure that the last argument passed is a hash.
-
2
def self.declare(method_name, args, options = {})
-
112
@signatures[method_name] ||= []
-
@signatures[method_name] << Signature.new(
-
170
args.map {|s| s.to_s},
-
options[:var_args],
-
112
options[:var_kwargs])
-
end
-
-
# Determine the correct signature for the number of arguments
-
# passed in for a given function.
-
# If no signatures match, the first signature is returned for error messaging.
-
#
-
# @param method_name [Symbol] The name of the Ruby function to be called.
-
# @param arg_arity [Number] The number of unnamed arguments the function was passed.
-
# @param kwarg_arity [Number] The number of keyword arguments the function was passed.
-
#
-
# @return [{Symbol => Object}, nil]
-
# The signature options for the matching signature,
-
# or nil if no signatures are declared for this function. See {declare}.
-
2
def self.signature(method_name, arg_arity, kwarg_arity)
-
return unless @signatures[method_name]
-
@signatures[method_name].each do |signature|
-
return signature if signature.args.size == arg_arity + kwarg_arity
-
next unless signature.args.size < arg_arity + kwarg_arity
-
-
# We have enough args.
-
# Now we need to figure out which args are varargs
-
# and if the signature allows them.
-
t_arg_arity, t_kwarg_arity = arg_arity, kwarg_arity
-
if signature.args.size > t_arg_arity
-
# we transfer some kwargs arity to args arity
-
# if it does not have enough args -- assuming the names will work out.
-
t_kwarg_arity -= (signature.args.size - t_arg_arity)
-
t_arg_arity = signature.args.size
-
end
-
-
if ( t_arg_arity == signature.args.size || t_arg_arity > signature.args.size && signature.var_args ) &&
-
(t_kwarg_arity == 0 || t_kwarg_arity > 0 && signature.var_kwargs)
-
return signature
-
end
-
end
-
@signatures[method_name].first
-
end
-
-
# The context in which methods in {Script::Functions} are evaluated.
-
# That means that all instance methods of {EvaluationContext}
-
# are available to use in functions.
-
2
class EvaluationContext
-
2
include Functions
-
-
# The options hash for the {Sass::Engine} that is processing the function call
-
#
-
# @return [{Symbol => Object}]
-
2
attr_reader :options
-
-
# @param options [{Symbol => Object}] See \{#options}
-
2
def initialize(options)
-
@options = options
-
end
-
-
# Asserts that the type of a given SassScript value
-
# is the expected type (designated by a symbol).
-
#
-
# Valid types are `:Bool`, `:Color`, `:Number`, and `:String`.
-
# Note that `:String` will match both double-quoted strings
-
# and unquoted identifiers.
-
#
-
# @example
-
# assert_type value, :String
-
# assert_type value, :Number
-
# @param value [Sass::Script::Literal] A SassScript value
-
# @param type [Symbol] The name of the type the value is expected to be
-
# @param name [String, Symbol, nil] The name of the argument.
-
2
def assert_type(value, type, name = nil)
-
return if value.is_a?(Sass::Script.const_get(type))
-
err = "#{value.inspect} is not a #{type.to_s.downcase}"
-
err = "$#{name.to_s.gsub('_', '-')}: " + err if name
-
raise ArgumentError.new(err)
-
end
-
end
-
-
2
class << self
-
# Returns whether user function with a given name exists.
-
#
-
# @param function_name [String]
-
# @return [Boolean]
-
2
alias_method :callable?, :public_method_defined?
-
-
2
private
-
2
def include(*args)
-
r = super
-
# We have to re-include ourselves into EvaluationContext to work around
-
# an icky Ruby restriction.
-
EvaluationContext.send :include, self
-
r
-
end
-
end
-
-
# Creates a {Color} object from red, green, and blue values.
-
#
-
# @see #rgba
-
# @overload rgb($red, $green, $blue)
-
# @param $red [Number] The amount of red in the color. Must be between 0 and
-
# 255 inclusive, or between `0%` and `100%` inclusive
-
# @param $green [Number] The amount of green in the color. Must be between 0
-
# and 255 inclusive, or between `0%` and `100%` inclusive
-
# @param $blue [Number] The amount of blue in the color. Must be between 0
-
# and 255 inclusive, or between `0%` and `100%` inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out of bounds
-
2
def rgb(red, green, blue)
-
assert_type red, :Number, :red
-
assert_type green, :Number, :green
-
assert_type blue, :Number, :blue
-
-
Color.new([[red, :red], [green, :green], [blue, :blue]].map do |(c, name)|
-
v = c.value
-
if c.numerator_units == ["%"] && c.denominator_units.empty?
-
v = Sass::Util.check_range("$#{name}: Color value", 0..100, c, '%')
-
v * 255 / 100.0
-
else
-
Sass::Util.check_range("$#{name}: Color value", 0..255, c)
-
end
-
end)
-
end
-
2
declare :rgb, [:red, :green, :blue]
-
-
# Creates a {Color} from red, green, blue, and alpha values.
-
# @see #rgb
-
#
-
# @overload rgba($red, $green, $blue, $alpha)
-
# @param $red [Number] The amount of red in the color. Must be between 0
-
# and 255 inclusive
-
# @param $green [Number] The amount of green in the color. Must be between
-
# 0 and 255 inclusive
-
# @param $blue [Number] The amount of blue in the color. Must be between 0
-
# and 255 inclusive
-
# @param $alpha [Number] The opacity of the color. Must be between 0 and 1
-
# inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out of
-
# bounds
-
#
-
# @overload rgba($color, $alpha)
-
# Sets the opacity of an existing color.
-
#
-
# @example
-
# rgba(#102030, 0.5) => rgba(16, 32, 48, 0.5)
-
# rgba(blue, 0.2) => rgba(0, 0, 255, 0.2)
-
#
-
# @param $color [Color] The color whose opacity will be changed.
-
# @param $alpha [Number] The new opacity of the color. Must be between 0
-
# and 1 inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if `$alpha` is out of bounds or either parameter
-
# is the wrong type
-
2
def rgba(*args)
-
case args.size
-
when 2
-
color, alpha = args
-
-
assert_type color, :Color, :color
-
assert_type alpha, :Number, :alpha
-
-
Sass::Util.check_range('Alpha channel', 0..1, alpha)
-
color.with(:alpha => alpha.value)
-
when 4
-
red, green, blue, alpha = args
-
rgba(rgb(red, green, blue), alpha)
-
else
-
raise ArgumentError.new("wrong number of arguments (#{args.size} for 4)")
-
end
-
end
-
2
declare :rgba, [:red, :green, :blue, :alpha]
-
2
declare :rgba, [:color, :alpha]
-
-
# Creates a {Color} from hue, saturation, and lightness values. Uses the
-
# algorithm from the [CSS3 spec][].
-
#
-
# [CSS3 spec]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @see #hsla
-
# @overload hsl($hue, $saturation, $lightness)
-
# @param $hue [Number] The hue of the color. Should be between 0 and 360
-
# degrees, inclusive
-
# @param $saturation [Number] The saturation of the color. Must be between
-
# `0%` and `100%`, inclusive
-
# @param $lightness [Number] The lightness of the color. Must be between
-
# `0%` and `100%`, inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if `$saturation` or `$lightness` are out of bounds
-
# or any parameter is the wrong type
-
2
def hsl(hue, saturation, lightness)
-
hsla(hue, saturation, lightness, Number.new(1))
-
end
-
2
declare :hsl, [:hue, :saturation, :lightness]
-
-
# Creates a {Color} from hue, saturation, lightness, and alpha
-
# values. Uses the algorithm from the [CSS3 spec][].
-
#
-
# [CSS3 spec]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @see #hsl
-
# @overload hsla($hue, $saturation, $lightness, $alpha)
-
# @param $hue [Number] The hue of the color. Should be between 0 and 360
-
# degrees, inclusive
-
# @param $saturation [Number] The saturation of the color. Must be between
-
# `0%` and `100%`, inclusive
-
# @param $lightness [Number] The lightness of the color. Must be between
-
# `0%` and `100%`, inclusive
-
# @param $alpha [Number] The opacity of the color. Must be between 0 and 1,
-
# inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if `$saturation`, `$lightness`, or `$alpha` are out
-
# of bounds or any parameter is the wrong type
-
2
def hsla(hue, saturation, lightness, alpha)
-
assert_type hue, :Number, :hue
-
assert_type saturation, :Number, :saturation
-
assert_type lightness, :Number, :lightness
-
assert_type alpha, :Number, :alpha
-
-
Sass::Util.check_range('Alpha channel', 0..1, alpha)
-
-
h = hue.value
-
s = Sass::Util.check_range('Saturation', 0..100, saturation, '%')
-
l = Sass::Util.check_range('Lightness', 0..100, lightness, '%')
-
-
Color.new(:hue => h, :saturation => s, :lightness => l, :alpha => alpha.value)
-
end
-
2
declare :hsla, [:hue, :saturation, :lightness, :alpha]
-
-
# Gets the red component of a color. Calculated from HSL where necessary via
-
# [this algorithm][hsl-to-rgb].
-
#
-
# [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @overload red($color)
-
# @param $color [Color]
-
# @return [Number] The red component, between 0 and 255 inclusive
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def red(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.red)
-
end
-
2
declare :red, [:color]
-
-
# Gets the green component of a color. Calculated from HSL where necessary
-
# via [this algorithm][hsl-to-rgb].
-
#
-
# [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @overload green($color)
-
# @param $color [Color]
-
# @return [Number] The green component, between 0 and 255 inclusive
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def green(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.green)
-
end
-
2
declare :green, [:color]
-
-
# Gets the blue component of a color. Calculated from HSL where necessary
-
# via [this algorithm][hsl-to-rgb].
-
#
-
# [hsl-to-rgb]: http://www.w3.org/TR/css3-color/#hsl-color
-
#
-
# @overload blue($color)
-
# @param $color [Color]
-
# @return [Number] The blue component, between 0 and 255 inclusive
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def blue(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.blue)
-
end
-
2
declare :blue, [:color]
-
-
# Returns the hue component of a color. See [the CSS3 HSL
-
# specification][hsl]. Calculated from RGB where necessary via [this
-
# algorithm][rgb-to-hsl].
-
#
-
# [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
# [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
#
-
# @overload hue($color)
-
# @param $color [Color]
-
# @return [Number] The hue component, between 0deg and 360deg
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def hue(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.hue, ["deg"])
-
end
-
2
declare :hue, [:color]
-
-
# Returns the saturation component of a color. See [the CSS3 HSL
-
# specification][hsl]. Calculated from RGB where necessary via [this
-
# algorithm][rgb-to-hsl].
-
#
-
# [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
# [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
#
-
# @overload saturation($color)
-
# @param $color [Color]
-
# @return [Number] The saturation component, between 0% and 100%
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def saturation(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.saturation, ["%"])
-
end
-
2
declare :saturation, [:color]
-
-
# Returns the lightness component of a color. See [the CSS3 HSL
-
# specification][hsl]. Calculated from RGB where necessary via [this
-
# algorithm][rgb-to-hsl].
-
#
-
# [hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
# [rgb-to-hsl]: http://en.wikipedia.org/wiki/HSL_and_HSV#Conversion_from_RGB_to_HSL_or_HSV
-
#
-
# @overload lightness($color)
-
# @param $color [Color]
-
# @return [Number] The lightness component, between 0% and 100%
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def lightness(color)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.lightness, ["%"])
-
end
-
2
declare :lightness, [:color]
-
-
# Returns the alpha component (opacity) of a color. This is 1 unless
-
# otherwise specified.
-
#
-
# This function also supports the proprietary Microsoft `alpha(opacity=20)`
-
# syntax as a special case.
-
#
-
# @overload alpha($color)
-
# @param $color [Color]
-
# @return [Number] The alpha component, between 0 and 1
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def alpha(*args)
-
if args.all? do |a|
-
a.is_a?(Sass::Script::String) && a.type == :identifier &&
-
a.value =~ /^[a-zA-Z]+\s*=/
-
end
-
# Support the proprietary MS alpha() function
-
return Sass::Script::String.new("alpha(#{args.map {|a| a.to_s}.join(", ")})")
-
end
-
-
raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size != 1
-
-
assert_type args.first, :Color, :color
-
Sass::Script::Number.new(args.first.alpha)
-
end
-
2
declare :alpha, [:color]
-
-
# Returns the alpha component (opacity) of a color. This is 1 unless
-
# otherwise specified.
-
#
-
# @overload opacity($color)
-
# @param $color [Color]
-
# @return [Number] The alpha component, between 0 and 1
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def opacity(color)
-
return Sass::Script::String.new("opacity(#{color})") if color.is_a?(Sass::Script::Number)
-
assert_type color, :Color, :color
-
Sass::Script::Number.new(color.alpha)
-
end
-
2
declare :opacity, [:color]
-
-
# Makes a color more opaque. Takes a color and a number between 0 and 1, and
-
# returns a color with the opacity increased by that amount.
-
#
-
# @see #transparentize
-
# @example
-
# opacify(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.6)
-
# opacify(rgba(0, 0, 17, 0.8), 0.2) => #001
-
# @overload opacify($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to increase the opacity by, between 0
-
# and 1
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
2
def opacify(color, amount)
-
_adjust(color, amount, :alpha, 0..1, :+)
-
end
-
2
declare :opacify, [:color, :amount]
-
-
2
alias_method :fade_in, :opacify
-
2
declare :fade_in, [:color, :amount]
-
-
# Makes a color more transparent. Takes a color and a number between 0 and
-
# 1, and returns a color with the opacity decreased by that amount.
-
#
-
# @see #opacify
-
# @example
-
# transparentize(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.4)
-
# transparentize(rgba(0, 0, 0, 0.8), 0.2) => rgba(0, 0, 0, 0.6)
-
# @overload transparentize($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to decrease the opacity by, between 0
-
# and 1
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
2
def transparentize(color, amount)
-
_adjust(color, amount, :alpha, 0..1, :-)
-
end
-
2
declare :transparentize, [:color, :amount]
-
-
2
alias_method :fade_out, :transparentize
-
2
declare :fade_out, [:color, :amount]
-
-
# Makes a color lighter. Takes a color and a number between `0%` and `100%`,
-
# and returns a color with the lightness increased by that amount.
-
#
-
# @see #darken
-
# @example
-
# lighten(hsl(0, 0%, 0%), 30%) => hsl(0, 0, 30)
-
# lighten(#800, 20%) => #e00
-
# @overload lighten($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to increase the lightness by, between
-
# `0%` and `100%`
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
2
def lighten(color, amount)
-
_adjust(color, amount, :lightness, 0..100, :+, "%")
-
end
-
2
declare :lighten, [:color, :amount]
-
-
# Makes a color darker. Takes a color and a number between 0% and 100%, and
-
# returns a color with the lightness decreased by that amount.
-
#
-
# @see #lighten
-
# @example
-
# darken(hsl(25, 100%, 80%), 30%) => hsl(25, 100%, 50%)
-
# darken(#800, 20%) => #200
-
# @overload darken($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to dencrease the lightness by, between
-
# `0%` and `100%`
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
2
def darken(color, amount)
-
_adjust(color, amount, :lightness, 0..100, :-, "%")
-
end
-
2
declare :darken, [:color, :amount]
-
-
# Makes a color more saturated. Takes a color and a number between 0% and
-
# 100%, and returns a color with the saturation increased by that amount.
-
#
-
# @see #desaturate
-
# @example
-
# saturate(hsl(120, 30%, 90%), 20%) => hsl(120, 50%, 90%)
-
# saturate(#855, 20%) => #9e3f3f
-
# @overload saturate($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to increase the saturation by, between
-
# `0%` and `100%`
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
2
def saturate(color, amount = nil)
-
# Support the filter effects definition of saturate.
-
# https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html
-
return Sass::Script::String.new("saturate(#{color})") if amount.nil?
-
_adjust(color, amount, :saturation, 0..100, :+, "%")
-
end
-
2
declare :saturate, [:color, :amount]
-
2
declare :saturate, [:amount]
-
-
# Makes a color less saturated. Takes a color and a number between 0% and
-
# 100%, and returns a color with the saturation decreased by that value.
-
#
-
# @see #saturate
-
# @example
-
# desaturate(hsl(120, 30%, 90%), 20%) => hsl(120, 10%, 90%)
-
# desaturate(#855, 20%) => #726b6b
-
# @overload desaturate($color, $amount)
-
# @param $color [Color]
-
# @param $amount [Number] The amount to decrease the saturation by, between
-
# `0%` and `100%`
-
# @return [Color]
-
# @raise [ArgumentError] if `$amount` is out of bounds, or either parameter
-
# is the wrong type
-
2
def desaturate(color, amount)
-
_adjust(color, amount, :saturation, 0..100, :-, "%")
-
end
-
2
declare :desaturate, [:color, :amount]
-
-
# Changes the hue of a color. Takes a color and a number of degrees (usually
-
# between `-360deg` and `360deg`), and returns a color with the hue rotated
-
# along the color wheel by that amount.
-
#
-
# @example
-
# adjust-hue(hsl(120, 30%, 90%), 60deg) => hsl(180, 30%, 90%)
-
# adjust-hue(hsl(120, 30%, 90%), 060deg) => hsl(60, 30%, 90%)
-
# adjust-hue(#811, 45deg) => #886a11
-
# @overload adjust_hue($color, $degrees)
-
# @param $color [Color]
-
# @param $degrees [Number] The number of degrees to rotate the hue
-
# @return [Color]
-
# @raise [ArgumentError] if either parameter is the wrong type
-
2
def adjust_hue(color, degrees)
-
assert_type color, :Color, :color
-
assert_type degrees, :Number, :degrees
-
color.with(:hue => color.hue + degrees.value)
-
end
-
2
declare :adjust_hue, [:color, :degrees]
-
-
# Converts a color into the format understood by IE filters.
-
#
-
# @example
-
# ie-hex-str(#abc) => #FFAABBCC
-
# ie-hex-str(#3322BB) => #FF3322BB
-
# ie-hex-str(rgba(0, 255, 0, 0.5)) => #8000FF00
-
# @overload ie_hex_str($color)
-
# @param $color [Color]
-
# @return [String] The IE-formatted string representation of the color
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def ie_hex_str(color)
-
assert_type color, :Color, :color
-
alpha = (color.alpha * 255).round.to_s(16).rjust(2, '0')
-
Sass::Script::String.new("##{alpha}#{color.send(:hex_str)[1..-1]}".upcase)
-
end
-
2
declare :ie_hex_str, [:color]
-
-
# Increases or decreases one or more properties of a color. This can change
-
# the red, green, blue, hue, saturation, value, and alpha properties. The
-
# properties are specified as keyword arguments, and are added to or
-
# subtracted from the color's current value for that property.
-
#
-
# All properties are optional. You can't specify both RGB properties
-
# (`$red`, `$green`, `$blue`) and HSL properties (`$hue`, `$saturation`,
-
# `$value`) at the same time.
-
#
-
# @example
-
# adjust-color(#102030, $blue: 5) => #102035
-
# adjust-color(#102030, $red: -5, $blue: 5) => #0b2035
-
# adjust-color(hsl(25, 100%, 80%), $lightness: -30%, $alpha: -0.4) => hsla(25, 100%, 50%, 0.6)
-
# @overload adjust_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
-
# @param $color [Color]
-
# @param $red [Number] The adjustment to make on the red component, between
-
# -255 and 255 inclusive
-
# @param $green [Number] The adjustment to make on the green component,
-
# between -255 and 255 inclusive
-
# @param $blue [Number] The adjustment to make on the blue component, between
-
# -255 and 255 inclusive
-
# @param $hue [Number] The adjustment to make on the hue component, in
-
# degrees
-
# @param $saturation [Number] The adjustment to make on the saturation
-
# component, between `-100%` and `100%` inclusive
-
# @param $lightness [Number] The adjustment to make on the lightness
-
# component, between `-100%` and `100%` inclusive
-
# @param $alpha [Number] The adjustment to make on the alpha component,
-
# between -1 and 1 inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out-of
-
# bounds, or if RGB properties and HSL properties are adjusted at the
-
# same time
-
2
def adjust_color(color, kwargs)
-
assert_type color, :Color, :color
-
with = Sass::Util.map_hash({
-
"red" => [-255..255, ""],
-
"green" => [-255..255, ""],
-
"blue" => [-255..255, ""],
-
"hue" => nil,
-
"saturation" => [-100..100, "%"],
-
"lightness" => [-100..100, "%"],
-
"alpha" => [-1..1, ""]
-
}) do |name, (range, units)|
-
-
next unless val = kwargs.delete(name)
-
assert_type val, :Number, name
-
Sass::Util.check_range("$#{name}: Amount", range, val, units) if range
-
adjusted = color.send(name) + val.value
-
adjusted = [0, Sass::Util.restrict(adjusted, range)].max if range
-
[name.to_sym, adjusted]
-
end
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
-
color.with(with)
-
end
-
2
declare :adjust_color, [:color], :var_kwargs => true
-
-
# Fluidly scales one or more properties of a color. Unlike
-
# \{#adjust_color adjust-color}, which changes a color's properties by fixed
-
# amounts, \{#scale_color scale-color} fluidly changes them based on how
-
# high or low they already are. That means that lightening an already-light
-
# color with \{#scale_color scale-color} won't change the lightness much,
-
# but lightening a dark color by the same amount will change it more
-
# dramatically. This has the benefit of making `scale-color($color, ...)`
-
# have a similar effect regardless of what `$color` is.
-
#
-
# For example, the lightness of a color can be anywhere between `0%` and
-
# `100%`. If `scale-color($color, $lightness: 40%)` is called, the resulting
-
# color's lightness will be 40% of the way between its original lightness
-
# and 100. If `scale-color($color, $lightness: -40%)` is called instead, the
-
# lightness will be 40% of the way between the original and 0.
-
#
-
# This can change the red, green, blue, saturation, value, and alpha
-
# properties. The properties are specified as keyword arguments. All
-
# arguments should be percentages between `0%` and `100%`.
-
#
-
# All properties are optional. You can't specify both RGB properties
-
# (`$red`, `$green`, `$blue`) and HSL properties (`$saturation`, `$value`)
-
# at the same time.
-
#
-
# @example
-
# scale-color(hsl(120, 70%, 80%), $lightness: 50%) => hsl(120, 70%, 90%)
-
# scale-color(rgb(200, 150%, 170%), $green: -40%, $blue: 70%) => rgb(200, 90, 229)
-
# scale-color(hsl(200, 70%, 80%), $saturation: -90%, $alpha: -30%) => hsla(200, 7%, 80%, 0.7)
-
# @overload scale_color($color, [$red], [$green], [$blue], [$saturation], [$lightness], [$alpha])
-
# @param $color [Color]
-
# @param $red [Number]
-
# @param $green [Number]
-
# @param $blue [Number]
-
# @param $saturation [Number]
-
# @param $lightness [Number]
-
# @param $alpha [Number]
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out-of
-
# bounds, or if RGB properties and HSL properties are adjusted at the
-
# same time
-
2
def scale_color(color, kwargs)
-
assert_type color, :Color, :color
-
with = Sass::Util.map_hash({
-
"red" => 255,
-
"green" => 255,
-
"blue" => 255,
-
"saturation" => 100,
-
"lightness" => 100,
-
"alpha" => 1
-
}) do |name, max|
-
-
next unless val = kwargs.delete(name)
-
assert_type val, :Number, name
-
if !(val.numerator_units == ['%'] && val.denominator_units.empty?)
-
raise ArgumentError.new("$#{name}: Amount #{val} must be a % (e.g. #{val.value}%)")
-
else
-
Sass::Util.check_range("$#{name}: Amount", -100..100, val, '%')
-
end
-
-
current = color.send(name)
-
scale = val.value/100.0
-
diff = scale > 0 ? max - current : current
-
[name.to_sym, current + diff*scale]
-
end
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
-
color.with(with)
-
end
-
2
declare :scale_color, [:color], :var_kwargs => true
-
-
# Changes one or more properties of a color. This can change the red, green,
-
# blue, hue, saturation, value, and alpha properties. The properties are
-
# specified as keyword arguments, and replace the color's current value for
-
# that property.
-
#
-
# All properties are optional. You can't specify both RGB properties
-
# (`$red`, `$green`, `$blue`) and HSL properties (`$hue`, `$saturation`,
-
# `$value`) at the same time.
-
#
-
# @example
-
# change-color(#102030, $blue: 5) => #102005
-
# change-color(#102030, $red: 120, $blue: 5) => #782005
-
# change-color(hsl(25, 100%, 80%), $lightness: 40%, $alpha: 0.8) => hsla(25, 100%, 40%, 0.8)
-
# @overload change_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
-
# @param $color [Color]
-
# @param $red [Number] The new red component for the color, within 0 and 255
-
# inclusive
-
# @param $green [Number] The new green component for the color, within 0 and
-
# 255 inclusive
-
# @param $blue [Number] The new blue component for the color, within 0 and
-
# 255 inclusive
-
# @param $hue [Number] The new hue component for the color, in degrees
-
# @param $saturation [Number] The new saturation component for the color,
-
# between `0%` and `100%` inclusive
-
# @param $lightness [Number] The new lightness component for the color,
-
# within `0%` and `100%` inclusive
-
# @param $alpha [Number] The new alpha component for the color, within 0 and
-
# 1 inclusive
-
# @return [Color]
-
# @raise [ArgumentError] if any parameter is the wrong type or out-of
-
# bounds, or if RGB properties and HSL properties are adjusted at the
-
# same time
-
2
def change_color(color, kwargs)
-
assert_type color, :Color, :color
-
with = Sass::Util.map_hash(%w[red green blue hue saturation lightness alpha]) do |name, max|
-
next unless val = kwargs.delete(name)
-
assert_type val, :Number, name
-
[name.to_sym, val.value]
-
end
-
-
unless kwargs.empty?
-
name, val = kwargs.to_a.first
-
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
-
end
-
-
color.with(with)
-
end
-
2
declare :change_color, [:color], :var_kwargs => true
-
-
# Mixes two colors together. Specifically, takes the average of each of the
-
# RGB components, optionally weighted by the given percentage. The opacity
-
# of the colors is also considered when weighting the components.
-
#
-
# The weight specifies the amount of the first color that should be included
-
# in the returned color. The default, `50%`, means that half the first color
-
# and half the second color should be used. `25%` means that a quarter of
-
# the first color and three quarters of the second color should be used.
-
#
-
# @example
-
# mix(#f00, #00f) => #7f007f
-
# mix(#f00, #00f, 25%) => #3f00bf
-
# mix(rgba(255, 0, 0, 0.5), #00f) => rgba(63, 0, 191, 0.75)
-
# @overload mix($color-1, $color-2, $weight: 50%)
-
# @param $color-1 [Color]
-
# @param $color-2 [Color]
-
# @param $weight [Number] The relative weight of each color. Closer to `0%`
-
# gives more weight to `$color`, closer to `100%` gives more weight to
-
# `$color2`
-
# @return [Color]
-
# @raise [ArgumentError] if `$weight` is out of bounds or any parameter is
-
# the wrong type
-
2
def mix(color_1, color_2, weight = Number.new(50))
-
assert_type color_1, :Color, :color_1
-
assert_type color_2, :Color, :color_2
-
assert_type weight, :Number, :weight
-
-
Sass::Util.check_range("Weight", 0..100, weight, '%')
-
-
# This algorithm factors in both the user-provided weight (w) and the
-
# difference between the alpha values of the two colors (a) to decide how
-
# to perform the weighted average of the two RGB values.
-
#
-
# It works by first normalizing both parameters to be within [-1, 1],
-
# where 1 indicates "only use color_1", -1 indicates "only use color_2", and
-
# all values in between indicated a proportionately weighted average.
-
#
-
# Once we have the normalized variables w and a, we apply the formula
-
# (w + a)/(1 + w*a) to get the combined weight (in [-1, 1]) of color_1.
-
# This formula has two especially nice properties:
-
#
-
# * When either w or a are -1 or 1, the combined weight is also that number
-
# (cases where w * a == -1 are undefined, and handled as a special case).
-
#
-
# * When a is 0, the combined weight is w, and vice versa.
-
#
-
# Finally, the weight of color_1 is renormalized to be within [0, 1]
-
# and the weight of color_2 is given by 1 minus the weight of color_1.
-
p = (weight.value/100.0).to_f
-
w = p*2 - 1
-
a = color_1.alpha - color_2.alpha
-
-
w1 = (((w * a == -1) ? w : (w + a)/(1 + w*a)) + 1)/2.0
-
w2 = 1 - w1
-
-
rgb = color_1.rgb.zip(color_2.rgb).map {|v1, v2| v1*w1 + v2*w2}
-
alpha = color_1.alpha*p + color_2.alpha*(1-p)
-
Color.new(rgb + [alpha])
-
end
-
2
declare :mix, [:color_1, :color_2]
-
2
declare :mix, [:color_1, :color_2, :weight]
-
-
# Converts a color to grayscale. This is identical to `desaturate(color,
-
# 100%)`.
-
#
-
# @see #desaturate
-
# @overload grayscale($color)
-
# @param $color [Color]
-
# @return [Color]
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def grayscale(color)
-
return Sass::Script::String.new("grayscale(#{color})") if color.is_a?(Sass::Script::Number)
-
desaturate color, Number.new(100)
-
end
-
2
declare :grayscale, [:color]
-
-
# Returns the complement of a color. This is identical to `adjust-hue(color,
-
# 180deg)`.
-
#
-
# @see #adjust_hue #adjust-hue
-
# @overload complement($color)
-
# @param $color [Color]
-
# @return [Color]
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def complement(color)
-
adjust_hue color, Number.new(180)
-
end
-
2
declare :complement, [:color]
-
-
# Returns the inverse (negative) of a color. The red, green, and blue values
-
# are inverted, while the opacity is left alone.
-
#
-
# @overload invert($color)
-
# @param $color [Color]
-
# @return [Color]
-
# @raise [ArgumentError] if `$color` isn't a color
-
2
def invert(color)
-
return Sass::Script::String.new("invert(#{color})") if color.is_a?(Sass::Script::Number)
-
-
assert_type color, :Color, :color
-
color.with(
-
:red => (255 - color.red),
-
:green => (255 - color.green),
-
:blue => (255 - color.blue))
-
end
-
2
declare :invert, [:color]
-
-
# Removes quotes from a string. If the string is already unquoted, this will
-
# return it unmodified.
-
#
-
# @see #quote
-
# @example
-
# unquote("foo") => foo
-
# unquote(foo) => foo
-
# @overload unquote($string)
-
# @param $string [String]
-
# @return [String]
-
# @raise [ArgumentError] if `$string` isn't a string
-
2
def unquote(string)
-
if string.is_a?(Sass::Script::String)
-
Sass::Script::String.new(string.value, :identifier)
-
else
-
string
-
end
-
end
-
2
declare :unquote, [:string]
-
-
# Add quotes to a string if the string isn't quoted,
-
# or returns the same string if it is.
-
#
-
# @see #unquote
-
# @example
-
# quote("foo") => "foo"
-
# quote(foo) => "foo"
-
# @overload quote($string)
-
# @param $string [String]
-
# @return [String]
-
# @raise [ArgumentError] if `$string` isn't a string
-
2
def quote(string)
-
assert_type string, :String, :string
-
Sass::Script::String.new(string.value, :string)
-
end
-
2
declare :quote, [:string]
-
-
# Returns the type of a value.
-
#
-
# @example
-
# type-of(100px) => number
-
# type-of(asdf) => string
-
# type-of("asdf") => string
-
# type-of(true) => bool
-
# type-of(#fff) => color
-
# type-of(blue) => color
-
# @overload type_of($value)
-
# @param $value [Literal] The value to inspect
-
# @return [String] The unquoted string name of the value's type
-
2
def type_of(value)
-
Sass::Script::String.new(value.class.name.gsub(/Sass::Script::/,'').downcase)
-
end
-
2
declare :type_of, [:value]
-
-
# Returns the unit(s) associated with a number. Complex units are sorted in
-
# alphabetical order by numerator and denominator.
-
#
-
# @example
-
# unit(100) => ""
-
# unit(100px) => "px"
-
# unit(3em) => "em"
-
# unit(10px * 5em) => "em*px"
-
# unit(10px * 5em / 30cm / 1rem) => "em*px/cm*rem"
-
# @overload unit($number)
-
# @param $number [Number]
-
# @return [String] The unit(s) of the number, as a quoted string
-
# @raise [ArgumentError] if `$number` isn't a number
-
2
def unit(number)
-
assert_type number, :Number, :number
-
Sass::Script::String.new(number.unit_str, :string)
-
end
-
2
declare :unit, [:number]
-
-
# Returns whether a number has units.
-
#
-
# @example
-
# unitless(100) => true
-
# unitless(100px) => false
-
# @overload unitless($number)
-
# @param $number [Number]
-
# @return [Bool]
-
# @raise [ArgumentError] if `$number` isn't a number
-
2
def unitless(number)
-
assert_type number, :Number, :number
-
Sass::Script::Bool.new(number.unitless?)
-
end
-
2
declare :unitless, [:number]
-
-
# Returns whether two numbers can added, subtracted, or compared.
-
#
-
# @example
-
# comparable(2px, 1px) => true
-
# comparable(100px, 3em) => false
-
# comparable(10cm, 3mm) => true
-
# @overload comparable($number-1, $number-2)
-
# @param $number-1 [Number]
-
# @param $number-2 [Number]
-
# @return [Bool]
-
# @raise [ArgumentError] if either parameter is the wrong type
-
2
def comparable(number_1, number_2)
-
assert_type number_1, :Number, :number_1
-
assert_type number_2, :Number, :number_2
-
Sass::Script::Bool.new(number_1.comparable_to?(number_2))
-
end
-
2
declare :comparable, [:number_1, :number_2]
-
-
# Converts a unitless number to a percentage.
-
#
-
# @example
-
# percentage(0.2) => 20%
-
# percentage(100px / 50px) => 200%
-
# @overload percentage($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a unitless number
-
2
def percentage(value)
-
unless value.is_a?(Sass::Script::Number) && value.unitless?
-
raise ArgumentError.new("$value: #{value.inspect} is not a unitless number")
-
end
-
Sass::Script::Number.new(value.value * 100, ['%'])
-
end
-
2
declare :percentage, [:value]
-
-
# Rounds a number to the nearest whole number.
-
#
-
# @example
-
# round(10.4px) => 10px
-
# round(10.6px) => 11px
-
# @overload round($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a number
-
2
def round(value)
-
numeric_transformation(value) {|n| n.round}
-
end
-
2
declare :round, [:value]
-
-
# Rounds a number up to the next whole number.
-
#
-
# @example
-
# ceil(10.4px) => 11px
-
# ceil(10.6px) => 11px
-
# @overload ceil($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a number
-
2
def ceil(value)
-
numeric_transformation(value) {|n| n.ceil}
-
end
-
2
declare :ceil, [:value]
-
-
# Rounds a number down to the previous whole number.
-
#
-
# @example
-
# floor(10.4px) => 10px
-
# floor(10.6px) => 10px
-
# @overload floor($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a number
-
2
def floor(value)
-
numeric_transformation(value) {|n| n.floor}
-
end
-
2
declare :floor, [:value]
-
-
# Returns the absolute value of a number.
-
#
-
# @example
-
# abs(10px) => 10px
-
# abs(-10px) => 10px
-
# @overload abs($value)
-
# @param $value [Number]
-
# @return [Number]
-
# @raise [ArgumentError] if `$value` isn't a number
-
2
def abs(value)
-
numeric_transformation(value) {|n| n.abs}
-
end
-
2
declare :abs, [:value]
-
-
# Finds the minimum of several numbers. This function takes any number of
-
# arguments.
-
#
-
# @example
-
# min(1px, 4px) => 1px
-
# min(5em, 3em, 4em) => 3em
-
# @overload min($numbers...)
-
# @param $numbers [[Number]]
-
# @return [Number]
-
# @raise [ArgumentError] if any argument isn't a number, or if not all of
-
# the arguments have comparable units
-
2
def min(*numbers)
-
numbers.each {|n| assert_type n, :Number}
-
numbers.inject {|min, num| min.lt(num).to_bool ? min : num}
-
end
-
2
declare :min, [], :var_args => :true
-
-
# Finds the maximum of several numbers. This function takes any number of
-
# arguments.
-
#
-
# @example
-
# max(1px, 4px) => 4px
-
# max(5em, 3em, 4em) => 5em
-
# @overload max($numbers...)
-
# @param $numbers [[Number]]
-
# @return [Number]
-
# @raise [ArgumentError] if any argument isn't a number, or if not all of
-
# the arguments have comparable units
-
2
def max(*values)
-
values.each {|v| assert_type v, :Number}
-
values.inject {|max, val| max.gt(val).to_bool ? max : val}
-
end
-
2
declare :max, [], :var_args => :true
-
-
# Return the length of a list.
-
#
-
# @example
-
# length(10px) => 1
-
# length(10px 20px 30px) => 3
-
# @overload length($list)
-
# @param $list [Literal]
-
# @return [Number]
-
2
def length(list)
-
Sass::Script::Number.new(list.to_a.size)
-
end
-
2
declare :length, [:list]
-
-
# Gets the nth item in a list.
-
#
-
# Note that unlike some languages, the first item in a Sass list is number
-
# 1, the second number 2, and so forth.
-
#
-
# @example
-
# nth(10px 20px 30px, 1) => 10px
-
# nth((Helvetica, Arial, sans-serif), 3) => sans-serif
-
# @overload nth($list, $n)
-
# @param $list [Literal]
-
# @param $n [Number] The index of the item to get
-
# @return [Literal]
-
# @raise [ArgumentError] if `$n` isn't an integer between 1 and the length
-
# of `$list`
-
2
def nth(list, n)
-
assert_type n, :Number, :n
-
if !n.int?
-
raise ArgumentError.new("List index #{n} must be an integer")
-
elsif n.to_i < 1
-
raise ArgumentError.new("List index #{n} must be greater than or equal to 1")
-
elsif list.to_a.size == 0
-
raise ArgumentError.new("List index is #{n} but list has no items")
-
elsif n.to_i > (size = list.to_a.size)
-
raise ArgumentError.new("List index is #{n} but list is only #{size} item#{'s' if size != 1} long")
-
end
-
-
list.to_a[n.to_i - 1]
-
end
-
2
declare :nth, [:list, :n]
-
-
# Joins together two lists into one.
-
#
-
# Unless `$separator` is passed, if one list is comma-separated and one is
-
# space-separated, the first parameter's separator is used for the resulting
-
# list. If both lists have fewer than two items, spaces are used for the
-
# resulting list.
-
#
-
# @example
-
# join(10px 20px, 30px 40px) => 10px 20px 30px 40px
-
# join((blue, red), (#abc, #def)) => blue, red, #abc, #def
-
# join(10px, 20px) => 10px 20px
-
# join(10px, 20px, comma) => 10px, 20px
-
# join((blue, red), (#abc, #def), space) => blue red #abc #def
-
# @overload join($list1, $list2, $separator: auto)
-
# @param $list1 [Literal]
-
# @param $list2 [Literal]
-
# @param $separator [String] The list separator to use. If this is `comma`
-
# or `space`, that separator will be used. If this is `auto` (the
-
# default), the separator is determined as explained above.
-
# @return [List]
-
2
def join(list1, list2, separator = Sass::Script::String.new("auto"))
-
assert_type separator, :String, :separator
-
unless %w[auto space comma].include?(separator.value)
-
raise ArgumentError.new("Separator name must be space, comma, or auto")
-
end
-
sep1 = list1.separator if list1.is_a?(Sass::Script::List) && !list1.value.empty?
-
sep2 = list2.separator if list2.is_a?(Sass::Script::List) && !list2.value.empty?
-
Sass::Script::List.new(
-
list1.to_a + list2.to_a,
-
if separator.value == 'auto'
-
sep1 || sep2 || :space
-
else
-
separator.value.to_sym
-
end)
-
end
-
2
declare :join, [:list1, :list2]
-
2
declare :join, [:list1, :list2, :separator]
-
-
# Appends a single value onto the end of a list.
-
#
-
# Unless the `$separator` argument is passed, if the list had only one item,
-
# the resulting list will be space-separated.
-
#
-
# @example
-
# append(10px 20px, 30px) => 10px 20px 30px
-
# append((blue, red), green) => blue, red, green
-
# append(10px 20px, 30px 40px) => 10px 20px (30px 40px)
-
# append(10px, 20px, comma) => 10px, 20px
-
# append((blue, red), green, space) => blue red green
-
# @overload append($list, $val, $separator: auto)
-
# @param $list [Literal]
-
# @param $val [Literal]
-
# @param $separator [String] The list separator to use. If this is `comma`
-
# or `space`, that separator will be used. If this is `auto` (the
-
# default), the separator is determined as explained above.
-
# @return [List]
-
2
def append(list, val, separator = Sass::Script::String.new("auto"))
-
assert_type separator, :String, :separator
-
unless %w[auto space comma].include?(separator.value)
-
raise ArgumentError.new("Separator name must be space, comma, or auto")
-
end
-
sep = list.separator if list.is_a?(Sass::Script::List)
-
Sass::Script::List.new(
-
list.to_a + [val],
-
if separator.value == 'auto'
-
sep || :space
-
else
-
separator.value.to_sym
-
end)
-
end
-
2
declare :append, [:list, :val]
-
2
declare :append, [:list, :val, :separator]
-
-
# Combines several lists into a single multidimensional list. The nth value
-
# of the resulting list is a space separated list of the source lists' nth
-
# values.
-
#
-
# The length of the resulting list is the length of the
-
# shortest list.
-
#
-
# @example
-
# zip(1px 1px 3px, solid dashed solid, red green blue)
-
# => 1px solid red, 1px dashed green, 3px solid blue
-
# @overload zip($lists...)
-
# @param $lists [[Literal]]
-
# @return [List]
-
2
def zip(*lists)
-
length = nil
-
values = []
-
lists.each do |list|
-
array = list.to_a
-
values << array.dup
-
length = length.nil? ? array.length : [length, array.length].min
-
end
-
values.each do |value|
-
value.slice!(length)
-
end
-
new_list_value = values.first.zip(*values[1..-1])
-
List.new(new_list_value.map{|list| List.new(list, :space)}, :comma)
-
end
-
2
declare :zip, [], :var_args => true
-
-
-
# Returns the position of a value within a list. If the value isn't found,
-
# returns false instead.
-
#
-
# Note that unlike some languages, the first item in a Sass list is number
-
# 1, the second number 2, and so forth.
-
#
-
# @example
-
# index(1px solid red, solid) => 2
-
# index(1px solid red, dashed) => false
-
# @overload index($list, $value)
-
# @param $list [Literal]
-
# @param $value [Literal]
-
# @return [Number, Bool] The 1-based index of `$value` in `$list`, or
-
# `false`
-
2
def index(list, value)
-
index = list.to_a.index {|e| e.eq(value).to_bool }
-
if index
-
Number.new(index + 1)
-
else
-
Bool.new(false)
-
end
-
end
-
2
declare :index, [:list, :value]
-
-
# Returns one of two values, depending on whether or not `$condition` is
-
# true. Just like in `@if`, all values other than `false` and `null` are
-
# considered to be true.
-
#
-
# @example
-
# if(true, 1px, 2px) => 1px
-
# if(false, 1px, 2px) => 2px
-
# @overload if($condition, $if-true, $if-false)
-
# @param $condition [Literal] Whether the `$if-true` or `$if-false` will be
-
# returned
-
# @param $if-true [Literal]
-
# @param $if-false [Literal]
-
# @return [Literal] `$if-true` or `$if-false`
-
2
def if(condition, if_true, if_false)
-
if condition.to_bool
-
if_true
-
else
-
if_false
-
end
-
end
-
2
declare :if, [:condition, :if_true, :if_false]
-
-
# This function only exists as a workaround for IE7's [`content: counter`
-
# bug][bug]. It works identically to any other plain-CSS function, except it
-
# avoids adding spaces between the argument commas.
-
#
-
# [bug]: http://jes.st/2013/ie7s-css-breaking-content-counter-bug/
-
#
-
# @example
-
# counter(item, ".") => counter(item,".")
-
# @overload counter($args...)
-
# @return [String]
-
2
def counter(*args)
-
Sass::Script::String.new("counter(#{args.map {|a| a.to_s(options)}.join(',')})")
-
end
-
2
declare :counter, [], :var_args => true
-
-
# This function only exists as a workaround for IE7's [`content: counters`
-
# bug][bug]. It works identically to any other plain-CSS function, except it
-
# avoids adding spaces between the argument commas.
-
#
-
# [bug]: http://jes.st/2013/ie7s-css-breaking-content-counter-bug/
-
#
-
# @example
-
# counters(item, ".") => counters(item,".")
-
# @overload counters($args...)
-
# @return [String]
-
2
def counters(*args)
-
Sass::Script::String.new("counters(#{args.map {|a| a.to_s(options)}.join(',')})")
-
end
-
2
declare :counters, [], :var_args => true
-
-
2
private
-
-
# This method implements the pattern of transforming a numeric value into
-
# another numeric value with the same units.
-
# It yields a number to a block to perform the operation and return a number
-
2
def numeric_transformation(value)
-
assert_type value, :Number, :value
-
Sass::Script::Number.new(yield(value.value), value.numerator_units, value.denominator_units)
-
end
-
-
2
def _adjust(color, amount, attr, range, op, units = "")
-
assert_type color, :Color, :color
-
assert_type amount, :Number, :amount
-
Sass::Util.check_range('Amount', range, amount, units)
-
-
# TODO: is it worth restricting here,
-
# or should we do so in the Color constructor itself,
-
# and allow clipping in rgb() et al?
-
color.with(attr => Sass::Util.restrict(
-
color.send(attr).send(op, amount.value), range))
-
end
-
end
-
end
-
2
module Sass::Script
-
# A SassScript object representing `#{}` interpolation outside a string.
-
#
-
# @see StringInterpolation
-
2
class Interpolation < Node
-
# Interpolation in a property is of the form `before #{mid} after`.
-
#
-
# @param before [Node] The SassScript before the interpolation
-
# @param mid [Node] The SassScript within the interpolation
-
# @param after [Node] The SassScript after the interpolation
-
# @param wb [Boolean] Whether there was whitespace between `before` and `#{`
-
# @param wa [Boolean] Whether there was whitespace between `}` and `after`
-
# @param originally_text [Boolean]
-
# Whether the original format of the interpolation was plain text,
-
# not an interpolation.
-
# This is used when converting back to SassScript.
-
2
def initialize(before, mid, after, wb, wa, originally_text = false)
-
@before = before
-
@mid = mid
-
@after = after
-
@whitespace_before = wb
-
@whitespace_after = wa
-
@originally_text = originally_text
-
end
-
-
# @return [String] A human-readable s-expression representation of the interpolation
-
2
def inspect
-
"(interpolation #{@before.inspect} #{@mid.inspect} #{@after.inspect})"
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
res = ""
-
res << @before.to_sass(opts) if @before
-
res << ' ' if @before && @whitespace_before
-
res << '#{' unless @originally_text
-
res << @mid.to_sass(opts)
-
res << '}' unless @originally_text
-
res << ' ' if @after && @whitespace_after
-
res << @after.to_sass(opts) if @after
-
res
-
end
-
-
# Returns the three components of the interpolation, `before`, `mid`, and `after`.
-
#
-
# @return [Array<Node>]
-
# @see #initialize
-
# @see Node#children
-
2
def children
-
[@before, @mid, @after].compact
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = dup
-
node.instance_variable_set('@before', @before.deep_copy) if @before
-
node.instance_variable_set('@mid', @mid.deep_copy)
-
node.instance_variable_set('@after', @after.deep_copy) if @after
-
node
-
end
-
-
2
protected
-
-
# Evaluates the interpolation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Sass::Script::String] The SassScript string that is the value of the interpolation
-
2
def _perform(environment)
-
res = ""
-
res << @before.perform(environment).to_s if @before
-
res << " " if @before && @whitespace_before
-
val = @mid.perform(environment)
-
res << (val.is_a?(Sass::Script::String) ? val.value : val.to_s)
-
res << " " if @after && @whitespace_after
-
res << @after.perform(environment).to_s if @after
-
opts(Sass::Script::String.new(res))
-
end
-
end
-
end
-
2
require 'sass/scss/rx'
-
-
2
module Sass
-
2
module Script
-
# The lexical analyzer for SassScript.
-
# It takes a raw string and converts it to individual tokens
-
# that are easier to parse.
-
2
class Lexer
-
2
include Sass::SCSS::RX
-
-
# A struct containing information about an individual token.
-
#
-
# `type`: \[`Symbol`\]
-
# : The type of token.
-
#
-
# `value`: \[`Object`\]
-
# : The Ruby object corresponding to the value of the token.
-
#
-
# `line`: \[`Fixnum`\]
-
# : The line of the source file on which the token appears.
-
#
-
# `offset`: \[`Fixnum`\]
-
# : The number of bytes into the line the SassScript token appeared.
-
#
-
# `pos`: \[`Fixnum`\]
-
# : The scanner position at which the SassScript token appeared.
-
2
Token = Struct.new(:type, :value, :line, :offset, :pos)
-
-
# The line number of the lexer's current position.
-
#
-
# @return [Fixnum]
-
2
attr_reader :line
-
-
# The number of bytes into the current line
-
# of the lexer's current position.
-
#
-
# @return [Fixnum]
-
2
attr_reader :offset
-
-
# A hash from operator strings to the corresponding token types.
-
2
OPERATORS = {
-
'+' => :plus,
-
'-' => :minus,
-
'*' => :times,
-
'/' => :div,
-
'%' => :mod,
-
'=' => :single_eq,
-
':' => :colon,
-
'(' => :lparen,
-
')' => :rparen,
-
',' => :comma,
-
'and' => :and,
-
'or' => :or,
-
'not' => :not,
-
'==' => :eq,
-
'!=' => :neq,
-
'>=' => :gte,
-
'<=' => :lte,
-
'>' => :gt,
-
'<' => :lt,
-
'#{' => :begin_interpolation,
-
'}' => :end_interpolation,
-
';' => :semicolon,
-
'{' => :lcurly,
-
'...' => :splat,
-
}
-
-
50
OPERATORS_REVERSE = Sass::Util.map_hash(OPERATORS) {|k, v| [v, k]}
-
-
50
TOKEN_NAMES = Sass::Util.map_hash(OPERATORS_REVERSE) {|k, v| [k, v.inspect]}.merge({
-
:const => "variable (e.g. $foo)",
-
:ident => "identifier (e.g. middle)",
-
:bool => "boolean (e.g. true, false)",
-
})
-
-
# A list of operator strings ordered with longer names first
-
# so that `>` and `<` don't clobber `>=` and `<=`.
-
50
OP_NAMES = OPERATORS.keys.sort_by {|o| -o.size}
-
-
# A sub-list of {OP_NAMES} that only includes operators
-
# with identifier names.
-
50
IDENT_OP_NAMES = OP_NAMES.select {|k, v| k =~ /^\w+/}
-
-
# A hash of regular expressions that are used for tokenizing.
-
2
REGULAR_EXPRESSIONS = {
-
:whitespace => /\s+/,
-
:comment => COMMENT,
-
:single_line_comment => SINGLE_LINE_COMMENT,
-
:variable => /(\$)(#{IDENT})/,
-
:ident => /(#{IDENT})(\()?/,
-
:number => /(-)?(?:(\d*\.\d+)|(\d+))([a-zA-Z%]+)?/,
-
:color => HEXCOLOR,
-
:bool => /(true|false)\b/,
-
:null => /null\b/,
-
6
:ident_op => %r{(#{Regexp.union(*IDENT_OP_NAMES.map{|s| Regexp.new(Regexp.escape(s) + "(?!#{NMCHAR}|\Z)")})})},
-
:op => %r{(#{Regexp.union(*OP_NAMES)})},
-
}
-
-
2
class << self
-
2
private
-
2
def string_re(open, close)
-
8
/#{open}((?:\\.|\#(?!\{)|[^#{close}\\#])*)(#{close}|#\{)/
-
end
-
end
-
-
# A hash of regular expressions that are used for tokenizing strings.
-
#
-
# The key is a `[Symbol, Boolean]` pair.
-
# The symbol represents which style of quotation to use,
-
# while the boolean represents whether or not the string
-
# is following an interpolated segment.
-
2
STRING_REGULAR_EXPRESSIONS = {
-
[:double, false] => string_re('"', '"'),
-
[:single, false] => string_re("'", "'"),
-
[:double, true] => string_re('', '"'),
-
[:single, true] => string_re('', "'"),
-
[:uri, false] => /url\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
[:uri, true] => /(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
# Defined in https://developer.mozilla.org/en/CSS/@-moz-document as a
-
# non-standard version of http://www.w3.org/TR/css3-conditional/
-
[:url_prefix, false] => /url-prefix\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
[:url_prefix, true] => /(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
[:domain, false] => /domain\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
[:domain, true] => /(#{URLCHAR}*?)(#{W}\)|#\{)/,
-
}
-
-
# @param str [String, StringScanner] The source text to lex
-
# @param line [Fixnum] The line on which the SassScript appears.
-
# Used for error reporting
-
# @param offset [Fixnum] The number of characters in on which the SassScript appears.
-
# Used for error reporting
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
2
def initialize(str, line, offset, options)
-
@scanner = str.is_a?(StringScanner) ? str : Sass::Util::MultibyteStringScanner.new(str)
-
@line = line
-
@offset = offset
-
@options = options
-
@interpolation_stack = []
-
@prev = nil
-
end
-
-
# Moves the lexer forward one token.
-
#
-
# @return [Token] The token that was moved past
-
2
def next
-
@tok ||= read_token
-
@tok, tok = nil, @tok
-
@prev = tok
-
return tok
-
end
-
-
# Returns whether or not there's whitespace before the next token.
-
#
-
# @return [Boolean]
-
2
def whitespace?(tok = @tok)
-
if tok
-
@scanner.string[0...tok.pos] =~ /\s\Z/
-
else
-
@scanner.string[@scanner.pos, 1] =~ /^\s/ ||
-
@scanner.string[@scanner.pos - 1, 1] =~ /\s\Z/
-
end
-
end
-
-
# Returns the next token without moving the lexer forward.
-
#
-
# @return [Token] The next token
-
2
def peek
-
@tok ||= read_token
-
end
-
-
# Rewinds the underlying StringScanner
-
# to before the token returned by \{#peek}.
-
2
def unpeek!
-
@scanner.pos = @tok.pos if @tok
-
end
-
-
# @return [Boolean] Whether or not there's more source text to lex.
-
2
def done?
-
whitespace unless after_interpolation? && @interpolation_stack.last
-
@scanner.eos? && @tok.nil?
-
end
-
-
# @return [Boolean] Whether or not the last token lexed was `:end_interpolation`.
-
2
def after_interpolation?
-
@prev && @prev.type == :end_interpolation
-
end
-
-
# Raise an error to the effect that `name` was expected in the input stream
-
# and wasn't found.
-
#
-
# This calls \{#unpeek!} to rewind the scanner to immediately after
-
# the last returned token.
-
#
-
# @param name [String] The name of the entity that was expected but not found
-
# @raise [Sass::SyntaxError]
-
2
def expected!(name)
-
unpeek!
-
Sass::SCSS::Parser.expected(@scanner, name, @line)
-
end
-
-
# Records all non-comment text the lexer consumes within the block
-
# and returns it as a string.
-
#
-
# @yield A block in which text is recorded
-
# @return [String]
-
2
def str
-
old_pos = @tok ? @tok.pos : @scanner.pos
-
yield
-
new_pos = @tok ? @tok.pos : @scanner.pos
-
@scanner.string[old_pos...new_pos]
-
end
-
-
2
private
-
-
2
def read_token
-
return if done?
-
return unless value = token
-
type, val, size = value
-
size ||= @scanner.matched_size
-
-
val.line = @line if val.is_a?(Script::Node)
-
Token.new(type, val, @line,
-
current_position - size, @scanner.pos - size)
-
end
-
-
2
def whitespace
-
nil while scan(REGULAR_EXPRESSIONS[:whitespace]) ||
-
scan(REGULAR_EXPRESSIONS[:comment]) ||
-
scan(REGULAR_EXPRESSIONS[:single_line_comment])
-
end
-
-
2
def token
-
if after_interpolation? && (interp_type = @interpolation_stack.pop)
-
return string(interp_type, true)
-
end
-
-
variable || string(:double, false) || string(:single, false) || number ||
-
color || bool || null || string(:uri, false) || raw(UNICODERANGE) ||
-
special_fun || special_val || ident_op || ident || op
-
end
-
-
2
def variable
-
_variable(REGULAR_EXPRESSIONS[:variable])
-
end
-
-
2
def _variable(rx)
-
return unless scan(rx)
-
-
[:const, @scanner[2]]
-
end
-
-
2
def ident
-
return unless scan(REGULAR_EXPRESSIONS[:ident])
-
[@scanner[2] ? :funcall : :ident, @scanner[1]]
-
end
-
-
2
def string(re, open)
-
return unless scan(STRING_REGULAR_EXPRESSIONS[[re, open]])
-
if @scanner[2] == '#{' #'
-
@scanner.pos -= 2 # Don't actually consume the #{
-
@interpolation_stack << re
-
end
-
str =
-
if re == :uri
-
Script::String.new("#{'url(' unless open}#{@scanner[1]}#{')' unless @scanner[2] == '#{'}")
-
else
-
Script::String.new(@scanner[1].gsub(/\\(['"]|\#\{)/, '\1'), :string)
-
end
-
[:string, str]
-
end
-
-
2
def number
-
return unless scan(REGULAR_EXPRESSIONS[:number])
-
value = @scanner[2] ? @scanner[2].to_f : @scanner[3].to_i
-
value = -value if @scanner[1]
-
[:number, Script::Number.new(value, Array(@scanner[4]))]
-
end
-
-
2
def color
-
return unless s = scan(REGULAR_EXPRESSIONS[:color])
-
raise Sass::SyntaxError.new(<<MESSAGE.rstrip) unless s.size == 4 || s.size == 7
-
Colors must have either three or six digits: '#{s}'
-
MESSAGE
-
value = s.scan(/^#(..?)(..?)(..?)$/).first.
-
map {|num| num.ljust(2, num).to_i(16)}
-
[:color, Script::Color.new(value)]
-
end
-
-
2
def bool
-
return unless s = scan(REGULAR_EXPRESSIONS[:bool])
-
[:bool, Script::Bool.new(s == 'true')]
-
end
-
-
2
def null
-
return unless scan(REGULAR_EXPRESSIONS[:null])
-
[:null, Script::Null.new]
-
end
-
-
2
def special_fun
-
return unless str1 = scan(/((-[\w-]+-)?(calc|element)|expression|progid:[a-z\.]*)\(/i)
-
str2, _ = Sass::Shared.balance(@scanner, ?(, ?), 1)
-
c = str2.count("\n")
-
old_line = @line
-
old_offset = @offset
-
@line += c
-
@offset = (c == 0 ? @offset + str2.size : str2[/\n(.*)/, 1].size)
-
[:special_fun,
-
Sass::Util.merge_adjacent_strings(
-
[str1] + Sass::Engine.parse_interp(str2, old_line, old_offset, @options)),
-
str1.size + str2.size]
-
end
-
-
2
def special_val
-
return unless scan(/!important/i)
-
[:string, Script::String.new("!important")]
-
end
-
-
2
def ident_op
-
return unless op = scan(REGULAR_EXPRESSIONS[:ident_op])
-
[OPERATORS[op]]
-
end
-
-
2
def op
-
return unless op = scan(REGULAR_EXPRESSIONS[:op])
-
@interpolation_stack << nil if op == :begin_interpolation
-
[OPERATORS[op]]
-
end
-
-
2
def raw(rx)
-
return unless val = scan(rx)
-
[:raw, val]
-
end
-
-
2
def scan(re)
-
return unless str = @scanner.scan(re)
-
c = str.count("\n")
-
@line += c
-
@offset = (c == 0 ? @offset + str.size : str[/\n(.*)/, 1].size)
-
str
-
end
-
-
2
def current_position
-
@offset + 1
-
end
-
end
-
end
-
end
-
2
module Sass::Script
-
# A SassScript object representing a CSS list.
-
# This includes both comma-separated lists and space-separated lists.
-
2
class List < Literal
-
# The Ruby array containing the contents of the list.
-
#
-
# @return [Array<Literal>]
-
2
attr_reader :value
-
2
alias_method :children, :value
-
2
alias_method :to_a, :value
-
-
# The operator separating the values of the list.
-
# Either `:comma` or `:space`.
-
#
-
# @return [Symbol]
-
2
attr_reader :separator
-
-
# Creates a new list.
-
#
-
# @param value [Array<Literal>] See \{#value}
-
# @param separator [String] See \{#separator}
-
2
def initialize(value, separator)
-
super(value)
-
@separator = separator
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = dup
-
node.instance_variable_set('@value', value.map {|c| c.deep_copy})
-
node
-
end
-
-
# @see Node#eq
-
2
def eq(other)
-
Sass::Script::Bool.new(
-
other.is_a?(List) && self.value == other.value &&
-
self.separator == other.separator)
-
end
-
-
# @see Node#to_s
-
2
def to_s(opts = {})
-
raise Sass::SyntaxError.new("() isn't a valid CSS value.") if value.empty?
-
return value.reject {|e| e.is_a?(Null) || e.is_a?(List) && e.value.empty?}.map {|e| e.to_s(opts)}.join(sep_str)
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
return "()" if value.empty?
-
precedence = Sass::Script::Parser.precedence_of(separator)
-
value.reject {|e| e.is_a?(Null)}.map do |v|
-
if v.is_a?(List) && Sass::Script::Parser.precedence_of(v.separator) <= precedence ||
-
separator == :space && v.is_a?(UnaryOperation) && (v.operator == :minus || v.operator == :plus)
-
"(#{v.to_sass(opts)})"
-
else
-
v.to_sass(opts)
-
end
-
end.join(sep_str(nil))
-
end
-
-
# @see Node#inspect
-
2
def inspect
-
"(#{to_sass})"
-
end
-
-
2
protected
-
-
# @see Node#_perform
-
2
def _perform(environment)
-
list = Sass::Script::List.new(
-
value.map {|e| e.perform(environment)},
-
separator)
-
list.options = self.options
-
list
-
end
-
-
2
private
-
-
2
def sep_str(opts = self.options)
-
return ' ' if separator == :space
-
return ',' if opts && opts[:style] == :compressed
-
return ', '
-
end
-
end
-
end
-
2
module Sass::Script
-
# The abstract superclass for SassScript objects.
-
#
-
# Many of these methods, especially the ones that correspond to SassScript operations,
-
# are designed to be overridden by subclasses which may change the semantics somewhat.
-
# The operations listed here are just the defaults.
-
2
class Literal < Node
-
2
require 'sass/script/string'
-
2
require 'sass/script/number'
-
2
require 'sass/script/color'
-
2
require 'sass/script/bool'
-
2
require 'sass/script/null'
-
2
require 'sass/script/list'
-
2
require 'sass/script/arg_list'
-
-
# Returns the Ruby value of the literal.
-
# The type of this value varies based on the subclass.
-
#
-
# @return [Object]
-
2
attr_reader :value
-
-
# Creates a new literal.
-
#
-
# @param value [Object] The object for \{#value}
-
2
def initialize(value = nil)
-
@value = value
-
super()
-
end
-
-
# Returns an empty array.
-
#
-
# @return [Array<Node>] empty
-
# @see Node#children
-
2
def children
-
[]
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
dup
-
end
-
-
# Returns the options hash for this node.
-
#
-
# @return [{Symbol => Object}]
-
# @raise [Sass::SyntaxError] if the options hash hasn't been set.
-
# This should only happen when the literal was created
-
# outside of the parser and \{#to\_s} was called on it
-
2
def options
-
opts = super
-
return opts if opts
-
raise Sass::SyntaxError.new(<<MSG)
-
The #options attribute is not set on this #{self.class}.
-
This error is probably occurring because #to_s was called
-
on this literal within a custom Sass function without first
-
setting the #option attribute.
-
MSG
-
end
-
-
# The SassScript `==` operation.
-
# **Note that this returns a {Sass::Script::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Bool] True if this literal is the same as the other,
-
# false otherwise
-
2
def eq(other)
-
Sass::Script::Bool.new(self.class == other.class && self.value == other.value)
-
end
-
-
# The SassScript `!=` operation.
-
# **Note that this returns a {Sass::Script::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Bool] False if this literal is the same as the other,
-
# true otherwise
-
2
def neq(other)
-
Sass::Script::Bool.new(!eq(other).to_bool)
-
end
-
-
# The SassScript `==` operation.
-
# **Note that this returns a {Sass::Script::Bool} object,
-
# not a Ruby boolean**.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Bool] True if this literal is the same as the other,
-
# false otherwise
-
2
def unary_not
-
Sass::Script::Bool.new(!to_bool)
-
end
-
-
# The SassScript `=` operation
-
# (used for proprietary MS syntax like `alpha(opacity=20)`).
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing both literals
-
# separated by `"="`
-
2
def single_eq(other)
-
Sass::Script::String.new("#{self.to_s}=#{other.to_s}")
-
end
-
-
# The SassScript `+` operation.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing both literals
-
# without any separation
-
2
def plus(other)
-
if other.is_a?(Sass::Script::String)
-
return Sass::Script::String.new(self.to_s + other.value, other.type)
-
end
-
Sass::Script::String.new(self.to_s + other.to_s)
-
end
-
-
# The SassScript `-` operation.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing both literals
-
# separated by `"-"`
-
2
def minus(other)
-
Sass::Script::String.new("#{self.to_s}-#{other.to_s}")
-
end
-
-
# The SassScript `/` operation.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing both literals
-
# separated by `"/"`
-
2
def div(other)
-
Sass::Script::String.new("#{self.to_s}/#{other.to_s}")
-
end
-
-
# The SassScript unary `+` operation (e.g. `+$a`).
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing the literal
-
# preceded by `"+"`
-
2
def unary_plus
-
Sass::Script::String.new("+#{self.to_s}")
-
end
-
-
# The SassScript unary `-` operation (e.g. `-$a`).
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing the literal
-
# preceded by `"-"`
-
2
def unary_minus
-
Sass::Script::String.new("-#{self.to_s}")
-
end
-
-
# The SassScript unary `/` operation (e.g. `/$a`).
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Script::String] A string containing the literal
-
# preceded by `"/"`
-
2
def unary_div
-
Sass::Script::String.new("/#{self.to_s}")
-
end
-
-
# @return [String] A readable representation of the literal
-
2
def inspect
-
value.inspect
-
end
-
-
# @return [Boolean] `true` (the Ruby boolean value)
-
2
def to_bool
-
true
-
end
-
-
# Compares this object with another.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this literal is equivalent to `other`
-
2
def ==(other)
-
eq(other).to_bool
-
end
-
-
# @return [Fixnum] The integer value of this literal
-
# @raise [Sass::SyntaxError] if this literal isn't an integer
-
2
def to_i
-
raise Sass::SyntaxError.new("#{self.inspect} is not an integer.")
-
end
-
-
# @raise [Sass::SyntaxError] if this literal isn't an integer
-
2
def assert_int!; to_i; end
-
-
# Returns the value of this literal as a list.
-
# Single literals are considered the same as single-element lists.
-
#
-
# @return [Array<Literal>] The of this literal as a list
-
2
def to_a
-
[self]
-
end
-
-
# Returns the string representation of this literal
-
# as it would be output to the CSS document.
-
#
-
# @return [String]
-
2
def to_s(opts = {})
-
raise Sass::SyntaxError.new("[BUG] All subclasses of Sass::Literal must implement #to_s.")
-
end
-
2
alias_method :to_sass, :to_s
-
-
# Returns whether or not this object is null.
-
#
-
# @return [Boolean] `false`
-
2
def null?
-
false
-
end
-
-
2
protected
-
-
# Evaluates the literal.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] This literal
-
2
def _perform(environment)
-
self
-
end
-
end
-
end
-
2
module Sass::Script
-
# The abstract superclass for SassScript parse tree nodes.
-
#
-
# Use \{#perform} to evaluate a parse tree.
-
2
class Node
-
# The options hash for this node.
-
#
-
# @return [{Symbol => Object}]
-
2
attr_reader :options
-
-
# The line of the document on which this node appeared.
-
#
-
# @return [Fixnum]
-
2
attr_accessor :line
-
-
# Sets the options hash for this node,
-
# as well as for all child nodes.
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
#
-
# @param options [{Symbol => Object}] The options
-
2
def options=(options)
-
@options = options
-
children.each do |c|
-
if c.is_a? Hash
-
c.values.each {|v| v.options = options }
-
else
-
c.options = options
-
end
-
end
-
end
-
-
# Evaluates the node.
-
#
-
# \{#perform} shouldn't be overridden directly;
-
# instead, override \{#\_perform}.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the SassScript
-
2
def perform(environment)
-
_perform(environment)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:line => line)
-
raise e
-
end
-
-
# Returns all child nodes of this node.
-
#
-
# @return [Array<Node>]
-
2
def children
-
Sass::Util.abstract(self)
-
end
-
-
# Returns the text of this SassScript expression.
-
#
-
# @return [String]
-
2
def to_sass(opts = {})
-
Sass::Util.abstract(self)
-
end
-
-
# Returns a deep clone of this node.
-
# The child nodes are cloned, but options are not.
-
#
-
# @return [Node]
-
2
def deep_copy
-
Sass::Util.abstract(self)
-
end
-
-
2
protected
-
-
# Converts underscores to dashes if the :dasherize option is set.
-
2
def dasherize(s, opts)
-
if opts[:dasherize]
-
s.gsub(/_/,'-')
-
else
-
s
-
end
-
end
-
-
# Evaluates this node.
-
# Note that all {Literal} objects created within this method
-
# should have their \{#options} attribute set, probably via \{#opts}.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the SassScript
-
# @see #perform
-
2
def _perform(environment)
-
Sass::Util.abstract(self)
-
end
-
-
# Sets the \{#options} field on the given literal and returns it
-
#
-
# @param literal [Literal]
-
# @return [Literal]
-
2
def opts(literal)
-
literal.options = options
-
literal
-
end
-
end
-
end
-
2
require 'sass/script/literal'
-
-
2
module Sass::Script
-
# A SassScript object representing a null value.
-
2
class Null < Literal
-
# Creates a new null literal.
-
2
def initialize
-
super nil
-
end
-
-
# @return [Boolean] `false` (the Ruby boolean value)
-
2
def to_bool
-
false
-
end
-
-
# @return [Boolean] `true`
-
2
def null?
-
true
-
end
-
-
# @return [String] '' (An empty string)
-
2
def to_s(opts = {})
-
''
-
end
-
-
2
def to_sass(opts = {})
-
'null'
-
end
-
-
# Returns a string representing a null value.
-
#
-
# @return [String]
-
2
def inspect
-
'null'
-
end
-
end
-
end
-
2
require 'sass/script/literal'
-
-
2
module Sass::Script
-
# A SassScript object representing a number.
-
# SassScript numbers can have decimal values,
-
# and can also have units.
-
# For example, `12`, `1px`, and `10.45em`
-
# are all valid values.
-
#
-
# Numbers can also have more complex units, such as `1px*em/in`.
-
# These cannot be inputted directly in Sass code at the moment.
-
2
class Number < Literal
-
# The Ruby value of the number.
-
#
-
# @return [Numeric]
-
2
attr_reader :value
-
-
# A list of units in the numerator of the number.
-
# For example, `1px*em/in*cm` would return `["px", "em"]`
-
# @return [Array<String>]
-
2
attr_reader :numerator_units
-
-
# A list of units in the denominator of the number.
-
# For example, `1px*em/in*cm` would return `["in", "cm"]`
-
# @return [Array<String>]
-
2
attr_reader :denominator_units
-
-
# The original representation of this number.
-
# For example, although the result of `1px/2px` is `0.5`,
-
# the value of `#original` is `"1px/2px"`.
-
#
-
# This is only non-nil when the original value should be used as the CSS value,
-
# as in `font: 1px/2px`.
-
#
-
# @return [Boolean, nil]
-
2
attr_accessor :original
-
-
2
def self.precision
-
@precision ||= 5
-
end
-
-
# Sets the number of digits of precision
-
# For example, if this is `3`,
-
# `3.1415926` will be printed as `3.142`.
-
2
def self.precision=(digits)
-
@precision = digits.round
-
@precision_factor = 10.0**@precision
-
end
-
-
# the precision factor used in numeric output
-
# it is derived from the `precision` method.
-
2
def self.precision_factor
-
@precision_factor ||= 10.0**precision
-
end
-
-
# Handles the deprecation warning for the PRECISION constant
-
# This can be removed in 3.2.
-
2
def self.const_missing(const)
-
if const == :PRECISION
-
Sass::Util.sass_warn("Sass::Script::Number::PRECISION is deprecated and will be removed in a future release. Use Sass::Script::Number.precision_factor instead.")
-
const_set(:PRECISION, self.precision_factor)
-
else
-
super
-
end
-
end
-
-
# Used so we don't allocate two new arrays for each new number.
-
2
NO_UNITS = []
-
-
# @param value [Numeric] The value of the number
-
# @param numerator_units [Array<String>] See \{#numerator\_units}
-
# @param denominator_units [Array<String>] See \{#denominator\_units}
-
2
def initialize(value, numerator_units = NO_UNITS, denominator_units = NO_UNITS)
-
super(value)
-
@numerator_units = numerator_units
-
@denominator_units = denominator_units
-
normalize!
-
end
-
-
# The SassScript `+` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Adds the two numbers together, converting units if possible.
-
#
-
# {Color}
-
# : Adds this number to each of the RGB color channels.
-
#
-
# {Literal}
-
# : See {Literal#plus}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Literal] The result of the operation
-
# @raise [Sass::UnitConversionError] if `other` is a number with incompatible units
-
2
def plus(other)
-
if other.is_a? Number
-
operate(other, :+)
-
elsif other.is_a?(Color)
-
other.plus(self)
-
else
-
super
-
end
-
end
-
-
# The SassScript binary `-` operation (e.g. `$a - $b`).
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Subtracts this number from the other, converting units if possible.
-
#
-
# {Literal}
-
# : See {Literal#minus}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Literal] The result of the operation
-
# @raise [Sass::UnitConversionError] if `other` is a number with incompatible units
-
2
def minus(other)
-
if other.is_a? Number
-
operate(other, :-)
-
else
-
super
-
end
-
end
-
-
# The SassScript unary `+` operation (e.g. `+$a`).
-
#
-
# @return [Number] The value of this number
-
2
def unary_plus
-
self
-
end
-
-
# The SassScript unary `-` operation (e.g. `-$a`).
-
#
-
# @return [Number] The negative value of this number
-
2
def unary_minus
-
Number.new(-value, @numerator_units, @denominator_units)
-
end
-
-
# The SassScript `*` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Multiplies the two numbers together, converting units appropriately.
-
#
-
# {Color}
-
# : Multiplies each of the RGB color channels by this number.
-
#
-
# @param other [Number, Color] The right-hand side of the operator
-
# @return [Number, Color] The result of the operation
-
# @raise [NoMethodError] if `other` is an invalid type
-
2
def times(other)
-
if other.is_a? Number
-
operate(other, :*)
-
elsif other.is_a? Color
-
other.times(self)
-
else
-
raise NoMethodError.new(nil, :times)
-
end
-
end
-
-
# The SassScript `/` operation.
-
# Its functionality depends on the type of its argument:
-
#
-
# {Number}
-
# : Divides this number by the other, converting units appropriately.
-
#
-
# {Literal}
-
# : See {Literal#div}.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Literal] The result of the operation
-
2
def div(other)
-
if other.is_a? Number
-
res = operate(other, :/)
-
if self.original && other.original
-
res.original = "#{self.original}/#{other.original}"
-
end
-
res
-
else
-
super
-
end
-
end
-
-
# The SassScript `%` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Number] This number modulo the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
# @raise [Sass::UnitConversionError] if `other` has any units
-
2
def mod(other)
-
if other.is_a?(Number)
-
unless other.unitless?
-
raise Sass::UnitConversionError.new("Cannot modulo by a number with units: #{other.inspect}.")
-
end
-
operate(other, :%)
-
else
-
raise NoMethodError.new(nil, :mod)
-
end
-
end
-
-
# The SassScript `==` operation.
-
#
-
# @param other [Literal] The right-hand side of the operator
-
# @return [Boolean] Whether this number is equal to the other object
-
2
def eq(other)
-
return Sass::Script::Bool.new(false) unless other.is_a?(Sass::Script::Number)
-
this = self
-
begin
-
if unitless?
-
this = this.coerce(other.numerator_units, other.denominator_units)
-
else
-
other = other.coerce(@numerator_units, @denominator_units)
-
end
-
rescue Sass::UnitConversionError
-
return Sass::Script::Bool.new(false)
-
end
-
-
Sass::Script::Bool.new(this.value == other.value)
-
end
-
-
# The SassScript `>` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is greater than the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
2
def gt(other)
-
raise NoMethodError.new(nil, :gt) unless other.is_a?(Number)
-
operate(other, :>)
-
end
-
-
# The SassScript `>=` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is greater than or equal to the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
2
def gte(other)
-
raise NoMethodError.new(nil, :gte) unless other.is_a?(Number)
-
operate(other, :>=)
-
end
-
-
# The SassScript `<` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is less than the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
2
def lt(other)
-
raise NoMethodError.new(nil, :lt) unless other.is_a?(Number)
-
operate(other, :<)
-
end
-
-
# The SassScript `<=` operation.
-
#
-
# @param other [Number] The right-hand side of the operator
-
# @return [Boolean] Whether this number is less than or equal to the other
-
# @raise [NoMethodError] if `other` is an invalid type
-
2
def lte(other)
-
raise NoMethodError.new(nil, :lte) unless other.is_a?(Number)
-
operate(other, :<=)
-
end
-
-
# @return [String] The CSS representation of this number
-
# @raise [Sass::SyntaxError] if this number has units that can't be used in CSS
-
# (e.g. `px*in`)
-
2
def to_s(opts = {})
-
return original if original
-
raise Sass::SyntaxError.new("#{inspect} isn't a valid CSS value.") unless legal_units?
-
inspect
-
end
-
-
# Returns a readable representation of this number.
-
#
-
# This representation is valid CSS (and valid SassScript)
-
# as long as there is only one unit.
-
#
-
# @return [String] The representation
-
2
def inspect(opts = {})
-
value = self.class.round(self.value)
-
unitless? ? value.to_s : "#{value}#{unit_str}"
-
end
-
2
alias_method :to_sass, :inspect
-
-
# @return [Fixnum] The integer value of the number
-
# @raise [Sass::SyntaxError] if the number isn't an integer
-
2
def to_i
-
super unless int?
-
return value
-
end
-
-
# @return [Boolean] Whether or not this number is an integer.
-
2
def int?
-
value % 1 == 0.0
-
end
-
-
# @return [Boolean] Whether or not this number has no units.
-
2
def unitless?
-
@numerator_units.empty? && @denominator_units.empty?
-
end
-
-
# @return [Boolean] Whether or not this number has units that can be represented in CSS
-
# (that is, zero or one \{#numerator\_units}).
-
2
def legal_units?
-
(@numerator_units.empty? || @numerator_units.size == 1) && @denominator_units.empty?
-
end
-
-
# Returns this number converted to other units.
-
# The conversion takes into account the relationship between e.g. mm and cm,
-
# as well as between e.g. in and cm.
-
#
-
# If this number has no units, it will simply return itself
-
# with the given units.
-
#
-
# An incompatible coercion, e.g. between px and cm, will raise an error.
-
#
-
# @param num_units [Array<String>] The numerator units to coerce this number into.
-
# See {\#numerator\_units}
-
# @param den_units [Array<String>] The denominator units to coerce this number into.
-
# See {\#denominator\_units}
-
# @return [Number] The number with the new units
-
# @raise [Sass::UnitConversionError] if the given units are incompatible with the number's
-
# current units
-
2
def coerce(num_units, den_units)
-
Number.new(if unitless?
-
self.value
-
else
-
self.value * coercion_factor(@numerator_units, num_units) /
-
coercion_factor(@denominator_units, den_units)
-
end, num_units, den_units)
-
end
-
-
# @param other [Number] A number to decide if it can be compared with this number.
-
# @return [Boolean] Whether or not this number can be compared with the other.
-
2
def comparable_to?(other)
-
begin
-
operate(other, :+)
-
true
-
rescue Sass::UnitConversionError
-
false
-
end
-
end
-
-
# Returns a human readable representation of the units in this number.
-
# For complex units this takes the form of:
-
# numerator_unit1 * numerator_unit2 / denominator_unit1 * denominator_unit2
-
# @return [String] a string that represents the units in this number
-
2
def unit_str
-
rv = @numerator_units.sort.join("*")
-
if @denominator_units.any?
-
rv << "/"
-
rv << @denominator_units.sort.join("*")
-
end
-
rv
-
end
-
-
2
private
-
-
# @private
-
2
def self.round(num)
-
if num.is_a?(Float) && (num.infinite? || num.nan?)
-
num
-
elsif num % 1 == 0.0
-
num.to_i
-
else
-
((num * self.precision_factor).round / self.precision_factor).to_f
-
end
-
end
-
-
2
OPERATIONS = [:+, :-, :<=, :<, :>, :>=]
-
-
2
def operate(other, operation)
-
this = self
-
if OPERATIONS.include?(operation)
-
if unitless?
-
this = this.coerce(other.numerator_units, other.denominator_units)
-
else
-
other = other.coerce(@numerator_units, @denominator_units)
-
end
-
end
-
# avoid integer division
-
value = (:/ == operation) ? this.value.to_f : this.value
-
result = value.send(operation, other.value)
-
-
if result.is_a?(Numeric)
-
Number.new(result, *compute_units(this, other, operation))
-
else # Boolean op
-
Bool.new(result)
-
end
-
end
-
-
2
def coercion_factor(from_units, to_units)
-
# get a list of unmatched units
-
from_units, to_units = sans_common_units(from_units, to_units)
-
-
if from_units.size != to_units.size || !convertable?(from_units | to_units)
-
raise Sass::UnitConversionError.new("Incompatible units: '#{from_units.join('*')}' and '#{to_units.join('*')}'.")
-
end
-
-
from_units.zip(to_units).inject(1) {|m,p| m * conversion_factor(p[0], p[1]) }
-
end
-
-
2
def compute_units(this, other, operation)
-
case operation
-
when :*
-
[this.numerator_units + other.numerator_units, this.denominator_units + other.denominator_units]
-
when :/
-
[this.numerator_units + other.denominator_units, this.denominator_units + other.numerator_units]
-
else
-
[this.numerator_units, this.denominator_units]
-
end
-
end
-
-
2
def normalize!
-
return if unitless?
-
@numerator_units, @denominator_units = sans_common_units(@numerator_units, @denominator_units)
-
-
@denominator_units.each_with_index do |d, i|
-
if convertable?(d) && (u = @numerator_units.detect(&method(:convertable?)))
-
@value /= conversion_factor(d, u)
-
@denominator_units.delete_at(i)
-
@numerator_units.delete_at(@numerator_units.index(u))
-
end
-
end
-
end
-
-
# A hash of unit names to their index in the conversion table
-
2
CONVERTABLE_UNITS = {"in" => 0, "cm" => 1, "pc" => 2, "mm" => 3, "pt" => 4, "px" => 5 }
-
2
CONVERSION_TABLE = [[ 1, 2.54, 6, 25.4, 72 , 96 ], # in
-
[ nil, 1, 2.36220473, 10, 28.3464567, 37.795275591], # cm
-
[ nil, nil, 1, 4.23333333, 12 , 16 ], # pc
-
[ nil, nil, nil, 1, 2.83464567, 3.7795275591], # mm
-
[ nil, nil, nil, nil, 1 , 1.3333333333], # pt
-
[ nil, nil, nil, nil, nil , 1 ]] # px
-
-
2
def conversion_factor(from_unit, to_unit)
-
res = CONVERSION_TABLE[CONVERTABLE_UNITS[from_unit]][CONVERTABLE_UNITS[to_unit]]
-
return 1.0 / conversion_factor(to_unit, from_unit) if res.nil?
-
res
-
end
-
-
2
def convertable?(units)
-
Array(units).all? {|u| CONVERTABLE_UNITS.include?(u)}
-
end
-
-
2
def sans_common_units(units1, units2)
-
units2 = units2.dup
-
# Can't just use -, because we want px*px to coerce properly to px*mm
-
return units1.map do |u|
-
next u unless j = units2.index(u)
-
units2.delete_at(j)
-
nil
-
end.compact, units2
-
end
-
end
-
end
-
2
require 'set'
-
2
require 'sass/script/string'
-
2
require 'sass/script/number'
-
2
require 'sass/script/color'
-
2
require 'sass/script/functions'
-
2
require 'sass/script/unary_operation'
-
2
require 'sass/script/interpolation'
-
2
require 'sass/script/string_interpolation'
-
-
2
module Sass::Script
-
# A SassScript parse node representing a binary operation,
-
# such as `$a + $b` or `"foo" + 1`.
-
2
class Operation < Node
-
2
attr_reader :operand1
-
2
attr_reader :operand2
-
2
attr_reader :operator
-
-
# @param operand1 [Script::Node] The parse-tree node
-
# for the right-hand side of the operator
-
# @param operand2 [Script::Node] The parse-tree node
-
# for the left-hand side of the operator
-
# @param operator [Symbol] The operator to perform.
-
# This should be one of the binary operator names in {Lexer::OPERATORS}
-
2
def initialize(operand1, operand2, operator)
-
@operand1 = operand1
-
@operand2 = operand2
-
@operator = operator
-
super()
-
end
-
-
# @return [String] A human-readable s-expression representation of the operation
-
2
def inspect
-
"(#{@operator.inspect} #{@operand1.inspect} #{@operand2.inspect})"
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
o1 = operand_to_sass @operand1, :left, opts
-
o2 = operand_to_sass @operand2, :right, opts
-
sep =
-
case @operator
-
when :comma; ", "
-
when :space; " "
-
else; " #{Lexer::OPERATORS_REVERSE[@operator]} "
-
end
-
"#{o1}#{sep}#{o2}"
-
end
-
-
# Returns the operands for this operation.
-
#
-
# @return [Array<Node>]
-
# @see Node#children
-
2
def children
-
[@operand1, @operand2]
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = dup
-
node.instance_variable_set('@operand1', @operand1.deep_copy)
-
node.instance_variable_set('@operand2', @operand2.deep_copy)
-
node
-
end
-
-
2
protected
-
-
# Evaluates the operation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the operation
-
# @raise [Sass::SyntaxError] if the operation is undefined for the operands
-
2
def _perform(environment)
-
literal1 = @operand1.perform(environment)
-
-
# Special-case :and and :or to support short-circuiting.
-
if @operator == :and
-
return literal1.to_bool ? @operand2.perform(environment) : literal1
-
elsif @operator == :or
-
return literal1.to_bool ? literal1 : @operand2.perform(environment)
-
end
-
-
literal2 = @operand2.perform(environment)
-
-
if (literal1.is_a?(Null) || literal2.is_a?(Null)) && @operator != :eq && @operator != :neq
-
raise Sass::SyntaxError.new("Invalid null operation: \"#{literal1.inspect} #{@operator} #{literal2.inspect}\".")
-
end
-
-
begin
-
opts(literal1.send(@operator, literal2))
-
rescue NoMethodError => e
-
raise e unless e.name.to_s == @operator.to_s
-
raise Sass::SyntaxError.new("Undefined operation: \"#{literal1} #{@operator} #{literal2}\".")
-
end
-
end
-
-
2
private
-
-
2
def operand_to_sass(op, side, opts)
-
return "(#{op.to_sass(opts)})" if op.is_a?(List)
-
return op.to_sass(opts) unless op.is_a?(Operation)
-
-
pred = Sass::Script::Parser.precedence_of(@operator)
-
sub_pred = Sass::Script::Parser.precedence_of(op.operator)
-
assoc = Sass::Script::Parser.associative?(@operator)
-
return "(#{op.to_sass(opts)})" if sub_pred < pred ||
-
(side == :right && sub_pred == pred && !assoc)
-
op.to_sass(opts)
-
end
-
end
-
end
-
2
require 'sass/script/lexer'
-
-
2
module Sass
-
2
module Script
-
# The parser for SassScript.
-
# It parses a string of code into a tree of {Script::Node}s.
-
2
class Parser
-
# The line number of the parser's current position.
-
#
-
# @return [Fixnum]
-
2
def line
-
@lexer.line
-
end
-
-
# @param str [String, StringScanner] The source text to parse
-
# @param line [Fixnum] The line on which the SassScript appears.
-
# Used for error reporting
-
# @param offset [Fixnum] The number of characters in on which the SassScript appears.
-
# Used for error reporting
-
# @param options [{Symbol => Object}] An options hash;
-
# see {file:SASS_REFERENCE.md#sass_options the Sass options documentation}
-
2
def initialize(str, line, offset, options = {})
-
@options = options
-
@lexer = lexer_class.new(str, line, offset, options)
-
end
-
-
# Parses a SassScript expression within an interpolated segment (`#{}`).
-
# This means that it stops when it comes across an unmatched `}`,
-
# which signals the end of an interpolated segment,
-
# it returns rather than throwing an error.
-
#
-
# @return [Script::Node] The root node of the parse tree
-
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
-
2
def parse_interpolated
-
expr = assert_expr :expr
-
assert_tok :end_interpolation
-
expr.options = @options
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses a SassScript expression.
-
#
-
# @return [Script::Node] The root node of the parse tree
-
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
-
2
def parse
-
expr = assert_expr :expr
-
assert_done
-
expr.options = @options
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses a SassScript expression,
-
# ending it when it encounters one of the given identifier tokens.
-
#
-
# @param [#include?(String)] A set of strings that delimit the expression.
-
# @return [Script::Node] The root node of the parse tree
-
# @raise [Sass::SyntaxError] if the expression isn't valid SassScript
-
2
def parse_until(tokens)
-
@stop_at = tokens
-
expr = assert_expr :expr
-
assert_done
-
expr.options = @options
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses the argument list for a mixin include.
-
#
-
# @return [(Array<Script::Node>, {String => Script::Node}, Script::Node)]
-
# The root nodes of the positional arguments, keyword arguments, and
-
# splat argument. Keyword arguments are in a hash from names to values.
-
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
-
2
def parse_mixin_include_arglist
-
args, keywords = [], {}
-
if try_tok(:lparen)
-
args, keywords, splat = mixin_arglist || [[], {}]
-
assert_tok(:rparen)
-
end
-
assert_done
-
-
args.each {|a| a.options = @options}
-
keywords.each {|k, v| v.options = @options}
-
splat.options = @options if splat
-
return args, keywords, splat
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses the argument list for a mixin definition.
-
#
-
# @return [(Array<Script::Node>, Script::Node)]
-
# The root nodes of the arguments, and the splat argument.
-
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
-
2
def parse_mixin_definition_arglist
-
args, splat = defn_arglist!(false)
-
assert_done
-
-
args.each do |k, v|
-
k.options = @options
-
v.options = @options if v
-
end
-
splat.options = @options if splat
-
return args, splat
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses the argument list for a function definition.
-
#
-
# @return [(Array<Script::Node>, Script::Node)]
-
# The root nodes of the arguments, and the splat argument.
-
# @raise [Sass::SyntaxError] if the argument list isn't valid SassScript
-
2
def parse_function_definition_arglist
-
args, splat = defn_arglist!(true)
-
assert_done
-
-
args.each do |k, v|
-
k.options = @options
-
v.options = @options if v
-
end
-
splat.options = @options if splat
-
return args, splat
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parse a single string value, possibly containing interpolation.
-
# Doesn't assert that the scanner is finished after parsing.
-
#
-
# @return [Script::Node] The root node of the parse tree.
-
# @raise [Sass::SyntaxError] if the string isn't valid SassScript
-
2
def parse_string
-
unless (peek = @lexer.peek) &&
-
(peek.type == :string ||
-
(peek.type == :funcall && peek.value.downcase == 'url'))
-
lexer.expected!("string")
-
end
-
-
expr = assert_expr :funcall
-
expr.options = @options
-
@lexer.unpeek!
-
expr
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace :line => @lexer.line, :filename => @options[:filename]
-
raise e
-
end
-
-
# Parses a SassScript expression.
-
#
-
# @overload parse(str, line, offset, filename = nil)
-
# @return [Script::Node] The root node of the parse tree
-
# @see Parser#initialize
-
# @see Parser#parse
-
2
def self.parse(*args)
-
new(*args).parse
-
end
-
-
2
PRECEDENCE = [
-
:comma, :single_eq, :space, :or, :and,
-
[:eq, :neq],
-
[:gt, :gte, :lt, :lte],
-
[:plus, :minus],
-
[:times, :div, :mod],
-
]
-
-
2
ASSOCIATIVE = [:plus, :times]
-
-
2
class << self
-
# Returns an integer representing the precedence
-
# of the given operator.
-
# A lower integer indicates a looser binding.
-
#
-
# @private
-
2
def precedence_of(op)
-
PRECEDENCE.each_with_index do |e, i|
-
return i if Array(e).include?(op)
-
end
-
raise "[BUG] Unknown operator #{op}"
-
end
-
-
# Returns whether or not the given operation is associative.
-
#
-
# @private
-
2
def associative?(op)
-
ASSOCIATIVE.include?(op)
-
end
-
-
2
private
-
-
# Defines a simple left-associative production.
-
# name is the name of the production,
-
# sub is the name of the production beneath it,
-
# and ops is a list of operators for this precedence level
-
2
def production(name, sub, *ops)
-
16
class_eval <<RUBY, __FILE__, __LINE__ + 1
-
def #{name}
-
interp = try_ops_after_interp(#{ops.inspect}, #{name.inspect}) and return interp
-
return unless e = #{sub}
-
30
while tok = try_tok(#{ops.map {|o| o.inspect}.join(', ')})
-
if interp = try_op_before_interp(tok, e)
-
return interp unless other_interp = try_ops_after_interp(#{ops.inspect}, #{name.inspect}, interp)
-
return other_interp
-
end
-
-
line = @lexer.line
-
e = Operation.new(e, assert_expr(#{sub.inspect}), tok.type)
-
e.line = line
-
end
-
e
-
end
-
RUBY
-
end
-
-
2
def unary(op, sub)
-
8
class_eval <<RUBY, __FILE__, __LINE__ + 1
-
def unary_#{op}
-
return #{sub} unless tok = try_tok(:#{op})
-
interp = try_op_before_interp(tok) and return interp
-
line = @lexer.line
-
op = UnaryOperation.new(assert_expr(:unary_#{op}), :#{op})
-
op.line = line
-
op
-
end
-
RUBY
-
end
-
end
-
-
2
private
-
-
# @private
-
2
def lexer_class; Lexer; end
-
-
2
def expr
-
line = @lexer.line
-
return unless e = interpolation
-
list = node(List.new([e], :comma), line)
-
while tok = try_tok(:comma)
-
if interp = try_op_before_interp(tok, list)
-
return interp unless other_interp = try_ops_after_interp([:comma], :expr, interp)
-
return other_interp
-
end
-
list.value << assert_expr(:interpolation)
-
end
-
list.value.size == 1 ? list.value.first : list
-
end
-
-
2
production :equals, :interpolation, :single_eq
-
-
2
def try_op_before_interp(op, prev = nil)
-
return unless @lexer.peek && @lexer.peek.type == :begin_interpolation
-
wb = @lexer.whitespace?(op)
-
str = Script::String.new(Lexer::OPERATORS_REVERSE[op.type])
-
str.line = @lexer.line
-
interp = Script::Interpolation.new(prev, str, nil, wb, !:wa, :originally_text)
-
interp.line = @lexer.line
-
interpolation(interp)
-
end
-
-
2
def try_ops_after_interp(ops, name, prev = nil)
-
return unless @lexer.after_interpolation?
-
return unless op = try_tok(*ops)
-
interp = try_op_before_interp(op, prev) and return interp
-
-
wa = @lexer.whitespace?
-
str = Script::String.new(Lexer::OPERATORS_REVERSE[op.type])
-
str.line = @lexer.line
-
interp = Script::Interpolation.new(prev, str, assert_expr(name), !:wb, wa, :originally_text)
-
interp.line = @lexer.line
-
return interp
-
end
-
-
2
def interpolation(first = space)
-
e = first
-
while interp = try_tok(:begin_interpolation)
-
wb = @lexer.whitespace?(interp)
-
line = @lexer.line
-
mid = parse_interpolated
-
wa = @lexer.whitespace?
-
e = Script::Interpolation.new(e, mid, space, wb, wa)
-
e.line = line
-
end
-
e
-
end
-
-
2
def space
-
line = @lexer.line
-
return unless e = or_expr
-
arr = [e]
-
while e = or_expr
-
arr << e
-
end
-
arr.size == 1 ? arr.first : node(List.new(arr, :space), line)
-
end
-
-
2
production :or_expr, :and_expr, :or
-
2
production :and_expr, :eq_or_neq, :and
-
2
production :eq_or_neq, :relational, :eq, :neq
-
2
production :relational, :plus_or_minus, :gt, :gte, :lt, :lte
-
2
production :plus_or_minus, :times_div_or_mod, :plus, :minus
-
2
production :times_div_or_mod, :unary_plus, :times, :div, :mod
-
-
2
unary :plus, :unary_minus
-
2
unary :minus, :unary_div
-
2
unary :div, :unary_not # For strings, so /foo/bar works
-
2
unary :not, :ident
-
-
2
def ident
-
return funcall unless @lexer.peek && @lexer.peek.type == :ident
-
return if @stop_at && @stop_at.include?(@lexer.peek.value)
-
-
name = @lexer.next
-
if color = Color::COLOR_NAMES[name.value.downcase]
-
return node(Color.new(color))
-
end
-
node(Script::String.new(name.value, :identifier))
-
end
-
-
2
def funcall
-
return raw unless tok = try_tok(:funcall)
-
args, keywords, splat = fn_arglist || [[], {}]
-
assert_tok(:rparen)
-
node(Script::Funcall.new(tok.value, args, keywords, splat))
-
end
-
-
2
def defn_arglist!(must_have_parens)
-
if must_have_parens
-
assert_tok(:lparen)
-
else
-
return [], nil unless try_tok(:lparen)
-
end
-
return [], nil if try_tok(:rparen)
-
-
res = []
-
splat = nil
-
must_have_default = false
-
loop do
-
c = assert_tok(:const)
-
var = Script::Variable.new(c.value)
-
if try_tok(:colon)
-
val = assert_expr(:space)
-
must_have_default = true
-
elsif must_have_default
-
raise SyntaxError.new("Required argument #{var.inspect} must come before any optional arguments.")
-
elsif try_tok(:splat)
-
splat = var
-
break
-
end
-
res << [var, val]
-
break unless try_tok(:comma)
-
end
-
assert_tok(:rparen)
-
return res, splat
-
end
-
-
2
def fn_arglist
-
arglist(:equals, "function argument")
-
end
-
-
2
def mixin_arglist
-
arglist(:interpolation, "mixin argument")
-
end
-
-
2
def arglist(subexpr, description)
-
return unless e = send(subexpr)
-
-
args = []
-
keywords = {}
-
loop do
-
if @lexer.peek && @lexer.peek.type == :colon
-
name = e
-
@lexer.expected!("comma") unless name.is_a?(Variable)
-
assert_tok(:colon)
-
value = assert_expr(subexpr, description)
-
-
if keywords[name.underscored_name]
-
raise SyntaxError.new("Keyword argument \"#{name.to_sass}\" passed more than once")
-
end
-
-
keywords[name.underscored_name] = value
-
else
-
if !keywords.empty?
-
raise SyntaxError.new("Positional arguments must come before keyword arguments.")
-
end
-
-
return args, keywords, e if try_tok(:splat)
-
args << e
-
end
-
-
return args, keywords unless try_tok(:comma)
-
e = assert_expr(subexpr, description)
-
end
-
end
-
-
2
def raw
-
return special_fun unless tok = try_tok(:raw)
-
node(Script::String.new(tok.value))
-
end
-
-
2
def special_fun
-
return paren unless tok = try_tok(:special_fun)
-
first = node(Script::String.new(tok.value.first))
-
Sass::Util.enum_slice(tok.value[1..-1], 2).inject(first) do |l, (i, r)|
-
Script::Interpolation.new(
-
l, i, r && node(Script::String.new(r)),
-
false, false)
-
end
-
end
-
-
2
def paren
-
return variable unless try_tok(:lparen)
-
was_in_parens = @in_parens
-
@in_parens = true
-
line = @lexer.line
-
e = expr
-
assert_tok(:rparen)
-
return e || node(List.new([], :space), line)
-
ensure
-
@in_parens = was_in_parens
-
end
-
-
2
def variable
-
return string unless c = try_tok(:const)
-
node(Variable.new(*c.value))
-
end
-
-
2
def string
-
return number unless first = try_tok(:string)
-
return first.value unless try_tok(:begin_interpolation)
-
line = @lexer.line
-
mid = parse_interpolated
-
last = assert_expr(:string)
-
interp = StringInterpolation.new(first.value, mid, last)
-
interp.line = line
-
interp
-
end
-
-
2
def number
-
return literal unless tok = try_tok(:number)
-
num = tok.value
-
num.original = num.to_s unless @in_parens
-
num
-
end
-
-
2
def literal
-
(t = try_tok(:color, :bool, :null)) && (return t.value)
-
end
-
-
# It would be possible to have unified #assert and #try methods,
-
# but detecting the method/token difference turns out to be quite expensive.
-
-
2
EXPR_NAMES = {
-
:string => "string",
-
:default => "expression (e.g. 1px, bold)",
-
:mixin_arglist => "mixin argument",
-
:fn_arglist => "function argument",
-
}
-
-
2
def assert_expr(name, expected = nil)
-
(e = send(name)) && (return e)
-
@lexer.expected!(expected || EXPR_NAMES[name] || EXPR_NAMES[:default])
-
end
-
-
2
def assert_tok(*names)
-
(t = try_tok(*names)) && (return t)
-
@lexer.expected!(names.map {|tok| Lexer::TOKEN_NAMES[tok] || tok}.join(" or "))
-
end
-
-
2
def try_tok(*names)
-
peeked = @lexer.peek
-
peeked && names.include?(peeked.type) && @lexer.next
-
end
-
-
2
def assert_done
-
return if @lexer.done?
-
@lexer.expected!(EXPR_NAMES[:default])
-
end
-
-
2
def node(node, line = @lexer.line)
-
node.line = line
-
node
-
end
-
end
-
end
-
end
-
2
require 'sass/script/literal'
-
-
2
module Sass::Script
-
# A SassScript object representing a CSS string *or* a CSS identifier.
-
2
class String < Literal
-
# The Ruby value of the string.
-
#
-
# @return [String]
-
2
attr_reader :value
-
-
# Whether this is a CSS string or a CSS identifier.
-
# The difference is that strings are written with double-quotes,
-
# while identifiers aren't.
-
#
-
# @return [Symbol] `:string` or `:identifier`
-
2
attr_reader :type
-
-
# Creates a new string.
-
#
-
# @param value [String] See \{#value}
-
# @param type [Symbol] See \{#type}
-
2
def initialize(value, type = :identifier)
-
super(value)
-
@type = type
-
end
-
-
# @see Literal#plus
-
2
def plus(other)
-
other_str = other.is_a?(Sass::Script::String) ? other.value : other.to_s
-
Sass::Script::String.new(self.value + other_str, self.type)
-
end
-
-
# @see Node#to_s
-
2
def to_s(opts = {})
-
if @type == :identifier
-
return @value.gsub(/\n\s*/, " ")
-
end
-
-
return "\"#{value.gsub('"', "\\\"")}\"" if opts[:quote] == %q{"}
-
return "'#{value.gsub("'", "\\'")}'" if opts[:quote] == %q{'}
-
return "\"#{value}\"" unless value.include?('"')
-
return "'#{value}'" unless value.include?("'")
-
"\"#{value.gsub('"', "\\\"")}\"" #'
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
to_s
-
end
-
end
-
end
-
2
module Sass::Script
-
# A SassScript object representing `#{}` interpolation within a string.
-
#
-
# @see Interpolation
-
2
class StringInterpolation < Node
-
# Interpolation in a string is of the form `"before #{mid} after"`,
-
# where `before` and `after` may include more interpolation.
-
#
-
# @param before [Node] The string before the interpolation
-
# @param mid [Node] The SassScript within the interpolation
-
# @param after [Node] The string after the interpolation
-
2
def initialize(before, mid, after)
-
@before = before
-
@mid = mid
-
@after = after
-
end
-
-
# @return [String] A human-readable s-expression representation of the interpolation
-
2
def inspect
-
"(string_interpolation #{@before.inspect} #{@mid.inspect} #{@after.inspect})"
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
# We can get rid of all of this when we remove the deprecated :equals context
-
# XXX CE: It's gone now but I'm not sure what can be removed now.
-
before_unquote, before_quote_char, before_str = parse_str(@before.to_sass(opts))
-
after_unquote, after_quote_char, after_str = parse_str(@after.to_sass(opts))
-
unquote = before_unquote || after_unquote ||
-
(before_quote_char && !after_quote_char && !after_str.empty?) ||
-
(!before_quote_char && after_quote_char && !before_str.empty?)
-
quote_char =
-
if before_quote_char && after_quote_char && before_quote_char != after_quote_char
-
before_str.gsub!("\\'", "'")
-
before_str.gsub!('"', "\\\"")
-
after_str.gsub!("\\'", "'")
-
after_str.gsub!('"', "\\\"")
-
'"'
-
else
-
before_quote_char || after_quote_char
-
end
-
-
res = ""
-
res << 'unquote(' if unquote
-
res << quote_char if quote_char
-
res << before_str
-
res << '#{' << @mid.to_sass(opts) << '}'
-
res << after_str
-
res << quote_char if quote_char
-
res << ')' if unquote
-
res
-
end
-
-
# Returns the three components of the interpolation, `before`, `mid`, and `after`.
-
#
-
# @return [Array<Node>]
-
# @see #initialize
-
# @see Node#children
-
2
def children
-
[@before, @mid, @after].compact
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = dup
-
node.instance_variable_set('@before', @before.deep_copy) if @before
-
node.instance_variable_set('@mid', @mid.deep_copy)
-
node.instance_variable_set('@after', @after.deep_copy) if @after
-
node
-
end
-
-
2
protected
-
-
# Evaluates the interpolation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Sass::Script::String] The SassScript string that is the value of the interpolation
-
2
def _perform(environment)
-
res = ""
-
before = @before.perform(environment)
-
res << before.value
-
mid = @mid.perform(environment)
-
res << (mid.is_a?(Sass::Script::String) ? mid.value : mid.to_s)
-
res << @after.perform(environment).value
-
opts(Sass::Script::String.new(res, before.type))
-
end
-
-
2
private
-
-
2
def parse_str(str)
-
case str
-
when /^unquote\((["'])(.*)\1\)$/
-
return true, $1, $2
-
when '""'
-
return false, nil, ""
-
when /^(["'])(.*)\1$/
-
return false, $1, $2
-
else
-
return false, nil, str
-
end
-
end
-
end
-
end
-
2
module Sass::Script
-
# A SassScript parse node representing a unary operation,
-
# such as `-$b` or `not true`.
-
#
-
# Currently only `-`, `/`, and `not` are unary operators.
-
2
class UnaryOperation < Node
-
# @return [Symbol] The operation to perform
-
2
attr_reader :operator
-
-
# @return [Script::Node] The parse-tree node for the object of the operator
-
2
attr_reader :operand
-
-
# @param operand [Script::Node] See \{#operand}
-
# @param operator [Symbol] See \{#operator}
-
2
def initialize(operand, operator)
-
@operand = operand
-
@operator = operator
-
super()
-
end
-
-
# @return [String] A human-readable s-expression representation of the operation
-
2
def inspect
-
"(#{@operator.inspect} #{@operand.inspect})"
-
end
-
-
# @see Node#to_sass
-
2
def to_sass(opts = {})
-
operand = @operand.to_sass(opts)
-
if @operand.is_a?(Operation) ||
-
(@operator == :minus &&
-
(operand =~ Sass::SCSS::RX::IDENT) == 0)
-
operand = "(#{@operand.to_sass(opts)})"
-
end
-
op = Lexer::OPERATORS_REVERSE[@operator]
-
op + (op =~ /[a-z]/ ? " " : "") + operand
-
end
-
-
# Returns the operand of the operation.
-
#
-
# @return [Array<Node>]
-
# @see Node#children
-
2
def children
-
[@operand]
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
node = dup
-
node.instance_variable_set('@operand', @operand.deep_copy)
-
node
-
end
-
-
2
protected
-
-
# Evaluates the operation.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the operation
-
# @raise [Sass::SyntaxError] if the operation is undefined for the operand
-
2
def _perform(environment)
-
operator = "unary_#{@operator}"
-
literal = @operand.perform(environment)
-
literal.send(operator)
-
rescue NoMethodError => e
-
raise e unless e.name.to_s == operator.to_s
-
raise Sass::SyntaxError.new("Undefined unary operation: \"#{@operator} #{literal}\".")
-
end
-
end
-
end
-
2
module Sass
-
2
module Script
-
# A SassScript parse node representing a variable.
-
2
class Variable < Node
-
# The name of the variable.
-
#
-
# @return [String]
-
2
attr_reader :name
-
-
# The underscored name of the variable.
-
#
-
# @return [String]
-
2
attr_reader :underscored_name
-
-
# @param name [String] See \{#name}
-
2
def initialize(name)
-
@name = name
-
@underscored_name = name.gsub(/-/,"_")
-
super()
-
end
-
-
# @return [String] A string representation of the variable
-
2
def inspect(opts = {})
-
"$#{dasherize(name, opts)}"
-
end
-
2
alias_method :to_sass, :inspect
-
-
# Returns an empty array.
-
#
-
# @return [Array<Node>] empty
-
# @see Node#children
-
2
def children
-
[]
-
end
-
-
# @see Node#deep_copy
-
2
def deep_copy
-
dup
-
end
-
-
2
protected
-
-
# Evaluates the variable.
-
#
-
# @param environment [Sass::Environment] The environment in which to evaluate the SassScript
-
# @return [Literal] The SassScript object that is the value of the variable
-
# @raise [Sass::SyntaxError] if the variable is undefined
-
2
def _perform(environment)
-
raise SyntaxError.new("Undefined variable: \"$#{name}\".") unless val = environment.var(name)
-
if val.is_a?(Number)
-
val = val.dup
-
val.original = nil
-
end
-
return val
-
end
-
end
-
end
-
end
-
2
require 'sass/scss/rx'
-
2
require 'sass/scss/script_lexer'
-
2
require 'sass/scss/script_parser'
-
2
require 'sass/scss/parser'
-
2
require 'sass/scss/static_parser'
-
2
require 'sass/scss/css_parser'
-
-
2
module Sass
-
# SCSS is the CSS syntax for Sass.
-
# It parses into the same syntax tree as Sass,
-
# and generates the same sort of output CSS.
-
#
-
# This module contains code for the parsing of SCSS.
-
# The evaluation is handled by the broader {Sass} module.
-
2
module SCSS; end
-
end
-
2
require 'sass/script/css_parser'
-
-
2
module Sass
-
2
module SCSS
-
# This is a subclass of {Parser} which only parses plain CSS.
-
# It doesn't support any Sass extensions, such as interpolation,
-
# parent references, nested selectors, and so forth.
-
# It does support all the same CSS hacks as the SCSS parser, though.
-
2
class CssParser < StaticParser
-
2
private
-
-
2
def placeholder_selector; nil; end
-
2
def parent_selector; nil; end
-
2
def interpolation; nil; end
-
2
def use_css_import?; true; end
-
-
2
def block_child(context)
-
case context
-
when :ruleset
-
declaration
-
when :stylesheet
-
directive || ruleset
-
when :directive
-
directive || declaration_or_ruleset
-
end
-
end
-
-
2
def nested_properties!(node, space)
-
expected('expression (e.g. 1px, bold)');
-
end
-
-
2
@sass_script_parser = Class.new(Sass::Script::CssParser)
-
2
@sass_script_parser.send(:include, ScriptParser)
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module Sass
-
2
module SCSS
-
# The parser for SCSS.
-
# It parses a string of code into a tree of {Sass::Tree::Node}s.
-
2
class Parser
-
# @param str [String, StringScanner] The source document to parse.
-
# Note that `Parser` *won't* raise a nice error message if this isn't properly parsed;
-
# for that, you should use the higher-level {Sass::Engine} or {Sass::CSS}.
-
# @param filename [String] The name of the file being parsed. Used for warnings.
-
# @param line [Fixnum] The line on which the source string appeared,
-
# if it's part of another document.
-
2
def initialize(str, filename, line = 1)
-
@template = str
-
@filename = filename
-
@line = line
-
@strs = []
-
end
-
-
# Parses an SCSS document.
-
#
-
# @return [Sass::Tree::RootNode] The root node of the document tree
-
# @raise [Sass::SyntaxError] if there's a syntax error in the document
-
2
def parse
-
init_scanner!
-
root = stylesheet
-
expected("selector or at-rule") unless @scanner.eos?
-
root
-
end
-
-
# Parses an identifier with interpolation.
-
# Note that this won't assert that the identifier takes up the entire input string;
-
# it's meant to be used with `StringScanner`s as part of other parsers.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
# The interpolated identifier, or nil if none could be parsed
-
2
def parse_interp_ident
-
init_scanner!
-
interp_ident
-
end
-
-
# Parses a media query list.
-
#
-
# @return [Sass::Media::QueryList] The parsed query list
-
# @raise [Sass::SyntaxError] if there's a syntax error in the query list,
-
# or if it doesn't take up the entire input string.
-
2
def parse_media_query_list
-
init_scanner!
-
ql = media_query_list
-
expected("media query list") unless @scanner.eos?
-
ql
-
end
-
-
# Parses a supports query condition.
-
#
-
# @return [Sass::Supports::Condition] The parsed condition
-
# @raise [Sass::SyntaxError] if there's a syntax error in the condition,
-
# or if it doesn't take up the entire input string.
-
2
def parse_supports_condition
-
init_scanner!
-
condition = supports_condition
-
expected("supports condition") unless @scanner.eos?
-
condition
-
end
-
-
2
private
-
-
2
include Sass::SCSS::RX
-
-
2
def init_scanner!
-
@scanner =
-
if @template.is_a?(StringScanner)
-
@template
-
else
-
Sass::Util::MultibyteStringScanner.new(@template.gsub("\r", ""))
-
end
-
end
-
-
2
def stylesheet
-
node = node(Sass::Tree::RootNode.new(@scanner.string))
-
block_contents(node, :stylesheet) {s(node)}
-
end
-
-
2
def s(node)
-
while tok(S) || tok(CDC) || tok(CDO) || (c = tok(SINGLE_LINE_COMMENT)) || (c = tok(COMMENT))
-
next unless c
-
process_comment c, node
-
c = nil
-
end
-
true
-
end
-
-
2
def ss
-
nil while tok(S) || tok(SINGLE_LINE_COMMENT) || tok(COMMENT)
-
true
-
end
-
-
2
def ss_comments(node)
-
while tok(S) || (c = tok(SINGLE_LINE_COMMENT)) || (c = tok(COMMENT))
-
next unless c
-
process_comment c, node
-
c = nil
-
end
-
-
true
-
end
-
-
2
def whitespace
-
return unless tok(S) || tok(SINGLE_LINE_COMMENT) || tok(COMMENT)
-
ss
-
end
-
-
2
def process_comment(text, node)
-
silent = text =~ /^\/\//
-
loud = !silent && text =~ %r{^/[/*]!}
-
line = @line - text.count("\n")
-
-
if silent
-
value = [text.sub(/^\s*\/\//, '/*').gsub(/^\s*\/\//, ' *') + ' */']
-
else
-
value = Sass::Engine.parse_interp(text, line, @scanner.pos - text.size, :filename => @filename)
-
value.unshift(@scanner.
-
string[0...@scanner.pos].
-
reverse[/.*?\*\/(.*?)($|\Z)/, 1].
-
reverse.gsub(/[^\s]/, ' '))
-
end
-
-
type = if silent then :silent elsif loud then :loud else :normal end
-
comment = Sass::Tree::CommentNode.new(value, type)
-
comment.line = line
-
node << comment
-
end
-
-
2
DIRECTIVES = Set[:mixin, :include, :function, :return, :debug, :warn, :for,
-
:each, :while, :if, :else, :extend, :import, :media, :charset, :content,
-
:_moz_document]
-
-
2
PREFIXED_DIRECTIVES = Set[:supports]
-
-
2
def directive
-
return unless tok(/@/)
-
name = tok!(IDENT)
-
ss
-
-
if dir = special_directive(name)
-
return dir
-
elsif dir = prefixed_directive(name)
-
return dir
-
end
-
-
# Most at-rules take expressions (e.g. @import),
-
# but some (e.g. @page) take selector-like arguments.
-
# Some take no arguments at all.
-
val = expr || selector
-
val = val ? ["@#{name} "] + Sass::Util.strip_string_array(val) : ["@#{name}"]
-
directive_body(val)
-
end
-
-
2
def directive_body(value)
-
node = node(Sass::Tree::DirectiveNode.new(value))
-
-
if tok(/\{/)
-
node.has_children = true
-
block_contents(node, :directive)
-
tok!(/\}/)
-
end
-
-
node
-
end
-
-
2
def special_directive(name)
-
sym = name.gsub('-', '_').to_sym
-
DIRECTIVES.include?(sym) && send("#{sym}_directive")
-
end
-
-
2
def prefixed_directive(name)
-
sym = name.gsub(/^-[a-z0-9]+-/i, '').gsub('-', '_').to_sym
-
PREFIXED_DIRECTIVES.include?(sym) && send("#{sym}_directive", name)
-
end
-
-
2
def mixin_directive
-
name = tok! IDENT
-
args, splat = sass_script(:parse_mixin_definition_arglist)
-
ss
-
block(node(Sass::Tree::MixinDefNode.new(name, args, splat)), :directive)
-
end
-
-
2
def include_directive
-
name = tok! IDENT
-
args, keywords, splat = sass_script(:parse_mixin_include_arglist)
-
ss
-
include_node = node(Sass::Tree::MixinNode.new(name, args, keywords, splat))
-
if tok?(/\{/)
-
include_node.has_children = true
-
block(include_node, :directive)
-
else
-
include_node
-
end
-
end
-
-
2
def content_directive
-
ss
-
node(Sass::Tree::ContentNode.new)
-
end
-
-
2
def function_directive
-
name = tok! IDENT
-
args, splat = sass_script(:parse_function_definition_arglist)
-
ss
-
block(node(Sass::Tree::FunctionNode.new(name, args, splat)), :function)
-
end
-
-
2
def return_directive
-
node(Sass::Tree::ReturnNode.new(sass_script(:parse)))
-
end
-
-
2
def debug_directive
-
node(Sass::Tree::DebugNode.new(sass_script(:parse)))
-
end
-
-
2
def warn_directive
-
node(Sass::Tree::WarnNode.new(sass_script(:parse)))
-
end
-
-
2
def for_directive
-
tok!(/\$/)
-
var = tok! IDENT
-
ss
-
-
tok!(/from/)
-
from = sass_script(:parse_until, Set["to", "through"])
-
ss
-
-
@expected = '"to" or "through"'
-
exclusive = (tok(/to/) || tok!(/through/)) == 'to'
-
to = sass_script(:parse)
-
ss
-
-
block(node(Sass::Tree::ForNode.new(var, from, to, exclusive)), :directive)
-
end
-
-
2
def each_directive
-
tok!(/\$/)
-
var = tok! IDENT
-
ss
-
-
tok!(/in/)
-
list = sass_script(:parse)
-
ss
-
-
block(node(Sass::Tree::EachNode.new(var, list)), :directive)
-
end
-
-
2
def while_directive
-
expr = sass_script(:parse)
-
ss
-
block(node(Sass::Tree::WhileNode.new(expr)), :directive)
-
end
-
-
2
def if_directive
-
expr = sass_script(:parse)
-
ss
-
node = block(node(Sass::Tree::IfNode.new(expr)), :directive)
-
pos = @scanner.pos
-
line = @line
-
ss
-
-
else_block(node) ||
-
begin
-
# Backtrack in case there are any comments we want to parse
-
@scanner.pos = pos
-
@line = line
-
node
-
end
-
end
-
-
2
def else_block(node)
-
return unless tok(/@else/)
-
ss
-
else_node = block(
-
Sass::Tree::IfNode.new((sass_script(:parse) if tok(/if/))),
-
:directive)
-
node.add_else(else_node)
-
pos = @scanner.pos
-
line = @line
-
ss
-
-
else_block(node) ||
-
begin
-
# Backtrack in case there are any comments we want to parse
-
@scanner.pos = pos
-
@line = line
-
node
-
end
-
end
-
-
2
def else_directive
-
err("Invalid CSS: @else must come after @if")
-
end
-
-
2
def extend_directive
-
selector = expr!(:selector_sequence)
-
optional = tok(OPTIONAL)
-
ss
-
node(Sass::Tree::ExtendNode.new(selector, !!optional))
-
end
-
-
2
def import_directive
-
values = []
-
-
loop do
-
values << expr!(:import_arg)
-
break if use_css_import?
-
break unless tok(/,/)
-
ss
-
end
-
-
return values
-
end
-
-
2
def import_arg
-
line = @line
-
return unless (str = tok(STRING)) || (uri = tok?(/url\(/i))
-
if uri
-
str = sass_script(:parse_string)
-
ss
-
media = media_query_list
-
ss
-
return node(Tree::CssImportNode.new(str, media.to_a))
-
end
-
-
path = @scanner[1] || @scanner[2]
-
ss
-
-
media = media_query_list
-
if path =~ /^(https?:)?\/\// || media || use_css_import?
-
node = Sass::Tree::CssImportNode.new(str, media.to_a)
-
else
-
node = Sass::Tree::ImportNode.new(path.strip)
-
end
-
node.line = line
-
node
-
end
-
-
2
def use_css_import?; false; end
-
-
2
def media_directive
-
block(node(Sass::Tree::MediaNode.new(expr!(:media_query_list).to_a)), :directive)
-
end
-
-
# http://www.w3.org/TR/css3-mediaqueries/#syntax
-
2
def media_query_list
-
return unless query = media_query
-
queries = [query]
-
-
ss
-
while tok(/,/)
-
ss; queries << expr!(:media_query)
-
end
-
ss
-
-
Sass::Media::QueryList.new(queries)
-
end
-
-
2
def media_query
-
if ident1 = interp_ident
-
ss
-
ident2 = interp_ident
-
ss
-
if ident2 && ident2.length == 1 && ident2[0].is_a?(String) && ident2[0].downcase == 'and'
-
query = Sass::Media::Query.new([], ident1, [])
-
else
-
if ident2
-
query = Sass::Media::Query.new(ident1, ident2, [])
-
else
-
query = Sass::Media::Query.new([], ident1, [])
-
end
-
return query unless tok(/and/i)
-
ss
-
end
-
end
-
-
if query
-
expr = expr!(:media_expr)
-
else
-
return unless expr = media_expr
-
end
-
query ||= Sass::Media::Query.new([], [], [])
-
query.expressions << expr
-
-
ss
-
while tok(/and/i)
-
ss; query.expressions << expr!(:media_expr)
-
end
-
-
query
-
end
-
-
2
def media_expr
-
interp = interpolation and return interp
-
return unless tok(/\(/)
-
res = ['(']
-
ss
-
res << sass_script(:parse)
-
-
if tok(/:/)
-
res << ': '
-
ss
-
res << sass_script(:parse)
-
end
-
res << tok!(/\)/)
-
ss
-
res
-
end
-
-
2
def charset_directive
-
tok! STRING
-
name = @scanner[1] || @scanner[2]
-
ss
-
node(Sass::Tree::CharsetNode.new(name))
-
end
-
-
# The document directive is specified in
-
# http://www.w3.org/TR/css3-conditional/, but Gecko allows the
-
# `url-prefix` and `domain` functions to omit quotation marks, contrary to
-
# the standard.
-
#
-
# We could parse all document directives according to Mozilla's syntax,
-
# but if someone's using e.g. @-webkit-document we don't want them to
-
# think WebKit works sans quotes.
-
2
def _moz_document_directive
-
res = ["@-moz-document "]
-
loop do
-
res << str{ss} << expr!(:moz_document_function)
-
break unless c = tok(/,/)
-
res << c
-
end
-
directive_body(res.flatten)
-
end
-
-
2
def moz_document_function
-
return unless val = interp_uri || _interp_string(:url_prefix) ||
-
_interp_string(:domain) || function(!:allow_var) || interpolation
-
ss
-
val
-
end
-
-
# http://www.w3.org/TR/css3-conditional/
-
2
def supports_directive(name)
-
condition = expr!(:supports_condition)
-
node = node(Sass::Tree::SupportsNode.new(name, condition))
-
-
tok!(/\{/)
-
node.has_children = true
-
block_contents(node, :directive)
-
tok!(/\}/)
-
-
node
-
end
-
-
2
def supports_condition
-
supports_negation || supports_operator || supports_interpolation
-
end
-
-
2
def supports_negation
-
return unless tok(/not/i)
-
ss
-
Sass::Supports::Negation.new(expr!(:supports_condition_in_parens))
-
end
-
-
2
def supports_operator
-
return unless cond = supports_condition_in_parens
-
return cond unless op = tok(/and|or/i)
-
begin
-
ss
-
cond = Sass::Supports::Operator.new(
-
cond, expr!(:supports_condition_in_parens), op)
-
end while op = tok(/and|or/i)
-
cond
-
end
-
-
2
def supports_condition_in_parens
-
interp = supports_interpolation and return interp
-
return unless tok(/\(/); ss
-
if cond = supports_condition
-
tok!(/\)/); ss
-
cond
-
else
-
name = sass_script(:parse)
-
tok!(/:/); ss
-
value = sass_script(:parse)
-
tok!(/\)/); ss
-
Sass::Supports::Declaration.new(name, value)
-
end
-
end
-
-
2
def supports_declaration_condition
-
return unless tok(/\(/); ss
-
supports_declaration_body
-
end
-
-
2
def supports_interpolation
-
return unless interp = interpolation
-
ss
-
Sass::Supports::Interpolation.new(interp)
-
end
-
-
2
def variable
-
return unless tok(/\$/)
-
name = tok!(IDENT)
-
ss; tok!(/:/); ss
-
-
expr = sass_script(:parse)
-
guarded = tok(DEFAULT)
-
node(Sass::Tree::VariableNode.new(name, expr, guarded))
-
end
-
-
2
def operator
-
# Many of these operators (all except / and ,)
-
# are disallowed by the CSS spec,
-
# but they're included here for compatibility
-
# with some proprietary MS properties
-
str {ss if tok(/[\/,:.=]/)}
-
end
-
-
2
def ruleset
-
return unless rules = selector_sequence
-
block(node(Sass::Tree::RuleNode.new(rules.flatten.compact)), :ruleset)
-
end
-
-
2
def block(node, context)
-
node.has_children = true
-
tok!(/\{/)
-
block_contents(node, context)
-
tok!(/\}/)
-
node
-
end
-
-
# A block may contain declarations and/or rulesets
-
2
def block_contents(node, context)
-
block_given? ? yield : ss_comments(node)
-
node << (child = block_child(context))
-
while tok(/;/) || has_children?(child)
-
block_given? ? yield : ss_comments(node)
-
node << (child = block_child(context))
-
end
-
node
-
end
-
-
2
def block_child(context)
-
return variable || directive if context == :function
-
return variable || directive || ruleset if context == :stylesheet
-
variable || directive || declaration_or_ruleset
-
end
-
-
2
def has_children?(child_or_array)
-
return false unless child_or_array
-
return child_or_array.last.has_children if child_or_array.is_a?(Array)
-
return child_or_array.has_children
-
end
-
-
# This is a nasty hack, and the only place in the parser
-
# that requires a large amount of backtracking.
-
# The reason is that we can't figure out if certain strings
-
# are declarations or rulesets with fixed finite lookahead.
-
# For example, "foo:bar baz baz baz..." could be either a property
-
# or a selector.
-
#
-
# To handle this, we simply check if it works as a property
-
# (which is the most common case)
-
# and, if it doesn't, try it as a ruleset.
-
#
-
# We could eke some more efficiency out of this
-
# by handling some easy cases (first token isn't an identifier,
-
# no colon after the identifier, whitespace after the colon),
-
# but I'm not sure the gains would be worth the added complexity.
-
2
def declaration_or_ruleset
-
old_use_property_exception, @use_property_exception =
-
@use_property_exception, false
-
decl_err = catch_error do
-
decl = declaration
-
unless decl && decl.has_children
-
# We want an exception if it's not there,
-
# but we don't want to consume if it is
-
tok!(/[;}]/) unless tok?(/[;}]/)
-
end
-
return decl
-
end
-
-
ruleset_err = catch_error {return ruleset}
-
rethrow(@use_property_exception ? decl_err : ruleset_err)
-
ensure
-
@use_property_exception = old_use_property_exception
-
end
-
-
2
def selector_sequence
-
if sel = tok(STATIC_SELECTOR, true)
-
return [sel]
-
end
-
-
rules = []
-
return unless v = selector
-
rules.concat v
-
-
ws = ''
-
while tok(/,/)
-
ws << str {ss}
-
if v = selector
-
rules << ',' << ws
-
rules.concat v
-
ws = ''
-
end
-
end
-
rules
-
end
-
-
2
def selector
-
return unless sel = _selector
-
sel.to_a
-
end
-
-
2
def selector_comma_sequence
-
return unless sel = _selector
-
selectors = [sel]
-
ws = ''
-
while tok(/,/)
-
ws << str{ss}
-
if sel = _selector
-
selectors << sel
-
selectors[-1] = Selector::Sequence.new(["\n"] + selectors.last.members) if ws.include?("\n")
-
ws = ''
-
end
-
end
-
Selector::CommaSequence.new(selectors)
-
end
-
-
2
def _selector
-
# The combinator here allows the "> E" hack
-
return unless val = combinator || simple_selector_sequence
-
nl = str{ss}.include?("\n")
-
res = []
-
res << val
-
res << "\n" if nl
-
-
while val = combinator || simple_selector_sequence
-
res << val
-
res << "\n" if str{ss}.include?("\n")
-
end
-
Selector::Sequence.new(res.compact)
-
end
-
-
2
def combinator
-
tok(PLUS) || tok(GREATER) || tok(TILDE) || reference_combinator
-
end
-
-
2
def reference_combinator
-
return unless tok(/\//)
-
res = ['/']
-
ns, name = expr!(:qualified_name)
-
res << ns << '|' if ns
-
res << name << tok!(/\//)
-
res = res.flatten
-
res = res.join '' if res.all? {|e| e.is_a?(String)}
-
res
-
end
-
-
2
def simple_selector_sequence
-
# Returning expr by default allows for stuff like
-
# http://www.w3.org/TR/css3-animations/#keyframes-
-
return expr(!:allow_var) unless e = element_name || id_selector ||
-
class_selector || placeholder_selector || attrib || pseudo ||
-
parent_selector || interpolation_selector
-
res = [e]
-
-
# The tok(/\*/) allows the "E*" hack
-
while v = id_selector || class_selector || placeholder_selector || attrib ||
-
pseudo || interpolation_selector ||
-
(tok(/\*/) && Selector::Universal.new(nil))
-
res << v
-
end
-
-
pos = @scanner.pos
-
line = @line
-
if sel = str? {simple_selector_sequence}
-
@scanner.pos = pos
-
@line = line
-
begin
-
# If we see "*E", don't force a throw because this could be the
-
# "*prop: val" hack.
-
expected('"{"') if res.length == 1 && res[0].is_a?(Selector::Universal)
-
throw_error {expected('"{"')}
-
rescue Sass::SyntaxError => e
-
e.message << "\n\n\"#{sel}\" may only be used at the beginning of a compound selector."
-
raise e
-
end
-
end
-
-
Selector::SimpleSequence.new(res, tok(/!/))
-
end
-
-
2
def parent_selector
-
return unless tok(/&/)
-
Selector::Parent.new
-
end
-
-
2
def class_selector
-
return unless tok(/\./)
-
@expected = "class name"
-
Selector::Class.new(merge(expr!(:interp_ident)))
-
end
-
-
2
def id_selector
-
return unless tok(/#(?!\{)/)
-
@expected = "id name"
-
Selector::Id.new(merge(expr!(:interp_name)))
-
end
-
-
2
def placeholder_selector
-
return unless tok(/%/)
-
@expected = "placeholder name"
-
Selector::Placeholder.new(merge(expr!(:interp_ident)))
-
end
-
-
2
def element_name
-
ns, name = Sass::Util.destructure(qualified_name(:allow_star_name))
-
return unless ns || name
-
-
if name == '*'
-
Selector::Universal.new(merge(ns))
-
else
-
Selector::Element.new(merge(name), merge(ns))
-
end
-
end
-
-
2
def qualified_name(allow_star_name=false)
-
return unless name = interp_ident || tok(/\*/) || (tok?(/\|/) && "")
-
return nil, name unless tok(/\|/)
-
-
return name, expr!(:interp_ident) unless allow_star_name
-
@expected = "identifier or *"
-
return name, interp_ident || tok!(/\*/)
-
end
-
-
2
def interpolation_selector
-
return unless script = interpolation
-
Selector::Interpolation.new(script)
-
end
-
-
2
def attrib
-
return unless tok(/\[/)
-
ss
-
ns, name = attrib_name!
-
ss
-
-
if op = tok(/=/) ||
-
tok(INCLUDES) ||
-
tok(DASHMATCH) ||
-
tok(PREFIXMATCH) ||
-
tok(SUFFIXMATCH) ||
-
tok(SUBSTRINGMATCH)
-
@expected = "identifier or string"
-
ss
-
val = interp_ident || expr!(:interp_string)
-
ss
-
end
-
flags = interp_ident || interp_string
-
tok!(/\]/)
-
-
Selector::Attribute.new(merge(name), merge(ns), op, merge(val), merge(flags))
-
end
-
-
2
def attrib_name!
-
if name_or_ns = interp_ident
-
# E, E|E
-
if tok(/\|(?!=)/)
-
ns = name_or_ns
-
name = interp_ident
-
else
-
name = name_or_ns
-
end
-
else
-
# *|E or |E
-
ns = [tok(/\*/) || ""]
-
tok!(/\|/)
-
name = expr!(:interp_ident)
-
end
-
return ns, name
-
end
-
-
2
def pseudo
-
return unless s = tok(/::?/)
-
@expected = "pseudoclass or pseudoelement"
-
name = expr!(:interp_ident)
-
if tok(/\(/)
-
ss
-
arg = expr!(:pseudo_arg)
-
while tok(/,/)
-
arg << ',' << str{ss}
-
arg.concat expr!(:pseudo_arg)
-
end
-
tok!(/\)/)
-
end
-
Selector::Pseudo.new(s == ':' ? :class : :element, merge(name), merge(arg))
-
end
-
-
2
def pseudo_arg
-
# In the CSS spec, every pseudo-class/element either takes a pseudo
-
# expression or a selector comma sequence as an argument. However, we
-
# don't want to have to know which takes which, so we handle both at
-
# once.
-
#
-
# However, there are some ambiguities between the two. For instance, "n"
-
# could start a pseudo expression like "n+1", or it could start a
-
# selector like "n|m". In order to handle this, we must regrettably
-
# backtrack.
-
expr, sel = nil, nil
-
pseudo_err = catch_error do
-
expr = pseudo_expr
-
next if tok?(/[,)]/)
-
expr = nil
-
expected '")"'
-
end
-
-
return expr if expr
-
sel_err = catch_error {sel = selector}
-
return sel if sel
-
rethrow pseudo_err if pseudo_err
-
rethrow sel_err if sel_err
-
return
-
end
-
-
2
def pseudo_expr
-
return unless e = tok(PLUS) || tok(/[-*]/) || tok(NUMBER) ||
-
interp_string || tok(IDENT) || interpolation
-
res = [e, str{ss}]
-
while e = tok(PLUS) || tok(/[-*]/) || tok(NUMBER) ||
-
interp_string || tok(IDENT) || interpolation
-
res << e << str{ss}
-
end
-
res
-
end
-
-
2
def declaration
-
# This allows the "*prop: val", ":prop: val", and ".prop: val" hacks
-
if s = tok(/[:\*\.]|\#(?!\{)/)
-
@use_property_exception = s !~ /[\.\#]/
-
name = [s, str{ss}, *expr!(:interp_ident)]
-
else
-
return unless name = interp_ident
-
name = [name] if name.is_a?(String)
-
end
-
if comment = tok(COMMENT)
-
name << comment
-
end
-
ss
-
-
tok!(/:/)
-
space, value = value!
-
ss
-
require_block = tok?(/\{/)
-
-
node = node(Sass::Tree::PropNode.new(name.flatten.compact, value, :new))
-
-
return node unless require_block
-
nested_properties! node, space
-
end
-
-
2
def value!
-
space = !str {ss}.empty?
-
@use_property_exception ||= space || !tok?(IDENT)
-
-
return true, Sass::Script::String.new("") if tok?(/\{/)
-
# This is a bit of a dirty trick:
-
# if the value is completely static,
-
# we don't parse it at all, and instead return a plain old string
-
# containing the value.
-
# This results in a dramatic speed increase.
-
if val = tok(STATIC_VALUE, true)
-
return space, Sass::Script::String.new(val.strip)
-
end
-
return space, sass_script(:parse)
-
end
-
-
2
def nested_properties!(node, space)
-
err(<<MESSAGE) unless space
-
Invalid CSS: a space is required between a property and its definition
-
when it has other properties nested beneath it.
-
MESSAGE
-
-
@use_property_exception = true
-
@expected = 'expression (e.g. 1px, bold) or "{"'
-
block(node, :property)
-
end
-
-
2
def expr(allow_var = true)
-
return unless t = term(allow_var)
-
res = [t, str{ss}]
-
-
while (o = operator) && (t = term(allow_var))
-
res << o << t << str{ss}
-
end
-
-
res.flatten
-
end
-
-
2
def term(allow_var)
-
if e = tok(NUMBER) ||
-
interp_uri ||
-
function(allow_var) ||
-
interp_string ||
-
tok(UNICODERANGE) ||
-
interp_ident ||
-
tok(HEXCOLOR) ||
-
(allow_var && var_expr)
-
return e
-
end
-
-
return unless op = tok(/[+-]/)
-
@expected = "number or function"
-
return [op, tok(NUMBER) || function(allow_var) ||
-
(allow_var && var_expr) || expr!(:interpolation)]
-
end
-
-
2
def function(allow_var)
-
return unless name = tok(FUNCTION)
-
if name == "expression(" || name == "calc("
-
str, _ = Sass::Shared.balance(@scanner, ?(, ?), 1)
-
[name, str]
-
else
-
[name, str{ss}, expr(allow_var), tok!(/\)/)]
-
end
-
end
-
-
2
def var_expr
-
return unless tok(/\$/)
-
line = @line
-
var = Sass::Script::Variable.new(tok!(IDENT))
-
var.line = line
-
var
-
end
-
-
2
def interpolation
-
return unless tok(INTERP_START)
-
sass_script(:parse_interpolated)
-
end
-
-
2
def interp_string
-
_interp_string(:double) || _interp_string(:single)
-
end
-
-
2
def interp_uri
-
_interp_string(:uri)
-
end
-
-
2
def _interp_string(type)
-
return unless start = tok(Sass::Script::Lexer::STRING_REGULAR_EXPRESSIONS[[type, false]])
-
res = [start]
-
-
mid_re = Sass::Script::Lexer::STRING_REGULAR_EXPRESSIONS[[type, true]]
-
# @scanner[2].empty? means we've started an interpolated section
-
while @scanner[2] == '#{'
-
@scanner.pos -= 2 # Don't consume the #{
-
res.last.slice!(-2..-1)
-
res << expr!(:interpolation) << tok(mid_re)
-
end
-
res
-
end
-
-
2
def interp_ident(start = IDENT)
-
return unless val = tok(start) || interpolation || tok(IDENT_HYPHEN_INTERP, true)
-
res = [val]
-
while val = tok(NAME) || interpolation
-
res << val
-
end
-
res
-
end
-
-
2
def interp_ident_or_var
-
(id = interp_ident) and return id
-
(var = var_expr) and return [var]
-
end
-
-
2
def interp_name
-
interp_ident NAME
-
end
-
-
2
def str
-
@strs.push ""
-
yield
-
@strs.last
-
ensure
-
@strs.pop
-
end
-
-
2
def str?
-
pos = @scanner.pos
-
line = @line
-
@strs.push ""
-
throw_error {yield} && @strs.last
-
rescue Sass::SyntaxError
-
@scanner.pos = pos
-
@line = line
-
nil
-
ensure
-
@strs.pop
-
end
-
-
2
def node(node)
-
node.line = @line
-
node
-
end
-
-
2
@sass_script_parser = Class.new(Sass::Script::Parser)
-
2
@sass_script_parser.send(:include, ScriptParser)
-
# @private
-
2
def self.sass_script_parser; @sass_script_parser; end
-
-
2
def sass_script(*args)
-
parser = self.class.sass_script_parser.new(@scanner, @line,
-
@scanner.pos - (@scanner.string[0...@scanner.pos].rindex("\n") || 0))
-
result = parser.send(*args)
-
unless @strs.empty?
-
# Convert to CSS manually so that comments are ignored.
-
src = result.to_sass
-
@strs.each {|s| s << src}
-
end
-
@line = parser.line
-
result
-
rescue Sass::SyntaxError => e
-
throw(:_sass_parser_error, true) if @throw_error
-
raise e
-
end
-
-
2
def merge(arr)
-
arr && Sass::Util.merge_adjacent_strings([arr].flatten)
-
end
-
-
2
EXPR_NAMES = {
-
:media_query => "media query (e.g. print, screen, print and screen)",
-
:media_query_list => "media query (e.g. print, screen, print and screen)",
-
:media_expr => "media expression (e.g. (min-device-width: 800px))",
-
:pseudo_arg => "expression (e.g. fr, 2n+1)",
-
:interp_ident => "identifier",
-
:interp_name => "identifier",
-
:qualified_name => "identifier",
-
:expr => "expression (e.g. 1px, bold)",
-
:_selector => "selector",
-
:selector_comma_sequence => "selector",
-
:simple_selector_sequence => "selector",
-
:import_arg => "file to import (string or url())",
-
:moz_document_function => "matching function (e.g. url-prefix(), domain())",
-
:supports_condition => "@supports condition (e.g. (display: flexbox))",
-
:supports_condition_in_parens => "@supports condition (e.g. (display: flexbox))",
-
}
-
-
2
TOK_NAMES = Sass::Util.to_hash(
-
104
Sass::SCSS::RX.constants.map {|c| [Sass::SCSS::RX.const_get(c), c.downcase]}).
-
merge(IDENT => "identifier", /[;}]/ => '";"')
-
-
2
def tok?(rx)
-
@scanner.match?(rx)
-
end
-
-
2
def expr!(name)
-
(e = send(name)) && (return e)
-
expected(EXPR_NAMES[name] || name.to_s)
-
end
-
-
2
def tok!(rx)
-
(t = tok(rx)) && (return t)
-
name = TOK_NAMES[rx]
-
-
unless name
-
# Display basic regexps as plain old strings
-
string = rx.source.gsub(/\\(.)/, '\1')
-
name = rx.source == Regexp.escape(string) ? string.inspect : rx.inspect
-
end
-
-
expected(name)
-
end
-
-
2
def expected(name)
-
throw(:_sass_parser_error, true) if @throw_error
-
self.class.expected(@scanner, @expected || name, @line)
-
end
-
-
2
def err(msg)
-
throw(:_sass_parser_error, true) if @throw_error
-
raise Sass::SyntaxError.new(msg, :line => @line)
-
end
-
-
2
def throw_error
-
old_throw_error, @throw_error = @throw_error, false
-
yield
-
ensure
-
@throw_error = old_throw_error
-
end
-
-
2
def catch_error(&block)
-
old_throw_error, @throw_error = @throw_error, true
-
pos = @scanner.pos
-
line = @line
-
expected = @expected
-
if catch(:_sass_parser_error) {yield; false}
-
@scanner.pos = pos
-
@line = line
-
@expected = expected
-
{:pos => pos, :line => line, :expected => @expected, :block => block}
-
end
-
ensure
-
@throw_error = old_throw_error
-
end
-
-
2
def rethrow(err)
-
if @throw_error
-
throw :_sass_parser_error, err
-
else
-
@scanner = Sass::Util::MultibyteStringScanner.new(@scanner.string)
-
@scanner.pos = err[:pos]
-
@line = err[:line]
-
@expected = err[:expected]
-
err[:block].call
-
end
-
end
-
-
# @private
-
2
def self.expected(scanner, expected, line)
-
pos = scanner.pos
-
-
after = scanner.string[0...pos]
-
# Get rid of whitespace between pos and the last token,
-
# but only if there's a newline in there
-
after.gsub!(/\s*\n\s*$/, '')
-
# Also get rid of stuff before the last newline
-
after.gsub!(/.*\n/, '')
-
after = "..." + after[-15..-1] if after.size > 18
-
-
was = scanner.rest.dup
-
# Get rid of whitespace between pos and the next token,
-
# but only if there's a newline in there
-
was.gsub!(/^\s*\n\s*/, '')
-
# Also get rid of stuff after the next newline
-
was.gsub!(/\n.*/, '')
-
was = was[0...15] + "..." if was.size > 18
-
-
raise Sass::SyntaxError.new(
-
"Invalid CSS after \"#{after}\": expected #{expected}, was \"#{was}\"",
-
:line => line)
-
end
-
-
# Avoid allocating lots of new strings for `#tok`.
-
# This is important because `#tok` is called all the time.
-
2
NEWLINE = "\n"
-
-
2
def tok(rx, last_group_lookahead = false)
-
res = @scanner.scan(rx)
-
if res
-
# This fixes https://github.com/nex3/sass/issues/104, which affects
-
# Ruby 1.8.7 and REE. This fix is to replace the ?= zero-width
-
# positive lookahead operator in the Regexp (which matches without
-
# consuming the matched group), with a match that does consume the
-
# group, but then rewinds the scanner and removes the group from the
-
# end of the matched string. This fix makes the assumption that the
-
# matched group will always occur at the end of the match.
-
if last_group_lookahead && @scanner[-1]
-
@scanner.pos -= @scanner[-1].length
-
res.slice!(-@scanner[-1].length..-1)
-
end
-
@line += res.count(NEWLINE)
-
@expected = nil
-
if !@strs.empty? && rx != COMMENT && rx != SINGLE_LINE_COMMENT
-
@strs.each {|s| s << res}
-
end
-
res
-
end
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module SCSS
-
# A module containing regular expressions used
-
# for lexing tokens in an SCSS document.
-
# Most of these are taken from [the CSS3 spec](http://www.w3.org/TR/css3-syntax/#lexical),
-
# although some have been modified for various reasons.
-
2
module RX
-
# Takes a string and returns a CSS identifier
-
# that will have the value of the given string.
-
#
-
# @param str [String] The string to escape
-
# @return [String] The escaped string
-
2
def self.escape_ident(str)
-
return "" if str.empty?
-
return "\\#{str}" if str == '-' || str == '_'
-
out = ""
-
value = str.dup
-
out << value.slice!(0...1) if value =~ /^[-_]/
-
if value[0...1] =~ NMSTART
-
out << value.slice!(0...1)
-
else
-
out << escape_char(value.slice!(0...1))
-
end
-
out << value.gsub(/[^a-zA-Z0-9_-]/) {|c| escape_char c}
-
return out
-
end
-
-
# Escapes a single character for a CSS identifier.
-
#
-
# @param c [String] The character to escape. Should have length 1
-
# @return [String] The escaped character
-
# @private
-
2
def self.escape_char(c)
-
return "\\%06x" % Sass::Util.ord(c) unless c =~ /[ -\/:-~]/
-
return "\\#{c}"
-
end
-
-
# Creates a Regexp from a plain text string,
-
# escaping all significant characters.
-
#
-
# @param str [String] The text of the regexp
-
# @param flags [Fixnum] Flags for the created regular expression
-
# @return [Regexp]
-
# @private
-
2
def self.quote(str, flags = 0)
-
16
Regexp.new(Regexp.quote(str), flags)
-
end
-
-
2
H = /[0-9a-fA-F]/
-
2
NL = /\n|\r\n|\r|\f/
-
2
UNICODE = /\\#{H}{1,6}[ \t\r\n\f]?/
-
2
s = if Sass::Util.ruby1_8?
-
'\200-\377'
-
elsif Sass::Util.macruby?
-
'\u0080-\uD7FF\uE000-\uFFFD\U00010000-\U0010FFFF'
-
else
-
2
'\u{80}-\u{D7FF}\u{E000}-\u{FFFD}\u{10000}-\u{10FFFF}'
-
end
-
2
NONASCII = /[#{s}]/
-
2
ESCAPE = /#{UNICODE}|\\[ -~#{s}]/
-
2
NMSTART = /[_a-zA-Z]|#{NONASCII}|#{ESCAPE}/
-
2
NMCHAR = /[a-zA-Z0-9_-]|#{NONASCII}|#{ESCAPE}/
-
2
STRING1 = /\"((?:[^\n\r\f\\"]|\\#{NL}|#{ESCAPE})*)\"/
-
2
STRING2 = /\'((?:[^\n\r\f\\']|\\#{NL}|#{ESCAPE})*)\'/
-
-
2
IDENT = /-?#{NMSTART}#{NMCHAR}*/
-
2
NAME = /#{NMCHAR}+/
-
2
NUM = /[0-9]+|[0-9]*\.[0-9]+/
-
2
STRING = /#{STRING1}|#{STRING2}/
-
2
URLCHAR = /[#%&*-~]|#{NONASCII}|#{ESCAPE}/
-
2
URL = /(#{URLCHAR}*)/
-
2
W = /[ \t\r\n\f]*/
-
2
VARIABLE = /(\$)(#{Sass::SCSS::RX::IDENT})/
-
-
# This is more liberal than the spec's definition,
-
# but that definition didn't work well with the greediness rules
-
2
RANGE = /(?:#{H}|\?){1,6}/
-
-
##
-
-
2
S = /[ \t\r\n\f]+/
-
-
2
COMMENT = /\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\//
-
2
SINGLE_LINE_COMMENT = /\/\/.*(\n[ \t]*\/\/.*)*/
-
-
2
CDO = quote("<!--")
-
2
CDC = quote("-->")
-
2
INCLUDES = quote("~=")
-
2
DASHMATCH = quote("|=")
-
2
PREFIXMATCH = quote("^=")
-
2
SUFFIXMATCH = quote("$=")
-
2
SUBSTRINGMATCH = quote("*=")
-
-
2
HASH = /##{NAME}/
-
-
2
IMPORTANT = /!#{W}important/i
-
2
DEFAULT = /!#{W}default/i
-
-
2
NUMBER = /#{NUM}(?:#{IDENT}|%)?/
-
-
2
URI = /url\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
-
2
FUNCTION = /#{IDENT}\(/
-
-
2
UNICODERANGE = /u\+(?:#{H}{1,6}-#{H}{1,6}|#{RANGE})/i
-
-
# Defined in http://www.w3.org/TR/css3-selectors/#lex
-
2
PLUS = /#{W}\+/
-
2
GREATER = /#{W}>/
-
2
TILDE = /#{W}~/
-
2
NOT = quote(":not(", Regexp::IGNORECASE)
-
-
# Defined in https://developer.mozilla.org/en/CSS/@-moz-document as a
-
# non-standard version of http://www.w3.org/TR/css3-conditional/
-
2
URL_PREFIX = /url-prefix\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
-
2
DOMAIN = /domain\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
-
-
# Custom
-
2
HEXCOLOR = /\#[0-9a-fA-F]+/
-
2
INTERP_START = /#\{/
-
2
ANY = /:(-[-\w]+-)?any\(/i
-
2
OPTIONAL = /!#{W}optional/i
-
-
2
IDENT_HYPHEN_INTERP = /-(#\{)/
-
2
STRING1_NOINTERP = /\"((?:[^\n\r\f\\"#]|#(?!\{)|\\#{NL}|#{ESCAPE})*)\"/
-
2
STRING2_NOINTERP = /\'((?:[^\n\r\f\\'#]|#(?!\{)|\\#{NL}|#{ESCAPE})*)\'/
-
2
STRING_NOINTERP = /#{STRING1_NOINTERP}|#{STRING2_NOINTERP}/
-
-
2
STATIC_COMPONENT = /#{IDENT}|#{STRING_NOINTERP}|#{HEXCOLOR}|[+-]?#{NUMBER}|\!important/i
-
2
STATIC_VALUE = /#{STATIC_COMPONENT}(\s*[\s,\/]\s*#{STATIC_COMPONENT})*([;}])/i
-
2
STATIC_SELECTOR = /(#{NMCHAR}|[ \t]|[,>+*]|[:#.]#{NMSTART}){0,50}([{])/i
-
end
-
end
-
end
-
2
module Sass
-
2
module SCSS
-
# A mixin for subclasses of {Sass::Script::Lexer}
-
# that makes them usable by {SCSS::Parser} to parse SassScript.
-
# In particular, the lexer doesn't support `!` for a variable prefix.
-
2
module ScriptLexer
-
2
private
-
-
2
def variable
-
return [:raw, "!important"] if scan(Sass::SCSS::RX::IMPORTANT)
-
_variable(Sass::SCSS::RX::VARIABLE)
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module SCSS
-
# A mixin for subclasses of {Sass::Script::Parser}
-
# that makes them usable by {SCSS::Parser} to parse SassScript.
-
# In particular, the parser won't raise an error
-
# when there's more content in the lexer once lexing is done.
-
# In addition, the parser doesn't support `!` for a variable prefix.
-
2
module ScriptParser
-
2
private
-
-
# @private
-
2
def lexer_class
-
klass = Class.new(super)
-
klass.send(:include, ScriptLexer)
-
klass
-
end
-
-
# Instead of raising an error when the parser is done,
-
# rewind the StringScanner so that it hasn't consumed the final token.
-
2
def assert_done
-
@lexer.unpeek!
-
end
-
end
-
end
-
end
-
2
require 'sass/script/css_parser'
-
-
2
module Sass
-
2
module SCSS
-
# A parser for a static SCSS tree.
-
# Parses with SCSS extensions, like nested rules and parent selectors,
-
# but without dynamic SassScript.
-
# This is useful for e.g. \{#parse\_selector parsing selectors}
-
# after resolving the interpolation.
-
2
class StaticParser < Parser
-
# Parses the text as a selector.
-
#
-
# @param filename [String, nil] The file in which the selector appears,
-
# or nil if there is no such file.
-
# Used for error reporting.
-
# @return [Selector::CommaSequence] The parsed selector
-
# @raise [Sass::SyntaxError] if there's a syntax error in the selector
-
2
def parse_selector
-
init_scanner!
-
seq = expr!(:selector_comma_sequence)
-
expected("selector") unless @scanner.eos?
-
seq.line = @line
-
seq.filename = @filename
-
seq
-
end
-
-
2
private
-
-
2
def moz_document_function
-
return unless val = tok(URI) || tok(URL_PREFIX) || tok(DOMAIN) ||
-
function(!:allow_var)
-
ss
-
[val]
-
end
-
-
2
def variable; nil; end
-
2
def script_value; nil; end
-
2
def interpolation; nil; end
-
2
def var_expr; nil; end
-
2
def interp_string; s = tok(STRING) and [s]; end
-
2
def interp_uri; s = tok(URI) and [s]; end
-
2
def interp_ident(ident = IDENT); s = tok(ident) and [s]; end
-
2
def use_css_import?; true; end
-
-
2
def special_directive(name)
-
return unless %w[media import charset -moz-document].include?(name)
-
super
-
end
-
-
2
@sass_script_parser = Class.new(Sass::Script::CssParser)
-
2
@sass_script_parser.send(:include, ScriptParser)
-
end
-
end
-
end
-
2
require 'sass/selector/simple'
-
2
require 'sass/selector/abstract_sequence'
-
2
require 'sass/selector/comma_sequence'
-
2
require 'sass/selector/sequence'
-
2
require 'sass/selector/simple_sequence'
-
-
2
module Sass
-
# A namespace for nodes in the parse tree for selectors.
-
#
-
# {CommaSequence} is the toplevel seelctor,
-
# representing a comma-separated sequence of {Sequence}s,
-
# such as `foo bar, baz bang`.
-
# {Sequence} is the next level,
-
# representing {SimpleSequence}s separated by combinators (e.g. descendant or child),
-
# such as `foo bar` or `foo > bar baz`.
-
# {SimpleSequence} is a sequence of selectors that all apply to a single element,
-
# such as `foo.bar[attr=val]`.
-
# Finally, {Simple} is the superclass of the simplest selectors,
-
# such as `.foo` or `#bar`.
-
2
module Selector
-
# The base used for calculating selector specificity. The spec says this
-
# should be "sufficiently high"; it's extremely unlikely that any single
-
# selector sequence will contain 1,000 simple selectors.
-
#
-
# @type [Fixnum]
-
2
SPECIFICITY_BASE = 1_000
-
-
# A parent-referencing selector (`&` in Sass).
-
# The function of this is to be replaced by the parent selector
-
# in the nested hierarchy.
-
2
class Parent < Simple
-
# @see Selector#to_a
-
2
def to_a
-
["&"]
-
end
-
-
# Always raises an exception.
-
#
-
# @raise [Sass::SyntaxError] Parent selectors should be resolved before unification
-
# @see Selector#unify
-
2
def unify(sels)
-
raise Sass::SyntaxError.new("[BUG] Cannot unify parent selectors.")
-
end
-
end
-
-
# A class selector (e.g. `.foo`).
-
2
class Class < Simple
-
# The class name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :name
-
-
# @param name [Array<String, Sass::Script::Node>] The class name
-
2
def initialize(name)
-
@name = name
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
[".", *@name]
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
-
# An id selector (e.g. `#foo`).
-
2
class Id < Simple
-
# The id name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :name
-
-
# @param name [Array<String, Sass::Script::Node>] The id name
-
2
def initialize(name)
-
@name = name
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
["#", *@name]
-
end
-
-
# Returns `nil` if `sels` contains an {Id} selector
-
# with a different name than this one.
-
#
-
# @see Selector#unify
-
2
def unify(sels)
-
return if sels.any? {|sel2| sel2.is_a?(Id) && self.name != sel2.name}
-
super
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
SPECIFICITY_BASE**2
-
end
-
end
-
-
# A placeholder selector (e.g. `%foo`).
-
# This exists to be replaced via `@extend`.
-
# Rulesets using this selector will not be printed, but can be extended.
-
# Otherwise, this acts just like a class selector.
-
2
class Placeholder < Simple
-
# The placeholder name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :name
-
-
# @param name [Array<String, Sass::Script::Node>] The placeholder name
-
2
def initialize(name)
-
@name = name
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
["%", *@name]
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
-
# A universal selector (`*` in CSS).
-
2
class Universal < Simple
-
# The selector namespace.
-
# `nil` means the default namespace,
-
# `[""]` means no namespace,
-
# `["*"]` means any namespace.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
2
attr_reader :namespace
-
-
# @param namespace [Array<String, Sass::Script::Node>, nil] See \{#namespace}
-
2
def initialize(namespace)
-
@namespace = namespace
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
@namespace ? @namespace + ["|*"] : ["*"]
-
end
-
-
# Unification of a universal selector is somewhat complicated,
-
# especially when a namespace is specified.
-
# If there is no namespace specified
-
# or any namespace is specified (namespace `"*"`),
-
# then `sel` is returned without change
-
# (unless it's empty, in which case `"*"` is required).
-
#
-
# If a namespace is specified
-
# but `sel` does not specify a namespace,
-
# then the given namespace is applied to `sel`,
-
# either by adding this {Universal} selector
-
# or applying this namespace to an existing {Element} selector.
-
#
-
# If both this selector *and* `sel` specify namespaces,
-
# those namespaces are unified via {Simple#unify_namespaces}
-
# and the unified namespace is used, if possible.
-
#
-
# @todo There are lots of cases that this documentation specifies;
-
# make sure we thoroughly test **all of them**.
-
# @todo Keep track of whether a default namespace has been declared
-
# and handle namespace-unspecified selectors accordingly.
-
# @todo If any branch of a CommaSequence ends up being just `"*"`,
-
# then all other branches should be eliminated
-
#
-
# @see Selector#unify
-
2
def unify(sels)
-
name =
-
case sels.first
-
when Universal; :universal
-
when Element; sels.first.name
-
else
-
return [self] + sels unless namespace.nil? || namespace == ['*']
-
return sels unless sels.empty?
-
return [self]
-
end
-
-
ns, accept = unify_namespaces(namespace, sels.first.namespace)
-
return unless accept
-
[name == :universal ? Universal.new(ns) : Element.new(name, ns)] + sels[1..-1]
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
0
-
end
-
end
-
-
# An element selector (e.g. `h1`).
-
2
class Element < Simple
-
# The element name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :name
-
-
# The selector namespace.
-
# `nil` means the default namespace,
-
# `[""]` means no namespace,
-
# `["*"]` means any namespace.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
2
attr_reader :namespace
-
-
# @param name [Array<String, Sass::Script::Node>] The element name
-
# @param namespace [Array<String, Sass::Script::Node>, nil] See \{#namespace}
-
2
def initialize(name, namespace)
-
@name = name
-
@namespace = namespace
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
@namespace ? @namespace + ["|"] + @name : @name
-
end
-
-
# Unification of an element selector is somewhat complicated,
-
# especially when a namespace is specified.
-
# First, if `sel` contains another {Element} with a different \{#name},
-
# then the selectors can't be unified and `nil` is returned.
-
#
-
# Otherwise, if `sel` doesn't specify a namespace,
-
# or it specifies any namespace (via `"*"`),
-
# then it's returned with this element selector
-
# (e.g. `.foo` becomes `a.foo` or `svg|a.foo`).
-
# Similarly, if this selector doesn't specify a namespace,
-
# the namespace from `sel` is used.
-
#
-
# If both this selector *and* `sel` specify namespaces,
-
# those namespaces are unified via {Simple#unify_namespaces}
-
# and the unified namespace is used, if possible.
-
#
-
# @todo There are lots of cases that this documentation specifies;
-
# make sure we thoroughly test **all of them**.
-
# @todo Keep track of whether a default namespace has been declared
-
# and handle namespace-unspecified selectors accordingly.
-
#
-
# @see Selector#unify
-
2
def unify(sels)
-
case sels.first
-
when Universal;
-
when Element; return unless name == sels.first.name
-
else return [self] + sels
-
end
-
-
ns, accept = unify_namespaces(namespace, sels.first.namespace)
-
return unless accept
-
[Element.new(name, ns)] + sels[1..-1]
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
1
-
end
-
end
-
-
# Selector interpolation (`#{}` in Sass).
-
2
class Interpolation < Simple
-
# The script to run.
-
#
-
# @return [Sass::Script::Node]
-
2
attr_reader :script
-
-
# @param script [Sass::Script::Node] The script to run
-
2
def initialize(script)
-
@script = script
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
[@script]
-
end
-
-
# Always raises an exception.
-
#
-
# @raise [Sass::SyntaxError] Interpolation selectors should be resolved before unification
-
# @see Selector#unify
-
2
def unify(sels)
-
raise Sass::SyntaxError.new("[BUG] Cannot unify interpolation selectors.")
-
end
-
end
-
-
# An attribute selector (e.g. `[href^="http://"]`).
-
2
class Attribute < Simple
-
# The attribute name.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :name
-
-
# The attribute namespace.
-
# `nil` means the default namespace,
-
# `[""]` means no namespace,
-
# `["*"]` means any namespace.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
2
attr_reader :namespace
-
-
# The matching operator, e.g. `"="` or `"^="`.
-
#
-
# @return [String]
-
2
attr_reader :operator
-
-
# The right-hand side of the operator.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :value
-
-
# Flags for the attribute selector (e.g. `i`).
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :flags
-
-
# @param name [Array<String, Sass::Script::Node>] The attribute name
-
# @param namespace [Array<String, Sass::Script::Node>, nil] See \{#namespace}
-
# @param operator [String] The matching operator, e.g. `"="` or `"^="`
-
# @param value [Array<String, Sass::Script::Node>] See \{#value}
-
# @param value [Array<String, Sass::Script::Node>] See \{#flags}
-
2
def initialize(name, namespace, operator, value, flags)
-
@name = name
-
@namespace = namespace
-
@operator = operator
-
@value = value
-
@flags = flags
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
res = ["["]
-
res.concat(@namespace) << "|" if @namespace
-
res.concat @name
-
(res << @operator).concat @value if @value
-
(res << " ").concat @flags if @flags
-
res << "]"
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
-
# A pseudoclass (e.g. `:visited`) or pseudoelement (e.g. `::first-line`) selector.
-
# It can have arguments (e.g. `:nth-child(2n+1)`).
-
2
class Pseudo < Simple
-
# Some psuedo-class-syntax selectors are actually considered
-
# pseudo-elements and must be treated differently. This is a list of such
-
# selectors
-
#
-
# @return [Array<String>]
-
2
ACTUALLY_ELEMENTS = %w[after before first-line first-letter]
-
-
# Like \{#type}, but returns the type of selector this looks like, rather
-
# than the type it is semantically. This only differs from type for
-
# selectors in \{ACTUALLY\_ELEMENTS}.
-
#
-
# @return [Symbol]
-
2
attr_reader :syntactic_type
-
-
# The name of the selector.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_reader :name
-
-
# The argument to the selector,
-
# or `nil` if no argument was given.
-
#
-
# This may include SassScript nodes that will be run during resolution.
-
# Note that this should not include SassScript nodes
-
# after resolution has taken place.
-
#
-
# @return [Array<String, Sass::Script::Node>, nil]
-
2
attr_reader :arg
-
-
# @param type [Symbol] See \{#type}
-
# @param name [Array<String, Sass::Script::Node>] The name of the selector
-
# @param arg [nil, Array<String, Sass::Script::Node>] The argument to the selector,
-
# or nil if no argument was given
-
2
def initialize(type, name, arg)
-
@syntactic_type = type
-
@name = name
-
@arg = arg
-
end
-
-
# The type of the selector. `:class` if this is a pseudoclass selector,
-
# `:element` if it's a pseudoelement.
-
#
-
# @return [Symbol]
-
2
def type
-
ACTUALLY_ELEMENTS.include?(name.first) ? :element : syntactic_type
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
res = [syntactic_type == :class ? ":" : "::"] + @name
-
(res << "(").concat(Sass::Util.strip_string_array(@arg)) << ")" if @arg
-
res
-
end
-
-
# Returns `nil` if this is a pseudoelement selector
-
# and `sels` contains a pseudoelement selector different than this one.
-
#
-
# @see Selector#unify
-
2
def unify(sels)
-
return if type == :element && sels.any? do |sel|
-
sel.is_a?(Pseudo) && sel.type == :element &&
-
(sel.name != self.name || sel.arg != self.arg)
-
end
-
super
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
type == :class ? SPECIFICITY_BASE : 1
-
end
-
end
-
-
# A pseudoclass selector whose argument is itself a selector
-
# (e.g. `:not(.foo)` or `:-moz-all(.foo, .bar)`).
-
2
class SelectorPseudoClass < Simple
-
# The name of the pseudoclass.
-
#
-
# @return [String]
-
2
attr_reader :name
-
-
# The selector argument.
-
#
-
# @return [Selector::Sequence]
-
2
attr_reader :selector
-
-
# @param [String] The name of the pseudoclass
-
# @param [Selector::CommaSequence] The selector argument
-
2
def initialize(name, selector)
-
@name = name
-
@selector = selector
-
end
-
-
# @see Selector#to_a
-
2
def to_a
-
[":", @name, "("] + @selector.to_a + [")"]
-
end
-
-
# @see AbstractSequence#specificity
-
2
def specificity
-
SPECIFICITY_BASE
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Selector
-
# The abstract parent class of the various selector sequence classes.
-
#
-
# All subclasses should implement a `members` method that returns an array
-
# of object that respond to `#line=` and `#filename=`, as well as a `to_a`
-
# method that returns an array of strings and script nodes.
-
2
class AbstractSequence
-
# The line of the Sass template on which this selector was declared.
-
#
-
# @return [Fixnum]
-
2
attr_reader :line
-
-
# The name of the file in which this selector was declared.
-
#
-
# @return [String, nil]
-
2
attr_reader :filename
-
-
# Sets the line of the Sass template on which this selector was declared.
-
# This also sets the line for all child selectors.
-
#
-
# @param line [Fixnum]
-
# @return [Fixnum]
-
2
def line=(line)
-
members.each {|m| m.line = line}
-
@line = line
-
end
-
-
# Sets the name of the file in which this selector was declared,
-
# or `nil` if it was not declared in a file (e.g. on stdin).
-
# This also sets the filename for all child selectors.
-
#
-
# @param filename [String, nil]
-
# @return [String, nil]
-
2
def filename=(filename)
-
members.each {|m| m.filename = filename}
-
@filename = filename
-
end
-
-
# Returns a hash code for this sequence.
-
#
-
# Subclasses should define `#_hash` rather than overriding this method,
-
# which automatically handles memoizing the result.
-
#
-
# @return [Fixnum]
-
2
def hash
-
@_hash ||= _hash
-
end
-
-
# Checks equality between this and another object.
-
#
-
# Subclasses should define `#_eql?` rather than overriding this method,
-
# which handles checking class equality and hash equality.
-
#
-
# @param other [Object] The object to test equality against
-
# @return [Boolean] Whether or not this is equal to `other`
-
2
def eql?(other)
-
other.class == self.class && other.hash == self.hash && _eql?(other)
-
end
-
2
alias_method :==, :eql?
-
-
# Whether or not this selector sequence contains a placeholder selector.
-
# Checks recursively.
-
2
def has_placeholder?
-
@has_placeholder ||=
-
members.any? {|m| m.is_a?(AbstractSequence) ? m.has_placeholder? : m.is_a?(Placeholder)}
-
end
-
-
# Converts the selector into a string. This is the standard selector
-
# string, along with any SassScript interpolation that may exist.
-
#
-
# @return [String]
-
2
def to_s
-
to_a.map {|e| e.is_a?(Sass::Script::Node) ? "\#{#{e.to_sass}}" : e}.join
-
end
-
-
# Returns the specificity of the selector as an integer. The base is given
-
# by {Sass::Selector::SPECIFICITY_BASE}.
-
#
-
# @return [Fixnum]
-
2
def specificity
-
_specificity(members)
-
end
-
-
2
protected
-
-
2
def _specificity(arr)
-
spec = 0
-
arr.map {|m| spec += m.is_a?(String) ? 0 : m.specificity}
-
spec
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Selector
-
# A comma-separated sequence of selectors.
-
2
class CommaSequence < AbstractSequence
-
# The comma-separated selector sequences
-
# represented by this class.
-
#
-
# @return [Array<Sequence>]
-
2
attr_reader :members
-
-
# @param seqs [Array<Sequence>] See \{#members}
-
2
def initialize(seqs)
-
@members = seqs
-
end
-
-
# Resolves the {Parent} selectors within this selector
-
# by replacing them with the given parent selector,
-
# handling commas appropriately.
-
#
-
# @param super_cseq [CommaSequence] The parent selector
-
# @return [CommaSequence] This selector, with parent references resolved
-
# @raise [Sass::SyntaxError] If a parent selector is invalid
-
2
def resolve_parent_refs(super_cseq)
-
if super_cseq.nil?
-
if @members.any? do |sel|
-
sel.members.any? do |sel_or_op|
-
sel_or_op.is_a?(SimpleSequence) && sel_or_op.members.any? {|ssel| ssel.is_a?(Parent)}
-
end
-
end
-
raise Sass::SyntaxError.new("Base-level rules cannot contain the parent-selector-referencing character '&'.")
-
end
-
return self
-
end
-
-
CommaSequence.new(
-
super_cseq.members.map do |super_seq|
-
@members.map {|seq| seq.resolve_parent_refs(super_seq)}
-
end.flatten)
-
end
-
-
# Non-destrucively extends this selector with the extensions specified in a hash
-
# (which should come from {Sass::Tree::Visitors::Cssize}).
-
#
-
# @todo Link this to the reference documentation on `@extend`
-
# when such a thing exists.
-
#
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this selector
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing this selector.
-
# @return [CommaSequence] A copy of this selector,
-
# with extensions made according to `extends`
-
2
def do_extend(extends, parent_directives)
-
CommaSequence.new(members.map do |seq|
-
extended = seq.do_extend(extends, parent_directives)
-
# First Law of Extend: the result of extending a selector should
-
# always contain the base selector.
-
#
-
# See https://github.com/nex3/sass/issues/324.
-
extended.unshift seq unless seq.has_placeholder? || extended.include?(seq)
-
extended
-
end.flatten)
-
end
-
-
# Returns a string representation of the sequence.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
2
def inspect
-
members.map {|m| m.inspect}.join(", ")
-
end
-
-
# @see Simple#to_a
-
2
def to_a
-
arr = Sass::Util.intersperse(@members.map {|m| m.to_a}, ", ").flatten
-
arr.delete("\n")
-
arr
-
end
-
-
2
private
-
-
2
def _hash
-
members.hash
-
end
-
-
2
def _eql?(other)
-
other.class == self.class && other.members.eql?(self.members)
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Selector
-
# An operator-separated sequence of
-
# {SimpleSequence simple selector sequences}.
-
2
class Sequence < AbstractSequence
-
# Sets the line of the Sass template on which this selector was declared.
-
# This also sets the line for all child selectors.
-
#
-
# @param line [Fixnum]
-
# @return [Fixnum]
-
2
def line=(line)
-
members.each {|m| m.line = line if m.is_a?(SimpleSequence)}
-
line
-
end
-
-
# Sets the name of the file in which this selector was declared,
-
# or `nil` if it was not declared in a file (e.g. on stdin).
-
# This also sets the filename for all child selectors.
-
#
-
# @param filename [String, nil]
-
# @return [String, nil]
-
2
def filename=(filename)
-
members.each {|m| m.filename = filename if m.is_a?(SimpleSequence)}
-
filename
-
end
-
-
# The array of {SimpleSequence simple selector sequences}, operators, and
-
# newlines. The operators are strings such as `"+"` and `">"` representing
-
# the corresponding CSS operators, or interpolated SassScript. Newlines
-
# are also newline strings; these aren't semantically relevant, but they
-
# do affect formatting.
-
#
-
# @return [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>]
-
2
attr_reader :members
-
-
# @param seqs_and_ops [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>] See \{#members}
-
2
def initialize(seqs_and_ops)
-
@members = seqs_and_ops
-
end
-
-
# Resolves the {Parent} selectors within this selector
-
# by replacing them with the given parent selector,
-
# handling commas appropriately.
-
#
-
# @param super_seq [Sequence] The parent selector sequence
-
# @return [Sequence] This selector, with parent references resolved
-
# @raise [Sass::SyntaxError] If a parent selector is invalid
-
2
def resolve_parent_refs(super_seq)
-
members = @members.dup
-
nl = (members.first == "\n" && members.shift)
-
unless members.any? do |seq_or_op|
-
seq_or_op.is_a?(SimpleSequence) && seq_or_op.members.first.is_a?(Parent)
-
end
-
old_members, members = members, []
-
members << nl if nl
-
members << SimpleSequence.new([Parent.new], false)
-
members += old_members
-
end
-
-
Sequence.new(
-
members.map do |seq_or_op|
-
next seq_or_op unless seq_or_op.is_a?(SimpleSequence)
-
seq_or_op.resolve_parent_refs(super_seq)
-
end.flatten)
-
end
-
-
# Non-destructively extends this selector with the extensions specified in a hash
-
# (which should come from {Sass::Tree::Visitors::Cssize}).
-
#
-
# @overload def do_extend(extends, parent_directives)
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this selector
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing this selector.
-
# @return [Array<Sequence>] A list of selectors generated
-
# by extending this selector with `extends`.
-
# These correspond to a {CommaSequence}'s {CommaSequence#members members array}.
-
# @see CommaSequence#do_extend
-
2
def do_extend(extends, parent_directives, seen = Set.new)
-
extended_not_expanded = members.map do |sseq_or_op|
-
next [[sseq_or_op]] unless sseq_or_op.is_a?(SimpleSequence)
-
extended = sseq_or_op.do_extend(extends, parent_directives, seen)
-
choices = extended.map {|seq| seq.members}
-
choices.unshift([sseq_or_op]) unless extended.any? {|seq| seq.superselector?(sseq_or_op)}
-
choices
-
end
-
weaves = Sass::Util.paths(extended_not_expanded).map {|path| weave(path)}
-
Sass::Util.flatten(trim(weaves), 1).map {|p| Sequence.new(p)}
-
end
-
-
# Returns whether or not this selector matches all elements
-
# that the given selector matches (as well as possibly more).
-
#
-
# @example
-
# (.foo).superselector?(.foo.bar) #=> true
-
# (.foo).superselector?(.bar) #=> false
-
# (.bar .foo).superselector?(.foo) #=> false
-
# @param sseq [SimpleSequence]
-
# @return [Boolean]
-
2
def superselector?(sseq)
-
return false unless members.size == 1
-
members.last.superselector?(sseq)
-
end
-
-
# @see Simple#to_a
-
2
def to_a
-
ary = @members.map {|seq_or_op| seq_or_op.is_a?(SimpleSequence) ? seq_or_op.to_a : seq_or_op}
-
Sass::Util.intersperse(ary, " ").flatten.compact
-
end
-
-
# Returns a string representation of the sequence.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
2
def inspect
-
members.map {|m| m.inspect}.join(" ")
-
end
-
-
# Add to the {SimpleSequence#sources} sets of the child simple sequences.
-
# This destructively modifies this sequence's members array, but not the
-
# child simple sequences.
-
#
-
# @param sources [Set<Sequence>]
-
2
def add_sources!(sources)
-
members.map! {|m| m.is_a?(SimpleSequence) ? m.with_more_sources(sources) : m}
-
end
-
-
2
private
-
-
# Conceptually, this expands "parenthesized selectors".
-
# That is, if we have `.A .B {@extend .C}` and `.D .C {...}`,
-
# this conceptually expands into `.D .C, .D (.A .B)`,
-
# and this function translates `.D (.A .B)` into `.D .A .B, .A.D .B, .D .A .B`.
-
#
-
# @param path [Array<Array<SimpleSequence or String>>] A list of parenthesized selector groups.
-
# @return [Array<Array<SimpleSequence or String>>] A list of fully-expanded selectors.
-
2
def weave(path)
-
# This function works by moving through the selector path left-to-right,
-
# building all possible prefixes simultaneously. These prefixes are
-
# `befores`, while the remaining parenthesized suffixes is `afters`.
-
befores = [[]]
-
afters = path.dup
-
-
until afters.empty?
-
current = afters.shift.dup
-
last_current = [current.pop]
-
befores = Sass::Util.flatten(befores.map do |before|
-
next [] unless sub = subweave(before, current)
-
sub.map {|seqs| seqs + last_current}
-
end, 1)
-
end
-
return befores
-
end
-
-
# This interweaves two lists of selectors,
-
# returning all possible orderings of them (including using unification)
-
# that maintain the relative ordering of the input arrays.
-
#
-
# For example, given `.foo .bar` and `.baz .bang`,
-
# this would return `.foo .bar .baz .bang`, `.foo .bar.baz .bang`,
-
# `.foo .baz .bar .bang`, `.foo .baz .bar.bang`, `.foo .baz .bang .bar`,
-
# and so on until `.baz .bang .foo .bar`.
-
#
-
# Semantically, for selectors A and B, this returns all selectors `AB_i`
-
# such that the union over all i of elements matched by `AB_i X` is
-
# identical to the intersection of all elements matched by `A X` and all
-
# elements matched by `B X`. Some `AB_i` are elided to reduce the size of
-
# the output.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Array<Array<SimpleSequence or String>>]
-
2
def subweave(seq1, seq2)
-
return [seq2] if seq1.empty?
-
return [seq1] if seq2.empty?
-
-
seq1, seq2 = seq1.dup, seq2.dup
-
return unless init = merge_initial_ops(seq1, seq2)
-
return unless fin = merge_final_ops(seq1, seq2)
-
seq1 = group_selectors(seq1)
-
seq2 = group_selectors(seq2)
-
lcs = Sass::Util.lcs(seq2, seq1) do |s1, s2|
-
next s1 if s1 == s2
-
next unless s1.first.is_a?(SimpleSequence) && s2.first.is_a?(SimpleSequence)
-
next s2 if parent_superselector?(s1, s2)
-
next s1 if parent_superselector?(s2, s1)
-
end
-
-
diff = [[init]]
-
until lcs.empty?
-
diff << chunks(seq1, seq2) {|s| parent_superselector?(s.first, lcs.first)} << [lcs.shift]
-
seq1.shift
-
seq2.shift
-
end
-
diff << chunks(seq1, seq2) {|s| s.empty?}
-
diff += fin.map {|sel| sel.is_a?(Array) ? sel : [sel]}
-
diff.reject! {|c| c.empty?}
-
-
Sass::Util.paths(diff).map {|p| p.flatten}.reject {|p| path_has_two_subjects?(p)}
-
end
-
-
# Extracts initial selector combinators (`"+"`, `">"`, `"~"`, and `"\n"`)
-
# from two sequences and merges them together into a single array of
-
# selector combinators.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Array<String>, nil] If there are no operators in the merged
-
# sequence, this will be the empty array. If the operators cannot be
-
# merged, this will be nil.
-
2
def merge_initial_ops(seq1, seq2)
-
ops1, ops2 = [], []
-
ops1 << seq1.shift while seq1.first.is_a?(String)
-
ops2 << seq2.shift while seq2.first.is_a?(String)
-
-
newline = false
-
newline ||= !!ops1.shift if ops1.first == "\n"
-
newline ||= !!ops2.shift if ops2.first == "\n"
-
-
# If neither sequence is a subsequence of the other, they cannot be
-
# merged successfully
-
lcs = Sass::Util.lcs(ops1, ops2)
-
return unless lcs == ops1 || lcs == ops2
-
return (newline ? ["\n"] : []) + (ops1.size > ops2.size ? ops1 : ops2)
-
end
-
-
# Extracts final selector combinators (`"+"`, `">"`, `"~"`) and the
-
# selectors to which they apply from two sequences and merges them
-
# together into a single array.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Array<SimpleSequence or String or
-
# Array<Array<SimpleSequence or String>>]
-
# If there are no trailing combinators to be merged, this will be the
-
# empty array. If the trailing combinators cannot be merged, this will
-
# be nil. Otherwise, this will contained the merged selector. Array
-
# elements are [Sass::Util#paths]-style options; conceptually, an "or"
-
# of multiple selectors.
-
2
def merge_final_ops(seq1, seq2, res = [])
-
ops1, ops2 = [], []
-
ops1 << seq1.pop while seq1.last.is_a?(String)
-
ops2 << seq2.pop while seq2.last.is_a?(String)
-
-
# Not worth the headache of trying to preserve newlines here. The most
-
# important use of newlines is at the beginning of the selector to wrap
-
# across lines anyway.
-
ops1.reject! {|o| o == "\n"}
-
ops2.reject! {|o| o == "\n"}
-
-
return res if ops1.empty? && ops2.empty?
-
if ops1.size > 1 || ops2.size > 1
-
# If there are multiple operators, something hacky's going on. If one
-
# is a supersequence of the other, use that, otherwise give up.
-
lcs = Sass::Util.lcs(ops1, ops2)
-
return unless lcs == ops1 || lcs == ops2
-
res.unshift(*(ops1.size > ops2.size ? ops1 : ops2).reverse)
-
return res
-
end
-
-
# This code looks complicated, but it's actually just a bunch of special
-
# cases for interactions between different combinators.
-
op1, op2 = ops1.first, ops2.first
-
if op1 && op2
-
sel1 = seq1.pop
-
sel2 = seq2.pop
-
if op1 == '~' && op2 == '~'
-
if sel1.superselector?(sel2)
-
res.unshift sel2, '~'
-
elsif sel2.superselector?(sel1)
-
res.unshift sel1, '~'
-
else
-
merged = sel1.unify(sel2.members, sel2.subject?)
-
res.unshift [
-
[sel1, '~', sel2, '~'],
-
[sel2, '~', sel1, '~'],
-
([merged, '~'] if merged)
-
].compact
-
end
-
elsif (op1 == '~' && op2 == '+') || (op1 == '+' && op2 == '~')
-
if op1 == '~'
-
tilde_sel, plus_sel = sel1, sel2
-
else
-
tilde_sel, plus_sel = sel2, sel1
-
end
-
-
if tilde_sel.superselector?(plus_sel)
-
res.unshift plus_sel, '+'
-
else
-
merged = plus_sel.unify(tilde_sel.members, tilde_sel.subject?)
-
res.unshift [
-
[tilde_sel, '~', plus_sel, '+'],
-
([merged, '+'] if merged)
-
].compact
-
end
-
elsif op1 == '>' && %w[~ +].include?(op2)
-
res.unshift sel2, op2
-
seq1.push sel1, op1
-
elsif op2 == '>' && %w[~ +].include?(op1)
-
res.unshift sel1, op1
-
seq2.push sel2, op2
-
elsif op1 == op2
-
return unless merged = sel1.unify(sel2.members, sel2.subject?)
-
res.unshift merged, op1
-
else
-
# Unknown selector combinators can't be unified
-
return
-
end
-
return merge_final_ops(seq1, seq2, res)
-
elsif op1
-
seq2.pop if op1 == '>' && seq2.last && seq2.last.superselector?(seq1.last)
-
res.unshift seq1.pop, op1
-
return merge_final_ops(seq1, seq2, res)
-
else # op2
-
seq1.pop if op2 == '>' && seq1.last && seq1.last.superselector?(seq2.last)
-
res.unshift seq2.pop, op2
-
return merge_final_ops(seq1, seq2, res)
-
end
-
end
-
-
# Takes initial subsequences of `seq1` and `seq2` and returns all
-
# orderings of those subsequences. The initial subsequences are determined
-
# by a block.
-
#
-
# Destructively removes the initial subsequences of `seq1` and `seq2`.
-
#
-
# For example, given `(A B C | D E)` and `(1 2 | 3 4 5)` (with `|`
-
# denoting the boundary of the initial subsequence), this would return
-
# `[(A B C 1 2), (1 2 A B C)]`. The sequences would then be `(D E)` and
-
# `(3 4 5)`.
-
#
-
# @param seq1 [Array]
-
# @param seq2 [Array]
-
# @yield [a] Used to determine when to cut off the initial subsequences.
-
# Called repeatedly for each sequence until it returns true.
-
# @yieldparam a [Array] A final subsequence of one input sequence after
-
# cutting off some initial subsequence.
-
# @yieldreturn [Boolean] Whether or not to cut off the initial subsequence
-
# here.
-
# @return [Array<Array>] All possible orderings of the initial subsequences.
-
2
def chunks(seq1, seq2)
-
chunk1 = []
-
chunk1 << seq1.shift until yield seq1
-
chunk2 = []
-
chunk2 << seq2.shift until yield seq2
-
return [] if chunk1.empty? && chunk2.empty?
-
return [chunk2] if chunk1.empty?
-
return [chunk1] if chunk2.empty?
-
[chunk1 + chunk2, chunk2 + chunk1]
-
end
-
-
# Groups a sequence into subsequences. The subsequences are determined by
-
# strings; adjacent non-string elements will be put into separate groups,
-
# but any element adjacent to a string will be grouped with that string.
-
#
-
# For example, `(A B "C" D E "F" G "H" "I" J)` will become `[(A) (B "C" D)
-
# (E "F" G "H" "I" J)]`.
-
#
-
# @param seq [Array]
-
# @return [Array<Array>]
-
2
def group_selectors(seq)
-
newseq = []
-
tail = seq.dup
-
until tail.empty?
-
head = []
-
begin
-
head << tail.shift
-
end while !tail.empty? && head.last.is_a?(String) || tail.first.is_a?(String)
-
newseq << head
-
end
-
return newseq
-
end
-
-
# Given two selector sequences, returns whether `seq1` is a
-
# superselector of `seq2`; that is, whether `seq1` matches every
-
# element `seq2` matches.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Boolean]
-
2
def _superselector?(seq1, seq2)
-
seq1 = seq1.reject {|e| e == "\n"}
-
seq2 = seq2.reject {|e| e == "\n"}
-
# Selectors with leading or trailing operators are neither
-
# superselectors nor subselectors.
-
return if seq1.last.is_a?(String) || seq2.last.is_a?(String) ||
-
seq1.first.is_a?(String) || seq2.first.is_a?(String)
-
# More complex selectors are never superselectors of less complex ones
-
return if seq1.size > seq2.size
-
return seq1.first.superselector?(seq2.last) if seq1.size == 1
-
-
_, si = Sass::Util.enum_with_index(seq2).find do |e, i|
-
return if i == seq2.size - 1
-
next if e.is_a?(String)
-
seq1.first.superselector?(e)
-
end
-
return unless si
-
-
if seq1[1].is_a?(String)
-
return unless seq2[si+1].is_a?(String)
-
# .foo ~ .bar is a superselector of .foo + .bar
-
return unless seq1[1] == "~" ? seq2[si+1] != ">" : seq1[1] == seq2[si+1]
-
return _superselector?(seq1[2..-1], seq2[si+2..-1])
-
elsif seq2[si+1].is_a?(String)
-
return unless seq2[si+1] == ">"
-
return _superselector?(seq1[1..-1], seq2[si+2..-1])
-
else
-
return _superselector?(seq1[1..-1], seq2[si+1..-1])
-
end
-
end
-
-
# Like \{#_superselector?}, but compares the selectors in the
-
# context of parent selectors, as though they shared an implicit
-
# base simple selector. For example, `B` is not normally a
-
# superselector of `B A`, since it doesn't match `A` elements.
-
# However, it is a parent superselector, since `B X` is a
-
# superselector of `B A X`.
-
#
-
# @param seq1 [Array<SimpleSequence or String>]
-
# @param seq2 [Array<SimpleSequence or String>]
-
# @return [Boolean]
-
2
def parent_superselector?(seq1, seq2)
-
base = Sass::Selector::SimpleSequence.new([Sass::Selector::Placeholder.new('<temp>')], false)
-
_superselector?(seq1 + [base], seq2 + [base])
-
end
-
-
# Removes redundant selectors from between multiple lists of
-
# selectors. This takes a list of lists of selector sequences;
-
# each individual list is assumed to have no redundancy within
-
# itself. A selector is only removed if it's redundant with a
-
# selector in another list.
-
#
-
# "Redundant" here means that one selector is a superselector of
-
# the other. The more specific selector is removed.
-
#
-
# @param seqses [Array<Array<Array<SimpleSequence or String>>>]
-
# @return [Array<Array<Array<SimpleSequence or String>>>]
-
2
def trim(seqses)
-
# Avoid truly horrific quadratic behavior. TODO: I think there
-
# may be a way to get perfect trimming without going quadratic.
-
return seqses if seqses.size > 100
-
-
# Keep the results in a separate array so we can be sure we aren't
-
# comparing against an already-trimmed selector. This ensures that two
-
# identical selectors don't mutually trim one another.
-
result = seqses.dup
-
-
# This is n^2 on the sequences, but only comparing between
-
# separate sequences should limit the quadratic behavior.
-
seqses.each_with_index do |seqs1, i|
-
result[i] = seqs1.reject do |seq1|
-
max_spec = _sources(seq1).map {|seq| seq.specificity}.max || 0
-
result.any? do |seqs2|
-
next if seqs1.equal?(seqs2)
-
# Second Law of Extend: the specificity of a generated selector
-
# should never be less than the specificity of the extending
-
# selector.
-
#
-
# See https://github.com/nex3/sass/issues/324.
-
seqs2.any? {|seq2| _specificity(seq2) >= max_spec && _superselector?(seq2, seq1)}
-
end
-
end
-
end
-
result
-
end
-
-
2
def _hash
-
members.reject {|m| m == "\n"}.hash
-
end
-
-
2
def _eql?(other)
-
other.members.reject {|m| m == "\n"}.eql?(self.members.reject {|m| m == "\n"})
-
end
-
-
2
private
-
-
2
def path_has_two_subjects?(path)
-
subject = false
-
path.each do |sseq_or_op|
-
next unless sseq_or_op.is_a?(SimpleSequence)
-
next unless sseq_or_op.subject?
-
return true if subject
-
subject = true
-
end
-
false
-
end
-
-
2
def _sources(seq)
-
s = Set.new
-
seq.map {|sseq_or_op| s.merge sseq_or_op.sources if sseq_or_op.is_a?(SimpleSequence)}
-
s
-
end
-
-
2
def extended_not_expanded_to_s(extended_not_expanded)
-
extended_not_expanded.map do |choices|
-
choices = choices.map do |sel|
-
next sel.first.to_s if sel.size == 1
-
"#{sel.join ' '}"
-
end
-
next choices.first if choices.size == 1 && !choices.include?(' ')
-
"(#{choices.join ', '})"
-
end.join ' '
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Selector
-
# The abstract superclass for simple selectors
-
# (that is, those that don't compose multiple selectors).
-
2
class Simple
-
# The line of the Sass template on which this selector was declared.
-
#
-
# @return [Fixnum]
-
2
attr_accessor :line
-
-
# The name of the file in which this selector was declared,
-
# or `nil` if it was not declared in a file (e.g. on stdin).
-
#
-
# @return [String, nil]
-
2
attr_accessor :filename
-
-
# Returns a representation of the node
-
# as an array of strings and potentially {Sass::Script::Node}s
-
# (if there's interpolation in the selector).
-
# When the interpolation is resolved and the strings are joined together,
-
# this will be the string representation of this node.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
def to_a
-
Sass::Util.abstract(self)
-
end
-
-
# Returns a string representation of the node.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
2
def inspect
-
to_a.map {|e| e.is_a?(Sass::Script::Node) ? "\#{#{e.to_sass}}" : e}.join
-
end
-
-
# @see \{#inspect}
-
# @return [String]
-
2
def to_s
-
inspect
-
end
-
-
# Returns a hash code for this selector object.
-
#
-
# By default, this is based on the value of \{#to\_a},
-
# so if that contains information irrelevant to the identity of the selector,
-
# this should be overridden.
-
#
-
# @return [Fixnum]
-
2
def hash
-
@_hash ||= to_a.hash
-
end
-
-
# Checks equality between this and another object.
-
#
-
# By default, this is based on the value of \{#to\_a},
-
# so if that contains information irrelevant to the identity of the selector,
-
# this should be overridden.
-
#
-
# @param other [Object] The object to test equality against
-
# @return [Boolean] Whether or not this is equal to `other`
-
2
def eql?(other)
-
other.class == self.class && other.hash == self.hash && other.to_a.eql?(to_a)
-
end
-
2
alias_method :==, :eql?
-
-
# Unifies this selector with a {SimpleSequence}'s {SimpleSequence#members members array},
-
# returning another `SimpleSequence` members array
-
# that matches both this selector and the input selector.
-
#
-
# By default, this just appends this selector to the end of the array
-
# (or returns the original array if this selector already exists in it).
-
#
-
# @param sels [Array<Simple>] A {SimpleSequence}'s {SimpleSequence#members members array}
-
# @return [Array<Simple>, nil] A {SimpleSequence} {SimpleSequence#members members array}
-
# matching both `sels` and this selector,
-
# or `nil` if this is impossible (e.g. unifying `#foo` and `#bar`)
-
# @raise [Sass::SyntaxError] If this selector cannot be unified.
-
# This will only ever occur when a dynamic selector,
-
# such as {Parent} or {Interpolation}, is used in unification.
-
# Since these selectors should be resolved
-
# by the time extension and unification happen,
-
# this exception will only ever be raised as a result of programmer error
-
2
def unify(sels)
-
return sels if sels.any? {|sel2| eql?(sel2)}
-
sels_with_ix = Sass::Util.enum_with_index(sels)
-
_, i =
-
if self.is_a?(Pseudo) || self.is_a?(SelectorPseudoClass)
-
sels_with_ix.find {|sel, _| sel.is_a?(Pseudo) && (sels.last.type == :element)}
-
else
-
sels_with_ix.find {|sel, _| sel.is_a?(Pseudo) || sel.is_a?(SelectorPseudoClass)}
-
end
-
return sels + [self] unless i
-
return sels[0...i] + [self] + sels[i..-1]
-
end
-
-
2
protected
-
-
# Unifies two namespaces,
-
# returning a namespace that works for both of them if possible.
-
#
-
# @param ns1 [String, nil] The first namespace.
-
# `nil` means none specified, e.g. `foo`.
-
# The empty string means no namespace specified, e.g. `|foo`.
-
# `"*"` means any namespace is allowed, e.g. `*|foo`.
-
# @param ns2 [String, nil] The second namespace. See `ns1`.
-
# @return [Array(String or nil, Boolean)]
-
# The first value is the unified namespace, or `nil` for no namespace.
-
# The second value is whether or not a namespace that works for both inputs
-
# could be found at all.
-
# If the second value is `false`, the first should be ignored.
-
2
def unify_namespaces(ns1, ns2)
-
return nil, false unless ns1 == ns2 || ns1.nil? || ns1 == ['*'] || ns2.nil? || ns2 == ['*']
-
return ns2, true if ns1 == ['*']
-
return ns1, true if ns2 == ['*']
-
return ns1 || ns2, true
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Selector
-
# A unseparated sequence of selectors
-
# that all apply to a single element.
-
# For example, `.foo#bar[attr=baz]` is a simple sequence
-
# of the selectors `.foo`, `#bar`, and `[attr=baz]`.
-
2
class SimpleSequence < AbstractSequence
-
# The array of individual selectors.
-
#
-
# @return [Array<Simple>]
-
2
attr_accessor :members
-
-
# The extending selectors that caused this selector sequence to be
-
# generated. For example:
-
#
-
# a.foo { ... }
-
# b.bar {@extend a}
-
# c.baz {@extend b}
-
#
-
# The generated selector `b.foo.bar` has `{b.bar}` as its `sources` set,
-
# and the generated selector `c.foo.bar.baz` has `{b.bar, c.baz}` as its
-
# `sources` set.
-
#
-
# This is populated during the {#do_extend} process.
-
#
-
# @return {Set<Sequence>}
-
2
attr_accessor :sources
-
-
# @see \{#subject?}
-
2
attr_writer :subject
-
-
# Returns the element or universal selector in this sequence,
-
# if it exists.
-
#
-
# @return [Element, Universal, nil]
-
2
def base
-
@base ||= (members.first if members.first.is_a?(Element) || members.first.is_a?(Universal))
-
end
-
-
2
def pseudo_elements
-
@pseudo_elements ||= (members - [base]).
-
select {|sel| sel.is_a?(Pseudo) && sel.type == :element}
-
end
-
-
# Returns the non-base, non-pseudo-class selectors in this sequence.
-
#
-
# @return [Set<Simple>]
-
2
def rest
-
@rest ||= Set.new(members - [base] - pseudo_elements)
-
end
-
-
# Whether or not this compound selector is the subject of the parent
-
# selector; that is, whether it is prepended with `$` and represents the
-
# actual element that will be selected.
-
#
-
# @return [Boolean]
-
2
def subject?
-
@subject
-
end
-
-
# @param selectors [Array<Simple>] See \{#members}
-
# @param subject [Boolean] See \{#subject?}
-
# @param sources [Set<Sequence>]
-
2
def initialize(selectors, subject, sources = Set.new)
-
@members = selectors
-
@subject = subject
-
@sources = sources
-
end
-
-
# Resolves the {Parent} selectors within this selector
-
# by replacing them with the given parent selector,
-
# handling commas appropriately.
-
#
-
# @param super_seq [Sequence] The parent selector sequence
-
# @return [Array<SimpleSequence>] This selector, with parent references resolved.
-
# This is an array because the parent selector is itself a {Sequence}
-
# @raise [Sass::SyntaxError] If a parent selector is invalid
-
2
def resolve_parent_refs(super_seq)
-
# Parent selector only appears as the first selector in the sequence
-
return [self] unless @members.first.is_a?(Parent)
-
-
return super_seq.members if @members.size == 1
-
unless super_seq.members.last.is_a?(SimpleSequence)
-
raise Sass::SyntaxError.new("Invalid parent selector: " + super_seq.to_a.join)
-
end
-
-
super_seq.members[0...-1] +
-
[SimpleSequence.new(super_seq.members.last.members + @members[1..-1], subject?)]
-
end
-
-
# Non-destrucively extends this selector with the extensions specified in a hash
-
# (which should come from {Sass::Tree::Visitors::Cssize}).
-
#
-
# @overload def do_extend(extends, parent_directives)
-
# @param extends [{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this selector
-
# @param parent_directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing this selector.
-
# @return [Array<Sequence>] A list of selectors generated
-
# by extending this selector with `extends`.
-
# @see CommaSequence#do_extend
-
2
def do_extend(extends, parent_directives, seen = Set.new)
-
Sass::Util.group_by_to_a(extends.get(members.to_set)) {|ex, _| ex.extender}.map do |seq, group|
-
sels = group.map {|_, s| s}.flatten
-
# If A {@extend B} and C {...},
-
# seq is A, sels is B, and self is C
-
-
self_without_sel = Sass::Util.array_minus(self.members, sels)
-
group.each {|e, _| e.result = :failed_to_unify unless e.result == :succeeded}
-
next unless unified = seq.members.last.unify(self_without_sel, subject?)
-
group.each {|e, _| e.result = :succeeded}
-
next if group.map {|e, _| check_directives_match!(e, parent_directives)}.none?
-
new_seq = Sequence.new(seq.members[0...-1] + [unified])
-
new_seq.add_sources!(sources + [seq])
-
[sels, new_seq]
-
end.compact.map do |sels, seq|
-
seen.include?(sels) ? [] : seq.do_extend(extends, parent_directives, seen + [sels])
-
end.flatten.uniq
-
end
-
-
# Unifies this selector with another {SimpleSequence}'s {SimpleSequence#members members array},
-
# returning another `SimpleSequence`
-
# that matches both this selector and the input selector.
-
#
-
# @param sels [Array<Simple>] A {SimpleSequence}'s {SimpleSequence#members members array}
-
# @param subject [Boolean] Whether the {SimpleSequence} being merged is a subject.
-
# @return [SimpleSequence, nil] A {SimpleSequence} matching both `sels` and this selector,
-
# or `nil` if this is impossible (e.g. unifying `#foo` and `#bar`)
-
# @raise [Sass::SyntaxError] If this selector cannot be unified.
-
# This will only ever occur when a dynamic selector,
-
# such as {Parent} or {Interpolation}, is used in unification.
-
# Since these selectors should be resolved
-
# by the time extension and unification happen,
-
# this exception will only ever be raised as a result of programmer error
-
2
def unify(sels, other_subject)
-
return unless sseq = members.inject(sels) do |member, sel|
-
return unless member
-
sel.unify(member)
-
end
-
SimpleSequence.new(sseq, other_subject || subject?)
-
end
-
-
# Returns whether or not this selector matches all elements
-
# that the given selector matches (as well as possibly more).
-
#
-
# @example
-
# (.foo).superselector?(.foo.bar) #=> true
-
# (.foo).superselector?(.bar) #=> false
-
# @param sseq [SimpleSequence]
-
# @return [Boolean]
-
2
def superselector?(sseq)
-
(base.nil? || base.eql?(sseq.base)) &&
-
pseudo_elements.eql?(sseq.pseudo_elements) &&
-
rest.subset?(sseq.rest)
-
end
-
-
# @see Simple#to_a
-
2
def to_a
-
res = @members.map {|sel| sel.to_a}.flatten
-
res << '!' if subject?
-
res
-
end
-
-
# Returns a string representation of the sequence.
-
# This is basically the selector string.
-
#
-
# @return [String]
-
2
def inspect
-
members.map {|m| m.inspect}.join
-
end
-
-
# Return a copy of this simple sequence with `sources` merged into the
-
# {#sources} set.
-
#
-
# @param sources [Set<Sequence>]
-
# @return [SimpleSequence]
-
2
def with_more_sources(sources)
-
sseq = dup
-
sseq.members = members.dup
-
sseq.sources = self.sources | sources
-
sseq
-
end
-
-
2
private
-
-
2
def check_directives_match!(extend, parent_directives)
-
dirs1 = extend.directives.map {|d| d.resolved_value}
-
dirs2 = parent_directives.map {|d| d.resolved_value}
-
return true if Sass::Util.subsequence?(dirs1, dirs2)
-
-
Sass::Util.sass_warn <<WARNING
-
DEPRECATION WARNING on line #{extend.node.line}#{" of #{extend.node.filename}" if extend.node.filename}:
-
@extending an outer selector from within #{extend.directives.last.name} is deprecated.
-
You may only @extend selectors within the same directive.
-
This will be an error in Sass 3.3.
-
It can only work once @extend is supported natively in the browser.
-
WARNING
-
return false
-
end
-
-
2
def _hash
-
[base, Sass::Util.set_hash(rest)].hash
-
end
-
-
2
def _eql?(other)
-
other.base.eql?(self.base) && other.pseudo_elements == pseudo_elements &&
-
Sass::Util.set_eql?(other.rest, self.rest) && other.subject? == self.subject?
-
end
-
end
-
end
-
end
-
2
module Sass
-
# This module contains functionality that's shared between Haml and Sass.
-
2
module Shared
-
2
extend self
-
-
# Scans through a string looking for the interoplation-opening `#{`
-
# and, when it's found, yields the scanner to the calling code
-
# so it can handle it properly.
-
#
-
# The scanner will have any backslashes immediately in front of the `#{`
-
# as the second capture group (`scan[2]`),
-
# and the text prior to that as the first (`scan[1]`).
-
#
-
# @yieldparam scan [StringScanner] The scanner scanning through the string
-
# @return [String] The text remaining in the scanner after all `#{`s have been processed
-
2
def handle_interpolation(str)
-
scan = Sass::Util::MultibyteStringScanner.new(str)
-
yield scan while scan.scan(/(.*?)(\\*)\#\{/m)
-
scan.rest
-
end
-
-
# Moves a scanner through a balanced pair of characters.
-
# For example:
-
#
-
# Foo (Bar (Baz bang) bop) (Bang (bop bip))
-
# ^ ^
-
# from to
-
#
-
# @param scanner [StringScanner] The string scanner to move
-
# @param start [Character] The character opening the balanced pair.
-
# A `Fixnum` in 1.8, a `String` in 1.9
-
# @param finish [Character] The character closing the balanced pair.
-
# A `Fixnum` in 1.8, a `String` in 1.9
-
# @param count [Fixnum] The number of opening characters matched
-
# before calling this method
-
# @return [(String, String)] The string matched within the balanced pair
-
# and the rest of the string.
-
# `["Foo (Bar (Baz bang) bop)", " (Bang (bop bip))"]` in the example above.
-
2
def balance(scanner, start, finish, count = 0)
-
str = ''
-
scanner = Sass::Util::MultibyteStringScanner.new(scanner) unless scanner.is_a? StringScanner
-
regexp = Regexp.new("(.*?)[\\#{start.chr}\\#{finish.chr}]", Regexp::MULTILINE)
-
while scanner.scan(regexp)
-
str << scanner.matched
-
count += 1 if scanner.matched[-1] == start
-
count -= 1 if scanner.matched[-1] == finish
-
return [str.strip, scanner.rest] if count == 0
-
end
-
end
-
-
# Formats a string for use in error messages about indentation.
-
#
-
# @param indentation [String] The string used for indentation
-
# @param was [Boolean] Whether or not to add `"was"` or `"were"`
-
# (depending on how many characters were in `indentation`)
-
# @return [String] The name of the indentation (e.g. `"12 spaces"`, `"1 tab"`)
-
2
def human_indentation(indentation, was = false)
-
if !indentation.include?(?\t)
-
noun = 'space'
-
elsif !indentation.include?(?\s)
-
noun = 'tab'
-
else
-
return indentation.inspect + (was ? ' was' : '')
-
end
-
-
singular = indentation.length == 1
-
if was
-
was = singular ? ' was' : ' were'
-
else
-
was = ''
-
end
-
-
"#{indentation.length} #{noun}#{'s' unless singular}#{was}"
-
end
-
end
-
end
-
# A namespace for the `@supports` condition parse tree.
-
2
module Sass::Supports
-
# The abstract superclass of all Supports conditions.
-
2
class Condition
-
# Runs the SassScript in the supports condition.
-
#
-
# @param env [Sass::Environment] The environment in which to run the script.
-
2
def perform(environment); Sass::Util.abstract(self); end
-
-
# Returns the CSS for this condition.
-
#
-
# @return [String]
-
2
def to_css; Sass::Util.abstract(self); end
-
-
# Returns the Sass/CSS code for this condition.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @return [String]
-
2
def to_src(options); Sass::Util.abstract(self); end
-
-
# Returns a deep copy of this condition and all its children.
-
#
-
# @return [Condition]
-
2
def deep_copy; Sass::Util.abstract(self); end
-
-
# Sets the options hash for the script nodes in the supports condition.
-
#
-
# @param options [{Symbol => Object}] The options has to set.
-
2
def options=(options); Sass::Util.abstract(self); end
-
end
-
-
# An operator condition (e.g. `CONDITION1 and CONDITION2`).
-
2
class Operator < Condition
-
# The left-hand condition.
-
#
-
# @return [Sass::Supports::Condition]
-
2
attr_accessor :left
-
-
# The right-hand condition.
-
#
-
# @return [Sass::Supports::Condition]
-
2
attr_accessor :right
-
-
# The operator ("and" or "or").
-
#
-
# @return [String]
-
2
attr_accessor :op
-
-
2
def initialize(left, right, op)
-
@left = left
-
@right = right
-
@op = op
-
end
-
-
2
def perform(env)
-
@left.perform(env)
-
@right.perform(env)
-
end
-
-
2
def to_css
-
"#{left_parens @left.to_css} #{op} #{right_parens @right.to_css}"
-
end
-
-
2
def to_src(options)
-
"#{left_parens @left.to_src(options)} #{op} #{right_parens @right.to_src(options)}"
-
end
-
-
2
def deep_copy
-
copy = dup
-
copy.left = @left.deep_copy
-
copy.right = @right.deep_copy
-
copy
-
end
-
-
2
def options=(options)
-
@left.options = options
-
@right.options = options
-
end
-
-
2
private
-
-
2
def left_parens(str)
-
return "(#{str})" if @left.is_a?(Negation)
-
return str
-
end
-
-
2
def right_parens(str)
-
return "(#{str})" if @right.is_a?(Negation) || @right.is_a?(Operator)
-
return str
-
end
-
end
-
-
# A negation condition (`not CONDITION`).
-
2
class Negation < Condition
-
# The condition being negated.
-
#
-
# @return [Sass::Supports::Condition]
-
2
attr_accessor :condition
-
-
2
def initialize(condition)
-
@condition = condition
-
end
-
-
2
def perform(env)
-
@condition.perform(env)
-
end
-
-
2
def to_css
-
"not #{parens @condition.to_css}"
-
end
-
-
2
def to_src(options)
-
"not #{parens @condition.to_src(options)}"
-
end
-
-
2
def deep_copy
-
copy = dup
-
copy.condition = condition.deep_copy
-
copy
-
end
-
-
2
def options=(options)
-
condition.options = options
-
end
-
-
2
private
-
-
2
def parens(str)
-
return "(#{str})" if @condition.is_a?(Negation) || @condition.is_a?(Operator)
-
return str
-
end
-
end
-
-
# A declaration condition (e.g. `(feature: value)`).
-
2
class Declaration < Condition
-
# The feature name.
-
#
-
# @param [Sass::Script::Node]
-
2
attr_accessor :name
-
-
# The name of the feature after any SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_name
-
-
# The feature value.
-
#
-
# @param [Sass::Script::Node]
-
2
attr_accessor :value
-
-
# The value of the feature after any SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_value
-
-
2
def initialize(name, value)
-
@name = name
-
@value = value
-
end
-
-
2
def perform(env)
-
@resolved_name = name.perform(env)
-
@resolved_value = value.perform(env)
-
end
-
-
2
def to_css
-
"(#{@resolved_name}: #{@resolved_value})"
-
end
-
-
2
def to_src(options)
-
"(#{@name.to_sass(options)}: #{@value.to_sass(options)})"
-
end
-
-
2
def deep_copy
-
copy = dup
-
copy.name = @name.deep_copy
-
copy.value = @value.deep_copy
-
copy
-
end
-
-
2
def options=(options)
-
@name.options = options
-
@value.options = options
-
end
-
end
-
-
# An interpolation condition (e.g. `#{$var}`).
-
2
class Interpolation < Condition
-
# The SassScript expression in the interpolation.
-
#
-
# @param [Sass::Script::Node]
-
2
attr_accessor :value
-
-
# The value of the expression after it's been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_value
-
-
2
def initialize(value)
-
@value = value
-
end
-
-
2
def perform(env)
-
val = value.perform(env)
-
@resolved_value = val.is_a?(Sass::Script::String) ? val.value : val.to_s
-
end
-
-
2
def to_css
-
@resolved_value
-
end
-
-
2
def to_src(options)
-
"\#{#{@value.to_sass(options)}}"
-
end
-
-
2
def deep_copy
-
copy = dup
-
copy.value = @value.deep_copy
-
copy
-
end
-
-
2
def options=(options)
-
@value.options = options
-
end
-
end
-
end
-
2
module Sass::Tree
-
# A static node representing an unproccessed Sass `@charset` directive.
-
#
-
# @see Sass::Tree
-
2
class CharsetNode < Node
-
# The name of the charset.
-
#
-
# @return [String]
-
2
attr_accessor :name
-
-
# @param name [String] see \{#name}
-
2
def initialize(name)
-
@name = name
-
super()
-
end
-
-
# @see Node#invisible?
-
2
def invisible?
-
!Sass::Util.ruby1_8?
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A static node representing a Sass comment (silent or loud).
-
#
-
# @see Sass::Tree
-
2
class CommentNode < Node
-
# The text of the comment, not including `/*` and `*/`.
-
# Interspersed with {Sass::Script::Node}s representing `#{}`-interpolation
-
# if this is a loud comment.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :value
-
-
# The text of the comment
-
# after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_value
-
-
# The type of the comment. `:silent` means it's never output to CSS,
-
# `:normal` means it's output in every compile mode except `:compressed`,
-
# and `:loud` means it's output even in `:compressed`.
-
#
-
# @return [Symbol]
-
2
attr_accessor :type
-
-
# @param value [Array<String, Sass::Script::Node>] See \{#value}
-
# @param type [Symbol] See \{#type}
-
2
def initialize(value, type)
-
@value = Sass::Util.with_extracted_values(value) {|str| normalize_indentation str}
-
@type = type
-
super()
-
end
-
-
# Compares the contents of two comments.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
2
def ==(other)
-
self.class == other.class && value == other.value && type == other.type
-
end
-
-
# Returns `true` if this is a silent comment
-
# or the current style doesn't render comments.
-
#
-
# Comments starting with ! are never invisible (and the ! is removed from the output.)
-
#
-
# @return [Boolean]
-
2
def invisible?
-
case @type
-
when :loud; false
-
when :silent; true
-
else; style == :compressed
-
end
-
end
-
-
# Returns the number of lines in the comment.
-
#
-
# @return [Fixnum]
-
2
def lines
-
@value.inject(0) do |s, e|
-
next s + e.count("\n") if e.is_a?(String)
-
next s
-
end
-
end
-
-
2
private
-
-
2
def normalize_indentation(str)
-
ind = str.split("\n").inject(str[/^[ \t]*/].split("")) do |pre, line|
-
line[/^[ \t]*/].split("").zip(pre).inject([]) do |arr, (a, b)|
-
break arr if a != b
-
arr << a
-
end
-
end.join
-
str.gsub(/^#{ind}/, '')
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A node representing the placement within a mixin of the include statement's content.
-
#
-
# @see Sass::Tree
-
2
class ContentNode < Node
-
end
-
end
-
end
-
2
module Sass::Tree
-
# A node representing an `@import` rule that's importing plain CSS.
-
#
-
# @see Sass::Tree
-
2
class CssImportNode < DirectiveNode
-
# The URI being imported, either as a plain string or an interpolated
-
# script string.
-
#
-
# @return [String, Sass::Script::Node]
-
2
attr_accessor :uri
-
-
# The text of the URI being imported after any interpolated SassScript has
-
# been resolved. Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_uri
-
-
# The media query for this rule, interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation. Any adjacent strings will be merged
-
# together.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :query
-
-
# The media query for this rule, without any unresolved interpolation. It's
-
# only set once {Tree::Node#perform} has been called.
-
#
-
# @return [Sass::Media::QueryList]
-
2
attr_accessor :resolved_query
-
-
# @param uri [String, Sass::Script::Node] See \{#uri}
-
# @param query [Array<String, Sass::Script::Node>] See \{#query}
-
2
def initialize(uri, query = nil)
-
@uri = uri
-
@query = query
-
super('')
-
end
-
-
# @param uri [String] See \{#resolved_uri}
-
# @return [CssImportNode]
-
2
def self.resolved(uri)
-
node = new(uri)
-
node.resolved_uri = uri
-
node
-
end
-
-
# @see DirectiveNode#value
-
2
def value; raise NotImplementedError; end
-
-
# @see DirectiveNode#resolved_value
-
2
def resolved_value
-
@resolved_value ||=
-
begin
-
str = "@import #{resolved_uri}"
-
str << " #{resolved_query.to_css}" if resolved_query
-
str
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A dynamic node representing a Sass `@debug` statement.
-
#
-
# @see Sass::Tree
-
2
class DebugNode < Node
-
# The expression to print.
-
# @return [Script::Node]
-
2
attr_accessor :expr
-
-
# @param expr [Script::Node] The expression to print
-
2
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
2
module Sass::Tree
-
# A static node representing an unproccessed Sass `@`-directive.
-
# Directives known to Sass, like `@for` and `@debug`,
-
# are handled by their own nodes;
-
# only CSS directives like `@media` and `@font-face` become {DirectiveNode}s.
-
#
-
# `@import` and `@charset` are special cases;
-
# they become {ImportNode}s and {CharsetNode}s, respectively.
-
#
-
# @see Sass::Tree
-
2
class DirectiveNode < Node
-
# The text of the directive, `@` and all, with interpolation included.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :value
-
-
# The text of the directive after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_value
-
-
# @param value [Array<String, Sass::Script::Node>] See \{#value}
-
2
def initialize(value)
-
@value = value
-
super()
-
end
-
-
# @param value [String] See \{#resolved_value}
-
# @return [DirectiveNode]
-
2
def self.resolved(value)
-
node = new([value])
-
node.resolved_value = value
-
node
-
end
-
-
# @return [String] The name of the directive, including `@`.
-
2
def name
-
value.first.gsub(/ .*$/, '')
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A dynamic node representing a Sass `@each` loop.
-
#
-
# @see Sass::Tree
-
2
class EachNode < Node
-
# The name of the loop variable.
-
# @return [String]
-
2
attr_reader :var
-
-
# The parse tree for the list.
-
# @param [Script::Node]
-
2
attr_accessor :list
-
-
# @param var [String] The name of the loop variable
-
# @param list [Script::Node] The parse tree for the list
-
2
def initialize(var, list)
-
@var = var
-
@list = list
-
super()
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A static node reprenting an `@extend` directive.
-
#
-
# @see Sass::Tree
-
2
class ExtendNode < Node
-
# The parsed selector after interpolation has been resolved.
-
# Only set once {Tree::Visitors::Perform} has been run.
-
#
-
# @return [Selector::CommaSequence]
-
2
attr_accessor :resolved_selector
-
-
# The CSS selector to extend, interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :selector
-
-
# Whether the `@extend` is allowed to match no selectors or not.
-
#
-
# @return [Boolean]
-
2
def optional?; @optional; end
-
-
# @param selector [Array<String, Sass::Script::Node>]
-
# The CSS selector to extend,
-
# interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation.
-
# @param optional [Boolean] See \{#optional}
-
2
def initialize(selector, optional)
-
@selector = selector
-
@optional = optional
-
super()
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A dynamic node representing a Sass `@for` loop.
-
#
-
# @see Sass::Tree
-
2
class ForNode < Node
-
# The name of the loop variable.
-
# @return [String]
-
2
attr_reader :var
-
-
# The parse tree for the initial expression.
-
# @return [Script::Node]
-
2
attr_accessor :from
-
-
# The parse tree for the final expression.
-
# @return [Script::Node]
-
2
attr_accessor :to
-
-
# Whether to include `to` in the loop or stop just before.
-
# @return [Boolean]
-
2
attr_reader :exclusive
-
-
# @param var [String] See \{#var}
-
# @param from [Script::Node] See \{#from}
-
# @param to [Script::Node] See \{#to}
-
# @param exclusive [Boolean] See \{#exclusive}
-
2
def initialize(var, from, to, exclusive)
-
@var = var
-
@from = from
-
@to = to
-
@exclusive = exclusive
-
super()
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A dynamic node representing a function definition.
-
#
-
# @see Sass::Tree
-
2
class FunctionNode < Node
-
# The name of the function.
-
# @return [String]
-
2
attr_reader :name
-
-
# The arguments to the function. Each element is a tuple
-
# containing the variable for argument and the parse tree for
-
# the default value of the argument
-
#
-
# @return [Array<Script::Node>]
-
2
attr_accessor :args
-
-
# The splat argument for this function, if one exists.
-
#
-
# @return [Script::Node?]
-
2
attr_accessor :splat
-
-
# @param name [String] The function name
-
# @param args [Array<(Script::Node, Script::Node)>] The arguments for the function.
-
# @param splat [Script::Node] See \{#splat}
-
2
def initialize(name, args, splat)
-
@name = name
-
@args = args
-
@splat = splat
-
super()
-
end
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A dynamic node representing a Sass `@if` statement.
-
#
-
# {IfNode}s are a little odd, in that they also represent `@else` and `@else if`s.
-
# This is done as a linked list:
-
# each {IfNode} has a link (\{#else}) to the next {IfNode}.
-
#
-
# @see Sass::Tree
-
2
class IfNode < Node
-
# The conditional expression.
-
# If this is nil, this is an `@else` node, not an `@else if`.
-
#
-
# @return [Script::Expr]
-
2
attr_accessor :expr
-
-
# The next {IfNode} in the if-else list, or `nil`.
-
#
-
# @return [IfNode]
-
2
attr_accessor :else
-
-
# @param expr [Script::Expr] See \{#expr}
-
2
def initialize(expr)
-
@expr = expr
-
@last_else = self
-
super()
-
end
-
-
# Append an `@else` node to the end of the list.
-
#
-
# @param node [IfNode] The `@else` node to append
-
2
def add_else(node)
-
@last_else.else = node
-
@last_else = node
-
end
-
-
2
def _dump(f)
-
Marshal.dump([self.expr, self.else, self.children])
-
end
-
-
2
def self._load(data)
-
expr, else_, children = Marshal.load(data)
-
node = IfNode.new(expr)
-
node.else = else_
-
node.children = children
-
node.instance_variable_set('@last_else',
-
node.else ? node.else.instance_variable_get('@last_else') : node)
-
node
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A static node that wraps the {Sass::Tree} for an `@import`ed file.
-
# It doesn't have a functional purpose other than to add the `@import`ed file
-
# to the backtrace if an error occurs.
-
2
class ImportNode < RootNode
-
# The name of the imported file as it appears in the Sass document.
-
#
-
# @return [String]
-
2
attr_reader :imported_filename
-
-
# Sets the imported file.
-
2
attr_writer :imported_file
-
-
# @param imported_filename [String] The name of the imported file
-
2
def initialize(imported_filename)
-
@imported_filename = imported_filename
-
super(nil)
-
end
-
-
2
def invisible?; to_s.empty?; end
-
-
# Returns the imported file.
-
#
-
# @return [Sass::Engine]
-
# @raise [Sass::SyntaxError] If no file could be found to import.
-
2
def imported_file
-
@imported_file ||= import
-
end
-
-
# Returns whether or not this import should emit a CSS @import declaration
-
#
-
# @return [Boolean] Whether or not this is a simple CSS @import declaration.
-
2
def css_import?
-
if @imported_filename =~ /\.css$/
-
@imported_filename
-
elsif imported_file.is_a?(String) && imported_file =~ /\.css$/
-
imported_file
-
end
-
end
-
-
2
private
-
-
2
def import
-
paths = @options[:load_paths]
-
-
if @options[:importer]
-
f = @options[:importer].find_relative(
-
@imported_filename, @options[:filename], options_for_importer)
-
return f if f
-
end
-
-
paths.each do |p|
-
if f = p.find(@imported_filename, options_for_importer)
-
return f
-
end
-
end
-
-
message = "File to import not found or unreadable: #{@imported_filename}.\n"
-
if paths.size == 1
-
message << "Load path: #{paths.first}"
-
else
-
message << "Load paths:\n " << paths.join("\n ")
-
end
-
raise SyntaxError.new(message)
-
rescue SyntaxError => e
-
raise SyntaxError.new(e.message, :line => self.line, :filename => @filename)
-
end
-
-
2
def options_for_importer
-
@options.merge(:_line => line)
-
end
-
end
-
end
-
end
-
2
module Sass::Tree
-
# A static node representing a `@media` rule.
-
# `@media` rules behave differently from other directives
-
# in that when they're nested within rules,
-
# they bubble up to top-level.
-
#
-
# @see Sass::Tree
-
2
class MediaNode < DirectiveNode
-
# TODO: parse and cache the query immediately if it has no dynamic elements
-
-
# The media query for this rule, interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation. Any adjacent strings will be merged
-
# together.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :query
-
-
# The media query for this rule, without any unresolved interpolation. It's
-
# only set once {Tree::Node#perform} has been called.
-
#
-
# @return [Sass::Media::QueryList]
-
2
attr_accessor :resolved_query
-
-
# @see RuleNode#tabs
-
2
attr_accessor :tabs
-
-
# @see RuleNode#group_end
-
2
attr_accessor :group_end
-
-
# @param query [Array<String, Sass::Script::Node>] See \{#query}
-
2
def initialize(query)
-
@query = query
-
@tabs = 0
-
super('')
-
end
-
-
# @see DirectiveNode#value
-
2
def value; raise NotImplementedError; end
-
-
# @see DirectiveNode#name
-
2
def name; '@media'; end
-
-
# @see DirectiveNode#resolved_value
-
2
def resolved_value
-
@resolved_value ||= "@media #{resolved_query.to_css}"
-
end
-
-
# True when the directive has no visible children.
-
#
-
# @return [Boolean]
-
2
def invisible?
-
children.all? {|c| c.invisible?}
-
end
-
-
# @see Node#bubbles?
-
2
def bubbles?; true; end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A dynamic node representing a mixin definition.
-
#
-
# @see Sass::Tree
-
2
class MixinDefNode < Node
-
# The mixin name.
-
# @return [String]
-
2
attr_reader :name
-
-
# The arguments for the mixin.
-
# Each element is a tuple containing the variable for argument
-
# and the parse tree for the default value of the argument.
-
#
-
# @return [Array<(Script::Node, Script::Node)>]
-
2
attr_accessor :args
-
-
# The splat argument for this mixin, if one exists.
-
#
-
# @return [Script::Node?]
-
2
attr_accessor :splat
-
-
# Whether the mixin uses `@content`. Set during the nesting check phase.
-
# @return [Boolean]
-
2
attr_accessor :has_content
-
-
# @param name [String] The mixin name
-
# @param args [Array<(Script::Node, Script::Node)>] See \{#args}
-
# @param splat [Script::Node] See \{#splat}
-
2
def initialize(name, args, splat)
-
@name = name
-
@args = args
-
@splat = splat
-
super()
-
end
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A static node representing a mixin include.
-
# When in a static tree, the sole purpose is to wrap exceptions
-
# to add the mixin to the backtrace.
-
#
-
# @see Sass::Tree
-
2
class MixinNode < Node
-
# The name of the mixin.
-
# @return [String]
-
2
attr_reader :name
-
-
# The arguments to the mixin.
-
# @return [Array<Script::Node>]
-
2
attr_accessor :args
-
-
# A hash from keyword argument names to values.
-
# @return [{String => Script::Node}]
-
2
attr_accessor :keywords
-
-
# The splat argument for this mixin, if one exists.
-
#
-
# @return [Script::Node?]
-
2
attr_accessor :splat
-
-
# @param name [String] The name of the mixin
-
# @param args [Array<Script::Node>] See \{#args}
-
# @param splat [Script::Node] See \{#splat}
-
# @param keywords [{String => Script::Node}] See \{#keywords}
-
2
def initialize(name, args, keywords, splat)
-
@name = name
-
@args = args
-
@keywords = keywords
-
@splat = splat
-
super()
-
end
-
end
-
end
-
2
module Sass
-
# A namespace for nodes in the Sass parse tree.
-
#
-
# The Sass parse tree has three states: dynamic, static Sass, and static CSS.
-
#
-
# When it's first parsed, a Sass document is in the dynamic state.
-
# It has nodes for mixin definitions and `@for` loops and so forth,
-
# in addition to nodes for CSS rules and properties.
-
# Nodes that only appear in this state are called **dynamic nodes**.
-
#
-
# {Tree::Visitors::Perform} creates a static Sass tree, which is different.
-
# It still has nodes for CSS rules and properties
-
# but it doesn't have any dynamic-generation-related nodes.
-
# The nodes in this state are in the same structure as the Sass document:
-
# rules and properties are nested beneath one another.
-
# Nodes that can be in this state or in the dynamic state
-
# are called **static nodes**; nodes that can only be in this state
-
# are called **solely static nodes**.
-
#
-
# {Tree::Visitors::Cssize} is then used to create a static CSS tree.
-
# This is like a static Sass tree,
-
# but the structure exactly mirrors that of the generated CSS.
-
# Rules and properties can't be nested beneath one another in this state.
-
#
-
# Finally, {Tree::Visitors::ToCss} can be called on a static CSS tree
-
# to get the actual CSS code as a string.
-
2
module Tree
-
# The abstract superclass of all parse-tree nodes.
-
2
class Node
-
2
include Enumerable
-
-
# The child nodes of this node.
-
#
-
# @return [Array<Tree::Node>]
-
2
attr_accessor :children
-
-
# Whether or not this node has child nodes.
-
# This may be true even when \{#children} is empty,
-
# in which case this node has an empty block (e.g. `{}`).
-
#
-
# @return [Boolean]
-
2
attr_accessor :has_children
-
-
# The line of the document on which this node appeared.
-
#
-
# @return [Fixnum]
-
2
attr_accessor :line
-
-
# The name of the document on which this node appeared.
-
#
-
# @return [String]
-
2
attr_writer :filename
-
-
# The options hash for the node.
-
# See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
#
-
# @return [{Symbol => Object}]
-
2
attr_reader :options
-
-
2
def initialize
-
@children = []
-
end
-
-
# Sets the options hash for the node and all its children.
-
#
-
# @param options [{Symbol => Object}] The options
-
# @see #options
-
2
def options=(options)
-
Sass::Tree::Visitors::SetOptions.visit(self, options)
-
end
-
-
# @private
-
2
def children=(children)
-
self.has_children ||= !children.empty?
-
@children = children
-
end
-
-
# The name of the document on which this node appeared.
-
#
-
# @return [String]
-
2
def filename
-
@filename || (@options && @options[:filename])
-
end
-
-
# Appends a child to the node.
-
#
-
# @param child [Tree::Node, Array<Tree::Node>] The child node or nodes
-
# @raise [Sass::SyntaxError] if `child` is invalid
-
2
def <<(child)
-
return if child.nil?
-
if child.is_a?(Array)
-
child.each {|c| self << c}
-
else
-
self.has_children = true
-
@children << child
-
end
-
end
-
-
# Compares this node and another object (only other {Tree::Node}s will be equal).
-
# This does a structural comparison;
-
# if the contents of the nodes and all the child nodes are equivalent,
-
# then the nodes are as well.
-
#
-
# Only static nodes need to override this.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
# @see Sass::Tree
-
2
def ==(other)
-
self.class == other.class && other.children == children
-
end
-
-
# True if \{#to\_s} will return `nil`;
-
# that is, if the node shouldn't be rendered.
-
# Should only be called in a static tree.
-
#
-
# @return [Boolean]
-
2
def invisible?; false; end
-
-
# The output style. See {file:SASS_REFERENCE.md#sass_options the Sass options documentation}.
-
#
-
# @return [Symbol]
-
2
def style
-
@options[:style]
-
end
-
-
# Computes the CSS corresponding to this static CSS tree.
-
#
-
# @return [String, nil] The resulting CSS
-
# @see Sass::Tree
-
2
def to_s
-
Sass::Tree::Visitors::ToCss.visit(self)
-
end
-
-
# Returns a representation of the node for debugging purposes.
-
#
-
# @return [String]
-
2
def inspect
-
return self.class.to_s unless has_children
-
"(#{self.class} #{children.map {|c| c.inspect}.join(' ')})"
-
end
-
-
# Iterates through each node in the tree rooted at this node
-
# in a pre-order walk.
-
#
-
# @yield node
-
# @yieldparam node [Node] a node in the tree
-
2
def each
-
yield self
-
children.each {|c| c.each {|n| yield n}}
-
end
-
-
# Converts a node to Sass code that will generate it.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize})
-
# @return [String] The Sass code corresponding to the node
-
2
def to_sass(options = {})
-
Sass::Tree::Visitors::Convert.visit(self, options, :sass)
-
end
-
-
# Converts a node to SCSS code that will generate it.
-
#
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize})
-
# @return [String] The Sass code corresponding to the node
-
2
def to_scss(options = {})
-
Sass::Tree::Visitors::Convert.visit(self, options, :scss)
-
end
-
-
# Return a deep clone of this node.
-
# The child nodes are cloned, but options are not.
-
#
-
# @return [Node]
-
2
def deep_copy
-
Sass::Tree::Visitors::DeepCopy.visit(self)
-
end
-
-
# Whether or not this node bubbles up through RuleNodes.
-
#
-
# @return [Boolean]
-
2
def bubbles?
-
false
-
end
-
-
2
protected
-
-
# @see Sass::Shared.balance
-
# @raise [Sass::SyntaxError] if the brackets aren't balanced
-
2
def balance(*args)
-
res = Sass::Shared.balance(*args)
-
return res if res
-
raise Sass::SyntaxError.new("Unbalanced brackets.", :line => line)
-
end
-
end
-
end
-
end
-
2
module Sass::Tree
-
# A static node reprenting a CSS property.
-
#
-
# @see Sass::Tree
-
2
class PropNode < Node
-
# The name of the property,
-
# interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation.
-
# Any adjacent strings will be merged together.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :name
-
-
# The name of the property
-
# after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_name
-
-
# The value of the property.
-
#
-
# @return [Sass::Script::Node]
-
2
attr_accessor :value
-
-
# The value of the property
-
# after any interpolated SassScript has been resolved.
-
# Only set once \{Tree::Visitors::Perform} has been run.
-
#
-
# @return [String]
-
2
attr_accessor :resolved_value
-
-
# How deep this property is indented
-
# relative to a normal property.
-
# This is only greater than 0 in the case that:
-
#
-
# * This node is in a CSS tree
-
# * The style is :nested
-
# * This is a child property of another property
-
# * The parent property has a value, and thus will be rendered
-
#
-
# @return [Fixnum]
-
2
attr_accessor :tabs
-
-
# @param name [Array<String, Sass::Script::Node>] See \{#name}
-
# @param value [Sass::Script::Node] See \{#value}
-
# @param prop_syntax [Symbol] `:new` if this property uses `a: b`-style syntax,
-
# `:old` if it uses `:a b`-style syntax
-
2
def initialize(name, value, prop_syntax)
-
@name = Sass::Util.strip_string_array(
-
Sass::Util.merge_adjacent_strings(name))
-
@value = value
-
@tabs = 0
-
@prop_syntax = prop_syntax
-
super()
-
end
-
-
# Compares the names and values of two properties.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
2
def ==(other)
-
self.class == other.class && name == other.name && value == other.value && super
-
end
-
-
# Returns a appropriate message indicating how to escape pseudo-class selectors.
-
# This only applies for old-style properties with no value,
-
# so returns the empty string if this is new-style.
-
#
-
# @return [String] The message
-
2
def pseudo_class_selector_message
-
return "" if @prop_syntax == :new || !value.is_a?(Sass::Script::String) || !value.value.empty?
-
"\nIf #{declaration.dump} should be a selector, use \"\\#{declaration}\" instead."
-
end
-
-
# Computes the Sass or SCSS code for the variable declaration.
-
# This is like \{#to\_scss} or \{#to\_sass},
-
# except it doesn't print any child properties or a trailing semicolon.
-
#
-
# @param opts [{Symbol => Object}] The options hash for the tree.
-
# @param fmt [Symbol] `:scss` or `:sass`.
-
2
def declaration(opts = {:old => @prop_syntax == :old}, fmt = :sass)
-
name = self.name.map {|n| n.is_a?(String) ? n : "\#{#{n.to_sass(opts)}}"}.join
-
if name[0] == ?:
-
raise Sass::SyntaxError.new("The \"#{name}: #{self.class.val_to_sass(value, opts)}\" hack is not allowed in the Sass indented syntax")
-
end
-
-
old = opts[:old] && fmt == :sass
-
initial = old ? ':' : ''
-
mid = old ? '' : ':'
-
"#{initial}#{name}#{mid} #{self.class.val_to_sass(value, opts)}".rstrip
-
end
-
-
# A property node is invisible if its value is empty.
-
#
-
# @return [Boolean]
-
2
def invisible?
-
resolved_value.empty?
-
end
-
-
2
private
-
-
2
def check!
-
if @options[:property_syntax] && @options[:property_syntax] != @prop_syntax
-
raise Sass::SyntaxError.new(
-
"Illegal property syntax: can't use #{@prop_syntax} syntax when :property_syntax => #{@options[:property_syntax].inspect} is set.")
-
end
-
end
-
-
2
class << self
-
# @private
-
2
def val_to_sass(value, opts)
-
val_to_sass_comma(value, opts).to_sass(opts)
-
end
-
-
2
private
-
-
2
def val_to_sass_comma(node, opts)
-
return node unless node.is_a?(Sass::Script::Operation)
-
return val_to_sass_concat(node, opts) unless node.operator == :comma
-
-
Sass::Script::Operation.new(
-
val_to_sass_concat(node.operand1, opts),
-
val_to_sass_comma(node.operand2, opts),
-
node.operator)
-
end
-
-
2
def val_to_sass_concat(node, opts)
-
return node unless node.is_a?(Sass::Script::Operation)
-
return val_to_sass_div(node, opts) unless node.operator == :space
-
-
Sass::Script::Operation.new(
-
val_to_sass_div(node.operand1, opts),
-
val_to_sass_concat(node.operand2, opts),
-
node.operator)
-
end
-
-
2
def val_to_sass_div(node, opts)
-
unless node.is_a?(Sass::Script::Operation) && node.operator == :div &&
-
node.operand1.is_a?(Sass::Script::Number) &&
-
node.operand2.is_a?(Sass::Script::Number) &&
-
(!node.operand1.original || !node.operand2.original)
-
return node
-
end
-
-
Sass::Script::String.new("(#{node.to_sass(opts)})")
-
end
-
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A dynamic node representing returning from a function.
-
#
-
# @see Sass::Tree
-
2
class ReturnNode < Node
-
# The expression to return.
-
# @type [Script::Node]
-
2
attr_accessor :expr
-
-
# @param expr [Script::Node] The expression to return
-
2
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A static node that is the root node of the Sass document.
-
2
class RootNode < Node
-
# The Sass template from which this node was created
-
#
-
# @param template [String]
-
2
attr_reader :template
-
-
# @param template [String] The Sass template from which this node was created
-
2
def initialize(template)
-
super()
-
@template = template
-
end
-
-
# Runs the dynamic Sass code *and* computes the CSS for the tree.
-
# @see #to_s
-
2
def render
-
Visitors::CheckNesting.visit(self)
-
result = Visitors::Perform.visit(self)
-
Visitors::CheckNesting.visit(result) # Check again to validate mixins
-
result, extends = Visitors::Cssize.visit(result)
-
Visitors::Extend.visit(result, extends)
-
result.to_s
-
end
-
end
-
end
-
end
-
2
require 'pathname'
-
2
require 'uri'
-
-
2
module Sass::Tree
-
# A static node reprenting a CSS rule.
-
#
-
# @see Sass::Tree
-
2
class RuleNode < Node
-
# The character used to include the parent selector
-
2
PARENT = '&'
-
-
# The CSS selector for this rule,
-
# interspersed with {Sass::Script::Node}s
-
# representing `#{}`-interpolation.
-
# Any adjacent strings will be merged together.
-
#
-
# @return [Array<String, Sass::Script::Node>]
-
2
attr_accessor :rule
-
-
# The CSS selector for this rule,
-
# without any unresolved interpolation
-
# but with parent references still intact.
-
# It's only set once {Tree::Node#perform} has been called.
-
#
-
# @return [Selector::CommaSequence]
-
2
attr_accessor :parsed_rules
-
-
# The CSS selector for this rule,
-
# without any unresolved interpolation or parent references.
-
# It's only set once {Tree::Visitors::Cssize} has been run.
-
#
-
# @return [Selector::CommaSequence]
-
2
attr_accessor :resolved_rules
-
-
# How deep this rule is indented
-
# relative to a base-level rule.
-
# This is only greater than 0 in the case that:
-
#
-
# * This node is in a CSS tree
-
# * The style is :nested
-
# * This is a child rule of another rule
-
# * The parent rule has properties, and thus will be rendered
-
#
-
# @return [Fixnum]
-
2
attr_accessor :tabs
-
-
# Whether or not this rule is the last rule in a nested group.
-
# This is only set in a CSS tree.
-
#
-
# @return [Boolean]
-
2
attr_accessor :group_end
-
-
# The stack trace.
-
# This is only readable in a CSS tree as it is written during the perform step
-
# and only when the :trace_selectors option is set.
-
#
-
# @return [Array<String>]
-
2
attr_accessor :stack_trace
-
-
# @param rule [Array<String, Sass::Script::Node>]
-
# The CSS rule. See \{#rule}
-
2
def initialize(rule)
-
merged = Sass::Util.merge_adjacent_strings(rule)
-
@rule = Sass::Util.strip_string_array(merged)
-
@tabs = 0
-
try_to_parse_non_interpolated_rules
-
super()
-
end
-
-
# If we've precached the parsed selector, set the line on it, too.
-
2
def line=(line)
-
@parsed_rules.line = line if @parsed_rules
-
super
-
end
-
-
# If we've precached the parsed selector, set the filename on it, too.
-
2
def filename=(filename)
-
@parsed_rules.filename = filename if @parsed_rules
-
super
-
end
-
-
# Compares the contents of two rules.
-
#
-
# @param other [Object] The object to compare with
-
# @return [Boolean] Whether or not this node and the other object
-
# are the same
-
2
def ==(other)
-
self.class == other.class && rule == other.rule && super
-
end
-
-
# Adds another {RuleNode}'s rules to this one's.
-
#
-
# @param node [RuleNode] The other node
-
2
def add_rules(node)
-
@rule = Sass::Util.strip_string_array(
-
Sass::Util.merge_adjacent_strings(@rule + ["\n"] + node.rule))
-
try_to_parse_non_interpolated_rules
-
end
-
-
# @return [Boolean] Whether or not this rule is continued on the next line
-
2
def continued?
-
last = @rule.last
-
last.is_a?(String) && last[-1] == ?,
-
end
-
-
# A hash that will be associated with this rule in the CSS document
-
# if the {file:SASS_REFERENCE.md#debug_info-option `:debug_info` option} is enabled.
-
# This data is used by e.g. [the FireSass Firebug extension](https://addons.mozilla.org/en-US/firefox/addon/103988).
-
#
-
# @return [{#to_s => #to_s}]
-
2
def debug_info
-
{:filename => filename && ("file://" + URI.escape(File.expand_path(filename))),
-
:line => self.line}
-
end
-
-
# A rule node is invisible if it has only placeholder selectors.
-
2
def invisible?
-
resolved_rules.members.all? {|seq| seq.has_placeholder?}
-
end
-
-
2
private
-
-
2
def try_to_parse_non_interpolated_rules
-
if @rule.all? {|t| t.kind_of?(String)}
-
# We don't use real filename/line info because we don't have it yet.
-
# When we get it, we'll set it on the parsed rules if possible.
-
parser = Sass::SCSS::StaticParser.new(@rule.join.strip, '', 1)
-
@parsed_rules = parser.parse_selector rescue nil
-
end
-
end
-
end
-
end
-
2
module Sass::Tree
-
# A static node representing a `@supports` rule.
-
# `@supports` rules behave differently from other directives
-
# in that when they're nested within rules,
-
# they bubble up to top-level.
-
#
-
# @see Sass::Tree
-
2
class SupportsNode < DirectiveNode
-
# The name, which may include a browser prefix.
-
#
-
# @return [String]
-
2
attr_accessor :name
-
-
# The supports condition.
-
#
-
# @return [Sass::Supports::Condition]
-
2
attr_accessor :condition
-
-
# @see RuleNode#tabs
-
2
attr_accessor :tabs
-
-
# @see RuleNode#group_end
-
2
attr_accessor :group_end
-
-
# @param condition [Sass::Supports::Condition] See \{#condition}
-
2
def initialize(name, condition)
-
@name = name
-
@condition = condition
-
@tabs = 0
-
super('')
-
end
-
-
# @see DirectiveNode#value
-
2
def value; raise NotImplementedError; end
-
-
# @see DirectiveNode#resolved_value
-
2
def resolved_value
-
@resolved_value ||= "@#{name} #{condition.to_css}"
-
end
-
-
# True when the directive has no visible children.
-
#
-
# @return [Boolean]
-
2
def invisible?
-
children.all? {|c| c.invisible?}
-
end
-
-
# @see Node#bubbles?
-
2
def bubbles?; true; end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A solely static node left over after a mixin include or @content has been performed.
-
# Its sole purpose is to wrap exceptions to add to the backtrace.
-
#
-
# @see Sass::Tree
-
2
class TraceNode < Node
-
# The name of the trace entry to add.
-
# @return [String]
-
2
attr_reader :name
-
-
# @param name [String] The name of the trace entry to add.
-
2
def initialize(name)
-
@name = name
-
self.has_children = true
-
super()
-
end
-
-
# Initializes this node from an existing node.
-
# @param name [String] The name of the trace entry to add.
-
# @param mixin [Node] The node to copy information from.
-
# @return [TraceNode]
-
2
def self.from_node(name, node)
-
trace = new(name)
-
trace.line = node.line
-
trace.filename = node.filename
-
trace.options = node.options
-
trace
-
end
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A dynamic node representing a variable definition.
-
#
-
# @see Sass::Tree
-
2
class VariableNode < Node
-
# The name of the variable.
-
# @return [String]
-
2
attr_reader :name
-
-
# The parse tree for the variable value.
-
# @return [Script::Node]
-
2
attr_accessor :expr
-
-
# Whether this is a guarded variable assignment (`!default`).
-
# @return [Boolean]
-
2
attr_reader :guarded
-
-
# @param name [String] The name of the variable
-
# @param expr [Script::Node] See \{#expr}
-
# @param guarded [Boolean] See \{#guarded}
-
2
def initialize(name, expr, guarded)
-
@name = name
-
@expr = expr
-
@guarded = guarded
-
super()
-
end
-
end
-
end
-
end
-
# Visitors are used to traverse the Sass parse tree.
-
# Visitors should extend {Visitors::Base},
-
# which provides a small amount of scaffolding for traversal.
-
2
module Sass::Tree::Visitors
-
# The abstract base class for Sass visitors.
-
# Visitors should extend this class,
-
# then implement `visit_*` methods for each node they care about
-
# (e.g. `visit_rule` for {RuleNode} or `visit_for` for {ForNode}).
-
# These methods take the node in question as argument.
-
# They may `yield` to visit the child nodes of the current node.
-
#
-
# *Note*: due to the unusual nature of {Sass::Tree::IfNode},
-
# special care must be taken to ensure that it is properly handled.
-
# In particular, there is no built-in scaffolding
-
# for dealing with the return value of `@else` nodes.
-
#
-
# @abstract
-
2
class Base
-
# Runs the visitor on a tree.
-
#
-
# @param root [Tree::Node] The root node of the Sass tree.
-
# @return [Object] The return value of \{#visit} for the root node.
-
2
def self.visit(root)
-
new.send(:visit, root)
-
end
-
-
2
protected
-
-
# Runs the visitor on the given node.
-
# This can be overridden by subclasses that need to do something for each node.
-
#
-
# @param node [Tree::Node] The node to visit.
-
# @return [Object] The return value of the `visit_*` method for this node.
-
2
def visit(node)
-
method = "visit_#{node_name node}"
-
if self.respond_to?(method, true)
-
self.send(method, node) {visit_children(node)}
-
else
-
visit_children(node)
-
end
-
end
-
-
# Visit the child nodes for a given node.
-
# This can be overridden by subclasses that need to do something
-
# with the child nodes' return values.
-
#
-
# This method is run when `visit_*` methods `yield`,
-
# and its return value is returned from the `yield`.
-
#
-
# @param parent [Tree::Node] The parent node of the children to visit.
-
# @return [Array<Object>] The return values of the `visit_*` methods for the children.
-
2
def visit_children(parent)
-
parent.children.map {|c| visit(c)}
-
end
-
-
2
NODE_NAME_RE = /.*::(.*?)Node$/
-
-
# Returns the name of a node as used in the `visit_*` method.
-
#
-
# @param [Tree::Node] node The node.
-
# @return [String] The name.
-
2
def node_name(node)
-
@@node_names ||= {}
-
@@node_names[node.class.name] ||= node.class.name.gsub(NODE_NAME_RE, '\\1').downcase
-
end
-
-
# `yield`s, then runs the visitor on the `@else` clause if the node has one.
-
# This exists to ensure that the contents of the `@else` clause get visited.
-
2
def visit_if(node)
-
yield
-
visit(node.else) if node.else
-
node
-
end
-
end
-
end
-
# A visitor for checking that all nodes are properly nested.
-
2
class Sass::Tree::Visitors::CheckNesting < Sass::Tree::Visitors::Base
-
2
protected
-
-
2
def initialize
-
@parents = []
-
end
-
-
2
def visit(node)
-
if error = @parent && (
-
try_send("invalid_#{node_name @parent}_child?", @parent, node) ||
-
try_send("invalid_#{node_name node}_parent?", @parent, node))
-
raise Sass::SyntaxError.new(error)
-
end
-
super
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
2
CONTROL_NODES = [Sass::Tree::EachNode, Sass::Tree::ForNode, Sass::Tree::IfNode,
-
Sass::Tree::WhileNode, Sass::Tree::TraceNode]
-
2
SCRIPT_NODES = [Sass::Tree::ImportNode] + CONTROL_NODES
-
2
def visit_children(parent)
-
old_parent = @parent
-
@parent = parent unless is_any_of?(parent, SCRIPT_NODES) ||
-
(parent.bubbles? && !old_parent.is_a?(Sass::Tree::RootNode))
-
@parents.push parent
-
super
-
ensure
-
@parent = old_parent
-
@parents.pop
-
end
-
-
2
def visit_root(node)
-
yield
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
2
def visit_import(node)
-
yield
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.children.first.filename)
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
2
def visit_mixindef(node)
-
@current_mixin_def, old_mixin_def = node, @current_mixin_def
-
yield
-
ensure
-
@current_mixin_def = old_mixin_def
-
end
-
-
2
def invalid_content_parent?(parent, child)
-
if @current_mixin_def
-
@current_mixin_def.has_content = true
-
nil
-
else
-
"@content may only be used within a mixin."
-
end
-
end
-
-
2
def invalid_charset_parent?(parent, child)
-
"@charset may only be used at the root of a document." unless parent.is_a?(Sass::Tree::RootNode)
-
end
-
-
2
VALID_EXTEND_PARENTS = [Sass::Tree::RuleNode, Sass::Tree::MixinDefNode, Sass::Tree::MixinNode]
-
2
def invalid_extend_parent?(parent, child)
-
unless is_any_of?(parent, VALID_EXTEND_PARENTS)
-
return "Extend directives may only be used within rules."
-
end
-
end
-
-
2
INVALID_IMPORT_PARENTS = CONTROL_NODES +
-
[Sass::Tree::MixinDefNode, Sass::Tree::MixinNode]
-
2
def invalid_import_parent?(parent, child)
-
unless (@parents.map {|p| p.class} & INVALID_IMPORT_PARENTS).empty?
-
return "Import directives may not be used within control directives or mixins."
-
end
-
return if parent.is_a?(Sass::Tree::RootNode)
-
return "CSS import directives may only be used at the root of a document." if child.css_import?
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => child.imported_file.options[:filename])
-
e.add_backtrace(:filename => child.filename, :line => child.line)
-
raise e
-
end
-
-
2
def invalid_mixindef_parent?(parent, child)
-
unless (@parents.map {|p| p.class} & INVALID_IMPORT_PARENTS).empty?
-
return "Mixins may not be defined within control directives or other mixins."
-
end
-
end
-
-
2
def invalid_function_parent?(parent, child)
-
unless (@parents.map {|p| p.class} & INVALID_IMPORT_PARENTS).empty?
-
return "Functions may not be defined within control directives or other mixins."
-
end
-
end
-
-
2
VALID_FUNCTION_CHILDREN = [
-
Sass::Tree::CommentNode, Sass::Tree::DebugNode, Sass::Tree::ReturnNode,
-
Sass::Tree::VariableNode, Sass::Tree::WarnNode
-
] + CONTROL_NODES
-
2
def invalid_function_child?(parent, child)
-
unless is_any_of?(child, VALID_FUNCTION_CHILDREN)
-
"Functions can only contain variable declarations and control directives."
-
end
-
end
-
-
2
VALID_PROP_CHILDREN = [Sass::Tree::CommentNode, Sass::Tree::PropNode, Sass::Tree::MixinNode] + CONTROL_NODES
-
2
def invalid_prop_child?(parent, child)
-
unless is_any_of?(child, VALID_PROP_CHILDREN)
-
"Illegal nesting: Only properties may be nested beneath properties."
-
end
-
end
-
-
2
VALID_PROP_PARENTS = [Sass::Tree::RuleNode, Sass::Tree::PropNode,
-
Sass::Tree::MixinDefNode, Sass::Tree::DirectiveNode,
-
Sass::Tree::MixinNode]
-
2
def invalid_prop_parent?(parent, child)
-
unless is_any_of?(parent, VALID_PROP_PARENTS)
-
"Properties are only allowed within rules, directives, mixin includes, or other properties." + child.pseudo_class_selector_message
-
end
-
end
-
-
2
def invalid_return_parent?(parent, child)
-
"@return may only be used within a function." unless parent.is_a?(Sass::Tree::FunctionNode)
-
end
-
-
2
private
-
-
2
def is_any_of?(val, classes)
-
for c in classes
-
return true if val.is_a?(c)
-
end
-
return false
-
end
-
-
2
def try_send(method, *args)
-
return unless respond_to?(method, true)
-
send(method, *args)
-
end
-
end
-
-
# A visitor for converting a Sass tree into a source string.
-
2
class Sass::Tree::Visitors::Convert < Sass::Tree::Visitors::Base
-
# Runs the visitor on a tree.
-
#
-
# @param root [Tree::Node] The root node of the Sass tree.
-
# @param options [{Symbol => Object}] An options hash (see {Sass::CSS#initialize}).
-
# @param format [Symbol] `:sass` or `:scss`.
-
# @return [String] The Sass or SCSS source for the tree.
-
2
def self.visit(root, options, format)
-
new(options, format).send(:visit, root)
-
end
-
-
2
protected
-
-
2
def initialize(options, format)
-
@options = options
-
@format = format
-
@tabs = 0
-
# 2 spaces by default
-
@tab_chars = @options[:indent] || " "
-
end
-
-
2
def visit_children(parent)
-
@tabs += 1
-
return @format == :sass ? "\n" : " {}\n" if parent.children.empty?
-
(@format == :sass ? "\n" : " {\n") + super.join.rstrip + (@format == :sass ? "\n" : "\n#{ @tab_chars * (@tabs-1)}}\n")
-
ensure
-
@tabs -= 1
-
end
-
-
# Ensures proper spacing between top-level nodes.
-
2
def visit_root(node)
-
Sass::Util.enum_cons(node.children + [nil], 2).map do |child, nxt|
-
visit(child) +
-
if nxt &&
-
(child.is_a?(Sass::Tree::CommentNode) &&
-
child.line + child.lines + 1 == nxt.line) ||
-
(child.is_a?(Sass::Tree::ImportNode) && nxt.is_a?(Sass::Tree::ImportNode) &&
-
child.line + 1 == nxt.line) ||
-
(child.is_a?(Sass::Tree::VariableNode) && nxt.is_a?(Sass::Tree::VariableNode) &&
-
child.line + 1 == nxt.line)
-
""
-
else
-
"\n"
-
end
-
end.join.rstrip + "\n"
-
end
-
-
2
def visit_charset(node)
-
"#{tab_str}@charset \"#{node.name}\"#{semi}\n"
-
end
-
-
2
def visit_comment(node)
-
value = interp_to_src(node.value)
-
content = if @format == :sass
-
content = value.gsub(/\*\/$/, '').rstrip
-
if content =~ /\A[ \t]/
-
# Re-indent SCSS comments like this:
-
# /* foo
-
# bar
-
# baz */
-
content.gsub!(/^/, ' ')
-
content.sub!(/\A([ \t]*)\/\*/, '/*\1')
-
end
-
-
content =
-
unless content.include?("\n")
-
content
-
else
-
content.gsub!(/\n( \*|\/\/)/, "\n ")
-
spaces = content.scan(/\n( *)/).map {|s| s.first.size}.min
-
sep = node.type == :silent ? "\n//" : "\n *"
-
if spaces >= 2
-
content.gsub(/\n /, sep)
-
else
-
content.gsub(/\n#{' ' * spaces}/, sep)
-
end
-
end
-
-
content.gsub!(/\A\/\*/, '//') if node.type == :silent
-
content.gsub!(/^/, tab_str)
-
content.rstrip + "\n"
-
else
-
spaces = (@tab_chars * [@tabs - value[/^ */].size, 0].max)
-
content = if node.type == :silent
-
value.gsub(/^[\/ ]\*/, '//').gsub(/ *\*\/$/, '')
-
else
-
value
-
end.gsub(/^/, spaces) + "\n"
-
content
-
end
-
content
-
end
-
-
2
def visit_debug(node)
-
"#{tab_str}@debug #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
2
def visit_directive(node)
-
res = "#{tab_str}#{interp_to_src(node.value)}"
-
res.gsub!(/^@import \#\{(.*)\}([^}]*)$/, '@import \1\2');
-
return res + "#{semi}\n" unless node.has_children
-
res + yield + "\n"
-
end
-
-
2
def visit_each(node)
-
"#{tab_str}@each $#{dasherize(node.var)} in #{node.list.to_sass(@options)}#{yield}"
-
end
-
-
2
def visit_extend(node)
-
"#{tab_str}@extend #{selector_to_src(node.selector).lstrip}#{semi}#{" !optional" if node.optional?}\n"
-
end
-
-
2
def visit_for(node)
-
"#{tab_str}@for $#{dasherize(node.var)} from #{node.from.to_sass(@options)} " +
-
"#{node.exclusive ? "to" : "through"} #{node.to.to_sass(@options)}#{yield}"
-
end
-
-
2
def visit_function(node)
-
args = node.args.map do |v, d|
-
d ? "#{v.to_sass(@options)}: #{d.to_sass(@options)}" : v.to_sass(@options)
-
end.join(", ")
-
if node.splat
-
args << ", " unless node.args.empty?
-
args << node.splat.to_sass(@options) << "..."
-
end
-
-
"#{tab_str}@function #{dasherize(node.name)}(#{args})#{yield}"
-
end
-
-
2
def visit_if(node)
-
name =
-
if !@is_else; "if"
-
elsif node.expr; "else if"
-
else; "else"
-
end
-
@is_else = false
-
str = "#{tab_str}@#{name}"
-
str << " #{node.expr.to_sass(@options)}" if node.expr
-
str << yield
-
@is_else = true
-
str << visit(node.else) if node.else
-
str
-
ensure
-
@is_else = false
-
end
-
-
2
def visit_import(node)
-
quote = @format == :scss ? '"' : ''
-
"#{tab_str}@import #{quote}#{node.imported_filename}#{quote}#{semi}\n"
-
end
-
-
2
def visit_media(node)
-
"#{tab_str}@media #{media_interp_to_src(node.query)}#{yield}"
-
end
-
-
2
def visit_supports(node)
-
"#{tab_str}@#{node.name} #{node.condition.to_src(@options)}#{yield}"
-
end
-
-
2
def visit_cssimport(node)
-
if node.uri.is_a?(Sass::Script::Node)
-
str = "#{tab_str}@import #{node.uri.to_sass(@options)}"
-
else
-
str = "#{tab_str}@import #{node.uri}"
-
end
-
str << " #{interp_to_src(node.query)}" unless node.query.empty?
-
"#{str}#{semi}\n"
-
end
-
-
2
def visit_mixindef(node)
-
args =
-
if node.args.empty? && node.splat.nil?
-
""
-
else
-
str = '('
-
str << node.args.map do |v, d|
-
if d
-
"#{v.to_sass(@options)}: #{d.to_sass(@options)}"
-
else
-
v.to_sass(@options)
-
end
-
end.join(", ")
-
-
if node.splat
-
str << ", " unless node.args.empty?
-
str << node.splat.to_sass(@options) << '...'
-
end
-
-
str << ')'
-
end
-
-
"#{tab_str}#{@format == :sass ? '=' : '@mixin '}#{dasherize(node.name)}#{args}#{yield}"
-
end
-
-
2
def visit_mixin(node)
-
arg_to_sass = lambda do |arg|
-
sass = arg.to_sass(@options)
-
sass = "(#{sass})" if arg.is_a?(Sass::Script::List) && arg.separator == :comma
-
sass
-
end
-
-
unless node.args.empty? && node.keywords.empty? && node.splat.nil?
-
args = node.args.map(&arg_to_sass).join(", ")
-
keywords = Sass::Util.hash_to_a(node.keywords).
-
map {|k, v| "$#{dasherize(k)}: #{arg_to_sass[v]}"}.join(', ')
-
if node.splat
-
splat = (args.empty? && keywords.empty?) ? "" : ", "
-
splat = "#{splat}#{arg_to_sass[node.splat]}..."
-
end
-
arglist = "(#{args}#{', ' unless args.empty? || keywords.empty?}#{keywords}#{splat})"
-
end
-
"#{tab_str}#{@format == :sass ? '+' : '@include '}#{dasherize(node.name)}#{arglist}#{node.has_children ? yield : semi}\n"
-
end
-
-
2
def visit_content(node)
-
"#{tab_str}@content#{semi}\n"
-
end
-
-
2
def visit_prop(node)
-
res = tab_str + node.declaration(@options, @format)
-
return res + semi + "\n" if node.children.empty?
-
res + yield.rstrip + semi + "\n"
-
end
-
-
2
def visit_return(node)
-
"#{tab_str}@return #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
2
def visit_rule(node)
-
if @format == :sass
-
name = selector_to_sass(node.rule)
-
name = "\\" + name if name[0] == ?:
-
name.gsub(/^/, tab_str) + yield
-
elsif @format == :scss
-
name = selector_to_scss(node.rule)
-
res = name + yield
-
if node.children.last.is_a?(Sass::Tree::CommentNode) && node.children.last.type == :silent
-
res.slice!(-3..-1)
-
res << "\n" << tab_str << "}\n"
-
end
-
res
-
end
-
end
-
-
2
def visit_variable(node)
-
"#{tab_str}$#{dasherize(node.name)}: #{node.expr.to_sass(@options)}#{' !default' if node.guarded}#{semi}\n"
-
end
-
-
2
def visit_warn(node)
-
"#{tab_str}@warn #{node.expr.to_sass(@options)}#{semi}\n"
-
end
-
-
2
def visit_while(node)
-
"#{tab_str}@while #{node.expr.to_sass(@options)}#{yield}"
-
end
-
-
2
private
-
-
2
def interp_to_src(interp)
-
interp.map do |r|
-
next r if r.is_a?(String)
-
"\#{#{r.to_sass(@options)}}"
-
end.join
-
end
-
-
# Like interp_to_src, but removes the unnecessary `#{}` around the keys and
-
# values in media expressions.
-
2
def media_interp_to_src(interp)
-
Sass::Util.enum_with_index(interp).map do |r, i|
-
next r if r.is_a?(String)
-
before, after = interp[i-1], interp[i+1]
-
if before.is_a?(String) && after.is_a?(String) &&
-
((before[-1] == ?( && after[0] == ?:) ||
-
(before =~ /:\s*/ && after[0] == ?)))
-
r.to_sass(@options)
-
else
-
"\#{#{r.to_sass(@options)}}"
-
end
-
end.join
-
end
-
-
2
def selector_to_src(sel)
-
@format == :sass ? selector_to_sass(sel) : selector_to_scss(sel)
-
end
-
-
2
def selector_to_sass(sel)
-
sel.map do |r|
-
if r.is_a?(String)
-
r.gsub(/(,)?([ \t]*)\n\s*/) {$1 ? "#{$1}#{$2}\n" : " "}
-
else
-
"\#{#{r.to_sass(@options)}}"
-
end
-
end.join
-
end
-
-
2
def selector_to_scss(sel)
-
interp_to_src(sel).gsub(/^[ \t]*/, tab_str).gsub(/[ \t]*$/, '')
-
end
-
-
2
def semi
-
@format == :sass ? "" : ";"
-
end
-
-
2
def tab_str
-
@tab_chars * @tabs
-
end
-
-
2
def dasherize(s)
-
if @options[:dasherize]
-
s.gsub('_', '-')
-
else
-
s
-
end
-
end
-
end
-
# A visitor for converting a static Sass tree into a static CSS tree.
-
2
class Sass::Tree::Visitors::Cssize < Sass::Tree::Visitors::Base
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @return [(Tree::Node, Sass::Util::SubsetMap)] The resulting tree of static nodes
-
# *and* the extensions defined for this tree
-
2
def self.visit(root); super; end
-
-
2
protected
-
-
# Returns the immediate parent of the current node.
-
# @return [Tree::Node]
-
2
attr_reader :parent
-
-
2
def initialize
-
@parent_directives = []
-
@extends = Sass::Util::SubsetMap.new
-
end
-
-
# If an exception is raised, this adds proper metadata to the backtrace.
-
2
def visit(node)
-
super(node)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Keeps track of the current parent node.
-
2
def visit_children(parent)
-
with_parent parent do
-
parent.children = super.flatten
-
parent
-
end
-
end
-
-
2
MERGEABLE_DIRECTIVES = [Sass::Tree::MediaNode]
-
-
# Runs a block of code with the current parent node
-
# replaced with the given node.
-
#
-
# @param parent [Tree::Node] The new parent for the duration of the block.
-
# @yield A block in which the parent is set to `parent`.
-
# @return [Object] The return value of the block.
-
2
def with_parent(parent)
-
if parent.is_a?(Sass::Tree::DirectiveNode)
-
if MERGEABLE_DIRECTIVES.any? {|klass| parent.is_a?(klass)}
-
old_parent_directive = @parent_directives.pop
-
end
-
@parent_directives.push parent
-
end
-
-
old_parent, @parent = @parent, parent
-
yield
-
ensure
-
@parent_directives.pop if parent.is_a?(Sass::Tree::DirectiveNode)
-
@parent_directives.push old_parent_directive if old_parent_directive
-
@parent = old_parent
-
end
-
-
# In Ruby 1.8, ensures that there's only one `@charset` directive
-
# and that it's at the top of the document.
-
#
-
# @return [(Tree::Node, Sass::Util::SubsetMap)] The resulting tree of static nodes
-
# *and* the extensions defined for this tree
-
2
def visit_root(node)
-
yield
-
-
if parent.nil?
-
# In Ruby 1.9 we can make all @charset nodes invisible
-
# and infer the final @charset from the encoding of the final string.
-
if Sass::Util.ruby1_8?
-
charset = node.children.find {|c| c.is_a?(Sass::Tree::CharsetNode)}
-
node.children.reject! {|c| c.is_a?(Sass::Tree::CharsetNode)}
-
node.children.unshift charset if charset
-
end
-
-
imports = Sass::Util.extract!(node.children) do |c|
-
c.is_a?(Sass::Tree::DirectiveNode) && !c.is_a?(Sass::Tree::MediaNode) &&
-
c.resolved_value =~ /^@import /i
-
end
-
charset_and_index = Sass::Util.ruby1_8? &&
-
node.children.each_with_index.find {|c, _| c.is_a?(Sass::Tree::CharsetNode)}
-
if charset_and_index
-
index = charset_and_index.last
-
node.children = node.children[0..index] + imports + node.children[index+1..-1]
-
else
-
node.children = imports + node.children
-
end
-
end
-
-
return node, @extends
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
# A simple struct wrapping up information about a single `@extend` instance. A
-
# single [ExtendNode] can have multiple Extends if either the parent node or
-
# the extended selector is a comma sequence.
-
#
-
# @attr extender [Sass::Selector::Sequence]
-
# The selector of the CSS rule containing the `@extend`.
-
# @attr target [Array<Sass::Selector::Simple>] The selector being `@extend`ed.
-
# @attr node [Sass::Tree::ExtendNode] The node that produced this extend.
-
# @attr directives [Array<Sass::Tree::DirectiveNode>]
-
# The directives containing the `@extend`.
-
# @attr result [Symbol]
-
# The result of this extend. One of `:not_found` (the target doesn't exist
-
# in the document), `:failed_to_unify` (the target exists but cannot be
-
# unified with the extender), or `:succeeded`.
-
2
Extend = Struct.new(:extender, :target, :node, :directives, :result)
-
-
# Registers an extension in the `@extends` subset map.
-
2
def visit_extend(node)
-
node.resolved_selector.members.each do |seq|
-
if seq.members.size > 1
-
raise Sass::SyntaxError.new("Can't extend #{seq.to_a.join}: can't extend nested selectors")
-
end
-
-
sseq = seq.members.first
-
if !sseq.is_a?(Sass::Selector::SimpleSequence)
-
raise Sass::SyntaxError.new("Can't extend #{seq.to_a.join}: invalid selector")
-
elsif sseq.members.any? {|ss| ss.is_a?(Sass::Selector::Parent)}
-
raise Sass::SyntaxError.new("Can't extend #{seq.to_a.join}: can't extend parent selectors")
-
end
-
-
sel = sseq.members
-
parent.resolved_rules.members.each do |member|
-
if !member.members.last.is_a?(Sass::Selector::SimpleSequence)
-
raise Sass::SyntaxError.new("#{member} can't extend: invalid selector")
-
end
-
-
@extends[sel] = Extend.new(member, sel, node, @parent_directives.dup, :not_found)
-
end
-
end
-
-
[]
-
end
-
-
# Modifies exception backtraces to include the imported file.
-
2
def visit_import(node)
-
# Don't use #visit_children to avoid adding the import node to the list of parents.
-
node.children.map {|c| visit(c)}.flatten
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.children.first.filename)
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Bubbles the `@media` directive up through RuleNodes
-
# and merges it with other `@media` directives.
-
2
def visit_media(node)
-
yield unless bubble(node)
-
media = node.children.select {|c| c.is_a?(Sass::Tree::MediaNode)}
-
node.children.reject! {|c| c.is_a?(Sass::Tree::MediaNode)}
-
media = media.select {|n| n.resolved_query = n.resolved_query.merge(node.resolved_query)}
-
(node.children.empty? ? [] : [node]) + media
-
end
-
-
# Bubbles the `@supports` directive up through RuleNodes.
-
2
def visit_supports(node)
-
yield unless bubble(node)
-
node
-
end
-
-
# Asserts that all the traced children are valid in their new location.
-
2
def visit_trace(node)
-
# Don't use #visit_children to avoid adding the trace node to the list of parents.
-
node.children.map {|c| visit(c)}.flatten
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:mixin => node.name, :filename => node.filename, :line => node.line)
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Converts nested properties into flat properties
-
# and updates the indentation of the prop node based on the nesting level.
-
2
def visit_prop(node)
-
if parent.is_a?(Sass::Tree::PropNode)
-
node.resolved_name = "#{parent.resolved_name}-#{node.resolved_name}"
-
node.tabs = parent.tabs + (parent.resolved_value.empty? ? 0 : 1) if node.style == :nested
-
end
-
-
yield
-
-
result = node.children.dup
-
if !node.resolved_value.empty? || node.children.empty?
-
node.send(:check!)
-
result.unshift(node)
-
end
-
-
result
-
end
-
-
# Resolves parent references and nested selectors,
-
# and updates the indentation of the rule node based on the nesting level.
-
2
def visit_rule(node)
-
parent_resolved_rules = parent.is_a?(Sass::Tree::RuleNode) ? parent.resolved_rules : nil
-
# It's possible for resolved_rules to be set if we've duplicated this node during @media bubbling
-
node.resolved_rules ||= node.parsed_rules.resolve_parent_refs(parent_resolved_rules)
-
-
yield
-
-
rules = node.children.select {|c| c.is_a?(Sass::Tree::RuleNode) || c.bubbles?}
-
props = node.children.reject {|c| c.is_a?(Sass::Tree::RuleNode) || c.bubbles? || c.invisible?}
-
-
unless props.empty?
-
node.children = props
-
rules.each {|r| r.tabs += 1} if node.style == :nested
-
rules.unshift(node)
-
end
-
-
rules.last.group_end = true unless parent.is_a?(Sass::Tree::RuleNode) || rules.empty?
-
-
rules
-
end
-
-
2
private
-
-
2
def bubble(node)
-
return unless parent.is_a?(Sass::Tree::RuleNode)
-
new_rule = parent.dup
-
new_rule.children = node.children
-
node.children = with_parent(node) {Array(visit(new_rule))}
-
# If the last child is actually the end of the group,
-
# the parent's cssize will set it properly
-
node.children.last.group_end = false unless node.children.empty?
-
true
-
end
-
end
-
# A visitor for copying the full structure of a Sass tree.
-
2
class Sass::Tree::Visitors::DeepCopy < Sass::Tree::Visitors::Base
-
2
protected
-
-
2
def visit(node)
-
super(node.dup)
-
end
-
-
2
def visit_children(parent)
-
parent.children = parent.children.map {|c| visit(c)}
-
parent
-
end
-
-
2
def visit_debug(node)
-
node.expr = node.expr.deep_copy
-
yield
-
end
-
-
2
def visit_each(node)
-
node.list = node.list.deep_copy
-
yield
-
end
-
-
2
def visit_extend(node)
-
node.selector = node.selector.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c}
-
yield
-
end
-
-
2
def visit_for(node)
-
node.from = node.from.deep_copy
-
node.to = node.to.deep_copy
-
yield
-
end
-
-
2
def visit_function(node)
-
node.args = node.args.map {|k, v| [k.deep_copy, v && v.deep_copy]}
-
yield
-
end
-
-
2
def visit_if(node)
-
node.expr = node.expr.deep_copy if node.expr
-
node.else = visit(node.else) if node.else
-
yield
-
end
-
-
2
def visit_mixindef(node)
-
node.args = node.args.map {|k, v| [k.deep_copy, v && v.deep_copy]}
-
yield
-
end
-
-
2
def visit_mixin(node)
-
node.args = node.args.map {|a| a.deep_copy}
-
node.keywords = Hash[node.keywords.map {|k, v| [k, v.deep_copy]}]
-
yield
-
end
-
-
2
def visit_prop(node)
-
node.name = node.name.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c}
-
node.value = node.value.deep_copy
-
yield
-
end
-
-
2
def visit_return(node)
-
node.expr = node.expr.deep_copy
-
yield
-
end
-
-
2
def visit_rule(node)
-
node.rule = node.rule.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c}
-
yield
-
end
-
-
2
def visit_variable(node)
-
node.expr = node.expr.deep_copy
-
yield
-
end
-
-
2
def visit_warn(node)
-
node.expr = node.expr.deep_copy
-
yield
-
end
-
-
2
def visit_while(node)
-
node.expr = node.expr.deep_copy
-
yield
-
end
-
-
2
def visit_directive(node)
-
node.value = node.value.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c}
-
yield
-
end
-
-
2
def visit_media(node)
-
node.query = node.query.map {|c| c.is_a?(Sass::Script::Node) ? c.deep_copy : c}
-
yield
-
end
-
-
2
def visit_supports(node)
-
node.condition = node.condition.deep_copy
-
yield
-
end
-
end
-
# A visitor for performing selector inheritance on a static CSS tree.
-
#
-
# Destructively modifies the tree.
-
2
class Sass::Tree::Visitors::Extend < Sass::Tree::Visitors::Base
-
# Performs the given extensions on the static CSS tree based in `root`, then
-
# validates that all extends matched some selector.
-
#
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @param extends [Sass::Util::SubsetMap{Selector::Simple =>
-
# Sass::Tree::Visitors::Cssize::Extend}]
-
# The extensions to perform on this tree.
-
# @return [Object] The return value of \{#visit} for the root node.
-
2
def self.visit(root, extends)
-
return if extends.empty?
-
new(extends).send(:visit, root)
-
check_extends_fired! extends
-
end
-
-
2
protected
-
-
2
def initialize(extends)
-
@parent_directives = []
-
@extends = extends
-
end
-
-
# If an exception is raised, this adds proper metadata to the backtrace.
-
2
def visit(node)
-
super(node)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Keeps track of the current parent directives.
-
2
def visit_children(parent)
-
@parent_directives.push parent if parent.is_a?(Sass::Tree::DirectiveNode)
-
super
-
ensure
-
@parent_directives.pop if parent.is_a?(Sass::Tree::DirectiveNode)
-
end
-
-
# Applies the extend to a single rule's selector.
-
2
def visit_rule(node)
-
node.resolved_rules = node.resolved_rules.do_extend(@extends, @parent_directives)
-
end
-
-
2
private
-
-
2
def self.check_extends_fired!(extends)
-
extends.each_value do |ex|
-
next if ex.result == :succeeded || ex.node.optional?
-
warn = "\"#{ex.extender}\" failed to @extend \"#{ex.target.join}\"."
-
reason =
-
if ex.result == :not_found
-
"The selector \"#{ex.target.join}\" was not found."
-
else
-
"No selectors matching \"#{ex.target.join}\" could be unified with \"#{ex.extender}\"."
-
end
-
-
Sass::Util.sass_warn <<WARN
-
WARNING on line #{ex.node.line}#{" of #{ex.node.filename}" if ex.node.filename}: #{warn}
-
#{reason}
-
This will be an error in future releases of Sass.
-
Use "@extend #{ex.target.join} !optional" if the extend should be able to fail.
-
WARN
-
end
-
end
-
end
-
# A visitor for converting a dynamic Sass tree into a static Sass tree.
-
2
class Sass::Tree::Visitors::Perform < Sass::Tree::Visitors::Base
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @param environment [Sass::Environment] The lexical environment.
-
# @return [Tree::Node] The resulting tree of static nodes.
-
2
def self.visit(root, environment = Sass::Environment.new)
-
new(environment).send(:visit, root)
-
end
-
-
# @api private
-
2
def self.perform_arguments(callable, args, keywords, splat)
-
desc = "#{callable.type.capitalize} #{callable.name}"
-
downcase_desc = "#{callable.type} #{callable.name}"
-
-
begin
-
unless keywords.empty?
-
unknown_args = Sass::Util.array_minus(keywords.keys,
-
callable.args.map {|var| var.first.underscored_name})
-
if callable.splat && unknown_args.include?(callable.splat.underscored_name)
-
raise Sass::SyntaxError.new("Argument $#{callable.splat.name} of #{downcase_desc} cannot be used as a named argument.")
-
elsif unknown_args.any?
-
description = unknown_args.length > 1 ? 'the following arguments:' : 'an argument named'
-
raise Sass::SyntaxError.new("#{desc} doesn't have #{description} #{unknown_args.map {|name| "$#{name}"}.join ', '}.")
-
end
-
end
-
rescue Sass::SyntaxError => keyword_exception
-
end
-
-
# If there's no splat, raise the keyword exception immediately. The actual
-
# raising happens in the ensure clause at the end of this function.
-
return if keyword_exception && !callable.splat
-
-
if args.size > callable.args.size && !callable.splat
-
takes = callable.args.size
-
passed = args.size
-
raise Sass::SyntaxError.new(
-
"#{desc} takes #{takes} argument#{'s' unless takes == 1} " +
-
"but #{passed} #{passed == 1 ? 'was' : 'were'} passed.")
-
end
-
-
splat_sep = :comma
-
if splat
-
args += splat.to_a
-
splat_sep = splat.separator if splat.is_a?(Sass::Script::List)
-
# If the splat argument exists, there won't be any keywords passed in
-
# manually, so we can safely overwrite rather than merge here.
-
keywords = splat.keywords if splat.is_a?(Sass::Script::ArgList)
-
end
-
-
keywords = keywords.dup
-
env = Sass::Environment.new(callable.environment)
-
callable.args.zip(args[0...callable.args.length]) do |(var, default), value|
-
if value && keywords.include?(var.underscored_name)
-
raise Sass::SyntaxError.new("#{desc} was passed argument $#{var.name} both by position and by name.")
-
end
-
-
value ||= keywords.delete(var.underscored_name)
-
value ||= default && default.perform(env)
-
raise Sass::SyntaxError.new("#{desc} is missing argument #{var.inspect}.") unless value
-
env.set_local_var(var.name, value)
-
end
-
-
if callable.splat
-
rest = args[callable.args.length..-1]
-
arg_list = Sass::Script::ArgList.new(rest, keywords.dup, splat_sep)
-
arg_list.options = env.options
-
env.set_local_var(callable.splat.name, arg_list)
-
end
-
-
yield env
-
rescue Exception => e
-
ensure
-
# If there's a keyword exception, we don't want to throw it immediately,
-
# because the invalid keywords may be part of a glob argument that should be
-
# passed on to another function. So we only raise it if we reach the end of
-
# this function *and* the keywords attached to the argument list glob object
-
# haven't been accessed.
-
#
-
# The keyword exception takes precedence over any Sass errors, but not over
-
# non-Sass exceptions.
-
if keyword_exception &&
-
!(arg_list && arg_list.keywords_accessed) &&
-
(e.nil? || e.is_a?(Sass::SyntaxError))
-
raise keyword_exception
-
elsif e
-
raise e
-
end
-
end
-
-
2
protected
-
-
2
def initialize(env)
-
@environment = env
-
# Stack trace information, including mixin includes and imports.
-
@stack = []
-
end
-
-
# If an exception is raised, this adds proper metadata to the backtrace.
-
2
def visit(node)
-
super(node.dup)
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
# Keeps track of the current environment.
-
2
def visit_children(parent)
-
with_environment Sass::Environment.new(@environment, parent.options) do
-
parent.children = super.flatten
-
parent
-
end
-
end
-
-
# Runs a block of code with the current environment replaced with the given one.
-
#
-
# @param env [Sass::Environment] The new environment for the duration of the block.
-
# @yield A block in which the environment is set to `env`.
-
# @return [Object] The return value of the block.
-
2
def with_environment(env)
-
old_env, @environment = @environment, env
-
yield
-
ensure
-
@environment = old_env
-
end
-
-
# Sets the options on the environment if this is the top-level root.
-
2
def visit_root(node)
-
yield
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
# Removes this node from the tree if it's a silent comment.
-
2
def visit_comment(node)
-
return [] if node.invisible?
-
node.resolved_value = run_interp_no_strip(node.value)
-
node.resolved_value.gsub!(/\\([\\#])/, '\1')
-
node
-
end
-
-
# Prints the expression to STDERR.
-
2
def visit_debug(node)
-
res = node.expr.perform(@environment)
-
res = res.value if res.is_a?(Sass::Script::String)
-
if node.filename
-
Sass::Util.sass_warn "#{node.filename}:#{node.line} DEBUG: #{res}"
-
else
-
Sass::Util.sass_warn "Line #{node.line} DEBUG: #{res}"
-
end
-
[]
-
end
-
-
# Runs the child nodes once for each value in the list.
-
2
def visit_each(node)
-
list = node.list.perform(@environment)
-
-
with_environment Sass::Environment.new(@environment) do
-
list.to_a.map do |v|
-
@environment.set_local_var(node.var, v)
-
node.children.map {|c| visit(c)}
-
end.flatten
-
end
-
end
-
-
# Runs SassScript interpolation in the selector,
-
# and then parses the result into a {Sass::Selector::CommaSequence}.
-
2
def visit_extend(node)
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.selector), node.filename, node.line)
-
node.resolved_selector = parser.parse_selector
-
node
-
end
-
-
# Runs the child nodes once for each time through the loop, varying the variable each time.
-
2
def visit_for(node)
-
from = node.from.perform(@environment)
-
to = node.to.perform(@environment)
-
from.assert_int!
-
to.assert_int!
-
-
to = to.coerce(from.numerator_units, from.denominator_units)
-
range = Range.new(from.to_i, to.to_i, node.exclusive)
-
-
with_environment Sass::Environment.new(@environment) do
-
range.map do |i|
-
@environment.set_local_var(node.var,
-
Sass::Script::Number.new(i, from.numerator_units, from.denominator_units))
-
node.children.map {|c| visit(c)}
-
end.flatten
-
end
-
end
-
-
# Loads the function into the environment.
-
2
def visit_function(node)
-
env = Sass::Environment.new(@environment, node.options)
-
@environment.set_local_function(node.name,
-
Sass::Callable.new(node.name, node.args, node.splat, env, node.children, !:has_content, "function"))
-
[]
-
end
-
-
# Runs the child nodes if the conditional expression is true;
-
# otherwise, tries the else nodes.
-
2
def visit_if(node)
-
if node.expr.nil? || node.expr.perform(@environment).to_bool
-
yield
-
node.children
-
elsif node.else
-
visit(node.else)
-
else
-
[]
-
end
-
end
-
-
# Returns a static DirectiveNode if this is importing a CSS file,
-
# or parses and includes the imported Sass file.
-
2
def visit_import(node)
-
if path = node.css_import?
-
return Sass::Tree::CssImportNode.resolved("url(#{path})")
-
end
-
file = node.imported_file
-
handle_import_loop!(node) if @stack.any? {|e| e[:filename] == file.options[:filename]}
-
-
begin
-
@stack.push(:filename => node.filename, :line => node.line)
-
root = file.to_tree
-
Sass::Tree::Visitors::CheckNesting.visit(root)
-
node.children = root.children.map {|c| visit(c)}.flatten
-
node
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.imported_file.options[:filename])
-
e.add_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
ensure
-
@stack.pop unless path
-
end
-
-
# Loads a mixin into the environment.
-
2
def visit_mixindef(node)
-
env = Sass::Environment.new(@environment, node.options)
-
@environment.set_local_mixin(node.name,
-
Sass::Callable.new(node.name, node.args, node.splat, env, node.children, node.has_content, "mixin"))
-
[]
-
end
-
-
# Runs a mixin.
-
2
def visit_mixin(node)
-
include_loop = true
-
handle_include_loop!(node) if @stack.any? {|e| e[:name] == node.name}
-
include_loop = false
-
-
@stack.push(:filename => node.filename, :line => node.line, :name => node.name)
-
raise Sass::SyntaxError.new("Undefined mixin '#{node.name}'.") unless mixin = @environment.mixin(node.name)
-
-
if node.children.any? && !mixin.has_content
-
raise Sass::SyntaxError.new(%Q{Mixin "#{node.name}" does not accept a content block.})
-
end
-
-
args = node.args.map {|a| a.perform(@environment)}
-
keywords = Sass::Util.map_hash(node.keywords) {|k, v| [k, v.perform(@environment)]}
-
splat = node.splat.perform(@environment) if node.splat
-
-
self.class.perform_arguments(mixin, args, keywords, splat) do |env|
-
env.caller = Sass::Environment.new(@environment)
-
env.content = node.children if node.has_children
-
-
trace_node = Sass::Tree::TraceNode.from_node(node.name, node)
-
with_environment(env) {trace_node.children = mixin.tree.map {|c| visit(c)}.flatten}
-
trace_node
-
end
-
rescue Sass::SyntaxError => e
-
unless include_loop
-
e.modify_backtrace(:mixin => node.name, :line => node.line)
-
e.add_backtrace(:line => node.line)
-
end
-
raise e
-
ensure
-
@stack.pop unless include_loop
-
end
-
-
2
def visit_content(node)
-
return [] unless content = @environment.content
-
@stack.push(:filename => node.filename, :line => node.line, :name => '@content')
-
trace_node = Sass::Tree::TraceNode.from_node('@content', node)
-
with_environment(@environment.caller) {trace_node.children = content.map {|c| visit(c.dup)}.flatten}
-
trace_node
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:mixin => '@content', :line => node.line)
-
e.add_backtrace(:line => node.line)
-
raise e
-
ensure
-
@stack.pop if content
-
end
-
-
# Runs any SassScript that may be embedded in a property.
-
2
def visit_prop(node)
-
node.resolved_name = run_interp(node.name)
-
val = node.value.perform(@environment)
-
node.resolved_value = val.to_s
-
yield
-
end
-
-
# Returns the value of the expression.
-
2
def visit_return(node)
-
throw :_sass_return, node.expr.perform(@environment)
-
end
-
-
# Runs SassScript interpolation in the selector,
-
# and then parses the result into a {Sass::Selector::CommaSequence}.
-
2
def visit_rule(node)
-
rule = node.rule
-
rule = rule.map {|e| e.is_a?(String) && e != ' ' ? e.strip : e} if node.style == :compressed
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.rule), node.filename, node.line)
-
node.parsed_rules ||= parser.parse_selector
-
if node.options[:trace_selectors]
-
@stack.push(:filename => node.filename, :line => node.line)
-
node.stack_trace = stack_trace
-
@stack.pop
-
end
-
yield
-
end
-
-
# Loads the new variable value into the environment.
-
2
def visit_variable(node)
-
var = @environment.var(node.name)
-
return [] if node.guarded && var && !var.null?
-
val = node.expr.perform(@environment)
-
@environment.set_var(node.name, val)
-
[]
-
end
-
-
# Prints the expression to STDERR with a stylesheet trace.
-
2
def visit_warn(node)
-
@stack.push(:filename => node.filename, :line => node.line)
-
res = node.expr.perform(@environment)
-
res = res.value if res.is_a?(Sass::Script::String)
-
msg = "WARNING: #{res}\n "
-
msg << stack_trace.join("\n ") << "\n"
-
Sass::Util.sass_warn msg
-
[]
-
ensure
-
@stack.pop
-
end
-
-
# Runs the child nodes until the continuation expression becomes false.
-
2
def visit_while(node)
-
children = []
-
with_environment Sass::Environment.new(@environment) do
-
children += node.children.map {|c| visit(c)} while node.expr.perform(@environment).to_bool
-
end
-
children.flatten
-
end
-
-
2
def visit_directive(node)
-
node.resolved_value = run_interp(node.value)
-
yield
-
end
-
-
2
def visit_media(node)
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.query), node.filename, node.line)
-
node.resolved_query ||= parser.parse_media_query_list
-
yield
-
end
-
-
2
def visit_supports(node)
-
node.condition = node.condition.deep_copy
-
node.condition.perform(@environment)
-
yield
-
end
-
-
2
def visit_cssimport(node)
-
node.resolved_uri = run_interp([node.uri])
-
if node.query
-
parser = Sass::SCSS::StaticParser.new(run_interp(node.query), node.filename, node.line)
-
node.resolved_query ||= parser.parse_media_query_list
-
end
-
yield
-
end
-
-
2
private
-
-
2
def stack_trace
-
trace = []
-
stack = @stack.map {|e| e.dup}.reverse
-
stack.each_cons(2) {|(e1, e2)| e1[:caller] = e2[:name]; [e1, e2]}
-
stack.each_with_index do |entry, i|
-
msg = "#{i == 0 ? "on" : "from"} line #{entry[:line]}"
-
msg << " of #{entry[:filename] || "an unknown file"}"
-
msg << ", in `#{entry[:caller]}'" if entry[:caller]
-
trace << msg
-
end
-
trace
-
end
-
-
2
def run_interp_no_strip(text)
-
text.map do |r|
-
next r if r.is_a?(String)
-
val = r.perform(@environment)
-
# Interpolated strings should never render with quotes
-
next val.value if val.is_a?(Sass::Script::String)
-
val.to_s
-
end.join
-
end
-
-
2
def run_interp(text)
-
run_interp_no_strip(text).strip
-
end
-
-
2
def handle_include_loop!(node)
-
msg = "An @include loop has been found:"
-
content_count = 0
-
mixins = @stack.reverse.map {|s| s[:name]}.compact.select do |s|
-
if s == '@content'
-
content_count += 1
-
false
-
elsif content_count > 0
-
content_count -= 1
-
false
-
else
-
true
-
end
-
end
-
-
return unless mixins.include?(node.name)
-
raise Sass::SyntaxError.new("#{msg} #{node.name} includes itself") if mixins.size == 1
-
-
msg << "\n" << Sass::Util.enum_cons(mixins.reverse + [node.name], 2).map do |m1, m2|
-
" #{m1} includes #{m2}"
-
end.join("\n")
-
raise Sass::SyntaxError.new(msg)
-
end
-
-
2
def handle_import_loop!(node)
-
msg = "An @import loop has been found:"
-
files = @stack.map {|s| s[:filename]}.compact
-
if node.filename == node.imported_file.options[:filename]
-
raise Sass::SyntaxError.new("#{msg} #{node.filename} imports itself")
-
end
-
-
files << node.filename << node.imported_file.options[:filename]
-
msg << "\n" << Sass::Util.enum_cons(files, 2).map do |m1, m2|
-
" #{m1} imports #{m2}"
-
end.join("\n")
-
raise Sass::SyntaxError.new(msg)
-
end
-
end
-
# A visitor for setting options on the Sass tree
-
2
class Sass::Tree::Visitors::SetOptions < Sass::Tree::Visitors::Base
-
# @param root [Tree::Node] The root node of the tree to visit.
-
# @param options [{Symbol => Object}] The options has to set.
-
2
def self.visit(root, options); new(options).send(:visit, root); end
-
-
2
protected
-
-
2
def initialize(options)
-
@options = options
-
end
-
-
2
def visit(node)
-
node.instance_variable_set('@options', @options)
-
super
-
end
-
-
2
def visit_debug(node)
-
node.expr.options = @options
-
yield
-
end
-
-
2
def visit_each(node)
-
node.list.options = @options
-
yield
-
end
-
-
2
def visit_extend(node)
-
node.selector.each {|c| c.options = @options if c.is_a?(Sass::Script::Node)}
-
yield
-
end
-
-
2
def visit_for(node)
-
node.from.options = @options
-
node.to.options = @options
-
yield
-
end
-
-
2
def visit_function(node)
-
node.args.each do |k, v|
-
k.options = @options
-
v.options = @options if v
-
end
-
yield
-
end
-
-
2
def visit_if(node)
-
node.expr.options = @options if node.expr
-
visit(node.else) if node.else
-
yield
-
end
-
-
2
def visit_import(node)
-
# We have no good way of propagating the new options through an Engine
-
# instance, so we just null it out. This also lets us avoid caching an
-
# imported Engine along with the importing source tree.
-
node.imported_file = nil
-
yield
-
end
-
-
2
def visit_mixindef(node)
-
node.args.each do |k, v|
-
k.options = @options
-
v.options = @options if v
-
end
-
yield
-
end
-
-
2
def visit_mixin(node)
-
node.args.each {|a| a.options = @options}
-
node.keywords.each {|k, v| v.options = @options}
-
yield
-
end
-
-
2
def visit_prop(node)
-
node.name.each {|c| c.options = @options if c.is_a?(Sass::Script::Node)}
-
node.value.options = @options
-
yield
-
end
-
-
2
def visit_return(node)
-
node.expr.options = @options
-
yield
-
end
-
-
2
def visit_rule(node)
-
node.rule.each {|c| c.options = @options if c.is_a?(Sass::Script::Node)}
-
yield
-
end
-
-
2
def visit_variable(node)
-
node.expr.options = @options
-
yield
-
end
-
-
2
def visit_warn(node)
-
node.expr.options = @options
-
yield
-
end
-
-
2
def visit_while(node)
-
node.expr.options = @options
-
yield
-
end
-
-
2
def visit_directive(node)
-
node.value.each {|c| c.options = @options if c.is_a?(Sass::Script::Node)}
-
yield
-
end
-
-
2
def visit_media(node)
-
node.query.each {|c| c.options = @options if c.is_a?(Sass::Script::Node)}
-
yield
-
end
-
-
2
def visit_cssimport(node)
-
node.query.each {|c| c.options = @options if c.is_a?(Sass::Script::Node)} if node.query
-
yield
-
end
-
-
2
def visit_supports(node)
-
node.condition.options = @options
-
yield
-
end
-
end
-
# A visitor for converting a Sass tree into CSS.
-
2
class Sass::Tree::Visitors::ToCss < Sass::Tree::Visitors::Base
-
2
protected
-
-
2
def initialize
-
@tabs = 0
-
end
-
-
2
def visit(node)
-
super
-
rescue Sass::SyntaxError => e
-
e.modify_backtrace(:filename => node.filename, :line => node.line)
-
raise e
-
end
-
-
2
def with_tabs(tabs)
-
old_tabs, @tabs = @tabs, tabs
-
yield
-
ensure
-
@tabs = old_tabs
-
end
-
-
2
def visit_root(node)
-
result = String.new
-
node.children.each do |child|
-
next if child.invisible?
-
child_str = visit(child)
-
result << child_str + (node.style == :compressed ? '' : "\n")
-
end
-
result.rstrip!
-
return "" if result.empty?
-
result << "\n"
-
unless Sass::Util.ruby1_8? || result.ascii_only?
-
if node.children.first.is_a?(Sass::Tree::CharsetNode)
-
begin
-
encoding = node.children.first.name
-
# Default to big-endian encoding, because we have to decide somehow
-
encoding << 'BE' if encoding =~ /\Autf-(16|32)\Z/i
-
result = result.encode(Encoding.find(encoding))
-
rescue EncodingError
-
end
-
end
-
-
result = "@charset \"#{result.encoding.name}\";#{
-
node.style == :compressed ? '' : "\n"
-
}".encode(result.encoding) + result
-
end
-
result
-
rescue Sass::SyntaxError => e
-
e.sass_template ||= node.template
-
raise e
-
end
-
-
2
def visit_charset(node)
-
"@charset \"#{node.name}\";"
-
end
-
-
2
def visit_comment(node)
-
return if node.invisible?
-
spaces = (' ' * [@tabs - node.resolved_value[/^ */].size, 0].max)
-
-
content = node.resolved_value.gsub(/^/, spaces)
-
content.gsub!(%r{^(\s*)//(.*)$}) {|md| "#{$1}/*#{$2} */"} if node.type == :silent
-
content.gsub!(/\n +(\* *(?!\/))?/, ' ') if (node.style == :compact || node.style == :compressed) && node.type != :loud
-
content
-
end
-
-
2
def visit_directive(node)
-
was_in_directive = @in_directive
-
tab_str = ' ' * @tabs
-
return tab_str + node.resolved_value + ";" unless node.has_children
-
return tab_str + node.resolved_value + " {}" if node.children.empty?
-
@in_directive = @in_directive || !node.is_a?(Sass::Tree::MediaNode)
-
result = if node.style == :compressed
-
"#{node.resolved_value}{"
-
else
-
"#{tab_str}#{node.resolved_value} {" + (node.style == :compact ? ' ' : "\n")
-
end
-
was_prop = false
-
first = true
-
node.children.each do |child|
-
next if child.invisible?
-
if node.style == :compact
-
if child.is_a?(Sass::Tree::PropNode)
-
with_tabs(first || was_prop ? 0 : @tabs + 1) {result << visit(child) << ' '}
-
else
-
result[-1] = "\n" if was_prop
-
rendered = with_tabs(@tabs + 1) {visit(child).dup}
-
rendered = rendered.lstrip if first
-
result << rendered.rstrip + "\n"
-
end
-
was_prop = child.is_a?(Sass::Tree::PropNode)
-
first = false
-
elsif node.style == :compressed
-
result << (was_prop ? ";" : "") << with_tabs(0) {visit(child)}
-
was_prop = child.is_a?(Sass::Tree::PropNode)
-
else
-
result << with_tabs(@tabs + 1) {visit(child)} + "\n"
-
end
-
end
-
result.rstrip + if node.style == :compressed
-
"}"
-
else
-
(node.style == :expanded ? "\n" : " ") + "}\n"
-
end
-
ensure
-
@in_directive = was_in_directive
-
end
-
-
2
def visit_media(node)
-
str = with_tabs(@tabs + node.tabs) {visit_directive(node)}
-
str.gsub!(/\n\Z/, '') unless node.style == :compressed || node.group_end
-
str
-
end
-
-
2
def visit_supports(node)
-
visit_media(node)
-
end
-
-
2
def visit_cssimport(node)
-
visit_directive(node)
-
end
-
-
2
def visit_prop(node)
-
return if node.resolved_value.empty?
-
tab_str = ' ' * (@tabs + node.tabs)
-
if node.style == :compressed
-
"#{tab_str}#{node.resolved_name}:#{node.resolved_value}"
-
else
-
"#{tab_str}#{node.resolved_name}: #{node.resolved_value};"
-
end
-
end
-
-
2
def visit_rule(node)
-
with_tabs(@tabs + node.tabs) do
-
rule_separator = node.style == :compressed ? ',' : ', '
-
line_separator =
-
case node.style
-
when :nested, :expanded; "\n"
-
when :compressed; ""
-
else; " "
-
end
-
rule_indent = ' ' * @tabs
-
per_rule_indent, total_indent = [:nested, :expanded].include?(node.style) ? [rule_indent, ''] : ['', rule_indent]
-
-
joined_rules = node.resolved_rules.members.map do |seq|
-
next if seq.has_placeholder?
-
rule_part = seq.to_a.join
-
if node.style == :compressed
-
rule_part.gsub!(/([^,])\s*\n\s*/m, '\1 ')
-
rule_part.gsub!(/\s*([,+>])\s*/m, '\1')
-
rule_part.strip!
-
end
-
rule_part
-
end.compact.join(rule_separator)
-
-
joined_rules.sub!(/\A\s*/, per_rule_indent)
-
joined_rules.gsub!(/\s*\n\s*/, "#{line_separator}#{per_rule_indent}")
-
total_rule = total_indent << joined_rules
-
-
to_return = ''
-
old_spaces = ' ' * @tabs
-
if node.style != :compressed
-
if node.options[:debug_info] && !@in_directive
-
to_return << visit(debug_info_rule(node.debug_info, node.options)) << "\n"
-
elsif node.options[:trace_selectors]
-
to_return << "#{old_spaces}/* "
-
to_return << node.stack_trace.join("\n #{old_spaces}")
-
to_return << " */\n"
-
elsif node.options[:line_comments]
-
to_return << "#{old_spaces}/* line #{node.line}"
-
-
if node.filename
-
relative_filename = if node.options[:css_filename]
-
begin
-
Pathname.new(node.filename).relative_path_from(
-
Pathname.new(File.dirname(node.options[:css_filename]))).to_s
-
rescue ArgumentError
-
nil
-
end
-
end
-
relative_filename ||= node.filename
-
to_return << ", #{relative_filename}"
-
end
-
-
to_return << " */\n"
-
end
-
end
-
-
if node.style == :compact
-
properties = with_tabs(0) {node.children.map {|a| visit(a)}.join(' ')}
-
to_return << "#{total_rule} { #{properties} }#{"\n" if node.group_end}"
-
elsif node.style == :compressed
-
properties = with_tabs(0) {node.children.map {|a| visit(a)}.join(';')}
-
to_return << "#{total_rule}{#{properties}}"
-
else
-
properties = with_tabs(@tabs + 1) {node.children.map {|a| visit(a)}.join("\n")}
-
end_props = (node.style == :expanded ? "\n" + old_spaces : ' ')
-
to_return << "#{total_rule} {\n#{properties}#{end_props}}#{"\n" if node.group_end}"
-
end
-
-
to_return
-
end
-
end
-
-
2
private
-
-
2
def debug_info_rule(debug_info, options)
-
node = Sass::Tree::DirectiveNode.resolved("@media -sass-debug-info")
-
Sass::Util.hash_to_a(debug_info.map {|k, v| [k.to_s, v.to_s]}).each do |k, v|
-
rule = Sass::Tree::RuleNode.new([""])
-
rule.resolved_rules = Sass::Selector::CommaSequence.new(
-
[Sass::Selector::Sequence.new(
-
[Sass::Selector::SimpleSequence.new(
-
[Sass::Selector::Element.new(k.to_s.gsub(/[^\w-]/, "\\\\\\0"), nil)],
-
false)
-
])
-
])
-
prop = Sass::Tree::PropNode.new([""], Sass::Script::String.new(''), :new)
-
prop.resolved_name = "font-family"
-
prop.resolved_value = Sass::SCSS::RX.escape_ident(v.to_s)
-
rule << prop
-
node << rule
-
end
-
node.options = options.merge(:debug_info => false, :line_comments => false, :style => :compressed)
-
node
-
end
-
end
-
2
module Sass
-
2
module Tree
-
# A dynamic node representing a Sass `@warn` statement.
-
#
-
# @see Sass::Tree
-
2
class WarnNode < Node
-
# The expression to print.
-
# @return [Script::Node]
-
2
attr_accessor :expr
-
-
# @param expr [Script::Node] The expression to print
-
2
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
end
-
2
require 'sass/tree/node'
-
-
2
module Sass::Tree
-
# A dynamic node representing a Sass `@while` loop.
-
#
-
# @see Sass::Tree
-
2
class WhileNode < Node
-
# The parse tree for the continuation expression.
-
# @return [Script::Node]
-
2
attr_accessor :expr
-
-
# @param expr [Script::Node] See \{#expr}
-
2
def initialize(expr)
-
@expr = expr
-
super()
-
end
-
end
-
end
-
2
require 'erb'
-
2
require 'set'
-
2
require 'enumerator'
-
2
require 'stringio'
-
2
require 'rbconfig'
-
2
require 'thread'
-
-
2
require 'sass/root'
-
2
require 'sass/util/subset_map'
-
-
2
module Sass
-
# A module containing various useful functions.
-
2
module Util
-
2
extend self
-
-
# An array of ints representing the Ruby version number.
-
# @api public
-
8
RUBY_VERSION = ::RUBY_VERSION.split(".").map {|s| s.to_i}
-
-
# The Ruby engine we're running under. Defaults to `"ruby"`
-
# if the top-level constant is undefined.
-
# @api public
-
2
RUBY_ENGINE = defined?(::RUBY_ENGINE) ? ::RUBY_ENGINE : "ruby"
-
-
# Returns the path of a file relative to the Sass root directory.
-
#
-
# @param file [String] The filename relative to the Sass root
-
# @return [String] The filename relative to the the working directory
-
2
def scope(file)
-
14
File.join(Sass::ROOT_DIR, file)
-
end
-
-
# Converts an array of `[key, value]` pairs to a hash.
-
#
-
# @example
-
# to_hash([[:foo, "bar"], [:baz, "bang"]])
-
# #=> {:foo => "bar", :baz => "bang"}
-
# @param arr [Array<(Object, Object)>] An array of pairs
-
# @return [Hash] A hash
-
2
def to_hash(arr)
-
10
Hash[arr.compact]
-
end
-
-
# Maps the keys in a hash according to a block.
-
#
-
# @example
-
# map_keys({:foo => "bar", :baz => "bang"}) {|k| k.to_s}
-
# #=> {"foo" => "bar", "baz" => "bang"}
-
# @param hash [Hash] The hash to map
-
# @yield [key] A block in which the keys are transformed
-
# @yieldparam key [Object] The key that should be mapped
-
# @yieldreturn [Object] The new value for the key
-
# @return [Hash] The mapped hash
-
# @see #map_vals
-
# @see #map_hash
-
2
def map_keys(hash)
-
to_hash(hash.map {|k, v| [yield(k), v]})
-
end
-
-
# Maps the values in a hash according to a block.
-
#
-
# @example
-
# map_values({:foo => "bar", :baz => "bang"}) {|v| v.to_sym}
-
# #=> {:foo => :bar, :baz => :bang}
-
# @param hash [Hash] The hash to map
-
# @yield [value] A block in which the values are transformed
-
# @yieldparam value [Object] The value that should be mapped
-
# @yieldreturn [Object] The new value for the value
-
# @return [Hash] The mapped hash
-
# @see #map_keys
-
# @see #map_hash
-
2
def map_vals(hash)
-
294
to_hash(hash.map {|k, v| [k, yield(v)]})
-
end
-
-
# Maps the key-value pairs of a hash according to a block.
-
#
-
# @example
-
# map_hash({:foo => "bar", :baz => "bang"}) {|k, v| [k.to_s, v.to_sym]}
-
# #=> {"foo" => :bar, "baz" => :bang}
-
# @param hash [Hash] The hash to map
-
# @yield [key, value] A block in which the key-value pairs are transformed
-
# @yieldparam [key] The hash key
-
# @yieldparam [value] The hash value
-
# @yieldreturn [(Object, Object)] The new value for the `[key, value]` pair
-
# @return [Hash] The mapped hash
-
# @see #map_keys
-
# @see #map_vals
-
2
def map_hash(hash)
-
# Using &block here completely hoses performance on 1.8.
-
394
to_hash(hash.map {|k, v| yield k, v})
-
end
-
-
# Computes the powerset of the given array.
-
# This is the set of all subsets of the array.
-
#
-
# @example
-
# powerset([1, 2, 3]) #=>
-
# Set[Set[], Set[1], Set[2], Set[3], Set[1, 2], Set[2, 3], Set[1, 3], Set[1, 2, 3]]
-
# @param arr [Enumerable]
-
# @return [Set<Set>] The subsets of `arr`
-
2
def powerset(arr)
-
arr.inject([Set.new].to_set) do |powerset, el|
-
new_powerset = Set.new
-
powerset.each do |subset|
-
new_powerset << subset
-
new_powerset << subset + [el]
-
end
-
new_powerset
-
end
-
end
-
-
# Restricts a number to falling within a given range.
-
# Returns the number if it falls within the range,
-
# or the closest value in the range if it doesn't.
-
#
-
# @param value [Numeric]
-
# @param range [Range<Numeric>]
-
# @return [Numeric]
-
2
def restrict(value, range)
-
[[value, range.first].max, range.last].min
-
end
-
-
# Concatenates all strings that are adjacent in an array,
-
# while leaving other elements as they are.
-
#
-
# @example
-
# merge_adjacent_strings([1, "foo", "bar", 2, "baz"])
-
# #=> [1, "foobar", 2, "baz"]
-
# @param arr [Array]
-
# @return [Array] The enumerable with strings merged
-
2
def merge_adjacent_strings(arr)
-
# Optimize for the common case of one element
-
return arr if arr.size < 2
-
arr.inject([]) do |a, e|
-
if e.is_a?(String)
-
if a.last.is_a?(String)
-
a.last << e
-
else
-
a << e.dup
-
end
-
else
-
a << e
-
end
-
a
-
end
-
end
-
-
# Intersperses a value in an enumerable, as would be done with `Array#join`
-
# but without concatenating the array together afterwards.
-
#
-
# @param enum [Enumerable]
-
# @param val
-
# @return [Array]
-
2
def intersperse(enum, val)
-
enum.inject([]) {|a, e| a << e << val}[0...-1]
-
end
-
-
# Substitutes a sub-array of one array with another sub-array.
-
#
-
# @param ary [Array] The array in which to make the substitution
-
# @param from [Array] The sequence of elements to replace with `to`
-
# @param to [Array] The sequence of elements to replace `from` with
-
2
def substitute(ary, from, to)
-
res = ary.dup
-
i = 0
-
while i < res.size
-
if res[i...i+from.size] == from
-
res[i...i+from.size] = to
-
end
-
i += 1
-
end
-
res
-
end
-
-
# Destructively strips whitespace from the beginning and end
-
# of the first and last elements, respectively,
-
# in the array (if those elements are strings).
-
#
-
# @param arr [Array]
-
# @return [Array] `arr`
-
2
def strip_string_array(arr)
-
arr.first.lstrip! if arr.first.is_a?(String)
-
arr.last.rstrip! if arr.last.is_a?(String)
-
arr
-
end
-
-
# Return an array of all possible paths through the given arrays.
-
#
-
# @param arrs [Array<Array>]
-
# @return [Array<Arrays>]
-
#
-
# @example
-
# paths([[1, 2], [3, 4], [5]]) #=>
-
# # [[1, 3, 5],
-
# # [2, 3, 5],
-
# # [1, 4, 5],
-
# # [2, 4, 5]]
-
2
def paths(arrs)
-
arrs.inject([[]]) do |paths, arr|
-
flatten(arr.map {|e| paths.map {|path| path + [e]}}, 1)
-
end
-
end
-
-
# Computes a single longest common subsequence for `x` and `y`.
-
# If there are more than one longest common subsequences,
-
# the one returned is that which starts first in `x`.
-
#
-
# @param x [Array]
-
# @param y [Array]
-
# @yield [a, b] An optional block to use in place of a check for equality
-
# between elements of `x` and `y`.
-
# @yieldreturn [Object, nil] If the two values register as equal,
-
# this will return the value to use in the LCS array.
-
# @return [Array] The LCS
-
2
def lcs(x, y, &block)
-
x = [nil, *x]
-
y = [nil, *y]
-
block ||= proc {|a, b| a == b && a}
-
lcs_backtrace(lcs_table(x, y, &block), x, y, x.size-1, y.size-1, &block)
-
end
-
-
# Converts a Hash to an Array. This is usually identical to `Hash#to_a`,
-
# with the following exceptions:
-
#
-
# * In Ruby 1.8, `Hash#to_a` is not deterministically ordered, but this is.
-
# * In Ruby 1.9 when running tests, this is ordered in the same way it would
-
# be under Ruby 1.8 (sorted key order rather than insertion order).
-
#
-
# @param hash [Hash]
-
# @return [Array]
-
2
def hash_to_a(hash)
-
2
return hash.to_a unless ruby1_8? || defined?(Test::Unit)
-
294
return hash.sort_by {|k, v| k}
-
end
-
-
# Performs the equivalent of `enum.group_by.to_a`, but with a guaranteed
-
# order. Unlike [#hash_to_a], the resulting order isn't sorted key order;
-
# instead, it's the same order as `#group_by` has under Ruby 1.9 (key
-
# appearance order).
-
#
-
# @param enum [Enumerable]
-
# @return [Array<[Object, Array]>] An array of pairs.
-
2
def group_by_to_a(enum, &block)
-
return enum.group_by(&block).to_a unless ruby1_8?
-
order = {}
-
arr = []
-
enum.group_by do |e|
-
res = block[e]
-
unless order.include?(res)
-
order[res] = order.size
-
end
-
res
-
end.each do |key, vals|
-
arr[order[key]] = [key, vals]
-
end
-
arr
-
end
-
-
# Returns a sub-array of `minuend` containing only elements that are also in
-
# `subtrahend`. Ensures that the return value has the same order as
-
# `minuend`, even on Rubinius where that's not guaranteed by {Array#-}.
-
#
-
# @param minuend [Array]
-
# @param subtrahend [Array]
-
# @return [Array]
-
2
def array_minus(minuend, subtrahend)
-
return minuend - subtrahend unless rbx?
-
set = Set.new(minuend) - subtrahend
-
minuend.select {|e| set.include?(e)}
-
end
-
-
# Returns a string description of the character that caused an
-
# `Encoding::UndefinedConversionError`.
-
#
-
# @param [Encoding::UndefinedConversionError]
-
# @return [String]
-
2
def undefined_conversion_error_char(e)
-
# Rubinius (as of 2.0.0.rc1) pre-quotes the error character.
-
return e.error_char if rbx?
-
# JRuby (as of 1.7.2) doesn't have an error_char field on
-
# Encoding::UndefinedConversionError.
-
return e.error_char.dump unless jruby?
-
e.message[/^"[^"]+"/] #"
-
end
-
-
# Asserts that `value` falls within `range` (inclusive), leaving
-
# room for slight floating-point errors.
-
#
-
# @param name [String] The name of the value. Used in the error message.
-
# @param range [Range] The allowed range of values.
-
# @param value [Numeric, Sass::Script::Number] The value to check.
-
# @param unit [String] The unit of the value. Used in error reporting.
-
# @return [Numeric] `value` adjusted to fall within range, if it
-
# was outside by a floating-point margin.
-
2
def check_range(name, range, value, unit='')
-
grace = (-0.00001..0.00001)
-
str = value.to_s
-
value = value.value if value.is_a?(Sass::Script::Number)
-
return value if range.include?(value)
-
return range.first if grace.include?(value - range.first)
-
return range.last if grace.include?(value - range.last)
-
raise ArgumentError.new(
-
"#{name} #{str} must be between #{range.first}#{unit} and #{range.last}#{unit}")
-
end
-
-
# Returns whether or not `seq1` is a subsequence of `seq2`. That is, whether
-
# or not `seq2` contains every element in `seq1` in the same order (and
-
# possibly more elements besides).
-
#
-
# @param seq1 [Array]
-
# @param seq2 [Array]
-
# @return [Boolean]
-
2
def subsequence?(seq1, seq2)
-
i = j = 0
-
loop do
-
return true if i == seq1.size
-
return false if j == seq2.size
-
i += 1 if seq1[i] == seq2[j]
-
j += 1
-
end
-
end
-
-
# Returns information about the caller of the previous method.
-
#
-
# @param entry [String] An entry in the `#caller` list, or a similarly formatted string
-
# @return [[String, Fixnum, (String, nil)]] An array containing the filename, line, and method name of the caller.
-
# The method name may be nil
-
2
def caller_info(entry = nil)
-
# JRuby evaluates `caller` incorrectly when it's in an actual default argument.
-
entry ||= caller[1]
-
info = entry.scan(/^(.*?):(-?.*?)(?::.*`(.+)')?$/).first
-
info[1] = info[1].to_i
-
# This is added by Rubinius to designate a block, but we don't care about it.
-
info[2].sub!(/ \{\}\Z/, '') if info[2]
-
info
-
end
-
-
# Returns whether one version string represents a more recent version than another.
-
#
-
# @param v1 [String] A version string.
-
# @param v2 [String] Another version string.
-
# @return [Boolean]
-
2
def version_gt(v1, v2)
-
# Construct an array to make sure the shorter version is padded with nil
-
2
Array.new([v1.length, v2.length].max).zip(v1.split("."), v2.split(".")) do |_, p1, p2|
-
4
p1 ||= "0"
-
4
p2 ||= "0"
-
4
release1 = p1 =~ /^[0-9]+$/
-
4
release2 = p2 =~ /^[0-9]+$/
-
4
if release1 && release2
-
# Integer comparison if both are full releases
-
4
p1, p2 = p1.to_i, p2.to_i
-
4
next if p1 == p2
-
2
return p1 > p2
-
elsif !release1 && !release2
-
# String comparison if both are prereleases
-
next if p1 == p2
-
return p1 > p2
-
else
-
# If only one is a release, that one is newer
-
return release1
-
end
-
end
-
end
-
-
# Returns whether one version string represents the same or a more
-
# recent version than another.
-
#
-
# @param v1 [String] A version string.
-
# @param v2 [String] Another version string.
-
# @return [Boolean]
-
2
def version_geq(v1, v2)
-
2
version_gt(v1, v2) || !version_gt(v2, v1)
-
end
-
-
# Throws a NotImplementedError for an abstract method.
-
#
-
# @param obj [Object] `self`
-
# @raise [NotImplementedError]
-
2
def abstract(obj)
-
raise NotImplementedError.new("#{obj.class} must implement ##{caller_info[2]}")
-
end
-
-
# Silence all output to STDERR within a block.
-
#
-
# @yield A block in which no output will be printed to STDERR
-
2
def silence_warnings
-
the_real_stderr, $stderr = $stderr, StringIO.new
-
yield
-
ensure
-
$stderr = the_real_stderr
-
end
-
-
2
@@silence_warnings = false
-
# Silences all Sass warnings within a block.
-
#
-
# @yield A block in which no Sass warnings will be printed
-
2
def silence_sass_warnings
-
old_level, Sass.logger.log_level = Sass.logger.log_level, :error
-
yield
-
ensure
-
Sass.logger.log_level = old_level
-
end
-
-
# The same as `Kernel#warn`, but is silenced by \{#silence\_sass\_warnings}.
-
#
-
# @param msg [String]
-
2
def sass_warn(msg)
-
msg = msg + "\n" unless ruby1?
-
Sass.logger.warn(msg)
-
end
-
-
## Cross Rails Version Compatibility
-
-
# Returns the root of the Rails application,
-
# if this is running in a Rails context.
-
# Returns `nil` if no such root is defined.
-
#
-
# @return [String, nil]
-
2
def rails_root
-
if defined?(::Rails.root)
-
return ::Rails.root.to_s if ::Rails.root
-
raise "ERROR: Rails.root is nil!"
-
end
-
return RAILS_ROOT.to_s if defined?(RAILS_ROOT)
-
return nil
-
end
-
-
# Returns the environment of the Rails application,
-
# if this is running in a Rails context.
-
# Returns `nil` if no such environment is defined.
-
#
-
# @return [String, nil]
-
2
def rails_env
-
return ::Rails.env.to_s if defined?(::Rails.env)
-
return RAILS_ENV.to_s if defined?(RAILS_ENV)
-
return nil
-
end
-
-
# Returns whether this environment is using ActionPack
-
# version 3.0.0 or greater.
-
#
-
# @return [Boolean]
-
2
def ap_geq_3?
-
ap_geq?("3.0.0.beta1")
-
end
-
-
# Returns whether this environment is using ActionPack
-
# of a version greater than or equal to that specified.
-
#
-
# @param version [String] The string version number to check against.
-
# Should be greater than or equal to Rails 3,
-
# because otherwise ActionPack::VERSION isn't autoloaded
-
# @return [Boolean]
-
2
def ap_geq?(version)
-
# The ActionPack module is always loaded automatically in Rails >= 3
-
2
return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) &&
-
defined?(ActionPack::VERSION::STRING)
-
-
2
version_geq(ActionPack::VERSION::STRING, version)
-
end
-
-
# Returns an ActionView::Template* class.
-
# In pre-3.0 versions of Rails, most of these classes
-
# were of the form `ActionView::TemplateFoo`,
-
# while afterwards they were of the form `ActionView;:Template::Foo`.
-
#
-
# @param name [#to_s] The name of the class to get.
-
# For example, `:Error` will return `ActionView::TemplateError`
-
# or `ActionView::Template::Error`.
-
2
def av_template_class(name)
-
return ActionView.const_get("Template#{name}") if ActionView.const_defined?("Template#{name}")
-
return ActionView::Template.const_get(name.to_s)
-
end
-
-
## Cross-OS Compatibility
-
-
# Whether or not this is running on Windows.
-
#
-
# @return [Boolean]
-
2
def windows?
-
RbConfig::CONFIG['host_os'] =~ /mswin|windows|mingw/i
-
end
-
-
# Whether or not this is running on IronRuby.
-
#
-
# @return [Boolean]
-
2
def ironruby?
-
10
RUBY_ENGINE == "ironruby"
-
end
-
-
# Whether or not this is running on Rubinius.
-
#
-
# @return [Boolean]
-
2
def rbx?
-
2
RUBY_ENGINE == "rbx"
-
end
-
-
# Whether or not this is running on JRuby.
-
#
-
# @return [Boolean]
-
2
def jruby?
-
RUBY_PLATFORM =~ /java/
-
end
-
-
# Returns an array of ints representing the JRuby version number.
-
#
-
# @return [Array<Fixnum>]
-
2
def jruby_version
-
$jruby_version ||= ::JRUBY_VERSION.split(".").map {|s| s.to_i}
-
end
-
-
# Like `Dir.glob`, but works with backslash-separated paths on Windows.
-
#
-
# @param path [String]
-
2
def glob(path, &block)
-
path = path.gsub('\\', '/') if windows?
-
Dir.glob(path, &block)
-
end
-
-
# Prepare a value for a destructuring assignment (e.g. `a, b =
-
# val`). This works around a performance bug when using
-
# ActiveSupport, and only needs to be called when `val` is likely
-
# to be `nil` reasonably often.
-
#
-
# See [this bug report](http://redmine.ruby-lang.org/issues/4917).
-
#
-
# @param val [Object]
-
# @return [Object]
-
2
def destructure(val)
-
val || []
-
end
-
-
## Cross-Ruby-Version Compatibility
-
-
# Whether or not this is running under a Ruby version under 2.0.
-
#
-
# @return [Boolean]
-
2
def ruby1?
-
Sass::Util::RUBY_VERSION[0] <= 1
-
end
-
-
# Whether or not this is running under Ruby 1.8 or lower.
-
#
-
# Note that IronRuby counts as Ruby 1.8,
-
# because it doesn't support the Ruby 1.9 encoding API.
-
#
-
# @return [Boolean]
-
2
def ruby1_8?
-
# IronRuby says its version is 1.9, but doesn't support any of the encoding APIs.
-
# We have to fall back to 1.8 behavior.
-
10
ironruby? || (Sass::Util::RUBY_VERSION[0] == 1 && Sass::Util::RUBY_VERSION[1] < 9)
-
end
-
-
# Whether or not this is running under Ruby 1.8.6 or lower.
-
# Note that lower versions are not officially supported.
-
#
-
# @return [Boolean]
-
2
def ruby1_8_6?
-
ruby1_8? && Sass::Util::RUBY_VERSION[2] < 7
-
end
-
-
# Wehter or not this is running under JRuby 1.6 or lower.
-
2
def jruby1_6?
-
jruby? && jruby_version[0] == 1 && jruby_version[1] < 7
-
end
-
-
# Whether or not this is running under MacRuby.
-
#
-
# @return [Boolean]
-
2
def macruby?
-
2
RUBY_ENGINE == 'macruby'
-
end
-
-
# Checks that the encoding of a string is valid in Ruby 1.9
-
# and cleans up potential encoding gotchas like the UTF-8 BOM.
-
# If it's not, yields an error string describing the invalid character
-
# and the line on which it occurrs.
-
#
-
# @param str [String] The string of which to check the encoding
-
# @yield [msg] A block in which an encoding error can be raised.
-
# Only yields if there is an encoding error
-
# @yieldparam msg [String] The error message to be raised
-
# @return [String] `str`, potentially with encoding gotchas like BOMs removed
-
2
def check_encoding(str)
-
if ruby1_8?
-
return str.gsub(/\A\xEF\xBB\xBF/, '') # Get rid of the UTF-8 BOM
-
elsif str.valid_encoding?
-
# Get rid of the Unicode BOM if possible
-
if str.encoding.name =~ /^UTF-(8|16|32)(BE|LE)?$/
-
return str.gsub(Regexp.new("\\A\uFEFF".encode(str.encoding.name)), '')
-
else
-
return str
-
end
-
end
-
-
encoding = str.encoding
-
newlines = Regexp.new("\r\n|\r|\n".encode(encoding).force_encoding("binary"))
-
str.force_encoding("binary").split(newlines).each_with_index do |line, i|
-
begin
-
line.encode(encoding)
-
rescue Encoding::UndefinedConversionError => e
-
yield <<MSG.rstrip, i + 1
-
Invalid #{encoding.name} character #{undefined_conversion_error_char(e)}
-
MSG
-
end
-
end
-
return str
-
end
-
-
# Like {\#check\_encoding}, but also checks for a `@charset` declaration
-
# at the beginning of the file and uses that encoding if it exists.
-
#
-
# The Sass encoding rules are simple.
-
# If a `@charset` declaration exists,
-
# we assume that that's the original encoding of the document.
-
# Otherwise, we use whatever encoding Ruby has.
-
# Then we convert that to UTF-8 to process internally.
-
# The UTF-8 end result is what's returned by this method.
-
#
-
# @param str [String] The string of which to check the encoding
-
# @yield [msg] A block in which an encoding error can be raised.
-
# Only yields if there is an encoding error
-
# @yieldparam msg [String] The error message to be raised
-
# @return [(String, Encoding)] The original string encoded as UTF-8,
-
# and the source encoding of the string (or `nil` under Ruby 1.8)
-
# @raise [Encoding::UndefinedConversionError] if the source encoding
-
# cannot be converted to UTF-8
-
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
-
2
def check_sass_encoding(str, &block)
-
return check_encoding(str, &block), nil if ruby1_8?
-
# We allow any printable ASCII characters but double quotes in the charset decl
-
bin = str.dup.force_encoding("BINARY")
-
encoding = Sass::Util::ENCODINGS_TO_CHECK.find do |enc|
-
re = Sass::Util::CHARSET_REGEXPS[enc]
-
re && bin =~ re
-
end
-
charset, bom = $1, $2
-
if charset
-
charset = charset.force_encoding(encoding).encode("UTF-8")
-
if endianness = encoding[/[BL]E$/]
-
begin
-
Encoding.find(charset + endianness)
-
charset << endianness
-
rescue ArgumentError # Encoding charset + endianness doesn't exist
-
end
-
end
-
str.force_encoding(charset)
-
elsif bom
-
str.force_encoding(encoding)
-
end
-
-
str = check_encoding(str, &block)
-
return str.encode("UTF-8"), str.encoding
-
end
-
-
2
unless ruby1_8?
-
# @private
-
2
def _enc(string, encoding)
-
string.encode(encoding).force_encoding("BINARY")
-
end
-
-
# We could automatically add in any non-ASCII-compatible encodings here,
-
# but there's not really a good way to do that
-
# without manually checking that each encoding
-
# encodes all ASCII characters properly,
-
# which takes long enough to affect the startup time of the CLI.
-
2
ENCODINGS_TO_CHECK = %w[UTF-8 UTF-16BE UTF-16LE UTF-32BE UTF-32LE]
-
-
2
CHARSET_REGEXPS = Hash.new do |h, e|
-
h[e] =
-
begin
-
# /\A(?:\uFEFF)?@charset "(.*?)"|\A(\uFEFF)/
-
Regexp.new(/\A(?:#{_enc("\uFEFF", e)})?#{
-
_enc('@charset "', e)}(.*?)#{_enc('"', e)}|\A(#{
-
_enc("\uFEFF", e)})/)
-
rescue Encoding::ConverterNotFoundError => _
-
nil # JRuby on Java 5 doesn't support UTF-32
-
rescue
-
# /\A@charset "(.*?)"/
-
Regexp.new(/\A#{_enc('@charset "', e)}(.*?)#{_enc('"', e)}/)
-
end
-
end
-
end
-
-
# Checks to see if a class has a given method.
-
# For example:
-
#
-
# Sass::Util.has?(:public_instance_method, String, :gsub) #=> true
-
#
-
# Method collections like `Class#instance_methods`
-
# return strings in Ruby 1.8 and symbols in Ruby 1.9 and on,
-
# so this handles checking for them in a compatible way.
-
#
-
# @param attr [#to_s] The (singular) name of the method-collection method
-
# (e.g. `:instance_methods`, `:private_methods`)
-
# @param klass [Module] The class to check the methods of which to check
-
# @param method [String, Symbol] The name of the method do check for
-
# @return [Boolean] Whether or not the given collection has the given method
-
2
def has?(attr, klass, method)
-
2
klass.send("#{attr}s").include?(ruby1_8? ? method.to_s : method.to_sym)
-
end
-
-
# A version of `Enumerable#enum_with_index` that works in Ruby 1.8 and 1.9.
-
#
-
# @param enum [Enumerable] The enumerable to get the enumerator for
-
# @return [Enumerator] The with-index enumerator
-
2
def enum_with_index(enum)
-
ruby1_8? ? enum.enum_with_index : enum.each_with_index
-
end
-
-
# A version of `Enumerable#enum_cons` that works in Ruby 1.8 and 1.9.
-
#
-
# @param enum [Enumerable] The enumerable to get the enumerator for
-
# @param n [Fixnum] The size of each cons
-
# @return [Enumerator] The consed enumerator
-
2
def enum_cons(enum, n)
-
ruby1_8? ? enum.enum_cons(n) : enum.each_cons(n)
-
end
-
-
# A version of `Enumerable#enum_slice` that works in Ruby 1.8 and 1.9.
-
#
-
# @param enum [Enumerable] The enumerable to get the enumerator for
-
# @param n [Fixnum] The size of each slice
-
# @return [Enumerator] The consed enumerator
-
2
def enum_slice(enum, n)
-
ruby1_8? ? enum.enum_slice(n) : enum.each_slice(n)
-
end
-
-
# Destructively removes all elements from an array that match a block, and
-
# returns the removed elements.
-
#
-
# @param array [Array] The array from which to remove elements.
-
# @yield [el] Called for each element.
-
# @yieldparam el [*] The element to test.
-
# @yieldreturn [Boolean] Whether or not to extract the element.
-
# @return [Array] The extracted elements.
-
2
def extract!(array)
-
out = []
-
array.reject! do |e|
-
next false unless yield e
-
out << e
-
true
-
end
-
out
-
end
-
-
# Returns the ASCII code of the given character.
-
#
-
# @param c [String] All characters but the first are ignored.
-
# @return [Fixnum] The ASCII code of `c`.
-
2
def ord(c)
-
ruby1_8? ? c[0] : c.ord
-
end
-
-
# Flattens the first `n` nested arrays in a cross-version manner.
-
#
-
# @param arr [Array] The array to flatten
-
# @param n [Fixnum] The number of levels to flatten
-
# @return [Array] The flattened array
-
2
def flatten(arr, n)
-
return arr.flatten(n) unless ruby1_8_6?
-
return arr if n == 0
-
arr.inject([]) {|res, e| e.is_a?(Array) ? res.concat(flatten(e, n - 1)) : res << e}
-
end
-
-
# Returns the hash code for a set in a cross-version manner.
-
# Aggravatingly, this is order-dependent in Ruby 1.8.6.
-
#
-
# @param set [Set]
-
# @return [Fixnum] The order-independent hashcode of `set`
-
2
def set_hash(set)
-
return set.hash unless ruby1_8_6?
-
set.map {|e| e.hash}.uniq.sort.hash
-
end
-
-
# Tests the hash-equality of two sets in a cross-version manner.
-
# Aggravatingly, this is order-dependent in Ruby 1.8.6.
-
#
-
# @param set1 [Set]
-
# @param set2 [Set]
-
# @return [Boolean] Whether or not the sets are hashcode equal
-
2
def set_eql?(set1, set2)
-
return set1.eql?(set2) unless ruby1_8_6?
-
set1.to_a.uniq.sort_by {|e| e.hash}.eql?(set2.to_a.uniq.sort_by {|e| e.hash})
-
end
-
-
# Like `Object#inspect`, but preserves non-ASCII characters rather than escaping them under Ruby 1.9.2.
-
# This is necessary so that the precompiled Haml template can be `#encode`d into `@options[:encoding]`
-
# before being evaluated.
-
#
-
# @param obj {Object}
-
# @return {String}
-
2
def inspect_obj(obj)
-
return obj.inspect unless version_geq(::RUBY_VERSION, "1.9.2")
-
return ':' + inspect_obj(obj.to_s) if obj.is_a?(Symbol)
-
return obj.inspect unless obj.is_a?(String)
-
'"' + obj.gsub(/[\x00-\x7F]+/) {|s| s.inspect[1...-1]} + '"'
-
end
-
-
# Extracts the non-string vlaues from an array containing both strings and non-strings.
-
# These values are replaced with escape sequences.
-
# This can be undone using \{#inject\_values}.
-
#
-
# This is useful e.g. when we want to do string manipulation
-
# on an interpolated string.
-
#
-
# The precise format of the resulting string is not guaranteed.
-
# However, it is guaranteed that newlines and whitespace won't be affected.
-
#
-
# @param arr [Array] The array from which values are extracted.
-
# @return [(String, Array)] The resulting string, and an array of extracted values.
-
2
def extract_values(arr)
-
values = []
-
return arr.map do |e|
-
next e.gsub('{', '{{') if e.is_a?(String)
-
values << e
-
next "{#{values.count - 1}}"
-
end.join, values
-
end
-
-
# Undoes \{#extract\_values} by transforming a string with escape sequences
-
# into an array of strings and non-string values.
-
#
-
# @param str [String] The string with escape sequences.
-
# @param values [Array] The array of values to inject.
-
# @return [Array] The array of strings and values.
-
2
def inject_values(str, values)
-
return [str.gsub('{{', '{')] if values.empty?
-
# Add an extra { so that we process the tail end of the string
-
result = (str + '{{').scan(/(.*?)(?:(\{\{)|\{(\d+)\})/m).map do |(pre, esc, n)|
-
[pre, esc ? '{' : '', n ? values[n.to_i] : '']
-
end.flatten(1)
-
result[-2] = '' # Get rid of the extra {
-
merge_adjacent_strings(result).reject {|s| s == ''}
-
end
-
-
# Allows modifications to be performed on the string form
-
# of an array containing both strings and non-strings.
-
#
-
# @param arr [Array] The array from which values are extracted.
-
# @yield [str] A block in which string manipulation can be done to the array.
-
# @yieldparam str [String] The string form of `arr`.
-
# @yieldreturn [String] The modified string.
-
# @return [Array] The modified, interpolated array.
-
2
def with_extracted_values(arr)
-
str, vals = extract_values(arr)
-
str = yield str
-
inject_values(str, vals)
-
end
-
-
## Static Method Stuff
-
-
# The context in which the ERB for \{#def\_static\_method} will be run.
-
2
class StaticConditionalContext
-
# @param set [#include?] The set of variables that are defined for this context.
-
2
def initialize(set)
-
@set = set
-
end
-
-
# Checks whether or not a variable is defined for this context.
-
#
-
# @param name [Symbol] The name of the variable
-
# @return [Boolean]
-
2
def method_missing(name, *args, &block)
-
super unless args.empty? && block.nil?
-
@set.include?(name)
-
end
-
end
-
-
# This creates a temp file and yields it for writing. When the
-
# write is complete, the file is moved into the desired location.
-
# The atomicity of this operation is provided by the filesystem's
-
# rename operation.
-
#
-
# @param filename [String] The file to write to.
-
# @yieldparam tmpfile [Tempfile] The temp file that can be written to.
-
# @return The value returned by the block.
-
2
def atomic_create_and_write_file(filename)
-
require 'tempfile'
-
tmpfile = Tempfile.new(File.basename(filename), File.dirname(filename))
-
tmp_path = tmpfile.path
-
tmpfile.binmode if tmpfile.respond_to?(:binmode)
-
result = yield tmpfile
-
File.rename tmpfile.path, filename
-
result
-
ensure
-
# close and remove the tempfile if it still exists,
-
# presumably due to an error during write
-
tmpfile.close if tmpfile
-
tmpfile.unlink if tmpfile
-
end
-
-
2
private
-
-
# Calculates the memoization table for the Least Common Subsequence algorithm.
-
# Algorithm from [Wikipedia](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Computing_the_length_of_the_LCS)
-
2
def lcs_table(x, y)
-
c = Array.new(x.size) {[]}
-
x.size.times {|i| c[i][0] = 0}
-
y.size.times {|j| c[0][j] = 0}
-
(1...x.size).each do |i|
-
(1...y.size).each do |j|
-
c[i][j] =
-
if yield x[i], y[j]
-
c[i-1][j-1] + 1
-
else
-
[c[i][j-1], c[i-1][j]].max
-
end
-
end
-
end
-
return c
-
end
-
-
# Computes a single longest common subsequence for arrays x and y.
-
# Algorithm from [Wikipedia](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Reading_out_an_LCS)
-
2
def lcs_backtrace(c, x, y, i, j, &block)
-
return [] if i == 0 || j == 0
-
if v = yield(x[i], y[j])
-
return lcs_backtrace(c, x, y, i-1, j-1, &block) << v
-
end
-
-
return lcs_backtrace(c, x, y, i, j-1, &block) if c[i][j-1] > c[i-1][j]
-
return lcs_backtrace(c, x, y, i-1, j, &block)
-
end
-
end
-
end
-
-
2
require 'sass/util/multibyte_string_scanner'
-
2
require 'strscan'
-
-
2
if Sass::Util.ruby1_8?
-
Sass::Util::MultibyteStringScanner = StringScanner
-
else
-
2
if Sass::Util.rbx?
-
# Rubinius's StringScanner class implements some of its methods in terms of
-
# others, which causes us to double-count bytes in some cases if we do
-
# straightforward inheritance. To work around this, we use a delegate class.
-
require 'delegate'
-
class Sass::Util::MultibyteStringScanner < DelegateClass(StringScanner)
-
def initialize(str)
-
super(StringScanner.new(str))
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
end
-
-
def is_a?(klass)
-
__getobj__.is_a?(klass) || super
-
end
-
end
-
else
-
2
class Sass::Util::MultibyteStringScanner < StringScanner
-
2
def initialize(str)
-
super
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
end
-
end
-
end
-
-
# A wrapper of the native StringScanner class that works correctly with
-
# multibyte character encodings. The native class deals only in bytes, not
-
# characters, for methods like [#pos] and [#matched_size]. This class deals
-
# only in characters, instead.
-
2
class Sass::Util::MultibyteStringScanner
-
2
def self.new(str)
-
return StringScanner.new(str) if str.ascii_only?
-
super
-
end
-
-
2
alias_method :byte_pos, :pos
-
2
alias_method :byte_matched_size, :matched_size
-
-
2
def check(pattern); _match super; end
-
2
def check_until(pattern); _matched super; end
-
2
def getch; _forward _match super; end
-
2
def match?(pattern); _size check(pattern); end
-
2
def matched_size; @mb_matched_size; end
-
2
def peek(len); string[@mb_pos, len]; end
-
2
alias_method :peep, :peek
-
2
def pos; @mb_pos; end
-
2
alias_method :pointer, :pos
-
2
def rest_size; rest.size; end
-
2
def scan(pattern); _forward _match super; end
-
2
def scan_until(pattern); _forward _matched super; end
-
2
def skip(pattern); _size scan(pattern); end
-
2
def skip_until(pattern); _matched _size scan_until(pattern); end
-
-
2
def get_byte
-
raise "MultibyteStringScanner doesn't support #get_byte."
-
end
-
-
2
def getbyte
-
raise "MultibyteStringScanner doesn't support #getbyte."
-
end
-
-
2
def pos=(n)
-
@mb_last_pos = nil
-
-
# We set position kind of a lot during parsing, so we want it to be as
-
# efficient as possible. This is complicated by the fact that UTF-8 is a
-
# variable-length encoding, so it's difficult to find the byte length that
-
# corresponds to a given character length.
-
#
-
# Our heuristic here is to try to count the fewest possible characters. So
-
# if the new position is close to the current one, just count the
-
# characters between the two; if the new position is closer to the
-
# beginning of the string, just count the characters from there.
-
if @mb_pos - n < @mb_pos / 2
-
# New position is close to old position
-
byte_delta = @mb_pos > n ? -string[n...@mb_pos].bytesize : string[@mb_pos...n].bytesize
-
super(byte_pos + byte_delta)
-
else
-
# New position is close to BOS
-
super(string[0...n].bytesize)
-
end
-
@mb_pos = n
-
end
-
-
2
def reset
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
super
-
end
-
-
2
def scan_full(pattern, advance_pointer_p, return_string_p)
-
res = _match super(pattern, advance_pointer_p, true)
-
_forward res if advance_pointer_p
-
return res if return_string_p
-
end
-
-
2
def search_full(pattern, advance_pointer_p, return_string_p)
-
res = super(pattern, advance_pointer_p, true)
-
_forward res if advance_pointer_p
-
_matched((res if return_string_p))
-
end
-
-
2
def string=(str)
-
@mb_pos = 0
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
super
-
end
-
-
2
def terminate
-
@mb_pos = string.size
-
@mb_matched_size = nil
-
@mb_last_pos = nil
-
super
-
end
-
2
alias_method :clear, :terminate
-
-
2
def unscan
-
super
-
@mb_pos = @mb_last_pos
-
@mb_last_pos = @mb_matched_size = nil
-
end
-
-
2
private
-
-
2
def _size(str)
-
str && str.size
-
end
-
-
2
def _match(str)
-
@mb_matched_size = str && str.size
-
str
-
end
-
-
2
def _matched(res)
-
_match matched
-
res
-
end
-
-
2
def _forward(str)
-
@mb_last_pos = @mb_pos
-
@mb_pos += str.size if str
-
str
-
end
-
end
-
end
-
2
require 'set'
-
-
2
module Sass
-
2
module Util
-
# A map from sets to values.
-
# A value is \{#\[]= set} by providing a set (the "set-set") and a value,
-
# which is then recorded as corresponding to that set.
-
# Values are \{#\[] accessed} by providing a set (the "get-set")
-
# and returning all values that correspond to set-sets
-
# that are subsets of the get-set.
-
#
-
# SubsetMap preserves the order of values as they're inserted.
-
#
-
# @example
-
# ssm = SubsetMap.new
-
# ssm[Set[1, 2]] = "Foo"
-
# ssm[Set[2, 3]] = "Bar"
-
# ssm[Set[1, 2, 3]] = "Baz"
-
#
-
# ssm[Set[1, 2, 3]] #=> ["Foo", "Bar", "Baz"]
-
2
class SubsetMap
-
# Creates a new, empty SubsetMap.
-
2
def initialize
-
@hash = {}
-
@vals = []
-
end
-
-
# Whether or not this SubsetMap has any key-value pairs.
-
#
-
# @return [Boolean]
-
2
def empty?
-
@hash.empty?
-
end
-
-
# Associates a value with a set.
-
# When `set` or any of its supersets is accessed,
-
# `value` will be among the values returned.
-
#
-
# Note that if the same `set` is passed to this method multiple times,
-
# all given `value`s will be associated with that `set`.
-
#
-
# This runs in `O(n)` time, where `n` is the size of `set`.
-
#
-
# @param set [#to_set] The set to use as the map key. May not be empty.
-
# @param value [Object] The value to associate with `set`.
-
# @raise [ArgumentError] If `set` is empty.
-
2
def []=(set, value)
-
raise ArgumentError.new("SubsetMap keys may not be empty.") if set.empty?
-
-
index = @vals.size
-
@vals << value
-
set.each do |k|
-
@hash[k] ||= []
-
@hash[k] << [set, set.to_set, index]
-
end
-
end
-
-
# Returns all values associated with subsets of `set`.
-
#
-
# In the worst case, this runs in `O(m*max(n, log m))` time,
-
# where `n` is the size of `set`
-
# and `m` is the number of assocations in the map.
-
# However, unless many keys in the map overlap with `set`,
-
# `m` will typically be much smaller.
-
#
-
# @param set [Set] The set to use as the map key.
-
# @return [Array<(Object, #to_set)>] An array of pairs,
-
# where the first value is the value associated with a subset of `set`,
-
# and the second value is that subset of `set`
-
# (or whatever `#to_set` object was used to set the value)
-
# This array is in insertion order.
-
# @see #[]
-
2
def get(set)
-
res = set.map do |k|
-
next unless subsets = @hash[k]
-
subsets.map do |subenum, subset, index|
-
next unless subset.subset?(set)
-
[index, subenum]
-
end
-
end
-
res = Sass::Util.flatten(res, 1)
-
res.compact!
-
res.uniq!
-
res.sort!
-
res.map! {|i, s| [@vals[i], s]}
-
return res
-
end
-
-
# Same as \{#get}, but doesn't return the subsets of the argument
-
# for which values were found.
-
#
-
# @param set [Set] The set to use as the map key.
-
# @return [Array] The array of all values
-
# associated with subsets of `set`, in insertion order.
-
# @see #get
-
2
def [](set)
-
get(set).map {|v, _| v}
-
end
-
-
# Iterates over each value in the subset map. Ignores keys completely. If
-
# multiple keys have the same value, this will return them multiple times.
-
#
-
# @yield [Object] Each value in the map.
-
2
def each_value
-
@vals.each {|v| yield v}
-
end
-
end
-
end
-
end
-
2
require 'date'
-
-
# This is necessary for loading Sass when Haml is required in Rails 3.
-
# Once the split is complete, we can remove it.
-
2
require File.dirname(__FILE__) + '/../sass'
-
2
require 'sass/util'
-
-
2
module Sass
-
# Handles Sass version-reporting.
-
# Sass not only reports the standard three version numbers,
-
# but its Git revision hash as well,
-
# if it was installed from Git.
-
2
module Version
-
2
include Sass::Util
-
-
# Returns a hash representing the version of Sass.
-
# The `:major`, `:minor`, and `:teeny` keys have their respective numbers as Fixnums.
-
# The `:name` key has the name of the version.
-
# The `:string` key contains a human-readable string representation of the version.
-
# The `:number` key is the major, minor, and teeny keys separated by periods.
-
# The `:date` key, which is not guaranteed to be defined, is the [DateTime] at which this release was cut.
-
# If Sass is checked out from Git, the `:rev` key will have the revision hash.
-
# For example:
-
#
-
# {
-
# :string => "2.1.0.9616393",
-
# :rev => "9616393b8924ef36639c7e82aa88a51a24d16949",
-
# :number => "2.1.0",
-
# :date => DateTime.parse("Apr 30 13:52:01 2009 -0700"),
-
# :major => 2, :minor => 1, :teeny => 0
-
# }
-
#
-
# If a prerelease version of Sass is being used,
-
# the `:string` and `:number` fields will reflect the full version
-
# (e.g. `"2.2.beta.1"`), and the `:teeny` field will be `-1`.
-
# A `:prerelease` key will contain the name of the prerelease (e.g. `"beta"`),
-
# and a `:prerelease_number` key will contain the rerelease number.
-
# For example:
-
#
-
# {
-
# :string => "3.0.beta.1",
-
# :number => "3.0.beta.1",
-
# :date => DateTime.parse("Mar 31 00:38:04 2010 -0700"),
-
# :major => 3, :minor => 0, :teeny => -1,
-
# :prerelease => "beta",
-
# :prerelease_number => 1
-
# }
-
#
-
# @return [{Symbol => String/Fixnum}] The version hash
-
2
def version
-
2
return @@version if defined?(@@version)
-
-
2
numbers = File.read(scope('VERSION')).strip.split('.').
-
6
map {|n| n =~ /^[0-9]+$/ ? n.to_i : n}
-
2
name = File.read(scope('VERSION_NAME')).strip
-
2
@@version = {
-
:major => numbers[0],
-
:minor => numbers[1],
-
:teeny => numbers[2],
-
:name => name
-
}
-
-
2
if date = version_date
-
2
@@version[:date] = date
-
end
-
-
2
if numbers[3].is_a?(String)
-
@@version[:teeny] = -1
-
@@version[:prerelease] = numbers[3]
-
@@version[:prerelease_number] = numbers[4]
-
end
-
-
2
@@version[:number] = numbers.join('.')
-
2
@@version[:string] = @@version[:number].dup
-
-
2
if rev = revision_number
-
@@version[:rev] = rev
-
unless rev[0] == ?(
-
@@version[:string] << "." << rev[0...7]
-
end
-
end
-
-
2
@@version[:string] << " (#{name})"
-
2
@@version
-
end
-
-
2
private
-
-
2
def revision_number
-
2
if File.exists?(scope('REVISION'))
-
2
rev = File.read(scope('REVISION')).strip
-
2
return rev unless rev =~ /^([a-f0-9]+|\(.*\))$/ || rev == '(unknown)'
-
end
-
-
2
return unless File.exists?(scope('.git/HEAD'))
-
rev = File.read(scope('.git/HEAD')).strip
-
return rev unless rev =~ /^ref: (.*)$/
-
-
ref_name = $1
-
ref_file = scope(".git/#{ref_name}")
-
info_file = scope(".git/info/refs")
-
return File.read(ref_file).strip if File.exists?(ref_file)
-
return unless File.exists?(info_file)
-
File.open(info_file) do |f|
-
f.each do |l|
-
sha, ref = l.strip.split("\t", 2)
-
next unless ref == ref_name
-
return sha
-
end
-
end
-
return nil
-
end
-
-
2
def version_date
-
2
return unless File.exists?(scope('VERSION_DATE'))
-
2
return DateTime.parse(File.read(scope('VERSION_DATE')).strip)
-
end
-
end
-
-
2
extend Sass::Version
-
-
# A string representing the version of Sass.
-
# A more fine-grained representation is available from Sass.version.
-
# @api public
-
2
VERSION = version[:string] unless defined?(Sass::VERSION)
-
end
-
2
require 'sass/rails'
-
2
module Sass
-
2
autoload :Script, 'sass/rails/helpers'
-
-
2
module Rails
-
2
autoload :CssCompressor, 'sass/rails/compressor'
-
2
autoload :Importer, 'sass/rails/importer'
-
2
autoload :Logger, 'sass/rails/logger'
-
2
autoload :Resolver, 'sass/rails/template_handlers'
-
2
autoload :SassTemplate, 'sass/rails/template_handlers'
-
2
autoload :ScssTemplate, 'sass/rails/template_handlers'
-
end
-
end
-
-
2
require 'sass/rails/version'
-
2
require 'sass/rails/helpers'
-
2
require 'sass/rails/railtie'
-
2
module Sass
-
2
module Rails
-
2
module Helpers
-
-
2
def asset_data_url(path)
-
data = context_asset_data_uri(path.value)
-
Sass::Script::String.new(%Q{url(#{data})})
-
end
-
-
2
def asset_path(asset, kind)
-
Sass::Script::String.new(public_path(asset.value, kind.value), true)
-
end
-
-
2
def asset_url(asset, kind)
-
Sass::Script::String.new(%Q{url(#{public_path(asset.value, kind.value)})})
-
end
-
-
2
[:image, :video, :audio, :javascript, :stylesheet, :font].each do |asset_class|
-
class_eval %Q{
-
def #{asset_class}_path(asset)
-
Sass::Script::String.new(resolver.#{asset_class}_path(asset.value), true)
-
end
-
def #{asset_class}_url(asset)
-
Sass::Script::String.new("url(" + resolver.#{asset_class}_path(asset.value) + ")")
-
end
-
12
}, __FILE__, __LINE__ - 6
-
end
-
-
2
protected
-
-
2
def resolver
-
options[:custom][:resolver]
-
end
-
-
2
def public_path(asset, kind)
-
resolver.public_path(asset, kind.pluralize)
-
end
-
-
2
def context_asset_data_uri(path)
-
resolver.context.asset_data_uri(path)
-
end
-
end
-
end
-
end
-
-
2
module Sass
-
2
module Script
-
2
module Functions
-
2
include Sass::Rails::Helpers
-
end
-
end
-
end
-
2
require 'sass/logger'
-
-
2
module Sass
-
2
module Rails
-
2
class Logger < Sass::Logger::Base
-
2
def _log(level, message)
-
-
case level
-
when :trace, :debug
-
::Rails.logger.debug message
-
when :warn
-
::Rails.logger.warn message
-
when :error
-
::Rails.logger.error message
-
when :info
-
::Rails.logger.info message
-
end
-
end
-
end
-
end
-
end
-
2
require 'sprockets/railtie'
-
-
2
module Sass::Rails
-
2
class Railtie < ::Rails::Railtie
-
2
module SassContext
-
2
attr_accessor :sass_config
-
end
-
-
2
config.sass = ActiveSupport::OrderedOptions.new
-
-
# Establish static configuration defaults
-
# Emit scss files during stylesheet generation of scaffold
-
2
config.sass.preferred_syntax = :scss
-
# Write sass cache files for performance
-
2
config.sass.cache = true
-
# Read sass cache files for performance
-
2
config.sass.read_cache = true
-
# Display line comments above each selector as a debugging aid
-
2
config.sass.line_comments = true
-
# Initialize the load paths to an empty array
-
2
config.sass.load_paths = []
-
# Send Sass logs to Rails.logger
-
2
config.sass.logger = Sass::Rails::Logger.new
-
-
# Set the default stylesheet engine
-
# It can be overridedden by passing:
-
# --stylesheet_engine=sass
-
# to the rails generate command
-
2
config.app_generators.stylesheet_engine config.sass.preferred_syntax
-
-
2
config.before_initialize do |app|
-
2
require 'sass'
-
-
2
if app.config.assets.enabled
-
2
require 'sprockets'
-
2
Sprockets::Engines #force autoloading
-
2
Sprockets.register_engine '.sass', Sass::Rails::SassTemplate
-
2
Sprockets.register_engine '.scss', Sass::Rails::ScssTemplate
-
end
-
end
-
-
# Remove the sass middleware if it gets inadvertently enabled by applications.
-
2
config.after_initialize do |app|
-
2
app.config.middleware.delete(Sass::Plugin::Rack) if defined?(Sass::Plugin::Rack)
-
end
-
-
2
initializer :setup_sass, :group => :all do |app|
-
# Only emit one kind of syntax because though we have registered two kinds of generators
-
2
syntax = app.config.sass.preferred_syntax.to_sym
-
2
alt_syntax = syntax == :sass ? "scss" : "sass"
-
2
app.config.generators.hide_namespace alt_syntax
-
-
# Override stylesheet engine to the preferred syntax
-
2
config.app_generators.stylesheet_engine syntax
-
-
# Set the sass cache location
-
2
config.sass.cache_location = File.join(Rails.root, "tmp/cache/sass")
-
-
# Establish configuration defaults that are evironmental in nature
-
2
if config.sass.full_exception.nil?
-
# Display a stack trace in the css output when in development-like environments.
-
2
config.sass.full_exception = app.config.consider_all_requests_local
-
end
-
-
2
if app.assets
-
2
app.assets.context_class.extend(SassContext)
-
2
app.assets.context_class.sass_config = app.config.sass
-
end
-
-
2
Sass.logger = app.config.sass.logger
-
end
-
-
2
initializer :setup_compression, :group => :all do |app|
-
2
if app.config.assets.compress
-
# Use compressed style if none specified
-
app.config.sass.style ||= :compressed
-
app.config.assets.css_compressor ||= CssCompressor.new(:style => app.config.sass.style)
-
else
-
# Use expanded output instead of the sass default of :nested unless specified
-
2
app.config.sass.style ||= :expanded
-
end
-
end
-
end
-
end
-
2
require 'tilt'
-
2
require 'sprockets'
-
-
2
module Sass::Rails
-
-
2
class Resolver
-
-
2
attr_accessor :context
-
-
2
def initialize(context)
-
@context = context
-
end
-
-
2
def resolve(path, content_type = :self)
-
options = {}
-
options[:content_type] = content_type unless content_type.nil?
-
context.resolve(path, options)
-
rescue Sprockets::FileNotFound, Sprockets::ContentTypeMismatch
-
nil
-
end
-
-
2
def source_path(path, ext)
-
context.asset_paths.compute_source_path(path, ::Rails.application.config.assets.prefix, ext)
-
end
-
-
2
def public_path(path, scope = nil, options = {})
-
context.asset_paths.compute_public_path(path, ::Rails.application.config.assets.prefix, options)
-
end
-
-
2
def process(path)
-
context.environment[path].to_s
-
end
-
-
2
def image_path(img)
-
context.image_path(img)
-
end
-
-
2
def video_path(video)
-
context.video_path(video)
-
end
-
-
2
def audio_path(audio)
-
context.audio_path(audio)
-
end
-
-
2
def javascript_path(javascript)
-
context.javascript_path(javascript)
-
end
-
-
2
def stylesheet_path(stylesheet)
-
context.stylesheet_path(stylesheet)
-
end
-
-
2
def font_path(font)
-
context.font_path(font)
-
end
-
end
-
-
2
class SassTemplate < Tilt::SassTemplate
-
2
self.default_mime_type = 'text/css'
-
-
2
def self.engine_initialized?
-
defined?(::Sass::Engine)
-
end
-
-
2
def initialize_engine
-
require_template_library 'sass'
-
end
-
-
2
def syntax
-
:sass
-
end
-
-
2
def sass_options_from_rails(scope)
-
scope.environment.context_class.sass_config
-
end
-
-
2
def sass_options(scope)
-
importer = self.importer(scope)
-
options = sass_options_from_rails(scope)
-
load_paths = (options[:load_paths] || []).dup
-
load_paths.unshift(importer)
-
resolver = Resolver.new(scope)
-
css_filename = resolver.source_path(scope.logical_path, 'css')
-
options.merge(
-
:filename => eval_file,
-
:css_filename => css_filename,
-
:line => line,
-
:syntax => syntax,
-
:importer => importer,
-
:load_paths => load_paths,
-
:custom => {
-
:resolver => resolver
-
}
-
)
-
end
-
-
2
def importer(scope)
-
Sass::Rails::Importer.new(scope)
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(scope, locals, &block)
-
Sass::Engine.new(data, sass_options(scope)).render
-
end
-
end
-
-
2
class ScssTemplate < SassTemplate
-
2
self.default_mime_type = 'text/css'
-
-
2
def syntax
-
:scss
-
end
-
end
-
end
-
2
module Sass
-
2
module Rails
-
2
VERSION = "3.2.6"
-
end
-
end
-
2
require 'shoulda/version'
-
2
require 'shoulda/matchers'
-
2
require 'shoulda/context'
-
2
module Shoulda
-
2
VERSION = "3.5.0"
-
end
-
2
begin
-
# if present, load and set base_test_case
-
2
ActiveSupport::TestCase
-
if defined?([ActiveSupport::TestCase, MiniTest::Unit::TestCase]) &&
-
2
(ActiveSupport::TestCase.ancestors.include?(MiniTest::Unit::TestCase))
-
2
base_test_case = MiniTest::Unit::TestCase
-
end
-
rescue
-
end
-
-
# no base_test_case set, using Test:Unit:TestCase
-
2
unless base_test_case
-
require 'test/unit/testcase' unless defined?(Test::Unit::TestCase)
-
base_test_case = Test::Unit::TestCase
-
end
-
-
2
require 'shoulda/context/version'
-
2
require 'shoulda/context/proc_extensions'
-
2
require 'shoulda/context/assertions'
-
2
require 'shoulda/context/context'
-
2
require 'shoulda/context/autoload_macros'
-
-
2
module ShouldaContextLoadable
-
2
def self.included(base)
-
2
base.class_eval do
-
2
include Shoulda::Context::Assertions
-
2
include Shoulda::Context::InstanceMethods
-
end
-
2
base.extend(Shoulda::Context::ClassMethods)
-
end
-
end
-
-
4
base_test_case.class_eval { include ShouldaContextLoadable }
-
2
module Shoulda # :nodoc:
-
2
module Context
-
2
module Assertions
-
# Asserts that two arrays contain the same elements, the same number of times. Essentially ==, but unordered.
-
#
-
# assert_same_elements([:a, :b, :c], [:c, :a, :b]) => passes
-
2
def assert_same_elements(a1, a2, msg = nil)
-
[:select, :inject, :size].each do |m|
-
[a1, a2].each {|a| assert_respond_to(a, m, "Are you sure that #{a.inspect} is an array? It doesn't respond to #{m}.") }
-
end
-
-
assert a1h = a1.inject({}) { |h,e| h[e] ||= a1.select { |i| i == e }.size; h }
-
assert a2h = a2.inject({}) { |h,e| h[e] ||= a2.select { |i| i == e }.size; h }
-
-
assert_equal(a1h, a2h, msg)
-
end
-
-
# Asserts that the given collection contains item x. If x is a regular expression, ensure that
-
# at least one element from the collection matches x. +extra_msg+ is appended to the error message if the assertion fails.
-
#
-
# assert_contains(['a', '1'], /\d/) => passes
-
# assert_contains(['a', '1'], 'a') => passes
-
# assert_contains(['a', '1'], /not there/) => fails
-
2
def assert_contains(collection, x, extra_msg = "")
-
collection = Array(collection)
-
msg = "#{x.inspect} not found in #{collection.to_a.inspect} #{extra_msg}"
-
case x
-
when Regexp
-
assert(collection.detect { |e| e =~ x }, msg)
-
else
-
assert(collection.include?(x), msg)
-
end
-
end
-
-
# Asserts that the given collection does not contain item x. If x is a regular expression, ensure that
-
# none of the elements from the collection match x.
-
2
def assert_does_not_contain(collection, x, extra_msg = "")
-
collection = Array(collection)
-
msg = "#{x.inspect} found in #{collection.to_a.inspect} " + extra_msg
-
case x
-
when Regexp
-
assert(!collection.detect { |e| e =~ x }, msg)
-
else
-
assert(!collection.include?(x), msg)
-
end
-
end
-
-
# Asserts that the given matcher returns true when +target+ is passed to #matches?
-
2
def assert_accepts(matcher, target, options = {})
-
29
if matcher.respond_to?(:in_context)
-
matcher.in_context(self)
-
end
-
-
29
if matcher.matches?(target)
-
58
safe_assert_block { true }
-
29
if options[:message]
-
message = matcher.respond_to?(:failure_message_for_should_not) ? matcher.failure_message_for_should_not : matcher.negative_failure_message
-
assert_match options[:message], message
-
end
-
else
-
message = matcher.respond_to?(:failure_message_for_should) ? matcher.failure_message_for_should : matcher.failure_message
-
safe_assert_block(message) { false }
-
end
-
end
-
-
# Asserts that the given matcher returns true when +target+ is passed to #does_not_match?
-
# or false when +target+ is passed to #matches? if #does_not_match? is not implemented
-
2
def assert_rejects(matcher, target, options = {})
-
if matcher.respond_to?(:in_context)
-
matcher.in_context(self)
-
end
-
-
not_match = matcher.respond_to?(:does_not_match?) ? matcher.does_not_match?(target) : !matcher.matches?(target)
-
-
if not_match
-
safe_assert_block { true }
-
if options[:message]
-
message = matcher.respond_to?(:failure_message_for_should) ? matcher.failure_message_for_should : matcher.failure_message
-
assert_match options[:message], message
-
end
-
else
-
message = matcher.respond_to?(:failure_message_for_should_not) ? matcher.failure_message_for_should_not : matcher.negative_failure_message
-
safe_assert_block(message) { false }
-
end
-
end
-
-
2
def safe_assert_block(message = "assert_block failed.", &block)
-
29
if respond_to?(:assert_block)
-
29
assert_block message, &block
-
else
-
assert yield, message
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
# Call autoload_macros when you want to load test macros automatically in a non-Rails
-
# project (it's done automatically for Rails projects).
-
# You don't need to specify ROOT/test/shoulda_macros explicitly. Your custom macros
-
# are loaded automatically when you call autoload_macros.
-
#
-
# The first argument is the path to you application's root directory.
-
# All following arguments are directories relative to your root, which contain
-
# shoulda_macros subdirectories. These directories support the same kinds of globs as the
-
# Dir class.
-
#
-
# Basic usage (from a test_helper):
-
# Shoulda.autoload_macros(File.dirname(__FILE__) + '/..')
-
# will load everything in
-
# - your_app/test/shoulda_macros
-
#
-
# To load vendored macros as well:
-
# Shoulda.autoload_macros(APP_ROOT, 'vendor/*')
-
# will load everything in
-
# - APP_ROOT/vendor/*/shoulda_macros
-
# - APP_ROOT/test/shoulda_macros
-
#
-
# To load macros in an app with a vendor directory laid out like Rails':
-
# Shoulda.autoload_macros(APP_ROOT, 'vendor/{plugins,gems}/*')
-
# or
-
# Shoulda.autoload_macros(APP_ROOT, 'vendor/plugins/*', 'vendor/gems/*')
-
# will load everything in
-
# - APP_ROOT/vendor/plugins/*/shoulda_macros
-
# - APP_ROOT/vendor/gems/*/shoulda_macros
-
# - APP_ROOT/test/shoulda_macros
-
#
-
# If you prefer to stick testing dependencies away from your production dependencies:
-
# Shoulda.autoload_macros(APP_ROOT, 'vendor/*', 'test/vendor/*')
-
# will load everything in
-
# - APP_ROOT/vendor/*/shoulda_macros
-
# - APP_ROOT/test/vendor/*/shoulda_macros
-
# - APP_ROOT/test/shoulda_macros
-
2
def self.autoload_macros(root, *dirs)
-
dirs << File.join('test')
-
complete_dirs = dirs.map{|d| File.join(root, d, 'shoulda_macros')}
-
all_files = complete_dirs.inject([]){ |files, dir| files + Dir[File.join(dir, '*.rb')] }
-
all_files.each do |file|
-
require file
-
end
-
end
-
end
-
2
module Shoulda
-
2
module Context
-
2
class << self
-
2
def contexts # :nodoc:
-
141
@contexts ||= []
-
end
-
2
attr_writer :contexts
-
-
2
def current_context # :nodoc:
-
39
self.contexts.last
-
end
-
-
2
def add_context(context) # :nodoc:
-
51
self.contexts.push(context)
-
end
-
-
2
def remove_context # :nodoc:
-
51
self.contexts.pop
-
end
-
end
-
-
2
module ClassMethods
-
# == Should statements
-
#
-
# Should statements are just syntactic sugar over normal Test::Unit test
-
# methods. A should block contains all the normal code and assertions
-
# you're used to seeing, with the added benefit that they can be wrapped
-
# inside context blocks (see below).
-
#
-
# === Example:
-
#
-
# class UserTest < Test::Unit::TestCase
-
#
-
# def setup
-
# @user = User.new("John", "Doe")
-
# end
-
#
-
# should "return its full name"
-
# assert_equal 'John Doe', @user.full_name
-
# end
-
#
-
# end
-
#
-
# ...will produce the following test:
-
# * <tt>"test: User should return its full name. "</tt>
-
#
-
# Note: The part before <tt>should</tt> in the test name is gleamed from the name of the Test::Unit class.
-
#
-
# Should statements can also take a Proc as a <tt>:before </tt>option. This proc runs after any
-
# parent context's setups but before the current context's setup.
-
#
-
# === Example:
-
#
-
# context "Some context" do
-
# setup { puts("I run after the :before proc") }
-
#
-
# should "run a :before proc", :before => lambda { puts("I run before the setup") } do
-
# assert true
-
# end
-
# end
-
#
-
# Should statements can also wrap matchers, making virtually any matcher
-
# usable in a macro style. The matcher's description is used to generate a
-
# test name and failure message, and the test will pass if the matcher
-
# matches the subject.
-
#
-
# === Example:
-
#
-
# should validate_presence_of(:first_name).with_message(/gotta be there/)
-
#
-
-
2
def should(name_or_matcher, options = {}, &blk)
-
29
if Shoulda::Context.current_context
-
Shoulda::Context.current_context.should(name_or_matcher, options, &blk)
-
else
-
29
context_name = self.name.gsub(/Test/, "") if self.name
-
29
context = Shoulda::Context::Context.new(context_name, self) do
-
29
should(name_or_matcher, options, &blk)
-
end
-
29
context.build
-
end
-
end
-
-
# Allows negative tests using matchers. The matcher's description is used
-
# to generate a test name and negative failure message, and the test will
-
# pass unless the matcher matches the subject.
-
#
-
# === Example:
-
#
-
# should_not set_the_flash
-
2
def should_not(matcher)
-
if Shoulda::Context.current_context
-
Shoulda::Context.current_context.should_not(matcher)
-
else
-
context_name = self.name.gsub(/Test/, "") if self.name
-
context = Shoulda::Context::Context.new(context_name, self) do
-
should_not(matcher)
-
end
-
context.build
-
end
-
end
-
-
# == Before statements
-
#
-
# Before statements are should statements that run before the current
-
# context's setup. These are especially useful when setting expectations.
-
#
-
# === Example:
-
#
-
# class UserControllerTest < Test::Unit::TestCase
-
# context "the index action" do
-
# setup do
-
# @users = [Factory(:user)]
-
# User.stubs(:find).returns(@users)
-
# end
-
#
-
# context "on GET" do
-
# setup { get :index }
-
#
-
# should respond_with(:success)
-
#
-
# # runs before "get :index"
-
# before_should "find all users" do
-
# User.expects(:find).with(:all).returns(@users)
-
# end
-
# end
-
# end
-
# end
-
2
def before_should(name, &blk)
-
should(name, :before => blk) { assert true }
-
end
-
-
# Just like should, but never runs, and instead prints an 'X' in the Test::Unit output.
-
2
def should_eventually(name, options = {}, &blk)
-
context_name = self.name.gsub(/Test/, "")
-
context = Shoulda::Context::Context.new(context_name, self) do
-
should_eventually(name, &blk)
-
end
-
context.build
-
end
-
-
# == Contexts
-
#
-
# A context block groups should statements under a common set of setup/teardown methods.
-
# Context blocks can be arbitrarily nested, and can do wonders for improving the maintainability
-
# and readability of your test code.
-
#
-
# A context block can contain setup, should, should_eventually, and teardown blocks.
-
#
-
# class UserTest < Test::Unit::TestCase
-
# context "A User instance" do
-
# setup do
-
# @user = User.find(:first)
-
# end
-
#
-
# should "return its full name"
-
# assert_equal 'John Doe', @user.full_name
-
# end
-
# end
-
# end
-
#
-
# This code will produce the method <tt>"test: A User instance should return its full name. "</tt>.
-
#
-
# Contexts may be nested. Nested contexts run their setup blocks from out to in before each
-
# should statement. They then run their teardown blocks from in to out after each should statement.
-
#
-
# class UserTest < Test::Unit::TestCase
-
# context "A User instance" do
-
# setup do
-
# @user = User.find(:first)
-
# end
-
#
-
# should "return its full name"
-
# assert_equal 'John Doe', @user.full_name
-
# end
-
#
-
# context "with a profile" do
-
# setup do
-
# @user.profile = Profile.find(:first)
-
# end
-
#
-
# should "return true when sent :has_profile?"
-
# assert @user.has_profile?
-
# end
-
# end
-
# end
-
# end
-
#
-
# This code will produce the following methods
-
# * <tt>"test: A User instance should return its full name. "</tt>
-
# * <tt>"test: A User instance with a profile should return true when sent :has_profile?. "</tt>
-
#
-
# <b>Just like should statements, a context block can exist next to normal <tt>def test_the_old_way; end</tt>
-
# tests</b>. This means you do not have to fully commit to the context/should syntax in a test file.
-
-
2
def context(name, &blk)
-
10
if Shoulda::Context.current_context
-
Shoulda::Context.current_context.context(name, &blk)
-
else
-
10
context = Shoulda::Context::Context.new(name, self, &blk)
-
10
context.build
-
end
-
end
-
-
# Returns the class being tested, as determined by the test class name.
-
#
-
# class UserTest; described_type; end
-
# # => User
-
2
def described_type
-
@described_type ||= self.name.
-
gsub(/Test$/, '').
-
split('::').
-
39
inject(Object) { |parent, local_name| parent.const_get(local_name) }
-
end
-
-
# Sets the return value of the subject instance method:
-
#
-
# class UserTest < Test::Unit::TestCase
-
# subject { User.first }
-
#
-
# # uses the existing user
-
# should validate_uniqueness_of(:email)
-
# end
-
2
def subject(&block)
-
@subject_block = block
-
end
-
-
2
def subject_block # :nodoc:
-
58
@subject_block ||= nil
-
end
-
end
-
-
2
module InstanceMethods
-
# Returns an instance of the class under test.
-
#
-
# class UserTest
-
# should "be a user" do
-
# assert_kind_of User, subject # passes
-
# end
-
# end
-
#
-
# The subject can be explicitly set using the subject class method:
-
#
-
# class UserTest
-
# subject { User.first }
-
# should "be an existing user" do
-
# assert !subject.new_record? # uses the first user
-
# end
-
# end
-
#
-
# The subject is used by all macros that require an instance of the class
-
# being tested.
-
2
def subject
-
29
@shoulda_subject ||= construct_subject
-
end
-
-
2
def subject_block # :nodoc:
-
29
(@shoulda_context && @shoulda_context.subject_block) || self.class.subject_block
-
end
-
-
2
def get_instance_of(object_or_klass) # :nodoc:
-
29
if object_or_klass.is_a?(Class)
-
29
object_or_klass.new
-
else
-
object_or_klass
-
end
-
end
-
-
2
def instance_variable_name_for(klass) # :nodoc:
-
klass.to_s.split('::').last.underscore
-
end
-
-
2
private
-
-
2
def construct_subject
-
29
if subject_block
-
instance_eval(&subject_block)
-
else
-
29
get_instance_of(self.class.described_type)
-
end
-
end
-
end
-
-
2
class Context # :nodoc:
-
-
2
attr_accessor :name # my name
-
2
attr_accessor :parent # may be another context, or the original test::unit class.
-
2
attr_accessor :subcontexts # array of contexts nested under myself
-
2
attr_accessor :setup_blocks # blocks given via setup methods
-
2
attr_accessor :teardown_blocks # blocks given via teardown methods
-
2
attr_accessor :shoulds # array of hashes representing the should statements
-
2
attr_accessor :should_eventuallys # array of hashes representing the should eventually statements
-
-
# accessor with cache
-
2
def subject_block
-
29
return @subject_block if @subject_block
-
29
parent.subject_block
-
end
-
2
attr_writer :subject_block
-
-
2
def initialize(name, parent, &blk)
-
51
Shoulda::Context.add_context(self)
-
51
self.name = name
-
51
self.parent = parent
-
51
self.setup_blocks = []
-
51
self.teardown_blocks = []
-
51
self.shoulds = []
-
51
self.should_eventuallys = []
-
51
self.subcontexts = []
-
51
self.subject_block = nil
-
-
51
if block_given?
-
51
merge_block(&blk)
-
else
-
merge_block { warn " * WARNING: Block missing for context '#{full_name}'" }
-
end
-
51
Shoulda::Context.remove_context
-
end
-
-
2
def merge_block(&blk)
-
51
if self.respond_to?(:instance_exec)
-
51
self.instance_exec(&blk)
-
else
-
# deprecated in Rails 4.x
-
blk.bind(self).call
-
end
-
end
-
-
2
def context(name, &blk)
-
12
self.subcontexts << Context.new(name, self, &blk)
-
end
-
-
2
def setup(&blk)
-
8
self.setup_blocks << blk
-
end
-
-
2
def teardown(&blk)
-
2
self.teardown_blocks << blk
-
end
-
-
2
def should(name_or_matcher, options = {}, &blk)
-
70
if name_or_matcher.respond_to?(:description) && name_or_matcher.respond_to?(:matches?)
-
29
name = name_or_matcher.description
-
58
blk = lambda { assert_accepts name_or_matcher, subject }
-
else
-
41
name = name_or_matcher
-
end
-
-
70
if blk
-
70
self.shoulds << { :name => name, :before => options[:before], :block => blk }
-
else
-
self.should_eventuallys << { :name => name }
-
end
-
end
-
-
2
def should_not(matcher)
-
name = matcher.description
-
blk = lambda { assert_rejects matcher, subject }
-
self.shoulds << { :name => "not #{name}", :block => blk }
-
end
-
-
2
def should_eventually(name, &blk)
-
self.should_eventuallys << { :name => name, :block => blk }
-
end
-
-
2
def subject(&block)
-
self.subject_block = block
-
end
-
-
2
def full_name
-
85
parent_name = parent.full_name if am_subcontext?
-
85
return [parent_name, name].join(" ").strip
-
end
-
-
2
def am_subcontext?
-
510
parent.is_a?(self.class) # my parent is the same class as myself.
-
end
-
-
2
def test_unit_class
-
255
am_subcontext? ? parent.test_unit_class : parent
-
end
-
-
2
def test_methods
-
@test_methods ||= Hash.new { |h,k|
-
11602
h[k] = Hash[k.instance_methods.map { |n| [n, true] }]
-
140
}
-
end
-
-
2
def create_test_from_should_hash(should)
-
70
test_name = ["test:", full_name, "should", "#{should[:name]}. "].flatten.join(' ').to_sym
-
-
70
if test_methods[test_unit_class][test_name.to_s] then
-
raise DuplicateTestError, "'#{test_name}' is defined more than once."
-
end
-
-
70
test_methods[test_unit_class][test_name.to_s] = true
-
-
70
context = self
-
70
test_unit_class.send(:define_method, test_name) do
-
70
@shoulda_context = context
-
70
begin
-
70
context.run_parent_setup_blocks(self)
-
70
if should[:before]
-
if self.respond_to?(:instance_exec)
-
self.instance_exec(&should[:before])
-
else
-
# deprecated in Rails 4.x
-
should[:before].bind(self).call
-
end
-
end
-
70
context.run_current_setup_blocks(self)
-
70
if self.respond_to?(:instance_exec)
-
70
self.instance_exec(&should[:block])
-
else
-
# deprecated in Rails 4.x
-
should[:block].bind(self).call
-
end
-
ensure
-
70
context.run_all_teardown_blocks(self)
-
end
-
end
-
end
-
-
2
def run_all_setup_blocks(binding)
-
15
run_parent_setup_blocks(binding)
-
15
run_current_setup_blocks(binding)
-
end
-
-
2
def run_parent_setup_blocks(binding)
-
85
self.parent.run_all_setup_blocks(binding) if am_subcontext?
-
end
-
-
2
def run_current_setup_blocks(binding)
-
85
setup_blocks.each do |setup_block|
-
22
if binding.respond_to?(:instance_exec)
-
22
binding.instance_exec(&setup_block)
-
else
-
# deprecated in Rails 4.x
-
setup_block.bind(binding).call
-
end
-
end
-
end
-
-
2
def run_all_teardown_blocks(binding)
-
85
teardown_blocks.reverse.each do |teardown_block|
-
2
if binding.respond_to?(:instance_exec)
-
2
binding.instance_exec(&teardown_block)
-
else
-
# deprecated in Rails 4.x
-
teardown_block.bind(binding).call
-
end
-
end
-
85
self.parent.run_all_teardown_blocks(binding) if am_subcontext?
-
end
-
-
2
def print_should_eventuallys
-
51
should_eventuallys.each do |should|
-
test_name = [full_name, "should", "#{should[:name]}. "].flatten.join(' ')
-
puts " * DEFERRED: " + test_name
-
end
-
end
-
-
2
def build
-
51
shoulds.each do |should|
-
70
create_test_from_should_hash(should)
-
end
-
-
63
subcontexts.each { |context| context.build }
-
-
51
print_should_eventuallys
-
end
-
-
2
def method_missing(method, *args, &blk)
-
test_unit_class.send(method, *args, &blk)
-
end
-
-
end
-
end
-
end
-
-
2
class DuplicateTestError < RuntimeError; end
-
# Stolen straight from ActiveSupport
-
-
2
class Proc #:nodoc:
-
2
def bind(object)
-
block, time = self, Time.now
-
(class << object; self end).class_eval do
-
method_name = "__bind_#{time.to_i}_#{time.usec}"
-
define_method(method_name, &block)
-
method = instance_method(method_name)
-
remove_method(method_name)
-
method
-
end.bind(object)
-
end
-
end
-
2
module Shoulda
-
2
module Context
-
2
VERSION = '1.1.6'.freeze
-
end
-
end
-
2
require 'shoulda/matchers/version'
-
2
require 'shoulda/matchers/assertion_error'
-
2
require 'shoulda/matchers/rails_shim'
-
-
2
if defined?(RSpec)
-
require 'shoulda/matchers/integrations/rspec'
-
end
-
-
2
require 'shoulda/matchers/integrations/test_unit'
-
2
require 'shoulda/matchers/action_controller/filter_param_matcher'
-
2
require 'shoulda/matchers/action_controller/set_the_flash_matcher'
-
2
require 'shoulda/matchers/action_controller/render_with_layout_matcher'
-
2
require 'shoulda/matchers/action_controller/respond_with_matcher'
-
2
require 'shoulda/matchers/action_controller/set_session_matcher'
-
2
require 'shoulda/matchers/action_controller/route_matcher'
-
2
require 'shoulda/matchers/action_controller/redirect_to_matcher'
-
2
require 'shoulda/matchers/action_controller/render_template_matcher'
-
2
require 'shoulda/matchers/action_controller/rescue_from_matcher'
-
-
2
module Shoulda
-
2
module Matchers
-
# By using the matchers you can quickly and easily create concise and
-
# easy to read test suites.
-
#
-
# This code segment:
-
#
-
# describe UsersController, 'on GET to show with a valid id' do
-
# before(:each) do
-
# get :show, :id => User.first.to_param
-
# end
-
#
-
# it { should respond_with(:success) }
-
# it { should render_template(:show) }
-
# it { should not_set_the_flash) }
-
#
-
# it 'does something else really cool' do
-
# assigns[:user].id.should == 1
-
# end
-
# end
-
#
-
# Would produce 5 tests for the show action
-
2
module ActionController
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActionController # :nodoc:
-
# Ensures that filter_parameter_logging is set for the specified key.
-
#
-
# Example:
-
#
-
# it { should filter_param(:password) }
-
2
def filter_param(key)
-
FilterParamMatcher.new(key)
-
end
-
-
2
class FilterParamMatcher # :nodoc:
-
2
def initialize(key)
-
@key = key.to_s
-
end
-
-
2
def matches?(controller)
-
filters_key?
-
end
-
-
2
def failure_message_for_should
-
"Expected #{@key} to be filtered; filtered keys: #{filtered_keys.join(', ')}"
-
end
-
-
2
def failure_message_for_should_not
-
"Did not expect #{@key} to be filtered"
-
end
-
-
2
def description
-
"filter #{@key}"
-
end
-
-
2
private
-
-
2
def filters_key?
-
filtered_keys.include?(@key)
-
end
-
-
2
def filtered_keys
-
Rails.application.config.filter_parameters.map(&:to_s)
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActionController # :nodoc:
-
# Ensures a controller redirected to the given url.
-
#
-
# Example:
-
#
-
# it { should redirect_to('http://somewhere.com') }
-
# it { should redirect_to(users_path) }
-
2
def redirect_to(url_or_description, &block)
-
RedirectToMatcher.new(url_or_description, self, &block)
-
end
-
-
2
class RedirectToMatcher # :nodoc:
-
2
attr_reader :failure_message_for_should, :failure_message_for_should_not
-
-
2
def initialize(url_or_description, context, &block)
-
if block
-
@url_block = block
-
@location = url_or_description
-
else
-
@url = url_or_description
-
@location = @url
-
end
-
@context = context
-
end
-
-
2
def in_context(context)
-
@context = context
-
self
-
end
-
-
2
def matches?(controller)
-
@controller = controller
-
redirects_to_url?
-
end
-
-
2
def description
-
"redirect to #{@location}"
-
end
-
-
2
private
-
-
2
def redirects_to_url?
-
begin
-
@context.send(:assert_redirected_to, url)
-
@failure_message_for_should_not = "Didn't expect to redirect to #{url}"
-
true
-
rescue Shoulda::Matchers::AssertionError => error
-
@failure_message_for_should = error.message
-
false
-
end
-
end
-
-
2
def url
-
if @url_block
-
@context.instance_eval(&@url_block)
-
else
-
@url
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActionController # :nodoc:
-
# Ensures a controller rendered the given template.
-
#
-
# Example:
-
#
-
# it { should render_template(:show) }
-
#
-
# assert that the "_customer" partial was rendered
-
# it { should render_template(:partial => '_customer') }
-
#
-
# assert that the "_customer" partial was rendered twice
-
# it { should render_template(:partial => '_customer', :count => 2) }
-
#
-
# assert that no partials were rendered
-
# it { should render_template(:partial => false) }
-
2
def render_template(options = {}, message = nil)
-
RenderTemplateMatcher.new(options, message, self)
-
end
-
-
2
class RenderTemplateMatcher # :nodoc:
-
2
attr_reader :failure_message_for_should, :failure_message_for_should_not
-
-
2
def initialize(options, message, context)
-
@options = options
-
@message = message
-
@template = options.is_a?(Hash) ? options[:partial] : options
-
@context = context
-
end
-
-
2
def matches?(controller)
-
@controller = controller
-
renders_template?
-
end
-
-
2
def description
-
"render template #{@template}"
-
end
-
-
2
def in_context(context)
-
@context = context
-
self
-
end
-
-
2
private
-
-
2
def renders_template?
-
begin
-
@context.send(:assert_template, @options, @message)
-
@failure_message_for_should_not = "Didn't expect to render #{@template}"
-
true
-
rescue Shoulda::Matchers::AssertionError => error
-
@failure_message_for_should = error.message
-
false
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActionController # :nodoc:
-
-
# Ensures that the controller rendered with the given layout.
-
#
-
# Example:
-
#
-
# it { should render_with_layout }
-
# it { should render_with_layout(:special) }
-
# it { should_not render_with_layout }
-
2
def render_with_layout(expected_layout = nil)
-
RenderWithLayoutMatcher.new(expected_layout).in_context(self)
-
end
-
-
2
class RenderWithLayoutMatcher # :nodoc:
-
-
2
def initialize(expected_layout)
-
unless expected_layout.nil?
-
@expected_layout = expected_layout.to_s
-
end
-
end
-
-
# Used to provide access to layouts recorded by
-
# ActionController::TemplateAssertions in Rails 3
-
2
def in_context(context)
-
@context = context
-
self
-
end
-
-
2
def matches?(controller)
-
@controller = controller
-
rendered_with_layout? && rendered_with_expected_layout?
-
end
-
-
2
def failure_message_for_should
-
"Expected #{expectation}, but #{result}"
-
end
-
-
2
def failure_message_for_should_not
-
"Did not expect #{expectation}, but #{result}"
-
end
-
-
2
def description
-
description = 'render with '
-
if @expected_layout.nil?
-
description << 'a layout'
-
else
-
description << "the #{@expected_layout.inspect} layout"
-
end
-
description
-
end
-
-
2
private
-
-
2
def rendered_with_layout?
-
!rendered_layouts.empty?
-
end
-
-
2
def rendered_with_expected_layout?
-
if @expected_layout.nil?
-
true
-
else
-
rendered_layouts.include?(@expected_layout)
-
end
-
end
-
-
2
def rendered_layouts
-
recorded_layouts.keys.compact.map { |layout| layout.sub(%r{^layouts/}, '') }
-
end
-
-
2
def recorded_layouts
-
if @context
-
@context.instance_variable_get(Shoulda::Matchers::RailsShim.layouts_ivar)
-
else
-
{}
-
end
-
end
-
-
2
def expectation
-
"to #{description}"
-
end
-
-
2
def result
-
if rendered_with_layout?
-
'rendered with ' + rendered_layouts.map(&:inspect).join(', ')
-
else
-
'rendered without a layout'
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda
-
2
module Matchers
-
2
module ActionController
-
2
def rescue_from(exception)
-
RescueFromMatcher.new exception
-
end
-
-
2
class RescueFromMatcher
-
2
def initialize(exception)
-
@exception = exception
-
end
-
-
2
def with(method)
-
@expected_method = method
-
self
-
end
-
-
2
def matches?(controller)
-
@controller = controller
-
rescues_from_exception? && method_name_matches? && handler_exists?
-
end
-
-
2
def description
-
description = "rescues from #{exception}"
-
description << " with ##{expected_method}" if expected_method
-
description
-
end
-
-
2
def failure_message_for_should
-
"Expected #{expectation}"
-
end
-
-
2
def failure_message_for_should_not
-
"Did not expect #{expectation}"
-
end
-
-
2
private
-
-
2
attr_reader :controller, :exception, :expected_method, :handlers
-
-
2
def expectation
-
expectation = "#{controller} to rescue from #{exception}"
-
-
if expected_method && !method_name_matches?
-
expectation << " with ##{expected_method}"
-
end
-
-
unless handler_exists?
-
expectation << " but #{controller} does not respond to #{expected_method}"
-
end
-
expectation
-
end
-
-
2
def rescues_from_exception?
-
@handlers = controller.rescue_handlers.select do |handler|
-
handler.first == exception.to_s
-
end
-
handlers.any?
-
end
-
-
2
def method_name_matches?
-
if expected_method.present?
-
handlers.any? do |handler|
-
handler.last == expected_method
-
end
-
else
-
true
-
end
-
end
-
-
2
def handler_exists?
-
if expected_method.present?
-
controller.respond_to? expected_method
-
else
-
true
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActionController # :nodoc:
-
-
# Ensures a controller responded with expected 'response' status code.
-
#
-
# You can pass an explicit status number like 200, 301, 404, 500
-
# or its symbolic equivalent :success, :redirect, :missing, :error.
-
# See ActionController::StatusCodes for a full list.
-
#
-
# Example:
-
#
-
# it { should respond_with(:success) }
-
# it { should respond_with(:redirect) }
-
# it { should respond_with(:missing) }
-
# it { should respond_with(:error) }
-
# it { should respond_with(501) }
-
2
def respond_with(status)
-
RespondWithMatcher.new(status)
-
end
-
-
2
class RespondWithMatcher # :nodoc:
-
-
2
def initialize(status)
-
@status = symbol_to_status_code(status)
-
end
-
-
2
def matches?(controller)
-
@controller = controller
-
correct_status_code? || correct_status_code_range?
-
end
-
-
2
def failure_message_for_should
-
"Expected #{expectation}"
-
end
-
-
2
def failure_message_for_should_not
-
"Did not expect #{expectation}"
-
end
-
-
2
def description
-
"respond with #{@status}"
-
end
-
-
2
protected
-
-
2
def correct_status_code?
-
response_code == @status
-
end
-
-
2
def correct_status_code_range?
-
@status.is_a?(Range) &&
-
@status.include?(response_code)
-
end
-
-
2
def response_code
-
@controller.response.response_code
-
end
-
-
2
def symbol_to_status_code(potential_symbol)
-
case potential_symbol
-
when :success then 200
-
when :redirect then 300..399
-
when :missing then 404
-
when :error then 500..599
-
when Symbol
-
if defined?(::Rack::Utils::SYMBOL_TO_STATUS_CODE)
-
::Rack::Utils::SYMBOL_TO_STATUS_CODE[potential_symbol]
-
else
-
::ActionController::Base::SYMBOL_TO_STATUS_CODE[potential_symbol]
-
end
-
else
-
potential_symbol
-
end
-
end
-
-
2
def expectation
-
"response to be a #{@status}, but was #{response_code}"
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActionController # :nodoc:
-
-
# Ensures that requesting +path+ using +method+ routes to +options+.
-
#
-
# If you don't specify a controller, it will use the controller from the
-
# example group.
-
#
-
# +to_param+ is called on the +options+ given.
-
#
-
# Examples:
-
#
-
# it { should route(:get, '/posts').
-
# to(:controller => :posts, :action => :index) }
-
# it { should route(:get, '/posts/new').to(:action => :new) }
-
# it { should route(:post, '/posts').to(:action => :create) }
-
# it { should route(:get, '/posts/1').to(:action => :show, :id => 1) }
-
# it { should route(:get, '/posts/1/edit').to(:action => :edit, :id => 1) }
-
# it { should route(:put, '/posts/1').to(:action => :update, :id => 1) }
-
# it { should route(:delete, '/posts/1').
-
# to(:action => :destroy, :id => 1) }
-
# it { should route(:get, '/users/1/posts/1').
-
# to(:action => :show, :id => 1, :user_id => 1) }
-
2
def route(method, path)
-
RouteMatcher.new(method, path, self)
-
end
-
-
2
class RouteMatcher # :nodoc:
-
2
def initialize(method, path, context)
-
@method = method
-
@path = path
-
@context = context
-
end
-
-
2
attr_reader :failure_message_for_should, :failure_message_for_should_not
-
-
2
def to(params)
-
@params = stringify_params(params)
-
self
-
end
-
-
2
def in_context(context)
-
@context = context
-
self
-
end
-
-
2
def matches?(controller)
-
guess_controller!(controller)
-
route_recognized?
-
end
-
-
2
def description
-
"route #{@method.to_s.upcase} #{@path} to/from #{@params.inspect}"
-
end
-
-
2
private
-
-
2
def guess_controller!(controller)
-
@params[:controller] ||= controller.controller_path
-
end
-
-
2
def stringify_params(params)
-
params.each do |key, value|
-
params[key] = stringify(value)
-
end
-
end
-
-
2
def stringify(value)
-
if value.is_a?(Array)
-
value.map(&:to_param)
-
else
-
value.to_param
-
end
-
end
-
-
2
def route_recognized?
-
begin
-
@context.send(:assert_routing,
-
{ :method => @method, :path => @path },
-
@params)
-
-
@failure_message_for_should_not = "Didn't expect to #{description}"
-
true
-
rescue ::ActionController::RoutingError => error
-
@failure_message_for_should = error.message
-
false
-
rescue Shoulda::Matchers::AssertionError => error
-
@failure_message_for_should = error.message
-
false
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActionController # :nodoc:
-
-
# Ensures that a session key was set to the expected value.
-
#
-
# Example:
-
#
-
# it { should set_session(:message) }
-
# it { should set_session(:user_id).to(@user.id) }
-
# it { should_not set_session(:user_id) }
-
2
def set_session(key)
-
SetSessionMatcher.new(key)
-
end
-
-
2
class SetSessionMatcher # :nodoc:
-
2
def initialize(key)
-
@key = key.to_s
-
end
-
-
2
def to(value = nil, &block)
-
@value = value
-
@value_block = block
-
self
-
end
-
-
2
def matches?(controller)
-
@controller = controller
-
if @value_block
-
@value = @context.instance_eval(&@value_block)
-
end
-
assigned_correct_value? || cleared_value?
-
end
-
-
2
def failure_message_for_should
-
"Expected #{expectation}, but #{result}"
-
end
-
-
2
def failure_message_for_should_not
-
"Didn't expect #{expectation}, but #{result}"
-
end
-
-
2
def description
-
description = "set session variable #{@key.inspect}"
-
if @value
-
description << " to #{@value.inspect}"
-
end
-
description
-
end
-
-
2
def in_context(context)
-
@context = context
-
self
-
end
-
-
2
private
-
-
2
def assigned_value?
-
!assigned_value.nil?
-
end
-
-
2
def cleared_value?
-
defined?(@value) && @value.nil? && assigned_value.nil?
-
end
-
-
2
def assigned_correct_value?
-
if assigned_value?
-
if @value.nil?
-
true
-
else
-
assigned_value == @value
-
end
-
end
-
end
-
-
2
def assigned_value
-
session[@key]
-
end
-
-
2
def expectation
-
expectation = "session variable #{@key} to be set"
-
if @value
-
expectation << " to #{@value.inspect}"
-
end
-
end
-
-
2
def result
-
if session.empty?
-
'no session variables were set'
-
else
-
"the session was #{session.inspect}"
-
end
-
end
-
-
2
def session
-
if @controller.request.respond_to?(:session)
-
@controller.request.session.to_hash
-
else
-
@controller.response.session.data
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActionController # :nodoc:
-
-
# Ensures that the flash contains the given value. Can be a String, a
-
# Regexp, or nil (indicating that the flash should not be set).
-
#
-
# Example:
-
#
-
# it { should set_the_flash }
-
# it { should set_the_flash.to('Thank you for placing this order.') }
-
# it { should set_the_flash.to(/created/i) }
-
# it { should set_the_flash[:alert].to('Password does not match') }
-
# it { should set_the_flash.to(/logged in/i).now }
-
# it { should_not set_the_flash }
-
2
def set_the_flash
-
SetTheFlashMatcher.new
-
end
-
-
2
class SetTheFlashMatcher # :nodoc:
-
2
def initialize
-
@options = {}
-
end
-
-
2
def to(value)
-
if !value.is_a?(String) && !value.is_a?(Regexp)
-
raise "cannot match against #{value.inspect}"
-
end
-
@value = value
-
self
-
end
-
-
2
def now
-
@options[:now] = true
-
self
-
end
-
-
2
def [](key)
-
@options[:key] = key
-
self
-
end
-
-
2
def matches?(controller)
-
@controller = controller
-
sets_the_flash? && string_value_matches? && regexp_value_matches?
-
end
-
-
2
def description
-
description = "set the #{expected_flash_invocation}"
-
description << " to #{@value.inspect}" unless @value.nil?
-
description
-
end
-
-
2
def failure_message_for_should
-
"Expected #{expectation}"
-
end
-
-
2
def failure_message_for_should_not
-
"Did not expect #{expectation}"
-
end
-
-
2
private
-
-
2
def sets_the_flash?
-
flash_values.any?
-
end
-
-
2
def string_value_matches?
-
if @value.is_a?(String)
-
flash_values.any? {|value| value == @value }
-
else
-
true
-
end
-
end
-
-
2
def regexp_value_matches?
-
if @value.is_a?(Regexp)
-
flash_values.any? {|value| value =~ @value }
-
else
-
true
-
end
-
end
-
-
2
def flash_values
-
if @options.key?(:key)
-
[flash.to_hash[@options[:key]]]
-
else
-
flash.to_hash.values
-
end
-
end
-
-
2
def flash
-
@flash ||= copy_of_flash_from_controller
-
end
-
-
2
def copy_of_flash_from_controller
-
@controller.flash.dup.tap do |flash|
-
copy_flashes(@controller.flash, flash)
-
copy_discard_if_necessary(@controller.flash, flash)
-
sweep_flash_if_necessary(flash)
-
end
-
end
-
-
2
def copy_flashes(original_flash, new_flash)
-
flashes_ivar = Shoulda::Matchers::RailsShim.flashes_ivar
-
flashes = original_flash.instance_variable_get(flashes_ivar).dup
-
new_flash.instance_variable_set(flashes_ivar, flashes)
-
end
-
-
2
def copy_discard_if_necessary(original_flash, new_flash)
-
discard_ivar = :@discard
-
if original_flash.instance_variable_defined?(discard_ivar)
-
discard = original_flash.instance_variable_get(discard_ivar).dup
-
new_flash.instance_variable_set(discard_ivar, discard)
-
end
-
end
-
-
2
def sweep_flash_if_necessary(flash)
-
unless @options[:now]
-
flash.sweep
-
end
-
end
-
-
2
def expectation
-
expectation = "the #{expected_flash_invocation} to be set"
-
expectation << " to #{@value.inspect}" unless @value.nil?
-
expectation << ", but #{flash_description}"
-
expectation
-
end
-
-
2
def flash_description
-
if flash.blank?
-
'no flash was set'
-
else
-
"was #{flash.inspect}"
-
end
-
end
-
-
2
def expected_flash_invocation
-
"flash#{pretty_now}#{pretty_key}"
-
end
-
-
2
def pretty_now
-
if @options[:now]
-
'.now'
-
else
-
''
-
end
-
end
-
-
2
def pretty_key
-
if @options[:key]
-
"[:#{@options[:key]}]"
-
else
-
''
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'shoulda/matchers/active_model/helpers'
-
2
require 'shoulda/matchers/active_model/validation_matcher'
-
2
require 'shoulda/matchers/active_model/validation_message_finder'
-
2
require 'shoulda/matchers/active_model/exception_message_finder'
-
2
require 'shoulda/matchers/active_model/allow_value_matcher'
-
2
require 'shoulda/matchers/active_model/disallow_value_matcher'
-
2
require 'shoulda/matchers/active_model/only_integer_matcher'
-
2
require 'shoulda/matchers/active_model/odd_even_number_matcher'
-
2
require 'shoulda/matchers/active_model/comparison_matcher'
-
2
require 'shoulda/matchers/active_model/ensure_length_of_matcher'
-
2
require 'shoulda/matchers/active_model/ensure_inclusion_of_matcher'
-
2
require 'shoulda/matchers/active_model/ensure_exclusion_of_matcher'
-
2
require 'shoulda/matchers/active_model/validate_presence_of_matcher'
-
2
require 'shoulda/matchers/active_model/validate_uniqueness_of_matcher'
-
2
require 'shoulda/matchers/active_model/validate_acceptance_of_matcher'
-
2
require 'shoulda/matchers/active_model/validate_confirmation_of_matcher'
-
2
require 'shoulda/matchers/active_model/validate_numericality_of_matcher'
-
2
require 'shoulda/matchers/active_model/allow_mass_assignment_of_matcher'
-
2
require 'shoulda/matchers/active_model/errors'
-
2
require 'shoulda/matchers/active_model/have_secure_password_matcher'
-
-
-
2
module Shoulda
-
2
module Matchers
-
# = Matchers for your active record models
-
#
-
# These matchers will test most of the validations of ActiveModel::Validations.
-
#
-
# describe User do
-
# it { should validate_presence_of(:name) }
-
# it { should validate_presence_of(:phone_number) }
-
# %w(abcd 1234).each do |value|
-
# it { should_not allow_value(value).for(:phone_number) }
-
# end
-
# it { should allow_value('(123) 456-7890').for(:phone_number) }
-
# it { should_not allow_mass_assignment_of(:password) }
-
# it { should allow_value('Activated', 'Pending').for(:status).strict }
-
# it { should_not allow_value('Amazing').for(:status).strict }
-
# end
-
#
-
# These tests work with the following model:
-
#
-
# class User < ActiveRecord::Base
-
# validates_presence_of :name
-
# validates_presence_of :phone_number
-
# validates_inclusion_of :status, :in => %w(Activated Pending), :strict => true
-
# attr_accessible :name, :phone_number
-
# end
-
2
module ActiveModel
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
-
# Ensures that the attribute can be set on mass update.
-
#
-
# it { should_not allow_mass_assignment_of(:password) }
-
# it { should allow_mass_assignment_of(:first_name) }
-
#
-
# In Rails 3.1 you can check role as well:
-
#
-
# it { should allow_mass_assignment_of(:first_name).as(:admin) }
-
#
-
2
def allow_mass_assignment_of(value)
-
AllowMassAssignmentOfMatcher.new(value)
-
end
-
-
2
class AllowMassAssignmentOfMatcher # :nodoc:
-
2
attr_reader :failure_message_for_should, :failure_message_for_should_not
-
-
2
def initialize(attribute)
-
@attribute = attribute.to_s
-
@options = {}
-
end
-
-
2
def as(role)
-
if active_model_less_than_3_1?
-
raise 'You can specify role only in Rails 3.1 or greater'
-
end
-
@options[:role] = role
-
self
-
end
-
-
2
def matches?(subject)
-
@subject = subject
-
if attr_mass_assignable?
-
if whitelisting?
-
@failure_message_for_should_not = "#{@attribute} was made accessible"
-
else
-
if protected_attributes.empty?
-
@failure_message_for_should_not = 'no attributes were protected'
-
else
-
@failure_message_for_should_not = "#{class_name} is protecting " <<
-
"#{protected_attributes.to_a.to_sentence}, " <<
-
"but not #{@attribute}."
-
end
-
end
-
true
-
else
-
if whitelisting?
-
@failure_message_for_should = "Expected #{@attribute} to be accessible"
-
else
-
@failure_message_for_should = "Did not expect #{@attribute} to be protected"
-
end
-
false
-
end
-
end
-
-
2
def description
-
[base_description, role_description].compact.join(' ')
-
end
-
-
2
private
-
-
2
def base_description
-
"allow mass assignment of #{@attribute}"
-
end
-
-
2
def role_description
-
if role != :default
-
"as #{role}"
-
end
-
end
-
-
2
def role
-
@options[:role] || :default
-
end
-
-
2
def protected_attributes
-
@protected_attributes ||= (@subject.class.protected_attributes || [])
-
end
-
-
2
def accessible_attributes
-
@accessible_attributes ||= (@subject.class.accessible_attributes || [])
-
end
-
-
2
def whitelisting?
-
authorizer.kind_of?(::ActiveModel::MassAssignmentSecurity::WhiteList)
-
end
-
-
2
def attr_mass_assignable?
-
!authorizer.deny?(@attribute)
-
end
-
-
2
def authorizer
-
if active_model_less_than_3_1?
-
@subject.class.active_authorizer
-
else
-
@subject.class.active_authorizer[role]
-
end
-
end
-
-
2
def class_name
-
@subject.class.name
-
end
-
-
2
def active_model_less_than_3_1?
-
::ActiveModel::VERSION::STRING.to_f < 3.1
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
-
# Ensures that the attribute can be set to the given value or values. If
-
# multiple values are given the match succeeds only if all given values
-
# are allowed. Otherwise, the matcher fails at the first bad value in the
-
# argument list (the remaining arguments are not processed then).
-
#
-
# Options:
-
# * <tt>with_message</tt> - value the test expects to find in
-
# <tt>errors.on(:attribute)</tt>. Regexp or string. If omitted,
-
# the test looks for any errors in <tt>errors.on(:attribute)</tt>.
-
# * <tt>strict</tt> - expects the model to raise an exception when the
-
# validation fails rather than adding to the errors collection. Used for
-
# testing `validates!` and the `:strict => true` validation options.
-
#
-
# Example:
-
# it { should_not allow_value('bad').for(:isbn) }
-
# it { should allow_value('isbn 1 2345 6789 0').for(:isbn) }
-
#
-
2
def allow_value(*values)
-
if values.empty?
-
raise ArgumentError, 'need at least one argument'
-
else
-
AllowValueMatcher.new(*values)
-
end
-
end
-
-
2
class AllowValueMatcher # :nodoc:
-
2
include Helpers
-
-
2
attr_accessor :attribute_with_message
-
2
attr_accessor :options
-
-
2
def initialize(*values)
-
self.values_to_match = values
-
self.message_finder_factory = ValidationMessageFinder
-
self.options = {}
-
end
-
-
2
def for(attribute)
-
self.attribute_to_set = attribute
-
self.attribute_to_check_message_against = attribute
-
self
-
end
-
-
2
def on(context)
-
@context = context
-
self
-
end
-
-
2
def with_message(message, options={})
-
self.options[:expected_message] = message
-
if options.key?(:against)
-
self.attribute_to_check_message_against = options[:against]
-
end
-
self
-
end
-
-
2
def strict
-
self.message_finder_factory = ExceptionMessageFinder
-
self
-
end
-
-
2
def matches?(instance)
-
self.instance = instance
-
-
values_to_match.none? do |value|
-
self.value = value
-
instance.send("#{attribute_to_set}=", value)
-
errors_match?
-
end
-
end
-
-
2
def failure_message_for_should
-
"Did not expect #{expectation}, got error: #{matched_error}"
-
end
-
-
2
def failure_message_for_should_not
-
"Expected #{expectation}, got #{error_description}"
-
end
-
-
2
def description
-
message_finder.allow_description(allowed_values)
-
end
-
-
2
private
-
-
2
attr_accessor :values_to_match, :message_finder_factory,
-
:instance, :attribute_to_set, :attribute_to_check_message_against,
-
:context, :value, :matched_error
-
-
2
def errors_match?
-
has_messages? && errors_for_attribute_match?
-
end
-
-
2
def has_messages?
-
message_finder.has_messages?
-
end
-
-
2
def errors_for_attribute_match?
-
if expected_message
-
self.matched_error = errors_match_regexp? || errors_match_string?
-
else
-
errors_for_attribute.compact.any?
-
end
-
end
-
-
2
def errors_for_attribute
-
message_finder.messages
-
end
-
-
2
def errors_match_regexp?
-
if Regexp === expected_message
-
errors_for_attribute.detect { |e| e =~ expected_message }
-
end
-
end
-
-
2
def errors_match_string?
-
if errors_for_attribute.include?(expected_message)
-
expected_message
-
end
-
end
-
-
2
def expectation
-
includes_expected_message = expected_message ? "to include #{expected_message.inspect}" : ''
-
[error_source, includes_expected_message, "when #{attribute_to_set} is set to #{value.inspect}"].join(' ')
-
end
-
-
2
def error_source
-
message_finder.source_description
-
end
-
-
2
def error_description
-
message_finder.messages_description
-
end
-
-
2
def allowed_values
-
if values_to_match.length > 1
-
"any of [#{values_to_match.map(&:inspect).join(', ')}]"
-
else
-
values_to_match.first.inspect
-
end
-
end
-
-
2
def expected_message
-
if options.key?(:expected_message)
-
if Symbol === options[:expected_message]
-
default_expected_message
-
else
-
options[:expected_message]
-
end
-
end
-
end
-
-
2
def default_expected_message
-
message_finder.expected_message_from(default_attribute_message)
-
end
-
-
2
def default_attribute_message
-
default_error_message(
-
options[:expected_message],
-
:model_name => model_name,
-
:instance => instance,
-
:attribute => attribute_to_set
-
)
-
end
-
-
2
def model_name
-
instance.class.to_s.underscore
-
end
-
-
2
def message_finder
-
message_finder_factory.new(instance, attribute_to_check_message_against, context)
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
# Examples:
-
# it { should validate_numericality_of(:attr).
-
# is_greater_than(6).
-
# less_than(20)...(and so on) }
-
2
class ComparisonMatcher < ValidationMatcher
-
2
def initialize(value, operator)
-
@value = value
-
@operator = operator
-
@message = nil
-
end
-
-
2
def for(attribute)
-
@attribute = attribute
-
self
-
end
-
-
2
def matches?(subject)
-
@subject = subject
-
disallows_value_of(value_to_compare, @message)
-
end
-
-
2
def allowed_types
-
'integer'
-
end
-
-
2
def with_message(message)
-
@message = message
-
end
-
-
2
private
-
-
2
def value_to_compare
-
case @operator
-
when :> then [@value, @value - 1].sample
-
when :>= then @value - 1
-
when :== then @value + 1
-
when :< then [@value, @value + 1].sample
-
when :<= then @value + 1
-
end
-
end
-
-
2
def expectation
-
case @operator
-
when :> then "greater than"
-
when :>= then "greater than or equal to"
-
when :== then "equal to"
-
when :< then "less than"
-
when :<= then "less than or equal to"
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
2
class DisallowValueMatcher # :nodoc:
-
2
def initialize(value)
-
@allow_matcher = AllowValueMatcher.new(value)
-
end
-
-
2
def matches?(subject)
-
!@allow_matcher.matches?(subject)
-
end
-
-
2
def for(attribute)
-
@allow_matcher.for(attribute)
-
self
-
end
-
-
2
def on(context)
-
@allow_matcher.on(context)
-
self
-
end
-
-
2
def with_message(message, options={})
-
@allow_matcher.with_message(message, options)
-
self
-
end
-
-
2
def failure_message_for_should
-
@allow_matcher.failure_message_for_should_not
-
end
-
-
2
def failure_message_for_should_not
-
@allow_matcher.failure_message_for_should
-
end
-
-
2
def allowed_types
-
''
-
end
-
-
2
def strict
-
@allow_matcher.strict
-
self
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
-
# Ensure that the attribute's value is not in the range specified
-
#
-
# Options:
-
# * <tt>in_array</tt> - the array of not allowed values for this attribute
-
# * <tt>in_range</tt> - the range of not allowed values for this attribute
-
# * <tt>with_message</tt> - value the test expects to find in
-
# <tt>errors.on(:attribute)</tt>. Regexp or string. Defaults to the
-
# translation for :exclusion.
-
#
-
# Example:
-
# it { should ensure_exclusion_of(:age).in_range(30..60) }
-
#
-
2
def ensure_exclusion_of(attr)
-
EnsureExclusionOfMatcher.new(attr)
-
end
-
-
2
class EnsureExclusionOfMatcher < ValidationMatcher # :nodoc:
-
2
def in_array(array)
-
@array = array
-
self
-
end
-
-
2
def in_range(range)
-
@range = range
-
@minimum = range.first
-
@maximum = range.max
-
self
-
end
-
-
2
def with_message(message)
-
@expected_message = message if message
-
self
-
end
-
-
2
def description
-
"ensure exclusion of #{@attribute} in #{inspect_message}"
-
end
-
-
2
def matches?(subject)
-
super(subject)
-
-
if @range
-
allows_lower_value &&
-
disallows_minimum_value &&
-
allows_higher_value &&
-
disallows_maximum_value
-
elsif @array
-
disallows_all_values_in_array?
-
end
-
end
-
-
2
private
-
-
2
def disallows_all_values_in_array?
-
@array.all? do |value|
-
disallows_value_of(value, expected_message)
-
end
-
end
-
-
2
def allows_lower_value
-
@minimum == 0 || allows_value_of(@minimum - 1, expected_message)
-
end
-
-
2
def allows_higher_value
-
allows_value_of(@maximum + 1, expected_message)
-
end
-
-
2
def disallows_minimum_value
-
disallows_value_of(@minimum, expected_message)
-
end
-
-
2
def disallows_maximum_value
-
disallows_value_of(@maximum, expected_message)
-
end
-
-
2
def expected_message
-
@expected_message || :exclusion
-
end
-
-
2
def inspect_message
-
if @range
-
@range.inspect
-
else
-
@array.inspect
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
-
# Ensure that the attribute's value is in the range specified
-
#
-
# Options:
-
# * <tt>in_array</tt> - the array of allowed values for this attribute
-
# * <tt>in_range</tt> - the range of allowed values for this attribute
-
# * <tt>with_low_message</tt> - value the test expects to find in
-
# <tt>errors.on(:attribute)</tt>. Regexp or string. Defaults to the
-
# translation for :inclusion.
-
# * <tt>with_high_message</tt> - value the test expects to find in
-
# <tt>errors.on(:attribute)</tt>. Regexp or string. Defaults to the
-
# translation for :inclusion.
-
#
-
# Example:
-
# it { should ensure_inclusion_of(:age).in_range(0..100) }
-
#
-
2
def ensure_inclusion_of(attr)
-
EnsureInclusionOfMatcher.new(attr)
-
end
-
-
2
class EnsureInclusionOfMatcher < ValidationMatcher # :nodoc:
-
2
ARBITRARY_OUTSIDE_STRING = 'shouldamatchersteststring'
-
2
ARBITRARY_OUTSIDE_FIXNUM = 123456789
-
-
2
def initialize(attribute)
-
super(attribute)
-
@options = {}
-
end
-
-
2
def in_array(array)
-
@array = array
-
self
-
end
-
-
2
def in_range(range)
-
@range = range
-
@minimum = range.first
-
@maximum = range.max
-
self
-
end
-
-
2
def allow_blank(allow_blank = true)
-
@options[:allow_blank] = allow_blank
-
self
-
end
-
-
2
def allow_nil(allow_nil = true)
-
@options[:allow_nil] = allow_nil
-
self
-
end
-
-
2
def with_message(message)
-
if message
-
@low_message = message
-
@high_message = message
-
end
-
self
-
end
-
-
2
def with_low_message(message)
-
@low_message = message if message
-
self
-
end
-
-
2
def with_high_message(message)
-
@high_message = message if message
-
self
-
end
-
-
2
def description
-
"ensure inclusion of #{@attribute} in #{inspect_message}"
-
end
-
-
2
def matches?(subject)
-
super(subject)
-
-
if @range
-
@low_message ||= :inclusion
-
@high_message ||= :inclusion
-
-
disallows_lower_value &&
-
allows_minimum_value &&
-
disallows_higher_value &&
-
allows_maximum_value
-
elsif @array
-
if allows_all_values_in_array? && allows_blank_value? && allows_nil_value? && disallows_value_outside_of_array?
-
true
-
else
-
@failure_message_for_should = "#{@array} doesn't match array in validation"
-
false
-
end
-
end
-
end
-
-
2
private
-
-
2
def allows_blank_value?
-
if @options.key?(:allow_blank)
-
blank_values = ['', ' ', "\n", "\r", "\t", "\f"]
-
@options[:allow_blank] == blank_values.all? { |value| allows_value_of(value) }
-
else
-
true
-
end
-
end
-
-
2
def allows_nil_value?
-
if @options.key?(:allow_nil)
-
@options[:allow_nil] == allows_value_of(nil)
-
else
-
true
-
end
-
end
-
-
2
def inspect_message
-
@range.nil? ? @array.inspect : @range.inspect
-
end
-
-
2
def allows_all_values_in_array?
-
@array.all? do |value|
-
allows_value_of(value, @low_message)
-
end
-
end
-
-
2
def disallows_lower_value
-
@minimum == 0 || disallows_value_of(@minimum - 1, @low_message)
-
end
-
-
2
def disallows_higher_value
-
disallows_value_of(@maximum + 1, @high_message)
-
end
-
-
2
def allows_minimum_value
-
allows_value_of(@minimum, @low_message)
-
end
-
-
2
def allows_maximum_value
-
allows_value_of(@maximum, @high_message)
-
end
-
-
2
def disallows_value_outside_of_array?
-
disallows_value_of(value_outside_of_array)
-
end
-
-
2
def value_outside_of_array
-
if @array.include?(outside_value)
-
raise CouldNotDetermineValueOutsideOfArray
-
else
-
outside_value
-
end
-
end
-
-
2
def outside_value
-
@outside_value ||= find_outside_value
-
end
-
-
2
def find_outside_value
-
case @subject.send(@attribute.to_s)
-
when Fixnum
-
ARBITRARY_OUTSIDE_FIXNUM
-
else
-
ARBITRARY_OUTSIDE_STRING
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
-
# Ensures that the length of the attribute is validated. Only works with
-
# string/text columns because it uses a string to check length.
-
#
-
# Options:
-
# * <tt>is_at_least</tt> - minimum length of this attribute
-
# * <tt>is_at_most</tt> - maximum length of this attribute
-
# * <tt>is_equal_to</tt> - exact requred length of this attribute
-
# * <tt>with_short_message</tt> - value the test expects to find in
-
# <tt>errors.on(:attribute)</tt>. Regexp or string. Defaults to the
-
# translation for :too_short.
-
# * <tt>with_long_message</tt> - value the test expects to find in
-
# <tt>errors.on(:attribute)</tt>. Regexp or string. Defaults to the
-
# translation for :too_long.
-
# * <tt>with_message</tt> - value the test expects to find in
-
# <tt>errors.on(:attribute)</tt>. Regexp or string. Defaults to the
-
# translation for :wrong_length. Used in conjunction with
-
# <tt>is_equal_to</tt>.
-
#
-
# Examples:
-
# it { should ensure_length_of(:password).
-
# is_at_least(6).
-
# is_at_most(20) }
-
# it { should ensure_length_of(:name).
-
# is_at_least(3).
-
# with_short_message(/not long enough/) }
-
# it { should ensure_length_of(:ssn).
-
# is_equal_to(9).
-
# with_message(/is invalid/) }
-
2
def ensure_length_of(attr)
-
EnsureLengthOfMatcher.new(attr)
-
end
-
-
2
class EnsureLengthOfMatcher < ValidationMatcher # :nodoc:
-
2
include Helpers
-
-
2
def initialize(attribute)
-
super(attribute)
-
@options = {}
-
end
-
-
2
def is_at_least(length)
-
@options[:minimum] = length
-
@short_message ||= :too_short
-
self
-
end
-
-
2
def is_at_most(length)
-
@options[:maximum] = length
-
@long_message ||= :too_long
-
self
-
end
-
-
2
def is_equal_to(length)
-
@options[:minimum] = length
-
@options[:maximum] = length
-
@short_message ||= :wrong_length
-
@long_message ||= :wrong_length
-
self
-
end
-
-
2
def with_short_message(message)
-
if message
-
@short_message = message
-
end
-
self
-
end
-
2
alias_method :with_message, :with_short_message
-
-
2
def with_long_message(message)
-
if message
-
@long_message = message
-
end
-
self
-
end
-
-
2
def description
-
description = "ensure #{@attribute} has a length "
-
if @options.key?(:minimum) && @options.key?(:maximum)
-
if @options[:minimum] == @options[:maximum]
-
description << "of exactly #{@options[:minimum]}"
-
else
-
description << "between #{@options[:minimum]} and #{@options[:maximum]}"
-
end
-
else
-
description << "of at least #{@options[:minimum]}" if @options[:minimum]
-
description << "of at most #{@options[:maximum]}" if @options[:maximum]
-
end
-
description
-
end
-
-
2
def matches?(subject)
-
super(subject)
-
translate_messages!
-
lower_bound_matches? && upper_bound_matches?
-
end
-
-
2
private
-
-
2
def translate_messages!
-
if Symbol === @short_message
-
@short_message = default_error_message(@short_message,
-
:model_name => @subject.class.to_s.underscore,
-
:instance => @subject,
-
:attribute => @attribute,
-
:count => @options[:minimum])
-
end
-
-
if Symbol === @long_message
-
@long_message = default_error_message(@long_message,
-
:model_name => @subject.class.to_s.underscore,
-
:instance => @subject,
-
:attribute => @attribute,
-
:count => @options[:maximum])
-
end
-
end
-
-
2
def lower_bound_matches?
-
disallows_lower_length? && allows_minimum_length?
-
end
-
-
2
def upper_bound_matches?
-
disallows_higher_length? && allows_maximum_length?
-
end
-
-
2
def disallows_lower_length?
-
if @options.key?(:minimum)
-
@options[:minimum] == 0 ||
-
disallows_length_of?(@options[:minimum] - 1, @short_message)
-
else
-
true
-
end
-
end
-
-
2
def disallows_higher_length?
-
if @options.key?(:maximum)
-
disallows_length_of?(@options[:maximum] + 1, @long_message)
-
else
-
true
-
end
-
end
-
-
2
def allows_minimum_length?
-
if @options.key?(:minimum)
-
allows_length_of?(@options[:minimum], @short_message)
-
else
-
true
-
end
-
end
-
-
2
def allows_maximum_length?
-
if @options.key?(:maximum)
-
allows_length_of?(@options[:maximum], @long_message)
-
else
-
true
-
end
-
end
-
-
2
def allows_length_of?(length, message)
-
allows_value_of(string_of_length(length), message)
-
end
-
-
2
def disallows_length_of?(length, message)
-
disallows_value_of(string_of_length(length), message)
-
end
-
-
2
def string_of_length(length)
-
'x' * length
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
2
class CouldNotDetermineValueOutsideOfArray < RuntimeError; end
-
end
-
end
-
end
-
2
module Shoulda
-
2
module Matchers
-
2
module ActiveModel
-
# Finds message information from exceptions thrown by #valid?
-
2
class ExceptionMessageFinder
-
2
def initialize(instance, attribute, context=nil)
-
@instance = instance
-
@attribute = attribute
-
@context = context
-
end
-
-
2
def allow_description(allowed_values)
-
"doesn't raise when #{@attribute} is set to #{allowed_values}"
-
end
-
-
2
def messages_description
-
if has_messages?
-
messages.join
-
else
-
'no exception'
-
end
-
end
-
-
2
def has_messages?
-
messages.any?
-
end
-
-
2
def messages
-
@messages ||= validate_and_rescue
-
end
-
-
2
def source_description
-
'exception'
-
end
-
-
2
def expected_message_from(attribute_message)
-
"#{human_attribute_name} #{attribute_message}"
-
end
-
-
2
private
-
-
2
def validate_and_rescue
-
@instance.valid?(@context)
-
[]
-
rescue ::ActiveModel::StrictValidationFailed => exception
-
[exception.message]
-
end
-
-
2
def human_attribute_name
-
@instance.class.human_attribute_name(@attribute)
-
end
-
end
-
-
end
-
end
-
end
-
-
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
-
# Ensures that the model exhibits behavior added by has_secure_password.
-
#
-
# Example:
-
# it { should have_secure_password }
-
2
def have_secure_password
-
HaveSecurePasswordMatcher.new
-
end
-
-
2
class HaveSecurePasswordMatcher # :nodoc:
-
2
attr_reader :failure_message_for_should
-
-
2
CORRECT_PASSWORD = "aBcDe12345"
-
2
INCORRECT_PASSWORD = "password"
-
-
2
EXPECTED_METHODS = [
-
:authenticate,
-
:password=,
-
:password_confirmation=,
-
:password_digest,
-
:password_digest=,
-
]
-
-
2
MESSAGES = {
-
authenticated_incorrect_password: "expected %{subject} to not authenticate an incorrect password",
-
did_not_authenticate_correct_password: "expected %{subject} to authenticate the correct password",
-
method_not_found: "expected %{subject} to respond to %{methods}"
-
}
-
-
2
def description
-
"have a secure password"
-
end
-
-
2
def matches?(subject)
-
@subject = subject
-
-
if failure = validate
-
key, params = failure
-
@failure_message_for_should = MESSAGES[key] % { subject: subject.class }.merge(params)
-
end
-
-
failure.nil?
-
end
-
-
2
private
-
-
2
attr_reader :subject
-
-
2
def validate
-
missing_methods = EXPECTED_METHODS.select {|m| !subject.respond_to?(m) }
-
-
if missing_methods.present?
-
[:method_not_found, { methods: missing_methods.to_sentence }]
-
else
-
subject.password = CORRECT_PASSWORD
-
subject.password_confirmation = CORRECT_PASSWORD
-
-
if not subject.authenticate(CORRECT_PASSWORD)
-
[:did_not_authenticate_correct_password, {}]
-
elsif subject.authenticate(INCORRECT_PASSWORD)
-
[:authenticated_incorrect_password, {}]
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
2
module Helpers
-
2
def pretty_error_messages(obj) # :nodoc:
-
obj.errors.map do |attribute, model|
-
msg = "#{attribute} #{model}"
-
if attribute.to_sym != :base && obj.respond_to?(attribute)
-
msg << " (#{obj.send(attribute).inspect})"
-
end
-
msg
-
end
-
end
-
-
# Helper method that determines the default error message used by Active
-
# Record. Works for both existing Rails 2.1 and Rails 2.2 with the newly
-
# introduced I18n module used for localization. Use with Rails 3.0 and
-
# up will delegate to ActiveModel::Errors.generate_error if a model
-
# instance is given.
-
#
-
# default_error_message(:blank)
-
# default_error_message(:too_short, :count => 5)
-
# default_error_message(:too_long, :count => 60)
-
# default_error_message(:blank, :model_name => 'user', :attribute => 'name')
-
# default_error_message(:blank, :instance => #<Model>, :attribute => 'name')
-
2
def default_error_message(key, options = {})
-
model_name = options.delete(:model_name)
-
attribute = options.delete(:attribute)
-
instance = options.delete(:instance)
-
-
if instance && instance.errors.respond_to?(:generate_message)
-
instance.errors.generate_message(attribute.to_sym, key, options)
-
else
-
default_translation = [ :"activerecord.errors.models.#{model_name}.#{key}",
-
:"activerecord.errors.messages.#{key}",
-
:"errors.attributes.#{attribute}.#{key}",
-
:"errors.messages.#{key}" ]
-
I18n.translate(:"activerecord.errors.models.#{model_name}.attributes.#{attribute}.#{key}",
-
{ :default => default_translation }.merge(options))
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
2
class OddEvenNumberMatcher # :nodoc:
-
2
NON_EVEN_NUMBER_VALUE = 1
-
2
NON_ODD_NUMBER_VALUE = 2
-
-
2
def initialize(attribute, options = {})
-
@attribute = attribute
-
options[:odd] ||= true
-
options[:even] ||= false
-
-
if options[:odd] && !options[:even]
-
@disallow_value_matcher = DisallowValueMatcher.new(NON_ODD_NUMBER_VALUE).
-
for(@attribute).
-
with_message(:odd)
-
else
-
@disallow_value_matcher = DisallowValueMatcher.new(NON_EVEN_NUMBER_VALUE).
-
for(@attribute).
-
with_message(:even)
-
end
-
end
-
-
2
def matches?(subject)
-
@disallow_value_matcher.matches?(subject)
-
end
-
-
2
def with_message(message)
-
@disallow_value_matcher.with_message(message)
-
self
-
end
-
-
2
def allowed_types
-
'integer'
-
end
-
-
2
def failure_message_for_should
-
@disallow_value_matcher.failure_message_for_should
-
end
-
-
2
def failure_message_for_should_not
-
@disallow_value_matcher.failure_message_for_should_not
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
2
class OnlyIntegerMatcher # :nodoc:
-
2
NON_INTEGER_VALUE = 0.1
-
-
2
def initialize(attribute)
-
@attribute = attribute
-
@disallow_value_matcher = DisallowValueMatcher.new(NON_INTEGER_VALUE).
-
for(attribute).
-
with_message(:not_an_integer)
-
end
-
-
2
def matches?(subject)
-
@disallow_value_matcher.matches?(subject)
-
end
-
-
2
def with_message(message)
-
@disallow_value_matcher.with_message(message)
-
self
-
end
-
-
2
def allowed_types
-
'integer'
-
end
-
-
2
def failure_message_for_should
-
@disallow_value_matcher.failure_message_for_should
-
end
-
-
2
def failure_message_for_should_not
-
@disallow_value_matcher.failure_message_for_should_not
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
-
# Ensures that the model cannot be saved if the given attribute is not
-
# accepted.
-
#
-
# Options:
-
# * <tt>with_message</tt> - value the test expects to find in
-
# <tt>errors.on(:attribute)</tt>. Regexp or string. Defaults to the
-
# translation for <tt>:accepted</tt>.
-
#
-
# Example:
-
# it { should validate_acceptance_of(:eula) }
-
#
-
2
def validate_acceptance_of(attr)
-
ValidateAcceptanceOfMatcher.new(attr)
-
end
-
-
2
class ValidateAcceptanceOfMatcher < ValidationMatcher # :nodoc:
-
-
2
def with_message(message)
-
if message
-
@expected_message = message
-
end
-
self
-
end
-
-
2
def matches?(subject)
-
super(subject)
-
@expected_message ||= :accepted
-
disallows_value_of(false, @expected_message)
-
end
-
-
2
def description
-
"require #{@attribute} to be accepted"
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
# Ensures that the model's attribute matches confirmation
-
#
-
# Example:
-
# it { should validate_confirmation_of(:password) }
-
#
-
2
def validate_confirmation_of(attr)
-
ValidateConfirmationOfMatcher.new(attr)
-
end
-
-
2
class ValidateConfirmationOfMatcher < ValidationMatcher # :nodoc:
-
2
include Helpers
-
-
2
attr_reader :attribute, :confirmation_attribute
-
-
2
def initialize(attribute)
-
@attribute = attribute
-
@confirmation_attribute = "#{attribute}_confirmation"
-
end
-
-
2
def with_message(message)
-
@message = message if message
-
self
-
end
-
-
2
def description
-
"require #{@confirmation_attribute} to match #{@attribute}"
-
end
-
-
2
def matches?(subject)
-
super(subject)
-
@message ||= :confirmation
-
-
disallows_different_value &&
-
allows_same_value &&
-
allows_missing_confirmation
-
end
-
-
2
private
-
-
2
def disallows_different_value
-
set_confirmation('some value')
-
disallows_value_of('different value') do |matcher|
-
matcher.with_message(@message, against: error_attribute)
-
end
-
end
-
-
2
def allows_same_value
-
set_confirmation('same value')
-
allows_value_of('same value') do |matcher|
-
matcher.with_message(@message, against: error_attribute)
-
end
-
end
-
-
2
def allows_missing_confirmation
-
set_confirmation(nil)
-
allows_value_of('any value') do |matcher|
-
matcher.with_message(@message, against: error_attribute)
-
end
-
end
-
-
2
def set_confirmation(val)
-
setter = :"#{@confirmation_attribute}="
-
if @subject.respond_to?(setter)
-
@subject.send(setter, val)
-
end
-
end
-
-
2
def error_attribute
-
RailsShim.validates_confirmation_of_error_attribute(self)
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
# Ensure that the attribute is numeric.
-
#
-
# Options:
-
# * <tt>with_message</tt> - value the test expects to find in
-
# <tt>errors.on(:attribute)</tt>. Regexp or string. Defaults to the
-
# translation for <tt>:not_a_number</tt>.
-
# * <tt>only_integer</tt> - allows only integer values
-
# * <tt>odd</tt> - Specifies the value must be an odd number.
-
# * <tt>even</tt> - Specifies the value must be an even number.
-
#
-
# Examples:
-
# it { should validate_numericality_of(:price) }
-
# it { should validate_numericality_of(:age).only_integer }
-
# it { should validate_numericality_of(:frequency).odd }
-
# it { should validate_numericality_of(:frequency).even }
-
#
-
2
def validate_numericality_of(attr)
-
ValidateNumericalityOfMatcher.new(attr)
-
end
-
-
2
class ValidateNumericalityOfMatcher
-
2
NON_NUMERIC_VALUE = 'abcd'
-
-
2
def initialize(attribute)
-
@attribute = attribute
-
@submatchers = []
-
-
add_disallow_value_matcher
-
end
-
-
2
def only_integer
-
add_submatcher(OnlyIntegerMatcher.new(@attribute))
-
self
-
end
-
-
2
def is_greater_than(value)
-
add_submatcher(ComparisonMatcher.new(value, :>).for(@attribute))
-
self
-
end
-
-
2
def is_greater_than_or_equal_to(value)
-
add_submatcher(ComparisonMatcher.new(value, :>=).for(@attribute))
-
self
-
end
-
-
2
def is_equal_to(value)
-
add_submatcher(ComparisonMatcher.new(value, :==).for(@attribute))
-
self
-
end
-
-
2
def is_less_than(value)
-
add_submatcher(ComparisonMatcher.new(value, :<).for(@attribute))
-
self
-
end
-
-
2
def is_less_than_or_equal_to(value)
-
add_submatcher(ComparisonMatcher.new(value, :<=).for(@attribute))
-
self
-
end
-
-
2
def odd
-
odd_number_matcher = OddEvenNumberMatcher.new(@attribute, :odd => true)
-
add_submatcher(odd_number_matcher)
-
self
-
end
-
-
2
def even
-
even_number_matcher = OddEvenNumberMatcher.new(@attribute, :even => true)
-
add_submatcher(even_number_matcher)
-
self
-
end
-
-
2
def with_message(message)
-
@submatchers.each { |matcher| matcher.with_message(message) }
-
self
-
end
-
-
2
def matches?(subject)
-
@subject = subject
-
submatchers_match?
-
end
-
-
2
def description
-
"only allow #{allowed_types} values for #{@attribute}"
-
end
-
-
2
def failure_message_for_should
-
submatcher_failure_messages_for_should.last
-
end
-
-
2
def failure_message_for_should_not
-
submatcher_failure_messages_for_should_not.last
-
end
-
-
2
private
-
-
2
def add_disallow_value_matcher
-
disallow_value_matcher = DisallowValueMatcher.new(NON_NUMERIC_VALUE).
-
for(@attribute).
-
with_message(:not_a_number)
-
-
add_submatcher(disallow_value_matcher)
-
end
-
-
2
def add_submatcher(submatcher)
-
@submatchers << submatcher
-
end
-
-
2
def submatchers_match?
-
failing_submatchers.empty?
-
end
-
-
2
def submatcher_failure_messages_for_should
-
failing_submatchers.map(&:failure_message_for_should)
-
end
-
-
2
def submatcher_failure_messages_for_should_not
-
failing_submatchers.map(&:failure_message_for_should_not)
-
end
-
-
2
def failing_submatchers
-
@failing_submatchers ||= @submatchers.select { |matcher| !matcher.matches?(@subject) }
-
end
-
-
2
def allowed_types
-
allowed = ['numeric'] + submatcher_allowed_types
-
allowed.join(', ')
-
end
-
-
2
def submatcher_allowed_types
-
@submatchers.map(&:allowed_types).reject(&:empty?)
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
-
# Ensures that the model is not valid if the given attribute is not
-
# present.
-
#
-
# Options:
-
# * <tt>with_message</tt> - value the test expects to find in
-
# <tt>errors.on(:attribute)</tt>. <tt>Regexp</tt> or <tt>String</tt>.
-
# Defaults to the translation for <tt>:blank</tt>.
-
#
-
# Examples:
-
# it { should validate_presence_of(:name) }
-
# it { should validate_presence_of(:name).
-
# with_message(/is not optional/) }
-
#
-
2
def validate_presence_of(attr)
-
ValidatePresenceOfMatcher.new(attr)
-
end
-
-
2
class ValidatePresenceOfMatcher < ValidationMatcher # :nodoc:
-
-
2
def with_message(message)
-
@expected_message = message if message
-
self
-
end
-
-
2
def matches?(subject)
-
super(subject)
-
@expected_message ||= :blank
-
disallows_value_of(blank_value, @expected_message)
-
end
-
-
2
def description
-
"require #{@attribute} to be set"
-
end
-
-
2
private
-
-
2
def blank_value
-
if collection?
-
[]
-
else
-
nil
-
end
-
end
-
-
2
def collection?
-
if reflection
-
[:has_many, :has_and_belongs_to_many].include?(reflection.macro)
-
else
-
false
-
end
-
end
-
-
2
def reflection
-
@subject.class.respond_to?(:reflect_on_association) &&
-
@subject.class.reflect_on_association(@attribute)
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
# Ensures that the model is invalid if the given attribute is not unique.
-
# It uses the first existing record or creates a new one if no record
-
# exists in the database. It simply uses `:validate => false` to get
-
# around validations, so it will probably fail if there are `NOT NULL`
-
# constraints. In that case, you must create a record before calling
-
# `validate_uniqueness_of`.
-
#
-
# Example:
-
# it { should validate_uniqueness_of(:email) }
-
#
-
# Options:
-
#
-
# * <tt>with_message</tt> - value the test expects to find in
-
# <tt>errors.on(:attribute)</tt>. <tt>Regexp</tt> or <tt>String</tt>.
-
# Defaults to the translation for <tt>:taken</tt>.
-
# * <tt>scoped_to</tt> - field(s) to scope the uniqueness to.
-
# * <tt>case_insensitive</tt> - ensures that the validation does not
-
# check case. Off by default. Ignored by non-text attributes.
-
#
-
# Examples:
-
# it { should validate_uniqueness_of(:keyword) }
-
# it { should validate_uniqueness_of(:keyword).with_message(/dup/) }
-
# it { should validate_uniqueness_of(:email).scoped_to(:name) }
-
# it { should validate_uniqueness_of(:email).
-
# scoped_to(:first_name, :last_name) }
-
# it { should validate_uniqueness_of(:keyword).case_insensitive }
-
#
-
2
def validate_uniqueness_of(attr)
-
ValidateUniquenessOfMatcher.new(attr)
-
end
-
-
2
class ValidateUniquenessOfMatcher < ValidationMatcher # :nodoc:
-
2
include Helpers
-
-
2
def initialize(attribute)
-
super(attribute)
-
@options = {}
-
end
-
-
2
def scoped_to(*scopes)
-
@options[:scopes] = [*scopes].flatten
-
self
-
end
-
-
2
def with_message(message)
-
@expected_message = message
-
self
-
end
-
-
2
def case_insensitive
-
@options[:case_insensitive] = true
-
self
-
end
-
-
2
def allow_nil
-
@options[:allow_nil] = true
-
self
-
end
-
-
2
def description
-
result = "require "
-
result << "case sensitive " unless @options[:case_insensitive]
-
result << "unique value for #{@attribute}"
-
result << " scoped to #{@options[:scopes].join(', ')}" if @options[:scopes].present?
-
result
-
end
-
-
2
def matches?(subject)
-
@subject = subject.class.new
-
@expected_message ||= :taken
-
set_scoped_attributes &&
-
validate_everything_except_duplicate_nils? &&
-
validate_after_scope_change? &&
-
allows_nil?
-
end
-
-
2
private
-
-
2
def allows_nil?
-
if @options[:allow_nil]
-
ensure_nil_record_in_database
-
allows_value_of(nil, @expected_message)
-
else
-
true
-
end
-
end
-
-
2
def existing_record
-
@existing_record ||= first_instance
-
end
-
-
2
def first_instance
-
@subject.class.first || create_record_in_database
-
end
-
-
2
def ensure_nil_record_in_database
-
unless existing_record_is_nil?
-
create_record_in_database(nil_value: true)
-
end
-
end
-
-
2
def existing_record_is_nil?
-
@existing_record.present? && existing_value.nil?
-
end
-
-
2
def create_record_in_database(options = {})
-
if options[:nil_value]
-
value = nil
-
else
-
value = "arbitrary_string"
-
end
-
-
@subject.class.new.tap do |instance|
-
instance.send("#{@attribute}=", value)
-
instance.save(:validate => false)
-
end
-
end
-
-
2
def set_scoped_attributes
-
if @options[:scopes].present?
-
@options[:scopes].all? do |scope|
-
setter = :"#{scope}="
-
if @subject.respond_to?(setter)
-
@subject.send(setter, existing_record.send(scope))
-
true
-
else
-
@failure_message_for_should = "#{class_name} doesn't seem to have a #{scope} attribute."
-
false
-
end
-
end
-
else
-
true
-
end
-
end
-
-
2
def validate_everything_except_duplicate_nils?
-
if @options[:allow_nil] && existing_value.nil?
-
create_record_without_nil
-
end
-
-
disallows_value_of(existing_value, @expected_message)
-
end
-
-
2
def create_record_without_nil
-
@existing_record = create_record_in_database
-
end
-
-
2
def validate_after_scope_change?
-
if @options[:scopes].blank?
-
true
-
else
-
all_records = @subject.class.all
-
@options[:scopes].all? do |scope|
-
previous_value = all_records.map(&scope).max
-
-
# Assume the scope is a foreign key if the field is nil
-
previous_value ||= correct_type_for_column(@subject.class.columns_hash[scope.to_s])
-
-
next_value =
-
if previous_value.respond_to?(:next)
-
previous_value.next
-
elsif previous_value.respond_to?(:to_datetime)
-
previous_value.to_datetime.next
-
else
-
previous_value.to_s.next
-
end
-
-
@subject.send("#{scope}=", next_value)
-
-
if allows_value_of(existing_value, @expected_message)
-
@subject.send("#{scope}=", previous_value)
-
-
@failure_message_for_should_not <<
-
" (with different value of #{scope})"
-
true
-
else
-
@failure_message_for_should << " (with different value of #{scope})"
-
false
-
end
-
end
-
end
-
end
-
-
2
def correct_type_for_column(column)
-
if column.type == :string
-
'0'
-
elsif column.type == :datetime
-
DateTime.now
-
elsif column.type == :uuid
-
SecureRandom.uuid
-
else
-
0
-
end
-
end
-
-
2
def class_name
-
@subject.class.name
-
end
-
-
2
def existing_value
-
value = existing_record.send(@attribute)
-
if @options[:case_insensitive] && value.respond_to?(:swapcase!)
-
value.swapcase!
-
end
-
value
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveModel # :nodoc:
-
2
class ValidationMatcher # :nodoc:
-
2
attr_reader :failure_message_for_should
-
-
2
def initialize(attribute)
-
@attribute = attribute
-
@strict = false
-
end
-
-
2
def on(context)
-
@context = context
-
self
-
end
-
-
2
def strict
-
@strict = true
-
self
-
end
-
-
2
def failure_message_for_should_not
-
@failure_message_for_should_not || @failure_message_for_should
-
end
-
-
2
def matches?(subject)
-
@subject = subject
-
false
-
end
-
-
2
private
-
-
2
def allows_value_of(value, message = nil, &block)
-
allow = allow_value_matcher(value, message)
-
yield allow if block_given?
-
-
if allow.matches?(@subject)
-
@failure_message_for_should_not = allow.failure_message_for_should_not
-
true
-
else
-
@failure_message_for_should = allow.failure_message_for_should
-
false
-
end
-
end
-
-
2
def disallows_value_of(value, message = nil, &block)
-
disallow = disallow_value_matcher(value, message)
-
yield disallow if block_given?
-
-
if disallow.matches?(@subject)
-
@failure_message_for_should_not = disallow.failure_message_for_should_not
-
true
-
else
-
@failure_message_for_should = disallow.failure_message_for_should
-
false
-
end
-
end
-
-
2
def allow_value_matcher(value, message)
-
matcher = AllowValueMatcher.
-
new(value).
-
for(@attribute).
-
on(@context).
-
with_message(message)
-
-
if strict?
-
matcher.strict
-
else
-
matcher
-
end
-
end
-
-
2
def disallow_value_matcher(value, message)
-
matcher = DisallowValueMatcher.
-
new(value).
-
for(@attribute).
-
on(@context).
-
with_message(message)
-
-
if strict?
-
matcher.strict
-
else
-
matcher
-
end
-
end
-
-
2
def strict?
-
@strict
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda
-
2
module Matchers
-
2
module ActiveModel
-
-
# Finds message information from a model's #errors method.
-
2
class ValidationMessageFinder
-
2
include Helpers
-
-
2
def initialize(instance, attribute, context=nil)
-
@instance = instance
-
@attribute = attribute
-
@context = context
-
end
-
-
2
def allow_description(allowed_values)
-
"allow #{@attribute} to be set to #{allowed_values}"
-
end
-
-
2
def expected_message_from(attribute_message)
-
attribute_message
-
end
-
-
2
def has_messages?
-
errors.present?
-
end
-
-
2
def source_description
-
'errors'
-
end
-
-
2
def messages_description
-
if errors.empty?
-
'no errors'
-
else
-
"errors: #{pretty_error_messages(validated_instance)}"
-
end
-
end
-
-
2
def messages
-
Array(messages_for_attribute)
-
end
-
-
2
private
-
-
2
def messages_for_attribute
-
if errors.respond_to?(:[])
-
errors[@attribute]
-
else
-
errors.on(@attribute)
-
end
-
end
-
-
2
def errors
-
validated_instance.errors
-
end
-
-
2
def validated_instance
-
@validated_instance ||= validate_instance
-
end
-
-
2
def validate_instance
-
@instance.valid?(*@context)
-
@instance
-
end
-
end
-
-
end
-
end
-
end
-
-
2
require 'shoulda/matchers/active_record/association_matcher'
-
2
require 'shoulda/matchers/active_record/association_matchers/counter_cache_matcher'
-
2
require 'shoulda/matchers/active_record/association_matchers/order_matcher'
-
2
require 'shoulda/matchers/active_record/association_matchers/through_matcher'
-
2
require 'shoulda/matchers/active_record/association_matchers/dependent_matcher'
-
2
require 'shoulda/matchers/active_record/association_matchers/model_reflector'
-
2
require 'shoulda/matchers/active_record/association_matchers/option_verifier'
-
2
require 'shoulda/matchers/active_record/have_db_column_matcher'
-
2
require 'shoulda/matchers/active_record/have_db_index_matcher'
-
2
require 'shoulda/matchers/active_record/have_readonly_attribute_matcher'
-
2
require 'shoulda/matchers/active_record/serialize_matcher'
-
2
require 'shoulda/matchers/active_record/accept_nested_attributes_for_matcher'
-
-
2
module Shoulda
-
2
module Matchers
-
# = Matchers for your active record models
-
#
-
# These matchers will test the associations for your
-
# ActiveRecord models.
-
#
-
# describe User do
-
# it { should have_one(:profile) }
-
# it { should have_many(:dogs) }
-
# it { should have_many(:messes).through(:dogs) }
-
# it { should belong_to(:lover) }
-
# end
-
#
-
2
module ActiveRecord
-
end
-
end
-
end
-
2
module Shoulda
-
2
module Matchers
-
2
module ActiveRecord
-
# Ensures that the model can accept nested attributes for the specified
-
# association.
-
#
-
# Options:
-
# * <tt>allow_destroy</tt> - Whether or not to allow destroy
-
# * <tt>limit</tt> - Max number of nested attributes
-
# * <tt>update_only</tt> - Only allow updates
-
#
-
# Example:
-
# it { should accept_nested_attributes_for(:friends) }
-
# it { should accept_nested_attributes_for(:friends).
-
# allow_destroy(true).
-
# limit(4) }
-
# it { should accept_nested_attributes_for(:friends).
-
# update_only(true) }
-
#
-
2
def accept_nested_attributes_for(name)
-
AcceptNestedAttributesForMatcher.new(name)
-
end
-
-
2
class AcceptNestedAttributesForMatcher
-
2
def initialize(name)
-
@name = name
-
@options = {}
-
end
-
-
2
def allow_destroy(allow_destroy)
-
@options[:allow_destroy] = allow_destroy
-
self
-
end
-
-
2
def limit(limit)
-
@options[:limit] = limit
-
self
-
end
-
-
2
def update_only(update_only)
-
@options[:update_only] = update_only
-
self
-
end
-
-
2
def matches?(subject)
-
@subject = subject
-
exists? &&
-
allow_destroy_correct? &&
-
limit_correct? &&
-
update_only_correct?
-
end
-
-
2
def failure_message_for_should
-
"Expected #{expectation} (#{@problem})"
-
end
-
-
2
def failure_message_for_should_not
-
"Did not expect #{expectation}"
-
end
-
-
2
def description
-
description = "accepts_nested_attributes_for :#{@name}"
-
if @options.key?(:allow_destroy)
-
description += " allow_destroy => #{@options[:allow_destroy]}"
-
end
-
if @options.key?(:limit)
-
description += " limit => #{@options[:limit]}"
-
end
-
if @options.key?(:update_only)
-
description += " update_only => #{@options[:update_only]}"
-
end
-
description
-
end
-
-
2
protected
-
-
2
def exists?
-
if config
-
true
-
else
-
@problem = 'is not declared'
-
false
-
end
-
end
-
-
2
def allow_destroy_correct?
-
failure_message = "#{should_or_should_not(@options[:allow_destroy])} allow destroy"
-
verify_option_is_correct(:allow_destroy, failure_message)
-
end
-
-
2
def limit_correct?
-
failure_message = "limit should be #{@options[:limit]}, got #{config[:limit]}"
-
verify_option_is_correct(:limit, failure_message)
-
end
-
-
2
def update_only_correct?
-
failure_message = "#{should_or_should_not(@options[:update_only])} be update only"
-
verify_option_is_correct(:update_only, failure_message)
-
end
-
-
2
def verify_option_is_correct(option, failure_message)
-
if @options.key?(option)
-
if @options[option] == config[option]
-
true
-
else
-
@problem = failure_message
-
false
-
end
-
else
-
true
-
end
-
end
-
-
2
def config
-
model_config[@name]
-
end
-
-
2
def model_config
-
model_class.nested_attributes_options
-
end
-
-
2
def model_class
-
@subject.class
-
end
-
-
2
def expectation
-
"#{model_class.name} to accept nested attributes for #{@name}"
-
end
-
-
2
def should_or_should_not(value)
-
if value
-
'should'
-
else
-
'should not'
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'forwardable'
-
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveRecord # :nodoc:
-
# Ensure that the belongs_to relationship exists.
-
#
-
# Options:
-
# * <tt>:class_name</tt> - tests that the association resolves to class_name.
-
# * <tt>:validate</tt> - tests that the association makes use of the validate
-
# option.
-
# * <tt>:touch</tt> - tests that the association makes use of the touch
-
# option.
-
#
-
# Example:
-
# it { should belong_to(:parent) }
-
#
-
2
def belong_to(name)
-
15
AssociationMatcher.new(:belongs_to, name)
-
end
-
-
# Ensures that the has_many relationship exists. Will also test that the
-
# associated table has the required columns. Works with polymorphic
-
# associations.
-
#
-
# Options:
-
# * <tt>through</tt> - association name for <tt>has_many :through</tt>
-
# * <tt>dependent</tt> - tests that the association makes use of the
-
# dependent option.
-
# * <tt>:class_name</tt> - tests that the association resoves to class_name.
-
# * <tt>:validate</tt> - tests that the association makes use of the validate
-
# option.
-
#
-
# Example:
-
# it { should have_many(:friends) }
-
# it { should have_many(:enemies).through(:friends) }
-
# it { should have_many(:enemies).dependent(:destroy) }
-
#
-
2
def have_many(name)
-
10
AssociationMatcher.new(:has_many, name)
-
end
-
-
# Ensure that the has_one relationship exists. Will also test that the
-
# associated table has the required columns. Works with polymorphic
-
# associations.
-
#
-
# Options:
-
# * <tt>:dependent</tt> - tests that the association makes use of the
-
# dependent option.
-
# * <tt>:class_name</tt> - tests that the association resolves to class_name.
-
# * <tt>:validate</tt> - tests that the association makes use of the validate
-
# option.
-
#
-
# Example:
-
# it { should have_one(:god) } # unless hindu
-
#
-
2
def have_one(name)
-
4
AssociationMatcher.new(:has_one, name)
-
end
-
-
# Ensures that the has_and_belongs_to_many relationship exists, and that
-
# the join table is in place.
-
#
-
# Options:
-
# * <tt>:class_name</tt> - tests that the association resolves to class_name.
-
# * <tt>:validate</tt> - tests that the association makes use of the validate
-
# option.
-
#
-
# Example:
-
# it { should have_and_belong_to_many(:posts) }
-
#
-
2
def have_and_belong_to_many(name)
-
AssociationMatcher.new(:has_and_belongs_to_many, name)
-
end
-
-
2
class AssociationMatcher # :nodoc:
-
2
delegate :reflection, :model_class, :associated_class, :through?,
-
:join_table, to: :reflector
-
-
2
def initialize(macro, name)
-
29
@macro = macro
-
29
@name = name
-
29
@options = {}
-
29
@submatchers = []
-
29
@missing = ''
-
end
-
-
2
def through(through)
-
through_matcher = AssociationMatchers::ThroughMatcher.new(through, name)
-
add_submatcher(through_matcher)
-
self
-
end
-
-
2
def dependent(dependent)
-
dependent_matcher = AssociationMatchers::DependentMatcher.new(dependent, name)
-
add_submatcher(dependent_matcher)
-
self
-
end
-
-
2
def order(order)
-
order_matcher = AssociationMatchers::OrderMatcher.new(order, name)
-
add_submatcher(order_matcher)
-
self
-
end
-
-
2
def counter_cache(counter_cache = true)
-
counter_cache_matcher = AssociationMatchers::CounterCacheMatcher.new(counter_cache, name)
-
add_submatcher(counter_cache_matcher)
-
self
-
end
-
-
2
def conditions(conditions)
-
@options[:conditions] = conditions
-
self
-
end
-
-
2
def class_name(class_name)
-
@options[:class_name] = class_name
-
self
-
end
-
-
2
def with_foreign_key(foreign_key)
-
@options[:foreign_key] = foreign_key
-
self
-
end
-
-
2
def validate(validate = true)
-
@options[:validate] = validate
-
self
-
end
-
-
2
def touch(touch = true)
-
@options[:touch] = touch
-
self
-
end
-
-
2
def description
-
29
description = "#{macro_description} #{name}"
-
29
description += " class_name => #{options[:class_name]}" if options.key?(:class_name)
-
29
[description, submatchers.map(&:description)].flatten.join(' ')
-
end
-
-
2
def failure_message_for_should
-
"Expected #{expectation} (#{missing_options})"
-
end
-
-
2
def failure_message_for_should_not
-
"Did not expect #{expectation}"
-
end
-
-
2
def matches?(subject)
-
29
@subject = subject
-
association_exists? &&
-
29
macro_correct? &&
-
foreign_key_exists? &&
-
class_name_correct? &&
-
conditions_correct? &&
-
join_table_exists? &&
-
validate_correct? &&
-
touch_correct? &&
-
submatchers_match?
-
end
-
-
2
private
-
-
2
attr_reader :submatchers, :missing, :subject, :macro, :name, :options
-
-
2
def reflector
-
259
@reflector ||= AssociationMatchers::ModelReflector.new(subject, name)
-
end
-
-
2
def option_verifier
-
58
@option_verifier ||= AssociationMatchers::OptionVerifier.new(reflector)
-
end
-
-
2
def add_submatcher(matcher)
-
@submatchers << matcher
-
end
-
-
2
def macro_description
-
29
case macro.to_s
-
when 'belongs_to'
-
15
'belong to'
-
when 'has_many'
-
10
'have many'
-
when 'has_one'
-
4
'have one'
-
when 'has_and_belongs_to_many'
-
'have and belong to many'
-
end
-
end
-
-
2
def expectation
-
"#{model_class.name} to have a #{macro} association called #{name}"
-
end
-
-
2
def missing_options
-
[missing, failing_submatchers.map(&:missing_option)].flatten.join
-
end
-
-
2
def failing_submatchers
-
@failing_submatchers ||= submatchers.select do |matcher|
-
!matcher.matches?(subject)
-
29
end
-
end
-
-
2
def association_exists?
-
29
if reflection.nil?
-
@missing = "no association called #{name}"
-
false
-
else
-
29
true
-
end
-
end
-
-
2
def macro_correct?
-
29
if reflection.macro == macro
-
29
true
-
else
-
@missing = "actual association type was #{reflection.macro}"
-
false
-
end
-
end
-
-
2
def foreign_key_exists?
-
29
!(belongs_foreign_key_missing? || has_foreign_key_missing?)
-
end
-
-
2
def belongs_foreign_key_missing?
-
29
macro == :belongs_to && !class_has_foreign_key?(model_class)
-
end
-
-
2
def has_foreign_key_missing?
-
[:has_many, :has_one].include?(macro) &&
-
29
!through? &&
-
!class_has_foreign_key?(associated_class)
-
end
-
-
2
def class_name_correct?
-
29
if options.key?(:class_name)
-
if option_verifier.correct_for_string?(:class_name, options[:class_name])
-
true
-
else
-
@missing = "#{name} should resolve to #{options[:class_name]} for class_name"
-
false
-
end
-
else
-
29
true
-
end
-
end
-
-
2
def conditions_correct?
-
29
if options.key?(:conditions)
-
if option_verifier.correct_for_relation_clause?(:conditions, options[:conditions])
-
true
-
else
-
@missing = "#{name} should have the following conditions: #{options[:conditions]}"
-
false
-
end
-
else
-
29
true
-
end
-
end
-
-
2
def join_table_exists?
-
if macro != :has_and_belongs_to_many ||
-
29
model_class.connection.tables.include?(join_table)
-
29
true
-
else
-
@missing = "join table #{join_table} doesn't exist"
-
false
-
end
-
end
-
-
2
def validate_correct?
-
29
if option_verifier.correct_for_boolean?(:validate, options[:validate])
-
29
true
-
else
-
@missing = "#{name} should have :validate => #{options[:validate]}"
-
false
-
end
-
end
-
-
2
def touch_correct?
-
29
if option_verifier.correct_for_boolean?(:touch, options[:touch])
-
29
true
-
else
-
@missing = "#{name} should have :touch => #{options[:touch]}"
-
false
-
end
-
end
-
-
2
def class_has_foreign_key?(klass)
-
29
if options.key?(:foreign_key)
-
option_verifier.correct_for_string?(:foreign_key, options[:foreign_key])
-
else
-
29
if klass.column_names.include?(foreign_key)
-
29
true
-
else
-
@missing = "#{klass} does not have a #{foreign_key} foreign key."
-
false
-
end
-
end
-
end
-
-
2
def foreign_key
-
29
if foreign_key_reflection
-
29
if foreign_key_reflection.respond_to?(:foreign_key)
-
29
foreign_key_reflection.foreign_key.to_s
-
else
-
foreign_key_reflection.primary_key_name.to_s
-
end
-
end
-
end
-
-
2
def foreign_key_reflection
-
87
if [:has_one, :has_many].include?(macro) && reflection.options.include?(:inverse_of)
-
associated_class.reflect_on_association(reflection.options[:inverse_of])
-
else
-
87
reflection
-
end
-
end
-
-
2
def submatchers_match?
-
29
failing_submatchers.empty?
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveRecord # :nodoc:
-
2
module AssociationMatchers
-
2
class CounterCacheMatcher
-
2
attr_accessor :missing_option
-
-
2
def initialize(counter_cache, name)
-
@counter_cache = counter_cache
-
@name = name
-
@missing_option = ''
-
end
-
-
2
def description
-
"counter_cache => #{counter_cache}"
-
end
-
-
2
def matches?(subject)
-
self.subject = ModelReflector.new(subject, name)
-
-
if option_verifier.correct_for_string?(:counter_cache, counter_cache)
-
true
-
else
-
self.missing_option = "#{name} should have #{description}"
-
false
-
end
-
end
-
-
2
private
-
-
2
attr_accessor :subject, :counter_cache, :name
-
-
2
def option_verifier
-
@option_verifier ||= OptionVerifier.new(subject)
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveRecord # :nodoc:
-
2
module AssociationMatchers
-
2
class DependentMatcher
-
2
attr_accessor :missing_option
-
-
2
def initialize(dependent, name)
-
@dependent = dependent
-
@name = name
-
@missing_option = ''
-
end
-
-
2
def description
-
"dependent => #{dependent}"
-
end
-
-
2
def matches?(subject)
-
self.subject = ModelReflector.new(subject, name)
-
-
if option_verifier.correct_for_string?(:dependent, dependent)
-
true
-
else
-
self.missing_option = "#{name} should have #{dependent} dependency"
-
false
-
end
-
end
-
-
2
private
-
-
2
attr_accessor :subject, :dependent, :name
-
-
2
def option_verifier
-
@option_verifier ||= OptionVerifier.new(subject)
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveRecord # :nodoc:
-
2
module AssociationMatchers
-
2
class ModelReflector
-
2
def initialize(subject, name)
-
29
@subject = subject
-
29
@name = name
-
end
-
-
2
def reflection
-
215
@reflection ||= reflect_on_association(name)
-
end
-
-
2
def reflect_on_association(name)
-
29
model_class.reflect_on_association(name)
-
end
-
-
2
def model_class
-
44
subject.class
-
end
-
-
2
def associated_class
-
14
reflection.klass
-
end
-
-
2
def through?
-
14
reflection.options[:through]
-
end
-
-
2
def join_table
-
if reflection.respond_to? :join_table
-
reflection.join_table.to_s
-
else
-
reflection.options[:join_table].to_s
-
end
-
end
-
-
2
def association_relation
-
if reflection.respond_to?(:scope) && reflection.scope
-
relation_from_scope(reflection.scope)
-
else
-
options = reflection.options
-
relation = RailsShim.clean_scope(reflection.klass)
-
if options[:conditions]
-
relation = relation.where(options[:conditions])
-
end
-
if options[:include]
-
relation = relation.include(options[:include])
-
end
-
if options[:order]
-
relation = relation.order(options[:order])
-
end
-
if options[:group]
-
relation = relation.group(options[:group])
-
end
-
if options[:having]
-
relation = relation.having(options[:having])
-
end
-
if options[:limit]
-
relation = relation.limit(options[:limit])
-
end
-
relation
-
end
-
end
-
-
2
def build_relation_with_clause(name, value)
-
case name
-
when :conditions then associated_class.where(value)
-
when :order then associated_class.order(value)
-
else raise ArgumentError, "Unknown clause '#{name}'"
-
end
-
end
-
-
2
def extract_relation_clause_from(relation, name)
-
case name
-
when :conditions then relation.where_values_hash
-
when :order then relation.order_values.join(', ')
-
else raise ArgumentError, "Unknown clause '#{name}'"
-
end
-
end
-
-
2
private
-
-
2
def relation_from_scope(scope)
-
# Source: AR::Associations::AssociationScope#eval_scope
-
if scope.is_a?(::Proc)
-
associated_class.all.instance_exec(subject, &scope)
-
else
-
scope
-
end
-
end
-
-
2
attr_reader :subject, :name
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveRecord # :nodoc:
-
2
module AssociationMatchers
-
2
class OptionVerifier
-
2
delegate :reflection, to: :reflector
-
-
2
attr_reader :reflector
-
-
2
RELATION_OPTIONS = [:conditions, :order]
-
-
2
def initialize(reflector)
-
29
@reflector = reflector
-
end
-
-
2
def correct_for_string?(name, expected_value)
-
correct_for?(:string, name, expected_value)
-
end
-
-
2
def correct_for_boolean?(name, expected_value)
-
58
correct_for?(:boolean, name, expected_value)
-
end
-
-
2
def correct_for_hash?(name, expected_value)
-
correct_for?(:hash, name, expected_value)
-
end
-
-
2
def correct_for_relation_clause?(name, expected_value)
-
correct_for?(:relation_clause, name, expected_value)
-
end
-
-
2
def actual_value_for(name)
-
if RELATION_OPTIONS.include?(name)
-
actual_value_for_relation_clause(name)
-
else
-
method_name = "actual_value_for_#{name}"
-
if respond_to?(method_name, true)
-
__send__(method_name)
-
else
-
reflection.options[name]
-
end
-
end
-
end
-
-
2
private
-
-
2
attr_reader :reflector
-
-
2
def correct_for?(*args)
-
58
expected_value, name, type = args.reverse
-
58
if expected_value.nil?
-
58
true
-
else
-
expected_value = type_cast(type, expected_value_for(name, expected_value))
-
actual_value = type_cast(type, actual_value_for(name))
-
expected_value == actual_value
-
end
-
end
-
-
2
def type_cast(type, value)
-
case type
-
when :string, :relation_clause then value.to_s
-
when :boolean then !!value
-
when :hash then Hash(value).stringify_keys
-
else value
-
end
-
end
-
-
2
def expected_value_for(name, value)
-
if RELATION_OPTIONS.include?(name)
-
expected_value_for_relation_clause(name, value)
-
else
-
value
-
end
-
end
-
-
2
def expected_value_for_relation_clause(name, value)
-
relation = reflector.build_relation_with_clause(name, value)
-
reflector.extract_relation_clause_from(relation, name)
-
end
-
-
2
def actual_value_for_relation_clause(name)
-
reflector.extract_relation_clause_from(reflector.association_relation, name)
-
end
-
-
2
def actual_value_for_class_name
-
reflector.associated_class
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveRecord # :nodoc:
-
2
module AssociationMatchers
-
2
class OrderMatcher
-
2
attr_accessor :missing_option
-
-
2
def initialize(order, name)
-
@order = order
-
@name = name
-
@missing_option = ''
-
end
-
-
2
def description
-
"order => #{order}"
-
end
-
-
2
def matches?(subject)
-
self.subject = ModelReflector.new(subject, name)
-
-
if option_verifier.correct_for_relation_clause?(:order, order)
-
true
-
else
-
self.missing_option = "#{name} should be ordered by #{order}"
-
false
-
end
-
end
-
-
2
private
-
-
2
attr_accessor :subject, :order, :name
-
-
2
def option_verifier
-
@option_verifier ||= OptionVerifier.new(subject)
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveRecord # :nodoc:
-
2
module AssociationMatchers
-
2
class ThroughMatcher
-
2
attr_accessor :missing_option
-
-
2
def initialize(through, name)
-
@through = through
-
@name = name
-
@missing_option = ''
-
end
-
-
2
def description
-
"through #{through}"
-
end
-
-
2
def matches?(subject)
-
self.subject = ModelReflector.new(subject, name)
-
through.nil? || association_set_properly?
-
end
-
-
2
def association_set_properly?
-
through_association_exists? && through_association_correct?
-
end
-
-
2
def through_association_exists?
-
if through_reflection.present?
-
true
-
else
-
self.missing_option = "#{name} does not have any relationship to #{through}"
-
false
-
end
-
end
-
-
2
def through_reflection
-
@through_reflection ||= subject.reflect_on_association(through)
-
end
-
-
2
def through_association_correct?
-
if option_verifier.correct_for_string?(:through, through)
-
true
-
else
-
self.missing_option =
-
"Expected #{name} to have #{name} through #{through}, " +
-
"but got it through #{option_verifier.actual_value_for(:through)}"
-
false
-
end
-
end
-
-
2
private
-
-
2
attr_accessor :through, :name, :subject
-
-
2
def option_verifier
-
@option_verifier ||= OptionVerifier.new(subject)
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveRecord # :nodoc:
-
-
# Ensures the database column exists.
-
#
-
# Options:
-
# * <tt>of_type</tt> - db column type (:integer, :string, etc.)
-
# * <tt>with_options</tt> - same options available in migrations
-
# (:default, :null, :limit, :precision, :scale)
-
#
-
# Examples:
-
# it { should_not have_db_column(:admin).of_type(:boolean) }
-
# it { should have_db_column(:salary).
-
# of_type(:decimal).
-
# with_options(:precision => 10, :scale => 2) }
-
#
-
2
def have_db_column(column)
-
HaveDbColumnMatcher.new(column)
-
end
-
-
2
class HaveDbColumnMatcher # :nodoc:
-
2
def initialize(column)
-
@column = column
-
@options = {}
-
end
-
-
2
def of_type(column_type)
-
@options[:column_type] = column_type
-
self
-
end
-
-
2
def with_options(opts = {})
-
%w(precision limit default null scale primary).each do |attribute|
-
if opts.key?(attribute.to_sym)
-
@options[attribute.to_sym] = opts[attribute.to_sym]
-
end
-
end
-
self
-
end
-
-
2
def matches?(subject)
-
@subject = subject
-
column_exists? &&
-
correct_column_type? &&
-
correct_precision? &&
-
correct_limit? &&
-
correct_default? &&
-
correct_null? &&
-
correct_scale? &&
-
correct_primary?
-
end
-
-
2
def failure_message_for_should
-
"Expected #{expectation} (#{@missing})"
-
end
-
-
2
def failure_message_for_should_not
-
"Did not expect #{expectation}"
-
end
-
-
2
def description
-
desc = "have db column named #{@column}"
-
desc << " of type #{@options[:column_type]}" if @options.key?(:column_type)
-
desc << " of precision #{@options[:precision]}" if @options.key?(:precision)
-
desc << " of limit #{@options[:limit]}" if @options.key?(:limit)
-
desc << " of default #{@options[:default]}" if @options.key?(:default)
-
desc << " of null #{@options[:null]}" if @options.key?(:null)
-
desc << " of primary #{@options[:primary]}" if @options.key?(:primary)
-
desc << " of scale #{@options[:scale]}" if @options.key?(:scale)
-
desc
-
end
-
-
2
protected
-
-
2
def column_exists?
-
if model_class.column_names.include?(@column.to_s)
-
true
-
else
-
@missing = "#{model_class} does not have a db column named #{@column}."
-
false
-
end
-
end
-
-
2
def correct_column_type?
-
return true unless @options.key?(:column_type)
-
-
if matched_column.type.to_s == @options[:column_type].to_s
-
true
-
else
-
@missing = "#{model_class} has a db column named #{@column} " <<
-
"of type #{matched_column.type}, not #{@options[:column_type]}."
-
false
-
end
-
end
-
-
2
def correct_precision?
-
return true unless @options.key?(:precision)
-
-
if matched_column.precision.to_s == @options[:precision].to_s
-
true
-
else
-
@missing = "#{model_class} has a db column named #{@column} " <<
-
"of precision #{matched_column.precision}, " <<
-
"not #{@options[:precision]}."
-
false
-
end
-
end
-
-
2
def correct_limit?
-
return true unless @options.key?(:limit)
-
-
if matched_column.limit.to_s == @options[:limit].to_s
-
true
-
else
-
@missing = "#{model_class} has a db column named #{@column} " <<
-
"of limit #{matched_column.limit}, " <<
-
"not #{@options[:limit]}."
-
false
-
end
-
end
-
-
2
def correct_default?
-
return true unless @options.key?(:default)
-
-
if matched_column.default.to_s == @options[:default].to_s
-
true
-
else
-
@missing = "#{model_class} has a db column named #{@column} " <<
-
"of default #{matched_column.default}, " <<
-
"not #{@options[:default]}."
-
false
-
end
-
end
-
-
2
def correct_null?
-
return true unless @options.key?(:null)
-
-
if matched_column.null.to_s == @options[:null].to_s
-
true
-
else
-
@missing = "#{model_class} has a db column named #{@column} " <<
-
"of null #{matched_column.null}, " <<
-
"not #{@options[:null]}."
-
false
-
end
-
end
-
-
2
def correct_scale?
-
return true unless @options.key?(:scale)
-
-
if actual_scale.to_s == @options[:scale].to_s
-
true
-
else
-
@missing = "#{model_class} has a db column named #{@column} "
-
@missing << "of scale #{actual_scale}, not #{@options[:scale]}."
-
false
-
end
-
end
-
-
2
def correct_primary?
-
return true unless @options.key?(:primary)
-
-
if matched_column.primary == @options[:primary]
-
true
-
else
-
@missing = "#{model_class} has a db column named #{@column} "
-
if @options[:primary]
-
@missing << 'that is not primary, but should be'
-
else
-
@missing << 'that is primary, but should not be'
-
end
-
false
-
end
-
end
-
-
2
def matched_column
-
model_class.columns.detect { |each| each.name == @column.to_s }
-
end
-
-
2
def model_class
-
@subject.class
-
end
-
-
2
def actual_scale
-
matched_column.scale
-
end
-
-
2
def expectation
-
expected = "#{model_class.name} to #{description}"
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveRecord # :nodoc:
-
-
# Ensures that there are DB indices on the given columns or tuples of
-
# columns.
-
#
-
# Options:
-
# * <tt>unique</tt> - whether or not the index has a unique
-
# constraint. Use <tt>true</tt> to explicitly test for a unique
-
# constraint. Use <tt>false</tt> to explicitly test for a non-unique
-
# constraint.
-
#
-
# Examples:
-
#
-
# it { should have_db_index(:age) }
-
# it { should have_db_index([:commentable_type, :commentable_id]) }
-
# it { should have_db_index(:ssn).unique(true) }
-
#
-
2
def have_db_index(columns)
-
HaveDbIndexMatcher.new(columns)
-
end
-
-
2
class HaveDbIndexMatcher # :nodoc:
-
2
def initialize(columns)
-
@columns = normalize_columns_to_array(columns)
-
@options = {}
-
end
-
-
2
def unique(unique)
-
@options[:unique] = unique
-
self
-
end
-
-
2
def matches?(subject)
-
@subject = subject
-
index_exists? && correct_unique?
-
end
-
-
2
def failure_message_for_should
-
"Expected #{expectation} (#{@missing})"
-
end
-
-
2
def failure_message_for_should_not
-
"Did not expect #{expectation}"
-
end
-
-
2
def description
-
if @options.key?(:unique)
-
"have a #{index_type} index on columns #{@columns.join(' and ')}"
-
else
-
"have an index on columns #{@columns.join(' and ')}"
-
end
-
end
-
-
2
protected
-
-
2
def index_exists?
-
! matched_index.nil?
-
end
-
-
2
def correct_unique?
-
return true unless @options.key?(:unique)
-
-
is_unique = matched_index.unique
-
-
is_unique = !is_unique unless @options[:unique]
-
-
unless is_unique
-
@missing = "#{table_name} has an index named #{matched_index.name} " <<
-
"of unique #{matched_index.unique}, not #{@options[:unique]}."
-
end
-
-
is_unique
-
end
-
-
2
def matched_index
-
indexes.detect { |each| each.columns == @columns }
-
end
-
-
2
def model_class
-
@subject.class
-
end
-
-
2
def table_name
-
model_class.table_name
-
end
-
-
2
def indexes
-
::ActiveRecord::Base.connection.indexes(table_name)
-
end
-
-
2
def expectation
-
"#{model_class.name} to #{description}"
-
end
-
-
2
def index_type
-
if @options[:unique]
-
'unique'
-
else
-
'non-unique'
-
end
-
end
-
-
2
def normalize_columns_to_array(columns)
-
Array.wrap(columns).map(&:to_s)
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveRecord # :nodoc:
-
-
# Ensures that the attribute cannot be changed once the record has been
-
# created.
-
#
-
# it { should have_readonly_attribute(:password) }
-
#
-
2
def have_readonly_attribute(value)
-
HaveReadonlyAttributeMatcher.new(value)
-
end
-
-
2
class HaveReadonlyAttributeMatcher # :nodoc:
-
2
def initialize(attribute)
-
@attribute = attribute.to_s
-
end
-
-
2
attr_reader :failure_message_for_should, :failure_message_for_should_not
-
-
2
def matches?(subject)
-
@subject = subject
-
if readonly_attributes.include?(@attribute)
-
@failure_message_for_should_not = "Did not expect #{@attribute} to be read-only"
-
true
-
else
-
if readonly_attributes.empty?
-
@failure_message_for_should = "#{class_name} attribute #{@attribute} " <<
-
'is not read-only'
-
else
-
@failure_message_for_should = "#{class_name} is making " <<
-
"#{readonly_attributes.to_a.to_sentence} " <<
-
"read-only, but not #{@attribute}."
-
end
-
false
-
end
-
end
-
-
2
def description
-
"make #{@attribute} read-only"
-
end
-
-
2
private
-
-
2
def readonly_attributes
-
@readonly_attributes ||= (@subject.class.readonly_attributes || [])
-
end
-
-
2
def class_name
-
@subject.class.name
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
module ActiveRecord # :nodoc:
-
# Ensure that the field becomes serialized.
-
#
-
# Options:
-
# * <tt>:as</tt> - tests that the serialized attribute makes use of the class_name option.
-
#
-
# Example:
-
# it { should serialize(:details) }
-
# it { should serialize(:details).as(Hash) }
-
# it { should serialize(:details).as_instance_of(ExampleSerializer) }
-
#
-
2
def serialize(name)
-
SerializeMatcher.new(name)
-
end
-
-
2
class SerializeMatcher # :nodoc:
-
2
def initialize(name)
-
@name = name.to_s
-
@options = {}
-
end
-
-
2
def as(type)
-
@options[:type] = type
-
self
-
end
-
-
2
def as_instance_of(type)
-
@options[:instance_type] = type
-
self
-
end
-
-
2
def matches?(subject)
-
@subject = subject
-
serialization_valid? && type_valid?
-
end
-
-
2
def failure_message_for_should
-
"Expected #{expectation} (#{@missing})"
-
end
-
-
2
def failure_message_for_should_not
-
"Did not expect #{expectation}"
-
end
-
-
2
def description
-
description = "serialize :#{@name}"
-
description += " class_name => #{@options[:type]}" if @options.key?(:type)
-
description
-
end
-
-
2
protected
-
-
2
def serialization_valid?
-
if model_class.serialized_attributes.keys.include?(@name)
-
true
-
else
-
@missing = "no serialized attribute called :#{@name}"
-
false
-
end
-
end
-
-
2
def class_valid?
-
if @options[:type]
-
klass = model_class.serialized_attributes[@name]
-
if klass == @options[:type]
-
true
-
else
-
if klass.respond_to?(:object_class) && klass.object_class == @options[:type]
-
true
-
else
-
@missing = ":#{@name} should be a type of #{@options[:type]}"
-
false
-
end
-
end
-
else
-
true
-
end
-
end
-
-
2
def model_class
-
@subject.class
-
end
-
-
2
def instance_class_valid?
-
if @options.key?(:instance_type)
-
if model_class.serialized_attributes[@name].class == @options[:instance_type]
-
true
-
else
-
@missing = ":#{@name} should be an instance of #{@options[:type]}"
-
false
-
end
-
else
-
true
-
end
-
end
-
-
2
def type_valid?
-
class_valid? && instance_class_valid?
-
end
-
-
2
def expectation
-
expectation = "#{model_class.name} to serialize the attribute called :#{@name}"
-
expectation += " with a type of #{@options[:type]}" if @options[:type]
-
expectation += " with an instance of #{@options[:instance_type]}" if @options[:instance_type]
-
expectation
-
end
-
end
-
end
-
end
-
end
-
2
module Shoulda
-
2
module Matchers
-
2
if Gem.ruby_version >= Gem::Version.new('1.8') && Gem.ruby_version < Gem::Version.new('1.9')
-
require 'test/unit'
-
AssertionError = Test::Unit::AssertionFailedError
-
elsif defined?(Test::Unit::AssertionFailedError)
-
# Test::Unit has been loaded already, so we use it
-
AssertionError = Test::Unit::AssertionFailedError
-
elsif Gem.ruby_version >= Gem::Version.new("1.9")
-
2
require 'minitest/unit'
-
2
AssertionError = MiniTest::Assertion
-
else
-
raise 'No unit test library available'
-
end
-
end
-
end
-
2
if defined?(ActionController)
-
2
require 'shoulda/matchers/action_controller'
-
-
2
ActionController::TestCase.class_eval do
-
2
include Shoulda::Matchers::ActionController
-
2
extend Shoulda::Matchers::ActionController
-
-
2
def subject
-
@controller
-
end
-
end
-
end
-
-
2
if defined?(ActiveRecord)
-
2
require 'shoulda/matchers/active_record'
-
-
2
ActiveSupport::TestCase.class_eval do
-
2
include Shoulda::Matchers::ActiveRecord
-
2
extend Shoulda::Matchers::ActiveRecord
-
end
-
end
-
-
2
if defined?(ActiveModel)
-
2
require 'shoulda/matchers/active_model'
-
-
2
ActiveSupport::TestCase.class_eval do
-
2
include Shoulda::Matchers::ActiveModel
-
2
extend Shoulda::Matchers::ActiveModel
-
end
-
end
-
2
module Shoulda # :nodoc:
-
2
module Matchers
-
2
class RailsShim # :nodoc:
-
2
def self.layouts_ivar
-
if rails_major_version >= 4
-
'@_layouts'
-
else
-
'@layouts'
-
end
-
end
-
-
2
def self.flashes_ivar
-
if rails_major_version >= 4
-
:@flashes
-
else
-
:@used
-
end
-
end
-
-
2
def self.clean_scope(klass)
-
if rails_major_version == 4
-
klass.all
-
else
-
klass.scoped
-
end
-
end
-
-
2
def self.validates_confirmation_of_error_attribute(matcher)
-
if rails_major_version == 4
-
matcher.confirmation_attribute
-
else
-
matcher.attribute
-
end
-
end
-
-
2
def self.rails_major_version
-
Rails::VERSION::MAJOR
-
end
-
end
-
end
-
end
-
2
module Shoulda
-
2
module Matchers
-
2
VERSION = '2.4.0'.freeze
-
end
-
end
-
2
require 'sprockets/version'
-
-
2
module Sprockets
-
# Environment
-
2
autoload :Base, "sprockets/base"
-
2
autoload :Engines, "sprockets/engines"
-
2
autoload :Environment, "sprockets/environment"
-
2
autoload :Index, "sprockets/index"
-
2
autoload :Manifest, "sprockets/manifest"
-
-
# Assets
-
2
autoload :Asset, "sprockets/asset"
-
2
autoload :BundledAsset, "sprockets/bundled_asset"
-
2
autoload :ProcessedAsset, "sprockets/processed_asset"
-
2
autoload :StaticAsset, "sprockets/static_asset"
-
-
# Processing
-
2
autoload :CharsetNormalizer, "sprockets/charset_normalizer"
-
2
autoload :Context, "sprockets/context"
-
2
autoload :DirectiveProcessor, "sprockets/directive_processor"
-
2
autoload :EcoTemplate, "sprockets/eco_template"
-
2
autoload :EjsTemplate, "sprockets/ejs_template"
-
2
autoload :JstProcessor, "sprockets/jst_processor"
-
2
autoload :Processor, "sprockets/processor"
-
2
autoload :SafetyColons, "sprockets/safety_colons"
-
-
# Internal utilities
-
2
autoload :ArgumentError, "sprockets/errors"
-
2
autoload :AssetAttributes, "sprockets/asset_attributes"
-
2
autoload :CircularDependencyError, "sprockets/errors"
-
2
autoload :ContentTypeMismatch, "sprockets/errors"
-
2
autoload :EngineError, "sprockets/errors"
-
2
autoload :Error, "sprockets/errors"
-
2
autoload :FileNotFound, "sprockets/errors"
-
2
autoload :Utils, "sprockets/utils"
-
-
2
module Cache
-
2
autoload :FileStore, "sprockets/cache/file_store"
-
end
-
-
# Extend Sprockets module to provide global registry
-
2
extend Engines
-
2
@engines = {}
-
-
# Cherry pick the default Tilt engines that make sense for
-
# Sprockets. We don't need ones that only generate html like HAML.
-
-
# Mmm, CoffeeScript
-
2
register_engine '.coffee', Tilt::CoffeeScriptTemplate
-
-
# JST engines
-
2
register_engine '.jst', JstProcessor
-
2
register_engine '.eco', EcoTemplate
-
2
register_engine '.ejs', EjsTemplate
-
-
# CSS engines
-
2
register_engine '.less', Tilt::LessTemplate
-
2
register_engine '.sass', Tilt::SassTemplate
-
2
register_engine '.scss', Tilt::ScssTemplate
-
-
# Other
-
2
register_engine '.erb', Tilt::ERBTemplate
-
2
register_engine '.str', Tilt::StringTemplate
-
end
-
2
require 'time'
-
2
require 'set'
-
-
2
module Sprockets
-
# `Asset` is the base class for `BundledAsset` and `StaticAsset`.
-
2
class Asset
-
# Internal initializer to load `Asset` from serialized `Hash`.
-
2
def self.from_hash(environment, hash)
-
return unless hash.is_a?(Hash)
-
-
klass = case hash['class']
-
when 'BundledAsset'
-
BundledAsset
-
when 'ProcessedAsset'
-
ProcessedAsset
-
when 'StaticAsset'
-
StaticAsset
-
else
-
nil
-
end
-
-
if klass
-
asset = klass.allocate
-
asset.init_with(environment, hash)
-
asset
-
end
-
rescue UnserializeError
-
nil
-
end
-
-
2
attr_reader :logical_path, :pathname
-
2
attr_reader :content_type, :mtime, :length, :digest
-
-
2
def initialize(environment, logical_path, pathname)
-
@root = environment.root
-
@logical_path = logical_path.to_s
-
@pathname = Pathname.new(pathname)
-
@content_type = environment.content_type_of(pathname)
-
@mtime = environment.stat(pathname).mtime
-
@length = environment.stat(pathname).size
-
@digest = environment.file_digest(pathname).hexdigest
-
end
-
-
# Initialize `Asset` from serialized `Hash`.
-
2
def init_with(environment, coder)
-
@root = environment.root
-
-
@logical_path = coder['logical_path']
-
@content_type = coder['content_type']
-
@digest = coder['digest']
-
-
if pathname = coder['pathname']
-
# Expand `$root` placeholder and wrapper string in a `Pathname`
-
@pathname = Pathname.new(expand_root_path(pathname))
-
end
-
-
if mtime = coder['mtime']
-
# Parse time string
-
@mtime = Time.parse(mtime)
-
end
-
-
if length = coder['length']
-
# Convert length to an `Integer`
-
@length = Integer(length)
-
end
-
end
-
-
# Copy serialized attributes to the coder object
-
2
def encode_with(coder)
-
coder['class'] = self.class.name.sub(/Sprockets::/, '')
-
coder['logical_path'] = logical_path
-
coder['pathname'] = relativize_root_path(pathname).to_s
-
coder['content_type'] = content_type
-
coder['mtime'] = mtime.iso8601
-
coder['length'] = length
-
coder['digest'] = digest
-
end
-
-
# Return logical path with digest spliced in.
-
#
-
# "foo/bar-37b51d194a7513e45b56f6524f2d51f2.js"
-
#
-
2
def digest_path
-
logical_path.sub(/\.(\w+)$/) { |ext| "-#{digest}#{ext}" }
-
end
-
-
# Return an `Array` of `Asset` files that are declared dependencies.
-
2
def dependencies
-
[]
-
end
-
-
# Expand asset into an `Array` of parts.
-
#
-
# Appending all of an assets body parts together should give you
-
# the asset's contents as a whole.
-
#
-
# This allows you to link to individual files for debugging
-
# purposes.
-
2
def to_a
-
[self]
-
end
-
-
# `body` is aliased to source by default if it can't have any dependencies.
-
2
def body
-
source
-
end
-
-
# Return `String` of concatenated source.
-
2
def to_s
-
source
-
end
-
-
# Add enumerator to allow `Asset` instances to be used as Rack
-
# compatible body objects.
-
2
def each
-
yield to_s
-
end
-
-
# Checks if Asset is fresh by comparing the actual mtime and
-
# digest to the inmemory model.
-
#
-
# Used to test if cached models need to be rebuilt.
-
2
def fresh?(environment)
-
# Check current mtime and digest
-
dependency_fresh?(environment, self)
-
end
-
-
# Checks if Asset is stale by comparing the actual mtime and
-
# digest to the inmemory model.
-
#
-
# Subclass must override `fresh?` or `stale?`.
-
2
def stale?(environment)
-
!fresh?(environment)
-
end
-
-
# Save asset to disk.
-
2
def write_to(filename, options = {})
-
# Gzip contents if filename has '.gz'
-
options[:compress] ||= File.extname(filename) == '.gz'
-
-
FileUtils.mkdir_p File.dirname(filename)
-
-
File.open("#{filename}+", 'wb') do |f|
-
if options[:compress]
-
# Run contents through `Zlib`
-
gz = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)
-
gz.write to_s
-
gz.close
-
else
-
# Write out as is
-
f.write to_s
-
f.close
-
end
-
end
-
-
# Atomic write
-
FileUtils.mv("#{filename}+", filename)
-
-
# Set mtime correctly
-
File.utime(mtime, mtime, filename)
-
-
nil
-
ensure
-
# Ensure tmp file gets cleaned up
-
FileUtils.rm("#{filename}+") if File.exist?("#{filename}+")
-
end
-
-
# Pretty inspect
-
2
def inspect
-
"#<#{self.class}:0x#{object_id.to_s(16)} " +
-
"pathname=#{pathname.to_s.inspect}, " +
-
"mtime=#{mtime.inspect}, " +
-
"digest=#{digest.inspect}" +
-
">"
-
end
-
-
2
def hash
-
digest.hash
-
end
-
-
# Assets are equal if they share the same path, mtime and digest.
-
2
def eql?(other)
-
other.class == self.class &&
-
other.logical_path == self.logical_path &&
-
other.mtime.to_i == self.mtime.to_i &&
-
other.digest == self.digest
-
end
-
2
alias_method :==, :eql?
-
-
2
protected
-
# Internal: String paths that are marked as dependencies after processing.
-
#
-
# Default to an empty `Array`.
-
2
def dependency_paths
-
@dependency_paths ||= []
-
end
-
-
# Internal: `ProccessedAsset`s that are required after processing.
-
#
-
# Default to an empty `Array`.
-
2
def required_assets
-
@required_assets ||= []
-
end
-
-
# Get pathname with its root stripped.
-
2
def relative_pathname
-
@relative_pathname ||= Pathname.new(relativize_root_path(pathname))
-
end
-
-
# Replace `$root` placeholder with actual environment root.
-
2
def expand_root_path(path)
-
path.to_s.sub(/^\$root/, @root)
-
end
-
-
# Replace actual environment root with `$root` placeholder.
-
2
def relativize_root_path(path)
-
path.to_s.sub(/^#{Regexp.escape(@root)}/, '$root')
-
end
-
-
# Check if dependency is fresh.
-
#
-
# `dep` is a `Hash` with `path`, `mtime` and `hexdigest` keys.
-
#
-
# A `Hash` is used rather than other `Asset` object because we
-
# want to test non-asset files and directories.
-
2
def dependency_fresh?(environment, dep)
-
path, mtime, hexdigest = dep.pathname.to_s, dep.mtime, dep.digest
-
-
stat = environment.stat(path)
-
-
# If path no longer exists, its definitely stale.
-
if stat.nil?
-
return false
-
end
-
-
# Compare dependency mime to the actual mtime. If the
-
# dependency mtime is newer than the actual mtime, the file
-
# hasn't changed since we created this `Asset` instance.
-
#
-
# However, if the mtime is newer it doesn't mean the asset is
-
# stale. Many deployment environments may recopy or recheckout
-
# assets on each deploy. In this case the mtime would be the
-
# time of deploy rather than modified time.
-
if mtime >= stat.mtime
-
return true
-
end
-
-
digest = environment.file_digest(path)
-
-
# If the mtime is newer, do a full digest comparsion. Return
-
# fresh if the digests match.
-
if hexdigest == digest.hexdigest
-
return true
-
end
-
-
# Otherwise, its stale.
-
false
-
end
-
end
-
end
-
2
require 'pathname'
-
-
2
module Sprockets
-
# `AssetAttributes` is a wrapper similar to `Pathname` that provides
-
# some helper accessors.
-
#
-
# These methods should be considered internalish.
-
2
class AssetAttributes
-
2
attr_reader :environment, :pathname
-
-
2
def initialize(environment, path)
-
@environment = environment
-
@pathname = path.is_a?(Pathname) ? path : Pathname.new(path.to_s)
-
end
-
-
# Returns paths search the load path for.
-
2
def search_paths
-
paths = [pathname.to_s]
-
-
if pathname.basename(extensions.join).to_s != 'index'
-
path_without_extensions = extensions.inject(pathname) { |p, ext| p.sub(ext, '') }
-
index_path = path_without_extensions.join("index#{extensions.join}").to_s
-
paths << index_path
-
end
-
-
paths
-
end
-
-
# Reverse guess logical path for fully expanded path.
-
#
-
# This has some known issues. For an example if a file is
-
# shaddowed in the path, but is required relatively, its logical
-
# path will be incorrect.
-
2
def logical_path
-
if root_path = environment.paths.detect { |path| pathname.to_s[path] }
-
path = pathname.to_s.sub("#{root_path}/", '')
-
path = pathname.relative_path_from(Pathname.new(root_path)).to_s
-
path = engine_extensions.inject(path) { |p, ext| p.sub(ext, '') }
-
path = "#{path}#{engine_format_extension}" unless format_extension
-
path
-
else
-
raise FileOutsidePaths, "#{pathname} isn't in paths: #{environment.paths.join(', ')}"
-
end
-
end
-
-
# Returns `Array` of extension `String`s.
-
#
-
# "foo.js.coffee"
-
# # => [".js", ".coffee"]
-
#
-
2
def extensions
-
@extensions ||= @pathname.basename.to_s.scan(/\.[^.]+/)
-
end
-
-
# Returns the format extension.
-
#
-
# "foo.js.coffee"
-
# # => ".js"
-
#
-
2
def format_extension
-
extensions.reverse.detect { |ext|
-
@environment.mime_types(ext) && !@environment.engines(ext)
-
}
-
end
-
-
# Returns an `Array` of engine extensions.
-
#
-
# "foo.js.coffee.erb"
-
# # => [".coffee", ".erb"]
-
#
-
2
def engine_extensions
-
exts = extensions
-
-
if offset = extensions.index(format_extension)
-
exts = extensions[offset+1..-1]
-
end
-
-
exts.select { |ext| @environment.engines(ext) }
-
end
-
-
# Returns engine classes.
-
2
def engines
-
engine_extensions.map { |ext| @environment.engines(ext) }
-
end
-
-
# Returns all processors to run on the path.
-
2
def processors
-
environment.preprocessors(content_type) +
-
engines.reverse +
-
environment.postprocessors(content_type)
-
end
-
-
# Returns the content type for the pathname. Falls back to `application/octet-stream`.
-
2
def content_type
-
@content_type ||= begin
-
if format_extension.nil?
-
engine_content_type || 'application/octet-stream'
-
else
-
@environment.mime_types(format_extension) ||
-
engine_content_type ||
-
'application/octet-stream'
-
end
-
end
-
end
-
-
2
private
-
# Returns implicit engine content type.
-
#
-
# `.coffee` files carry an implicit `application/javascript`
-
# content type.
-
2
def engine_content_type
-
engines.reverse.each do |engine|
-
if engine.respond_to?(:default_mime_type) && engine.default_mime_type
-
return engine.default_mime_type
-
end
-
end
-
nil
-
end
-
-
2
def engine_format_extension
-
if content_type = engine_content_type
-
environment.extension_for_mime_type(content_type)
-
end
-
end
-
end
-
end
-
2
require 'sprockets/asset_attributes'
-
2
require 'sprockets/bundled_asset'
-
2
require 'sprockets/caching'
-
2
require 'sprockets/processed_asset'
-
2
require 'sprockets/processing'
-
2
require 'sprockets/server'
-
2
require 'sprockets/static_asset'
-
2
require 'sprockets/trail'
-
2
require 'pathname'
-
-
2
module Sprockets
-
# `Base` class for `Environment` and `Index`.
-
2
class Base
-
2
include Caching, Processing, Server, Trail
-
-
# Returns a `Digest` implementation class.
-
#
-
# Defaults to `Digest::MD5`.
-
2
attr_reader :digest_class
-
-
# Assign a `Digest` implementation class. This maybe any Ruby
-
# `Digest::` implementation such as `Digest::MD5` or
-
# `Digest::SHA1`.
-
#
-
# environment.digest_class = Digest::SHA1
-
#
-
2
def digest_class=(klass)
-
expire_index!
-
@digest_class = klass
-
end
-
-
# The `Environment#version` is a custom value used for manually
-
# expiring all asset caches.
-
#
-
# Sprockets is able to track most file and directory changes and
-
# will take care of expiring the cache for you. However, its
-
# impossible to know when any custom helpers change that you mix
-
# into the `Context`.
-
#
-
# It would be wise to increment this value anytime you make a
-
# configuration change to the `Environment` object.
-
2
attr_reader :version
-
-
# Assign an environment version.
-
#
-
# environment.version = '2.0'
-
#
-
2
def version=(version)
-
2
expire_index!
-
2
@version = version
-
end
-
-
# Returns a `Digest` instance for the `Environment`.
-
#
-
# This value serves two purposes. If two `Environment`s have the
-
# same digest value they can be treated as equal. This is more
-
# useful for comparing environment states between processes rather
-
# than in the same. Two equal `Environment`s can share the same
-
# cached assets.
-
#
-
# The value also provides a seed digest for all `Asset`
-
# digests. Any change in the environment digest will affect all of
-
# its assets.
-
2
def digest
-
# Compute the initial digest using the implementation class. The
-
# Sprockets release version and custom environment version are
-
# mixed in. So any new releases will affect all your assets.
-
@digest ||= digest_class.new.update(VERSION).update(version.to_s)
-
-
# Returned a dupped copy so the caller can safely mutate it with `.update`
-
@digest.dup
-
end
-
-
# Get and set `Logger` instance.
-
2
attr_accessor :logger
-
-
# Get `Context` class.
-
#
-
# This class maybe mutated and mixed in with custom helpers.
-
#
-
# environment.context_class.instance_eval do
-
# include MyHelpers
-
# def asset_url; end
-
# end
-
#
-
2
attr_reader :context_class
-
-
# Get persistent cache store
-
2
attr_reader :cache
-
-
# Set persistent cache store
-
#
-
# The cache store must implement a pair of getters and
-
# setters. Either `get(key)`/`set(key, value)`,
-
# `[key]`/`[key]=value`, `read(key)`/`write(key, value)`.
-
2
def cache=(cache)
-
2
expire_index!
-
2
@cache = cache
-
end
-
-
# Return an `Index`. Must be implemented by the subclass.
-
2
def index
-
raise NotImplementedError
-
end
-
-
2
if defined? Encoding.default_external
-
# Define `default_external_encoding` accessor on 1.9.
-
# Defaults to UTF-8.
-
2
attr_accessor :default_external_encoding
-
end
-
-
# Works like `Dir.entries`.
-
#
-
# Subclasses may cache this method.
-
2
def entries(pathname)
-
trail.entries(pathname)
-
end
-
-
# Works like `File.stat`.
-
#
-
# Subclasses may cache this method.
-
2
def stat(path)
-
trail.stat(path)
-
end
-
-
# Read and compute digest of filename.
-
#
-
# Subclasses may cache this method.
-
2
def file_digest(path)
-
if stat = self.stat(path)
-
# If its a file, digest the contents
-
if stat.file?
-
digest.file(path.to_s)
-
-
# If its a directive, digest the list of filenames
-
elsif stat.directory?
-
contents = self.entries(path).join(',')
-
digest.update(contents)
-
end
-
end
-
end
-
-
# Internal. Return a `AssetAttributes` for `path`.
-
2
def attributes_for(path)
-
AssetAttributes.new(self, path)
-
end
-
-
# Internal. Return content type of `path`.
-
2
def content_type_of(path)
-
attributes_for(path).content_type
-
end
-
-
# Find asset by logical path or expanded path.
-
2
def find_asset(path, options = {})
-
logical_path = path
-
pathname = Pathname.new(path)
-
-
if pathname.absolute?
-
return unless stat(pathname)
-
logical_path = attributes_for(pathname).logical_path
-
else
-
begin
-
pathname = resolve(logical_path)
-
rescue FileNotFound
-
return nil
-
end
-
end
-
-
build_asset(logical_path, pathname, options)
-
end
-
-
# Preferred `find_asset` shorthand.
-
#
-
# environment['application.js']
-
#
-
2
def [](*args)
-
find_asset(*args)
-
end
-
-
2
def each_entry(root, &block)
-
return to_enum(__method__, root) unless block_given?
-
root = Pathname.new(root) unless root.is_a?(Pathname)
-
-
paths = []
-
entries(root).sort.each do |filename|
-
path = root.join(filename)
-
paths << path
-
-
if stat(path).directory?
-
each_entry(path) do |subpath|
-
paths << subpath
-
end
-
end
-
end
-
-
paths.sort_by(&:to_s).each(&block)
-
-
nil
-
end
-
-
2
def each_file
-
return to_enum(__method__) unless block_given?
-
paths.each do |root|
-
each_entry(root) do |path|
-
if !stat(path).directory?
-
yield path
-
end
-
end
-
end
-
nil
-
end
-
-
2
def each_logical_path(*args)
-
return to_enum(__method__, *args) unless block_given?
-
filters = args.flatten
-
files = {}
-
each_file do |filename|
-
if logical_path = logical_path_for_filename(filename, filters)
-
yield logical_path unless files[logical_path]
-
files[logical_path] = true
-
end
-
end
-
nil
-
end
-
-
# Pretty inspect
-
2
def inspect
-
"#<#{self.class}:0x#{object_id.to_s(16)} " +
-
"root=#{root.to_s.inspect}, " +
-
"paths=#{paths.inspect}, " +
-
"digest=#{digest.to_s.inspect}" +
-
">"
-
end
-
-
2
protected
-
# Clear index after mutating state. Must be implemented by the subclass.
-
2
def expire_index!
-
raise NotImplementedError
-
end
-
-
2
def build_asset(logical_path, pathname, options)
-
pathname = Pathname.new(pathname)
-
-
# If there are any processors to run on the pathname, use
-
# `BundledAsset`. Otherwise use `StaticAsset` and treat is as binary.
-
if attributes_for(pathname).processors.any?
-
if options[:bundle] == false
-
circular_call_protection(pathname.to_s) do
-
ProcessedAsset.new(index, logical_path, pathname)
-
end
-
else
-
BundledAsset.new(index, logical_path, pathname)
-
end
-
else
-
StaticAsset.new(index, logical_path, pathname)
-
end
-
end
-
-
2
def cache_key_for(path, options)
-
"#{path}:#{options[:bundle] ? '1' : '0'}"
-
end
-
-
2
def circular_call_protection(path)
-
reset = Thread.current[:sprockets_circular_calls].nil?
-
calls = Thread.current[:sprockets_circular_calls] ||= Set.new
-
if calls.include?(path)
-
raise CircularDependencyError, "#{path} has already been required"
-
end
-
calls << path
-
yield
-
ensure
-
Thread.current[:sprockets_circular_calls] = nil if reset
-
end
-
-
2
def logical_path_for_filename(filename, filters)
-
logical_path = attributes_for(filename).logical_path.to_s
-
-
if matches_filter(filters, logical_path)
-
return logical_path
-
end
-
-
# If filename is an index file, retest with alias
-
if File.basename(logical_path)[/[^\.]+/, 0] == 'index'
-
path = logical_path.sub(/\/index\./, '.')
-
if matches_filter(filters, path)
-
return path
-
end
-
end
-
-
nil
-
end
-
-
2
def matches_filter(filters, filename)
-
return true if filters.empty?
-
-
filters.any? do |filter|
-
if filter.is_a?(Regexp)
-
filter.match(filename)
-
elsif filter.respond_to?(:call)
-
filter.call(filename)
-
else
-
File.fnmatch(filter.to_s, filename)
-
end
-
end
-
end
-
end
-
end
-
2
require 'sprockets/asset'
-
2
require 'sprockets/errors'
-
2
require 'fileutils'
-
2
require 'set'
-
2
require 'zlib'
-
-
2
module Sprockets
-
# `BundledAsset`s are used for files that need to be processed and
-
# concatenated with other assets. Use for `.js` and `.css` files.
-
2
class BundledAsset < Asset
-
2
attr_reader :source
-
-
2
def initialize(environment, logical_path, pathname)
-
super(environment, logical_path, pathname)
-
-
@processed_asset = environment.find_asset(pathname, :bundle => false)
-
@required_assets = @processed_asset.required_assets
-
-
@source = ""
-
-
# Explode Asset into parts and gather the dependency bodies
-
to_a.each { |dependency| @source << dependency.to_s }
-
-
# Run bundle processors on concatenated source
-
context = environment.context_class.new(environment, logical_path, pathname)
-
@source = context.evaluate(pathname, :data => @source,
-
:processors => environment.bundle_processors(content_type))
-
-
@mtime = to_a.map(&:mtime).max
-
@length = Rack::Utils.bytesize(source)
-
@digest = environment.digest.update(source).hexdigest
-
end
-
-
# Initialize `BundledAsset` from serialized `Hash`.
-
2
def init_with(environment, coder)
-
super
-
-
@processed_asset = environment.find_asset(pathname, :bundle => false)
-
@required_assets = @processed_asset.required_assets
-
-
if @processed_asset.dependency_digest != coder['required_assets_digest']
-
raise UnserializeError, "processed asset belongs to a stale environment"
-
end
-
-
@source = coder['source']
-
end
-
-
# Serialize custom attributes in `BundledAsset`.
-
2
def encode_with(coder)
-
super
-
-
coder['source'] = source
-
coder['required_assets_digest'] = @processed_asset.dependency_digest
-
end
-
-
# Get asset's own processed contents. Excludes any of its required
-
# dependencies but does run any processors or engines on the
-
# original file.
-
2
def body
-
@processed_asset.source
-
end
-
-
# Return an `Array` of `Asset` files that are declared dependencies.
-
2
def dependencies
-
to_a.reject { |a| a.eql?(@processed_asset) }
-
end
-
-
# Expand asset into an `Array` of parts.
-
2
def to_a
-
required_assets
-
end
-
-
# Checks if Asset is stale by comparing the actual mtime and
-
# digest to the inmemory model.
-
2
def fresh?(environment)
-
@processed_asset.fresh?(environment)
-
end
-
end
-
end
-
2
module Sprockets
-
# `Caching` is an internal mixin whose public methods are exposed on
-
# the `Environment` and `Index` classes.
-
2
module Caching
-
2
protected
-
# Cache helper method. Takes a `path` argument which maybe a
-
# logical path or fully expanded path. The `&block` is passed
-
# for finding and building the asset if its not in cache.
-
2
def cache_asset(path)
-
# If `cache` is not set, return fast
-
if cache.nil?
-
yield
-
-
# Check cache for `path`
-
elsif (asset = Asset.from_hash(self, cache_get_hash(path.to_s))) && asset.fresh?(self)
-
asset
-
-
# Otherwise yield block that slowly finds and builds the asset
-
elsif asset = yield
-
hash = {}
-
asset.encode_with(hash)
-
-
# Save the asset to its path
-
cache_set_hash(path.to_s, hash)
-
-
# Since path maybe a logical or full pathname, save the
-
# asset its its full path too
-
if path.to_s != asset.pathname.to_s
-
cache_set_hash(asset.pathname.to_s, hash)
-
end
-
-
asset
-
end
-
end
-
-
2
private
-
# Strips `Environment#root` from key to make the key work
-
# consisently across different servers. The key is also hashed
-
# so it does not exceed 250 characters.
-
2
def expand_cache_key(key)
-
File.join('sprockets', digest_class.hexdigest(key.sub(root, '')))
-
end
-
-
2
def cache_get_hash(key)
-
hash = cache_get(expand_cache_key(key))
-
if hash.is_a?(Hash) && digest.hexdigest == hash['_version']
-
hash
-
end
-
end
-
-
2
def cache_set_hash(key, hash)
-
hash['_version'] = digest.hexdigest
-
cache_set(expand_cache_key(key), hash)
-
hash
-
end
-
-
# Low level cache getter for `key`. Checks a number of supported
-
# cache interfaces.
-
2
def cache_get(key)
-
# `Cache#get(key)` for Memcache
-
if cache.respond_to?(:get)
-
cache.get(key)
-
-
# `Cache#[key]` so `Hash` can be used
-
elsif cache.respond_to?(:[])
-
cache[key]
-
-
# `Cache#read(key)` for `ActiveSupport::Cache` support
-
elsif cache.respond_to?(:read)
-
cache.read(key)
-
-
else
-
nil
-
end
-
end
-
-
# Low level cache setter for `key`. Checks a number of supported
-
# cache interfaces.
-
2
def cache_set(key, value)
-
# `Cache#set(key, value)` for Memcache
-
if cache.respond_to?(:set)
-
cache.set(key, value)
-
-
# `Cache#[key]=value` so `Hash` can be used
-
elsif cache.respond_to?(:[]=)
-
cache[key] = value
-
-
# `Cache#write(key, value)` for `ActiveSupport::Cache` support
-
elsif cache.respond_to?(:write)
-
cache.write(key, value)
-
end
-
-
value
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
# Some browsers have issues with stylesheets that contain multiple
-
# `@charset` definitions. The issue surfaces while using Sass since
-
# it inserts a `@charset` at the top of each file. Then Sprockets
-
# concatenates them together.
-
#
-
# The `CharsetNormalizer` processor strips out multiple `@charset`
-
# definitions.
-
#
-
# The current implementation is naive. It picks the first `@charset`
-
# it sees and strips the others. This works for most people because
-
# the other definitions are usually `UTF-8`. A more sophisticated
-
# approach would be to re-encode stylesheets with mixed encodings.
-
#
-
# This behavior can be disabled with:
-
#
-
# environment.unregister_bundle_processor 'text/css', Sprockets::CharsetNormalizer
-
#
-
2
class CharsetNormalizer < Tilt::Template
-
2
def prepare
-
end
-
-
2
def evaluate(context, locals, &block)
-
charset = nil
-
-
# Find and strip out any `@charset` definitions
-
filtered_data = data.gsub(/^@charset "([^"]+)";$/) {
-
charset ||= $1; ""
-
}
-
-
if charset
-
# If there was a charset, move it to the top
-
"@charset \"#{charset}\";#{filtered_data}"
-
else
-
data
-
end
-
end
-
end
-
end
-
2
require 'base64'
-
2
require 'rack/utils'
-
2
require 'sprockets/errors'
-
2
require 'sprockets/utils'
-
2
require 'pathname'
-
2
require 'set'
-
-
2
module Sprockets
-
# `Context` provides helper methods to all `Tilt` processors. They
-
# are typically accessed by ERB templates. You can mix in custom
-
# helpers by injecting them into `Environment#context_class`. Do not
-
# mix them into `Context` directly.
-
#
-
# environment.context_class.class_eval do
-
# include MyHelper
-
# def asset_url; end
-
# end
-
#
-
# <%= asset_url "foo.png" %>
-
#
-
# The `Context` also collects dependencies declared by
-
# assets. See `DirectiveProcessor` for an example of this.
-
2
class Context
-
2
attr_reader :environment, :pathname
-
2
attr_reader :_required_paths, :_stubbed_assets
-
2
attr_reader :_dependency_paths, :_dependency_assets
-
2
attr_writer :__LINE__
-
-
2
def initialize(environment, logical_path, pathname)
-
@environment = environment
-
@logical_path = logical_path
-
@pathname = pathname
-
@__LINE__ = nil
-
-
@_required_paths = []
-
@_stubbed_assets = Set.new
-
@_dependency_paths = Set.new
-
@_dependency_assets = Set.new([pathname.to_s])
-
end
-
-
# Returns the environment path that contains the file.
-
#
-
# If `app/javascripts` and `app/stylesheets` are in your path, and
-
# current file is `app/javascripts/foo/bar.js`, `root_path` would
-
# return `app/javascripts`.
-
2
def root_path
-
environment.paths.detect { |path| pathname.to_s[path] }
-
end
-
-
# Returns logical path without any file extensions.
-
#
-
# 'app/javascripts/application.js'
-
# # => 'application'
-
#
-
2
def logical_path
-
@logical_path[/^([^.]+)/, 0]
-
end
-
-
# Returns content type of file
-
#
-
# 'application/javascript'
-
# 'text/css'
-
#
-
2
def content_type
-
environment.content_type_of(pathname)
-
end
-
-
# Given a logical path, `resolve` will find and return the fully
-
# expanded path. Relative paths will also be resolved. An optional
-
# `:content_type` restriction can be supplied to restrict the
-
# search.
-
#
-
# resolve("foo.js")
-
# # => "/path/to/app/javascripts/foo.js"
-
#
-
# resolve("./bar.js")
-
# # => "/path/to/app/javascripts/bar.js"
-
#
-
2
def resolve(path, options = {}, &block)
-
pathname = Pathname.new(path)
-
attributes = environment.attributes_for(pathname)
-
-
if pathname.absolute?
-
pathname
-
-
elsif content_type = options[:content_type]
-
content_type = self.content_type if content_type == :self
-
-
if attributes.format_extension
-
if content_type != attributes.content_type
-
raise ContentTypeMismatch, "#{path} is " +
-
"'#{attributes.content_type}', not '#{content_type}'"
-
end
-
end
-
-
resolve(path) do |candidate|
-
if self.content_type == environment.content_type_of(candidate)
-
return candidate
-
end
-
end
-
-
raise FileNotFound, "couldn't find file '#{path}'"
-
else
-
environment.resolve(path, :base_path => self.pathname.dirname, &block)
-
end
-
end
-
-
# `depend_on` allows you to state a dependency on a file without
-
# including it.
-
#
-
# This is used for caching purposes. Any changes made to
-
# the dependency file with invalidate the cache of the
-
# source file.
-
2
def depend_on(path)
-
@_dependency_paths << resolve(path).to_s
-
nil
-
end
-
-
# `depend_on_asset` allows you to state an asset dependency
-
# without including it.
-
#
-
# This is used for caching purposes. Any changes that would
-
# invalidate the dependency asset will invalidate the source
-
# file. Unlike `depend_on`, this will include recursively include
-
# the target asset's dependencies.
-
2
def depend_on_asset(path)
-
filename = resolve(path).to_s
-
@_dependency_assets << filename
-
nil
-
end
-
-
# `require_asset` declares `path` as a dependency of the file. The
-
# dependency will be inserted before the file and will only be
-
# included once.
-
#
-
# If ERB processing is enabled, you can use it to dynamically
-
# require assets.
-
#
-
# <%= require_asset "#{framework}.js" %>
-
#
-
2
def require_asset(path)
-
pathname = resolve(path, :content_type => :self)
-
depend_on_asset(pathname)
-
@_required_paths << pathname.to_s
-
nil
-
end
-
-
# `stub_asset` blacklists `path` from being included in the bundle.
-
# `path` must be an asset which may or may not already be included
-
# in the bundle.
-
2
def stub_asset(path)
-
@_stubbed_assets << resolve(path, :content_type => :self).to_s
-
nil
-
end
-
-
# Tests if target path is able to be safely required into the
-
# current concatenation.
-
2
def asset_requirable?(path)
-
pathname = resolve(path)
-
content_type = environment.content_type_of(pathname)
-
stat = environment.stat(path)
-
return false unless stat && stat.file?
-
self.content_type.nil? || self.content_type == content_type
-
end
-
-
# Reads `path` and runs processors on the file.
-
#
-
# This allows you to capture the result of an asset and include it
-
# directly in another.
-
#
-
# <%= evaluate "bar.js" %>
-
#
-
2
def evaluate(path, options = {})
-
pathname = resolve(path)
-
attributes = environment.attributes_for(pathname)
-
processors = options[:processors] || attributes.processors
-
-
if options[:data]
-
result = options[:data]
-
else
-
if environment.respond_to?(:default_external_encoding)
-
mime_type = environment.mime_types(pathname.extname)
-
encoding = environment.encoding_for_mime_type(mime_type)
-
result = Sprockets::Utils.read_unicode(pathname, encoding)
-
else
-
result = Sprockets::Utils.read_unicode(pathname)
-
end
-
end
-
-
processors.each do |processor|
-
begin
-
template = processor.new(pathname.to_s) { result }
-
result = template.render(self, {})
-
rescue Exception => e
-
annotate_exception! e
-
raise
-
end
-
end
-
-
result
-
end
-
-
# Returns a Base64-encoded `data:` URI with the contents of the
-
# asset at the specified path, and marks that path as a dependency
-
# of the current file.
-
#
-
# Use `asset_data_uri` from ERB with CSS or JavaScript assets:
-
#
-
# #logo { background: url(<%= asset_data_uri 'logo.png' %>) }
-
#
-
# $('<img>').attr('src', '<%= asset_data_uri 'avatar.jpg' %>')
-
#
-
2
def asset_data_uri(path)
-
depend_on_asset(path)
-
asset = environment.find_asset(path)
-
base64 = Base64.encode64(asset.to_s).gsub(/\s+/, "")
-
"data:#{asset.content_type};base64,#{Rack::Utils.escape(base64)}"
-
end
-
-
2
private
-
# Annotates exception backtrace with the original template that
-
# the exception was raised in.
-
2
def annotate_exception!(exception)
-
location = pathname.to_s
-
location << ":#{@__LINE__}" if @__LINE__
-
-
exception.extend(Sprockets::EngineError)
-
exception.sprockets_annotation = " (in #{location})"
-
end
-
-
2
def logger
-
environment.logger
-
end
-
end
-
end
-
2
require 'pathname'
-
2
require 'shellwords'
-
2
require 'tilt'
-
2
require 'yaml'
-
-
2
module Sprockets
-
# The `DirectiveProcessor` is responsible for parsing and evaluating
-
# directive comments in a source file.
-
#
-
# A directive comment starts with a comment prefix, followed by an "=",
-
# then the directive name, then any arguments.
-
#
-
# // JavaScript
-
# //= require "foo"
-
#
-
# # CoffeeScript
-
# #= require "bar"
-
#
-
# /* CSS
-
# *= require "baz"
-
# */
-
#
-
# The Processor is implemented as a `Tilt::Template` and is loosely
-
# coupled to Sprockets. This makes it possible to disable or modify
-
# the processor to do whatever you'd like. You could add your own
-
# custom directives or invent your own directive syntax.
-
#
-
# `Environment#processors` includes `DirectiveProcessor` by default.
-
#
-
# To remove the processor entirely:
-
#
-
# env.unregister_processor('text/css', Sprockets::DirectiveProcessor)
-
# env.unregister_processor('application/javascript', Sprockets::DirectiveProcessor)
-
#
-
# Then inject your own preprocessor:
-
#
-
# env.register_processor('text/css', MyProcessor)
-
#
-
2
class DirectiveProcessor < Tilt::Template
-
# Directives will only be picked up if they are in the header
-
# of the source file. C style (/* */), JavaScript (//), and
-
# Ruby (#) comments are supported.
-
#
-
# Directives in comments after the first non-whitespace line
-
# of code will not be processed.
-
#
-
2
HEADER_PATTERN = /
-
\A (
-
(?m:\s*) (
-
(\/\* (?m:.*?) \*\/) |
-
(\#\#\# (?m:.*?) \#\#\#) |
-
(\/\/ .* \n?)+ |
-
(\# .* \n?)+
-
)
-
)+
-
/x
-
-
# Directives are denoted by a `=` followed by the name, then
-
# argument list.
-
#
-
# A few different styles are allowed:
-
#
-
# // =require foo
-
# //= require foo
-
# //= require "foo"
-
#
-
2
DIRECTIVE_PATTERN = /
-
^ [\W]* = \s* (\w+.*?) (\*\/)? $
-
/x
-
-
2
attr_reader :pathname
-
2
attr_reader :header, :body
-
-
2
def prepare
-
@pathname = Pathname.new(file)
-
-
@header = data[HEADER_PATTERN, 0] || ""
-
@body = $' || data
-
# Ensure body ends in a new line
-
@body += "\n" if @body != "" && @body !~ /\n\Z/m
-
-
@included_pathnames = []
-
@compat = false
-
end
-
-
# Implemented for Tilt#render.
-
#
-
# `context` is a `Context` instance with methods that allow you to
-
# access the environment and append to the bundle. See `Context`
-
# for the complete API.
-
2
def evaluate(context, locals, &block)
-
@context = context
-
-
@result = ""
-
@has_written_body = false
-
-
process_directives
-
process_source
-
-
@result
-
end
-
-
# Returns the header String with any directives stripped.
-
2
def processed_header
-
lineno = 0
-
@processed_header ||= header.lines.map { |line|
-
lineno += 1
-
# Replace directive line with a clean break
-
directives.assoc(lineno) ? "\n" : line
-
}.join.chomp
-
end
-
-
# Returns the source String with any directives stripped.
-
2
def processed_source
-
@processed_source ||= processed_header + body
-
end
-
-
# Returns an Array of directive structures. Each structure
-
# is an Array with the line number as the first element, the
-
# directive name as the second element, followed by any
-
# arguments.
-
#
-
# [[1, "require", "foo"], [2, "require", "bar"]]
-
#
-
2
def directives
-
@directives ||= header.lines.each_with_index.map { |line, index|
-
if directive = line[DIRECTIVE_PATTERN, 1]
-
name, *args = Shellwords.shellwords(directive)
-
if respond_to?("process_#{name}_directive", true)
-
[index + 1, name, *args]
-
end
-
end
-
}.compact
-
end
-
-
2
protected
-
2
attr_reader :included_pathnames
-
2
attr_reader :context
-
-
# Gathers comment directives in the source and processes them.
-
# Any directive method matching `process_*_directive` will
-
# automatically be available. This makes it easy to extend the
-
# processor.
-
#
-
# To implement a custom directive called `require_glob`, subclass
-
# `Sprockets::DirectiveProcessor`, then add a method called
-
# `process_require_glob_directive`.
-
#
-
# class DirectiveProcessor < Sprockets::DirectiveProcessor
-
# def process_require_glob_directive
-
# Dir["#{pathname.dirname}/#{glob}"].sort.each do |filename|
-
# require(filename)
-
# end
-
# end
-
# end
-
#
-
# Replace the current processor on the environment with your own:
-
#
-
# env.unregister_processor('text/css', Sprockets::DirectiveProcessor)
-
# env.register_processor('text/css', DirectiveProcessor)
-
#
-
2
def process_directives
-
directives.each do |line_number, name, *args|
-
context.__LINE__ = line_number
-
send("process_#{name}_directive", *args)
-
context.__LINE__ = nil
-
end
-
end
-
-
2
def process_source
-
unless @has_written_body || processed_header.empty?
-
@result << processed_header << "\n"
-
end
-
-
included_pathnames.each do |pathname|
-
@result << context.evaluate(pathname)
-
end
-
-
unless @has_written_body
-
@result << body
-
end
-
-
if compat? && constants.any?
-
@result.gsub!(/<%=(.*?)%>/) { constants[$1.strip] }
-
end
-
end
-
-
# The `require` directive functions similar to Ruby's own `require`.
-
# It provides a way to declare a dependency on a file in your path
-
# and ensures its only loaded once before the source file.
-
#
-
# `require` works with files in the environment path:
-
#
-
# //= require "foo.js"
-
#
-
# Extensions are optional. If your source file is ".js", it
-
# assumes you are requiring another ".js".
-
#
-
# //= require "foo"
-
#
-
# Relative paths work too. Use a leading `./` to denote a relative
-
# path:
-
#
-
# //= require "./bar"
-
#
-
2
def process_require_directive(path)
-
if @compat
-
if path =~ /<([^>]+)>/
-
path = $1
-
else
-
path = "./#{path}" unless relative?(path)
-
end
-
end
-
-
context.require_asset(path)
-
end
-
-
# `require_self` causes the body of the current file to be
-
# inserted before any subsequent `require` or `include`
-
# directives. Useful in CSS files, where it's common for the
-
# index file to contain global styles that need to be defined
-
# before other dependencies are loaded.
-
#
-
# /*= require "reset"
-
# *= require_self
-
# *= require_tree .
-
# */
-
#
-
2
def process_require_self_directive
-
if @has_written_body
-
raise ArgumentError, "require_self can only be called once per source file"
-
end
-
-
context.require_asset(pathname)
-
process_source
-
included_pathnames.clear
-
@has_written_body = true
-
end
-
-
# The `include` directive works similar to `require` but
-
# inserts the contents of the dependency even if it already
-
# has been required.
-
#
-
# //= include "header"
-
#
-
2
def process_include_directive(path)
-
pathname = context.resolve(path)
-
context.depend_on_asset(pathname)
-
included_pathnames << pathname
-
end
-
-
# `require_directory` requires all the files inside a single
-
# directory. It's similar to `path/*` since it does not follow
-
# nested directories.
-
#
-
# //= require_directory "./javascripts"
-
#
-
2
def process_require_directory_directive(path = ".")
-
if relative?(path)
-
root = pathname.dirname.join(path).expand_path
-
-
unless (stats = stat(root)) && stats.directory?
-
raise ArgumentError, "require_directory argument must be a directory"
-
end
-
-
context.depend_on(root)
-
-
entries(root).each do |pathname|
-
pathname = root.join(pathname)
-
if pathname.to_s == self.file
-
next
-
elsif context.asset_requirable?(pathname)
-
context.require_asset(pathname)
-
end
-
end
-
else
-
# The path must be relative and start with a `./`.
-
raise ArgumentError, "require_directory argument must be a relative path"
-
end
-
end
-
-
# `require_tree` requires all the nested files in a directory.
-
# Its glob equivalent is `path/**/*`.
-
#
-
# //= require_tree "./public"
-
#
-
2
def process_require_tree_directive(path = ".")
-
if relative?(path)
-
root = pathname.dirname.join(path).expand_path
-
-
unless (stats = stat(root)) && stats.directory?
-
raise ArgumentError, "require_tree argument must be a directory"
-
end
-
-
context.depend_on(root)
-
-
each_entry(root) do |pathname|
-
if pathname.to_s == self.file
-
next
-
elsif stat(pathname).directory?
-
context.depend_on(pathname)
-
elsif context.asset_requirable?(pathname)
-
context.require_asset(pathname)
-
end
-
end
-
else
-
# The path must be relative and start with a `./`.
-
raise ArgumentError, "require_tree argument must be a relative path"
-
end
-
end
-
-
# Allows you to state a dependency on a file without
-
# including it.
-
#
-
# This is used for caching purposes. Any changes made to
-
# the dependency file will invalidate the cache of the
-
# source file.
-
#
-
# This is useful if you are using ERB and File.read to pull
-
# in contents from another file.
-
#
-
# //= depend_on "foo.png"
-
#
-
2
def process_depend_on_directive(path)
-
context.depend_on(path)
-
end
-
-
# Allows you to state a dependency on an asset without including
-
# it.
-
#
-
# This is used for caching purposes. Any changes that would
-
# invalid the asset dependency will invalidate the cache our the
-
# source file.
-
#
-
# Unlike `depend_on`, the path must be a requirable asset.
-
#
-
# //= depend_on_asset "bar.js"
-
#
-
2
def process_depend_on_asset_directive(path)
-
context.depend_on_asset(path)
-
end
-
-
# Allows dependency to be excluded from the asset bundle.
-
#
-
# The `path` must be a valid asset and may or may not already
-
# be part of the bundle. Once stubbed, it is blacklisted and
-
# can't be brought back by any other `require`.
-
#
-
# //= stub "jquery"
-
#
-
2
def process_stub_directive(path)
-
context.stub_asset(path)
-
end
-
-
# Enable Sprockets 1.x compat mode.
-
#
-
# Makes it possible to use the same JavaScript source
-
# file in both Sprockets 1 and 2.
-
#
-
# //= compat
-
#
-
2
def process_compat_directive
-
@compat = true
-
end
-
-
# Checks if Sprockets 1.x compat mode enabled
-
2
def compat?
-
@compat
-
end
-
-
# Sprockets 1.x allowed for constant interpolation if a
-
# constants.yml was present. This is only available if
-
# compat mode is on.
-
2
def constants
-
if compat?
-
pathname = Pathname.new(context.root_path).join("constants.yml")
-
stat(pathname) ? YAML.load_file(pathname) : {}
-
else
-
{}
-
end
-
end
-
-
# `provide` is stubbed out for Sprockets 1.x compat.
-
# Mutating the path when an asset is being built is
-
# not permitted.
-
2
def process_provide_directive(path)
-
end
-
-
2
private
-
2
def relative?(path)
-
path =~ /^\.($|\.?\/)/
-
end
-
-
2
def stat(path)
-
context.environment.stat(path)
-
end
-
-
2
def entries(path)
-
context.environment.entries(path)
-
end
-
-
2
def each_entry(root, &block)
-
context.environment.each_entry(root, &block)
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
# Tilt engine class for the Eco compiler. Depends on the `eco` gem.
-
#
-
# For more infomation see:
-
#
-
# https://github.com/sstephenson/ruby-eco
-
# https://github.com/sstephenson/eco
-
#
-
2
class EcoTemplate < Tilt::Template
-
# Check to see if Eco is loaded
-
2
def self.engine_initialized?
-
defined? ::Eco
-
end
-
-
# Autoload eco library. If the library isn't loaded, Tilt will produce
-
# a thread safetly warning. If you intend to use `.eco` files, you
-
# should explicitly require it.
-
2
def initialize_engine
-
require_template_library 'eco'
-
end
-
-
2
def prepare
-
end
-
-
# Compile template data with Eco compiler.
-
#
-
# Returns a JS function definition String. The result should be
-
# assigned to a JS variable.
-
#
-
# # => "function(...) {...}"
-
#
-
2
def evaluate(scope, locals, &block)
-
Eco.compile(data)
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
# Tilt engine class for the EJS compiler. Depends on the `ejs` gem.
-
#
-
# For more infomation see:
-
#
-
# https://github.com/sstephenson/ruby-ejs
-
#
-
2
class EjsTemplate < Tilt::Template
-
# Check to see if EJS is loaded
-
2
def self.engine_initialized?
-
defined? ::EJS
-
end
-
-
# Autoload ejs library. If the library isn't loaded, Tilt will produce
-
# a thread safetly warning. If you intend to use `.ejs` files, you
-
# should explicitly require it.
-
2
def initialize_engine
-
require_template_library 'ejs'
-
end
-
-
2
def prepare
-
end
-
-
# Compile template data with EJS compiler.
-
#
-
# Returns a JS function definition String. The result should be
-
# assigned to a JS variable.
-
#
-
# # => "function(obj){...}"
-
#
-
2
def evaluate(scope, locals, &block)
-
EJS.compile(data)
-
end
-
end
-
end
-
2
require 'sprockets/eco_template'
-
2
require 'sprockets/ejs_template'
-
2
require 'sprockets/jst_processor'
-
2
require 'sprockets/utils'
-
2
require 'tilt'
-
-
2
module Sprockets
-
# `Engines` provides a global and `Environment` instance registry.
-
#
-
# An engine is a type of processor that is bound to an filename
-
# extension. `application.js.coffee` indicates that the
-
# `CoffeeScriptTemplate` engine will be ran on the file.
-
#
-
# Extensions can be stacked and will be evaulated from right to
-
# left. `application.js.coffee.erb` will first run `ERBTemplate`
-
# then `CoffeeScriptTemplate`.
-
#
-
# All `Engine`s must follow the `Tilt::Template` interface. It is
-
# recommended to subclass `Tilt::Template`.
-
#
-
# Its recommended that you register engine changes on your local
-
# `Environment` instance.
-
#
-
# environment.register_engine '.foo', FooProcessor
-
#
-
# The global registry is exposed for plugins to register themselves.
-
#
-
# Sprockets.register_engine '.sass', SassTemplate
-
#
-
2
module Engines
-
# Returns an `Array` of `Engine`s registered on the
-
# `Environment`. If an `ext` argument is supplied, the `Engine`
-
# register under that extension will be returned.
-
#
-
# environment.engines
-
# # => [CoffeeScriptTemplate, SassTemplate, ...]
-
#
-
# environment.engines('.coffee')
-
# # => CoffeeScriptTemplate
-
#
-
2
def engines(ext = nil)
-
2
if ext
-
ext = Sprockets::Utils.normalize_extension(ext)
-
@engines[ext]
-
else
-
2
@engines.dup
-
end
-
end
-
-
# Returns an `Array` of engine extension `String`s.
-
#
-
# environment.engine_extensions
-
# # => ['.coffee', '.sass', ...]
-
2
def engine_extensions
-
@engines.keys
-
end
-
-
# Registers a new Engine `klass` for `ext`. If the `ext` already
-
# has an engine registered, it will be overridden.
-
#
-
# environment.register_engine '.coffee', CoffeeScriptTemplate
-
#
-
2
def register_engine(ext, klass)
-
24
ext = Sprockets::Utils.normalize_extension(ext)
-
24
@engines[ext] = klass
-
end
-
-
2
private
-
2
def deep_copy_hash(hash)
-
initial = Hash.new { |h, k| h[k] = [] }
-
hash.inject(initial) { |h, (k, a)| h[k] = a.dup; h }
-
end
-
end
-
end
-
2
require 'sprockets/base'
-
2
require 'sprockets/charset_normalizer'
-
2
require 'sprockets/context'
-
2
require 'sprockets/directive_processor'
-
2
require 'sprockets/index'
-
2
require 'sprockets/safety_colons'
-
-
2
require 'hike'
-
2
require 'logger'
-
2
require 'pathname'
-
2
require 'tilt'
-
-
2
module Sprockets
-
2
class Environment < Base
-
# `Environment` should initialized with your application's root
-
# directory. This should be the same as your Rails or Rack root.
-
#
-
# env = Environment.new(Rails.root)
-
#
-
2
def initialize(root = ".")
-
2
@trail = Hike::Trail.new(root)
-
-
2
self.logger = Logger.new($stderr)
-
2
self.logger.level = Logger::FATAL
-
-
2
if respond_to?(:default_external_encoding)
-
2
self.default_external_encoding = Encoding::UTF_8
-
end
-
-
# Create a safe `Context` subclass to mutate
-
2
@context_class = Class.new(Context)
-
-
# Set MD5 as the default digest
-
2
require 'digest/md5'
-
2
@digest_class = ::Digest::MD5
-
2
@version = ''
-
-
2
@mime_types = {}
-
2
@engines = Sprockets.engines
-
6
@preprocessors = Hash.new { |h, k| h[k] = [] }
-
4
@postprocessors = Hash.new { |h, k| h[k] = [] }
-
4
@bundle_processors = Hash.new { |h, k| h[k] = [] }
-
-
2
@engines.each do |ext, klass|
-
18
add_engine_to_trail(ext, klass)
-
end
-
-
2
register_mime_type 'text/css', '.css'
-
2
register_mime_type 'application/javascript', '.js'
-
-
2
register_preprocessor 'text/css', DirectiveProcessor
-
2
register_preprocessor 'application/javascript', DirectiveProcessor
-
-
2
register_postprocessor 'application/javascript', SafetyColons
-
2
register_bundle_processor 'text/css', CharsetNormalizer
-
-
2
expire_index!
-
-
2
yield self if block_given?
-
end
-
-
# Returns a cached version of the environment.
-
#
-
# All its file system calls are cached which makes `index` much
-
# faster. This behavior is ideal in production since the file
-
# system only changes between deploys.
-
2
def index
-
Index.new(self)
-
end
-
-
# Cache `find_asset` calls
-
2
def find_asset(path, options = {})
-
options[:bundle] = true unless options.key?(:bundle)
-
-
# Ensure inmemory cached assets are still fresh on every lookup
-
if (asset = @assets[cache_key_for(path, options)]) && asset.fresh?(self)
-
asset
-
elsif asset = index.find_asset(path, options)
-
# Cache is pushed upstream by Index#find_asset
-
asset
-
end
-
end
-
-
2
protected
-
2
def expire_index!
-
# Clear digest to be recomputed
-
46
@digest = nil
-
46
@assets = {}
-
end
-
end
-
end
-
# Define some basic Sprockets error classes
-
2
module Sprockets
-
2
class Error < StandardError; end
-
2
class ArgumentError < Error; end
-
2
class CircularDependencyError < Error; end
-
2
class ContentTypeMismatch < Error; end
-
2
class EncodingError < Error; end
-
2
class FileNotFound < Error; end
-
2
class FileOutsidePaths < Error; end
-
2
class UnserializeError < Error; end
-
-
2
module EngineError
-
2
attr_accessor :sprockets_annotation
-
-
2
def message
-
[super, sprockets_annotation].compact.join("\n")
-
end
-
end
-
end
-
2
require 'sprockets/base'
-
-
2
module Sprockets
-
# `Index` is a special cached version of `Environment`.
-
#
-
# The expection is that all of its file system methods are cached
-
# for the instances lifetime. This makes `Index` much faster. This
-
# behavior is ideal in production environments where the file system
-
# is immutable.
-
#
-
# `Index` should not be initialized directly. Instead use
-
# `Environment#index`.
-
2
class Index < Base
-
2
def initialize(environment)
-
@environment = environment
-
-
if environment.respond_to?(:default_external_encoding)
-
@default_external_encoding = environment.default_external_encoding
-
end
-
-
# Copy environment attributes
-
@logger = environment.logger
-
@context_class = environment.context_class
-
@cache = environment.cache
-
@trail = environment.trail.index
-
@digest = environment.digest
-
@digest_class = environment.digest_class
-
@version = environment.version
-
@mime_types = environment.mime_types
-
@engines = environment.engines
-
@preprocessors = environment.preprocessors
-
@postprocessors = environment.postprocessors
-
@bundle_processors = environment.bundle_processors
-
-
# Initialize caches
-
@assets = {}
-
@digests = {}
-
end
-
-
# No-op return self as index
-
2
def index
-
self
-
end
-
-
# Cache calls to `file_digest`
-
2
def file_digest(pathname)
-
key = pathname.to_s
-
if @digests.key?(key)
-
@digests[key]
-
else
-
@digests[key] = super
-
end
-
end
-
-
# Cache `find_asset` calls
-
2
def find_asset(path, options = {})
-
options[:bundle] = true unless options.key?(:bundle)
-
if asset = @assets[cache_key_for(path, options)]
-
asset
-
elsif asset = super
-
logical_path_cache_key = cache_key_for(path, options)
-
full_path_cache_key = cache_key_for(asset.pathname, options)
-
-
# Cache on Index
-
@assets[logical_path_cache_key] = @assets[full_path_cache_key] = asset
-
-
# Push cache upstream to Environment
-
@environment.instance_eval do
-
@assets[logical_path_cache_key] = @assets[full_path_cache_key] = asset
-
end
-
-
asset
-
end
-
end
-
-
2
protected
-
# Index is immutable, any methods that try to clear the cache
-
# should bomb.
-
2
def expire_index!
-
raise TypeError, "can't modify immutable index"
-
end
-
-
# Cache asset building in memory and in persisted cache.
-
2
def build_asset(path, pathname, options)
-
# Memory cache
-
key = cache_key_for(pathname, options)
-
if @assets.key?(key)
-
@assets[key]
-
else
-
@assets[key] = begin
-
# Persisted cache
-
cache_asset(key) do
-
super
-
end
-
end
-
end
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
2
class JstProcessor < Tilt::Template
-
2
def self.default_mime_type
-
4
'application/javascript'
-
end
-
-
2
def self.default_namespace
-
'this.JST'
-
end
-
-
2
def prepare
-
@namespace = self.class.default_namespace
-
end
-
-
2
attr_reader :namespace
-
-
2
def evaluate(scope, locals, &block)
-
<<-JST
-
(function() {
-
#{namespace} || (#{namespace} = {});
-
#{namespace}[#{scope.logical_path.inspect}] = #{indent(data)};
-
}).call(this);
-
JST
-
end
-
-
2
private
-
2
def indent(string)
-
string.gsub(/$(.)/m, "\\1 ").strip
-
end
-
end
-
end
-
2
require 'rack/mime'
-
-
2
module Sprockets
-
2
module Mime
-
# Returns a `Hash` of registered mime types registered on the
-
# environment and those part of `Rack::Mime`.
-
#
-
# If an `ext` is given, it will lookup the mime type for that extension.
-
2
def mime_types(ext = nil)
-
10
if ext.nil?
-
10
Rack::Mime::MIME_TYPES.merge(@mime_types)
-
else
-
ext = Sprockets::Utils.normalize_extension(ext)
-
@mime_types[ext] || Rack::Mime::MIME_TYPES[ext]
-
end
-
end
-
-
2
if {}.respond_to?(:key)
-
2
def extension_for_mime_type(type)
-
10
mime_types.key(type)
-
end
-
else
-
def extension_for_mime_type(type)
-
mime_types.index(type)
-
end
-
end
-
-
# Register a new mime type.
-
2
def register_mime_type(mime_type, ext)
-
4
ext = Sprockets::Utils.normalize_extension(ext)
-
4
@mime_types[ext] = mime_type
-
end
-
-
2
if defined? Encoding
-
# Returns the correct encoding for a given mime type, while falling
-
# back on the default external encoding, if it exists.
-
2
def encoding_for_mime_type(type)
-
encoding = Encoding::BINARY if type =~ %r{^(image|audio|video)/}
-
encoding ||= default_external_encoding if respond_to?(:default_external_encoding)
-
encoding
-
end
-
end
-
end
-
-
# Extend Sprockets module to provide global registry
-
2
extend Mime
-
2
@mime_types = {}
-
end
-
2
require 'sprockets/asset'
-
2
require 'sprockets/utils'
-
-
2
module Sprockets
-
2
class ProcessedAsset < Asset
-
2
def initialize(environment, logical_path, pathname)
-
super
-
-
start_time = Time.now.to_f
-
-
context = environment.context_class.new(environment, logical_path, pathname)
-
@source = context.evaluate(pathname)
-
@length = Rack::Utils.bytesize(source)
-
@digest = environment.digest.update(source).hexdigest
-
-
build_required_assets(environment, context)
-
build_dependency_paths(environment, context)
-
-
@dependency_digest = compute_dependency_digest(environment)
-
-
elapsed_time = ((Time.now.to_f - start_time) * 1000).to_i
-
environment.logger.info "Compiled #{logical_path} (#{elapsed_time}ms) (pid #{Process.pid})"
-
end
-
-
# Interal: Used to check equality
-
2
attr_reader :dependency_digest
-
-
2
attr_reader :source
-
-
# Initialize `BundledAsset` from serialized `Hash`.
-
2
def init_with(environment, coder)
-
super
-
-
@source = coder['source']
-
@dependency_digest = coder['dependency_digest']
-
-
@required_assets = coder['required_paths'].map { |p|
-
p = expand_root_path(p)
-
-
unless environment.paths.detect { |path| p[path] }
-
raise UnserializeError, "#{p} isn't in paths"
-
end
-
-
p == pathname.to_s ? self : environment.find_asset(p, :bundle => false)
-
}
-
@dependency_paths = coder['dependency_paths'].map { |h|
-
DependencyFile.new(expand_root_path(h['path']), h['mtime'], h['digest'])
-
}
-
end
-
-
# Serialize custom attributes in `BundledAsset`.
-
2
def encode_with(coder)
-
super
-
-
coder['source'] = source
-
coder['dependency_digest'] = dependency_digest
-
-
coder['required_paths'] = required_assets.map { |a|
-
relativize_root_path(a.pathname).to_s
-
}
-
coder['dependency_paths'] = dependency_paths.map { |d|
-
{ 'path' => relativize_root_path(d.pathname).to_s,
-
'mtime' => d.mtime.iso8601,
-
'digest' => d.digest }
-
}
-
end
-
-
# Checks if Asset is stale by comparing the actual mtime and
-
# digest to the inmemory model.
-
2
def fresh?(environment)
-
# Check freshness of all declared dependencies
-
@dependency_paths.all? { |dep| dependency_fresh?(environment, dep) }
-
end
-
-
2
protected
-
2
class DependencyFile < Struct.new(:pathname, :mtime, :digest)
-
2
def initialize(pathname, mtime, digest)
-
pathname = Pathname.new(pathname) unless pathname.is_a?(Pathname)
-
mtime = Time.parse(mtime) if mtime.is_a?(String)
-
super
-
end
-
-
2
def eql?(other)
-
other.is_a?(DependencyFile) &&
-
pathname.eql?(other.pathname) &&
-
mtime.eql?(other.mtime) &&
-
digest.eql?(other.digest)
-
end
-
-
2
def hash
-
pathname.to_s.hash
-
end
-
end
-
-
2
private
-
2
def build_required_assets(environment, context)
-
@required_assets = resolve_dependencies(environment, context._required_paths + [pathname.to_s]) -
-
resolve_dependencies(environment, context._stubbed_assets.to_a)
-
end
-
-
2
def resolve_dependencies(environment, paths)
-
assets = []
-
cache = {}
-
-
paths.each do |path|
-
if path == self.pathname.to_s
-
unless cache[self]
-
cache[self] = true
-
assets << self
-
end
-
elsif asset = environment.find_asset(path, :bundle => false)
-
asset.required_assets.each do |asset_dependency|
-
unless cache[asset_dependency]
-
cache[asset_dependency] = true
-
assets << asset_dependency
-
end
-
end
-
end
-
end
-
-
assets
-
end
-
-
2
def build_dependency_paths(environment, context)
-
dependency_paths = {}
-
-
context._dependency_paths.each do |path|
-
dep = DependencyFile.new(path, environment.stat(path).mtime, environment.file_digest(path).hexdigest)
-
dependency_paths[dep] = true
-
end
-
-
context._dependency_assets.each do |path|
-
if path == self.pathname.to_s
-
dep = DependencyFile.new(pathname, environment.stat(path).mtime, environment.file_digest(path).hexdigest)
-
dependency_paths[dep] = true
-
elsif asset = environment.find_asset(path, :bundle => false)
-
asset.dependency_paths.each do |d|
-
dependency_paths[d] = true
-
end
-
end
-
end
-
-
@dependency_paths = dependency_paths.keys
-
end
-
-
2
def compute_dependency_digest(environment)
-
required_assets.inject(environment.digest) { |digest, asset|
-
digest.update asset.digest
-
}.hexdigest
-
end
-
end
-
end
-
2
require 'sprockets/engines'
-
2
require 'sprockets/mime'
-
2
require 'sprockets/processor'
-
2
require 'sprockets/utils'
-
-
2
module Sprockets
-
# `Processing` is an internal mixin whose public methods are exposed on
-
# the `Environment` and `Index` classes.
-
2
module Processing
-
2
include Engines, Mime
-
-
# Register a new mime type.
-
2
def register_mime_type(mime_type, ext)
-
# Overrides the global behavior to expire the index
-
4
expire_index!
-
4
@trail.append_extension(ext)
-
4
super
-
end
-
-
# Returns an `Array` of format extension `String`s.
-
#
-
# format_extensions
-
# # => ['.js', '.css']
-
#
-
2
def format_extensions
-
@trail.extensions - @engines.keys
-
end
-
-
# Registers a new Engine `klass` for `ext`.
-
2
def register_engine(ext, klass)
-
# Overrides the global behavior to expire the index
-
expire_index!
-
add_engine_to_trail(ext, klass)
-
super
-
end
-
-
# Deprecated alias for `preprocessors`.
-
2
def processors(*args)
-
preprocessors(*args)
-
end
-
-
# Returns an `Array` of `Processor` classes. If a `mime_type`
-
# argument is supplied, the processors registered under that
-
# extension will be returned.
-
#
-
# Preprocessors are ran before Postprocessors and Engine
-
# processors.
-
#
-
# All `Processor`s must follow the `Tilt::Template` interface. It is
-
# recommended to subclass `Tilt::Template`.
-
2
def preprocessors(mime_type = nil)
-
if mime_type
-
@preprocessors[mime_type].dup
-
else
-
deep_copy_hash(@preprocessors)
-
end
-
end
-
-
# Returns an `Array` of `Processor` classes. If a `mime_type`
-
# argument is supplied, the processors registered under that
-
# extension will be returned.
-
#
-
# Postprocessors are ran after Preprocessors and Engine processors.
-
#
-
# All `Processor`s must follow the `Tilt::Template` interface. It is
-
# recommended to subclass `Tilt::Template`.
-
2
def postprocessors(mime_type = nil)
-
if mime_type
-
@postprocessors[mime_type].dup
-
else
-
deep_copy_hash(@postprocessors)
-
end
-
end
-
-
# Deprecated alias for `register_preprocessor`.
-
2
def register_processor(*args, &block)
-
register_preprocessor(*args, &block)
-
end
-
-
# Registers a new Preprocessor `klass` for `mime_type`.
-
#
-
# register_preprocessor 'text/css', Sprockets::DirectiveProcessor
-
#
-
# A block can be passed for to create a shorthand processor.
-
#
-
# register_preprocessor :my_processor do |context, data|
-
# data.gsub(...)
-
# end
-
#
-
2
def register_preprocessor(mime_type, klass, &block)
-
6
expire_index!
-
-
6
if block_given?
-
name = klass.to_s
-
klass = Class.new(Processor) do
-
@name = name
-
@processor = block
-
end
-
end
-
-
6
@preprocessors[mime_type].push(klass)
-
end
-
-
# Registers a new Postprocessor `klass` for `mime_type`.
-
#
-
# register_postprocessor 'text/css', Sprockets::CharsetNormalizer
-
#
-
# A block can be passed for to create a shorthand processor.
-
#
-
# register_postprocessor :my_processor do |context, data|
-
# data.gsub(...)
-
# end
-
#
-
2
def register_postprocessor(mime_type, klass, &block)
-
2
expire_index!
-
-
2
if block_given?
-
name = klass.to_s
-
klass = Class.new(Processor) do
-
@name = name
-
@processor = block
-
end
-
end
-
-
2
@postprocessors[mime_type].push(klass)
-
end
-
-
# Deprecated alias for `unregister_preprocessor`.
-
2
def unregister_processor(*args)
-
unregister_preprocessor(*args)
-
end
-
-
# Remove Preprocessor `klass` for `mime_type`.
-
#
-
# unregister_preprocessor 'text/css', Sprockets::DirectiveProcessor
-
#
-
2
def unregister_preprocessor(mime_type, klass)
-
expire_index!
-
-
if klass.is_a?(String) || klass.is_a?(Symbol)
-
klass = @preprocessors[mime_type].detect { |cls|
-
cls.respond_to?(:name) &&
-
cls.name == "Sprockets::Processor (#{klass})"
-
}
-
end
-
-
@preprocessors[mime_type].delete(klass)
-
end
-
-
# Remove Postprocessor `klass` for `mime_type`.
-
#
-
# unregister_postprocessor 'text/css', Sprockets::DirectiveProcessor
-
#
-
2
def unregister_postprocessor(mime_type, klass)
-
expire_index!
-
-
if klass.is_a?(String) || klass.is_a?(Symbol)
-
klass = @postprocessors[mime_type].detect { |cls|
-
cls.respond_to?(:name) &&
-
cls.name == "Sprockets::Processor (#{klass})"
-
}
-
end
-
-
@postprocessors[mime_type].delete(klass)
-
end
-
-
# Returns an `Array` of `Processor` classes. If a `mime_type`
-
# argument is supplied, the processors registered under that
-
# extension will be returned.
-
#
-
# Bundle Processors are ran on concatenated assets rather than
-
# individual files.
-
#
-
# All `Processor`s must follow the `Tilt::Template` interface. It is
-
# recommended to subclass `Tilt::Template`.
-
2
def bundle_processors(mime_type = nil)
-
if mime_type
-
@bundle_processors[mime_type].dup
-
else
-
deep_copy_hash(@bundle_processors)
-
end
-
end
-
-
# Registers a new Bundle Processor `klass` for `mime_type`.
-
#
-
# register_bundle_processor 'text/css', Sprockets::CharsetNormalizer
-
#
-
# A block can be passed for to create a shorthand processor.
-
#
-
# register_bundle_processor :my_processor do |context, data|
-
# data.gsub(...)
-
# end
-
#
-
2
def register_bundle_processor(mime_type, klass, &block)
-
2
expire_index!
-
-
2
if block_given?
-
name = klass.to_s
-
klass = Class.new(Processor) do
-
@name = name
-
@processor = block
-
end
-
end
-
-
2
@bundle_processors[mime_type].push(klass)
-
end
-
-
# Remove Bundle Processor `klass` for `mime_type`.
-
#
-
# unregister_bundle_processor 'text/css', Sprockets::CharsetNormalizer
-
#
-
2
def unregister_bundle_processor(mime_type, klass)
-
expire_index!
-
-
if klass.is_a?(String) || klass.is_a?(Symbol)
-
klass = @bundle_processors[mime_type].detect { |cls|
-
cls.respond_to?(:name) &&
-
cls.name == "Sprockets::Processor (#{klass})"
-
}
-
end
-
-
@bundle_processors[mime_type].delete(klass)
-
end
-
-
# Return CSS compressor or nil if none is set
-
2
def css_compressor
-
bundle_processors('text/css').detect { |klass|
-
klass.respond_to?(:name) &&
-
klass.name == 'Sprockets::Processor (css_compressor)'
-
}
-
end
-
-
# Assign a compressor to run on `text/css` assets.
-
#
-
# The compressor object must respond to `compress` or `compile`.
-
2
def css_compressor=(compressor)
-
expire_index!
-
-
unregister_bundle_processor 'text/css', :css_compressor
-
return unless compressor
-
-
register_bundle_processor 'text/css', :css_compressor do |context, data|
-
compressor.compress(data)
-
end
-
end
-
-
# Return JS compressor or nil if none is set
-
2
def js_compressor
-
bundle_processors('application/javascript').detect { |klass|
-
klass.respond_to?(:name) &&
-
klass.name == 'Sprockets::Processor (js_compressor)'
-
}
-
end
-
-
# Assign a compressor to run on `application/javascript` assets.
-
#
-
# The compressor object must respond to `compress` or `compile`.
-
2
def js_compressor=(compressor)
-
expire_index!
-
-
unregister_bundle_processor 'application/javascript', :js_compressor
-
return unless compressor
-
-
register_bundle_processor 'application/javascript', :js_compressor do |context, data|
-
compressor.compress(data)
-
end
-
end
-
-
2
private
-
2
def add_engine_to_trail(ext, klass)
-
18
@trail.append_extension(ext.to_s)
-
-
18
if klass.respond_to?(:default_mime_type) && klass.default_mime_type
-
10
if format_ext = extension_for_mime_type(klass.default_mime_type)
-
10
@trail.alias_extension(ext.to_s, format_ext)
-
end
-
end
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
# `Processor` creates an anonymous processor class from a block.
-
#
-
# register_preprocessor :my_processor do |context, data|
-
# # ...
-
# end
-
#
-
2
class Processor < Tilt::Template
-
# `processor` is a lambda or block
-
2
def self.processor
-
@processor
-
end
-
-
2
def self.name
-
"Sprockets::Processor (#{@name})"
-
end
-
-
2
def self.to_s
-
name
-
end
-
-
2
def prepare
-
end
-
-
# Call processor block with `context` and `data`.
-
2
def evaluate(context, locals)
-
self.class.processor.call(context, data)
-
end
-
end
-
end
-
2
require 'tilt'
-
-
2
module Sprockets
-
# For JS developers who are colonfobic, concatenating JS files using
-
# the module pattern usually leads to syntax errors.
-
#
-
# The `SafetyColons` processor will insert missing semicolons to the
-
# end of the file.
-
#
-
# This behavior can be disabled with:
-
#
-
# environment.unregister_postprocessor 'application/javascript', Sprockets::SafetyColons
-
#
-
2
class SafetyColons < Tilt::Template
-
2
def prepare
-
end
-
-
2
def evaluate(context, locals, &block)
-
# If the file is blank or ends in a semicolon, leave it as is
-
if data =~ /\A\s*\Z/m || data =~ /;\s*\Z/m
-
data
-
else
-
# Otherwise, append a semicolon and newline
-
"#{data};\n"
-
end
-
end
-
end
-
end
-
2
require 'time'
-
2
require 'uri'
-
-
2
module Sprockets
-
# `Server` is a concern mixed into `Environment` and
-
# `Index` that provides a Rack compatible `call`
-
# interface and url generation helpers.
-
2
module Server
-
# `call` implements the Rack 1.x specification which accepts an
-
# `env` Hash and returns a three item tuple with the status code,
-
# headers, and body.
-
#
-
# Mapping your environment at a url prefix will serve all assets
-
# in the path.
-
#
-
# map "/assets" do
-
# run Sprockets::Environment.new
-
# end
-
#
-
# A request for `"/assets/foo/bar.js"` will search your
-
# environment for `"foo/bar.js"`.
-
2
def call(env)
-
start_time = Time.now.to_f
-
time_elapsed = lambda { ((Time.now.to_f - start_time) * 1000).to_i }
-
-
msg = "Served asset #{env['PATH_INFO']} -"
-
-
# Mark session as "skipped" so no `Set-Cookie` header is set
-
env['rack.session.options'] ||= {}
-
env['rack.session.options'][:defer] = true
-
env['rack.session.options'][:skip] = true
-
-
# Extract the path from everything after the leading slash
-
path = unescape(env['PATH_INFO'].to_s.sub(/^\//, ''))
-
-
# URLs containing a `".."` are rejected for security reasons.
-
if forbidden_request?(path)
-
return forbidden_response
-
end
-
-
# Strip fingerprint
-
if fingerprint = path_fingerprint(path)
-
path = path.sub("-#{fingerprint}", '')
-
end
-
-
# Look up the asset.
-
asset = find_asset(path, :bundle => !body_only?(env))
-
-
# `find_asset` returns nil if the asset doesn't exist
-
if asset.nil?
-
logger.info "#{msg} 404 Not Found (#{time_elapsed.call}ms)"
-
-
# Return a 404 Not Found
-
not_found_response
-
-
# Check request headers `HTTP_IF_NONE_MATCH` against the asset digest
-
elsif etag_match?(asset, env)
-
logger.info "#{msg} 304 Not Modified (#{time_elapsed.call}ms)"
-
-
# Return a 304 Not Modified
-
not_modified_response(asset, env)
-
-
else
-
logger.info "#{msg} 200 OK (#{time_elapsed.call}ms)"
-
-
# Return a 200 with the asset contents
-
ok_response(asset, env)
-
end
-
rescue Exception => e
-
logger.error "Error compiling asset #{path}:"
-
logger.error "#{e.class.name}: #{e.message}"
-
-
case content_type_of(path)
-
when "application/javascript"
-
# Re-throw JavaScript asset exceptions to the browser
-
logger.info "#{msg} 500 Internal Server Error\n\n"
-
return javascript_exception_response(e)
-
when "text/css"
-
# Display CSS asset exceptions in the browser
-
logger.info "#{msg} 500 Internal Server Error\n\n"
-
return css_exception_response(e)
-
else
-
raise
-
end
-
end
-
-
2
private
-
2
def forbidden_request?(path)
-
# Prevent access to files elsewhere on the file system
-
#
-
# http://example.org/assets/../../../etc/passwd
-
#
-
path.include?("..")
-
end
-
-
# Returns a 403 Forbidden response tuple
-
2
def forbidden_response
-
[ 403, { "Content-Type" => "text/plain", "Content-Length" => "9" }, [ "Forbidden" ] ]
-
end
-
-
# Returns a 404 Not Found response tuple
-
2
def not_found_response
-
[ 404, { "Content-Type" => "text/plain", "Content-Length" => "9", "X-Cascade" => "pass" }, [ "Not found" ] ]
-
end
-
-
# Returns a JavaScript response that re-throws a Ruby exception
-
# in the browser
-
2
def javascript_exception_response(exception)
-
err = "#{exception.class.name}: #{exception.message}"
-
body = "throw Error(#{err.inspect})"
-
[ 200, { "Content-Type" => "application/javascript", "Content-Length" => Rack::Utils.bytesize(body).to_s }, [ body ] ]
-
end
-
-
# Returns a CSS response that hides all elements on the page and
-
# displays the exception
-
2
def css_exception_response(exception)
-
message = "\n#{exception.class.name}: #{exception.message}"
-
backtrace = "\n #{exception.backtrace.first}"
-
-
body = <<-CSS
-
html {
-
padding: 18px 36px;
-
}
-
-
head {
-
display: block;
-
}
-
-
body {
-
margin: 0;
-
padding: 0;
-
}
-
-
body > * {
-
display: none !important;
-
}
-
-
head:after, body:before, body:after {
-
display: block !important;
-
}
-
-
head:after {
-
font-family: sans-serif;
-
font-size: large;
-
font-weight: bold;
-
content: "Error compiling CSS asset";
-
}
-
-
body:before, body:after {
-
font-family: monospace;
-
white-space: pre-wrap;
-
}
-
-
body:before {
-
font-weight: bold;
-
content: "#{escape_css_content(message)}";
-
}
-
-
body:after {
-
content: "#{escape_css_content(backtrace)}";
-
}
-
CSS
-
-
[ 200, { "Content-Type" => "text/css;charset=utf-8", "Content-Length" => Rack::Utils.bytesize(body).to_s }, [ body ] ]
-
end
-
-
# Escape special characters for use inside a CSS content("...") string
-
2
def escape_css_content(content)
-
content.
-
gsub('\\', '\\\\005c ').
-
gsub("\n", '\\\\000a ').
-
gsub('"', '\\\\0022 ').
-
gsub('/', '\\\\002f ')
-
end
-
-
# Compare the requests `HTTP_IF_NONE_MATCH` against the assets digest
-
2
def etag_match?(asset, env)
-
env["HTTP_IF_NONE_MATCH"] == etag(asset)
-
end
-
-
# Test if `?body=1` or `body=true` query param is set
-
2
def body_only?(env)
-
env["QUERY_STRING"].to_s =~ /body=(1|t)/
-
end
-
-
# Returns a 304 Not Modified response tuple
-
2
def not_modified_response(asset, env)
-
[ 304, {}, [] ]
-
end
-
-
# Returns a 200 OK response tuple
-
2
def ok_response(asset, env)
-
[ 200, headers(env, asset, asset.length), asset ]
-
end
-
-
2
def headers(env, asset, length)
-
Hash.new.tap do |headers|
-
# Set content type and length headers
-
headers["Content-Type"] = asset.content_type
-
headers["Content-Length"] = length.to_s
-
-
# Set caching headers
-
headers["Cache-Control"] = "public"
-
headers["Last-Modified"] = asset.mtime.httpdate
-
headers["ETag"] = etag(asset)
-
-
# If the request url contains a fingerprint, set a long
-
# expires on the response
-
if path_fingerprint(env["PATH_INFO"])
-
headers["Cache-Control"] << ", max-age=31536000"
-
-
# Otherwise set `must-revalidate` since the asset could be modified.
-
else
-
headers["Cache-Control"] << ", must-revalidate"
-
end
-
end
-
end
-
-
# Gets digest fingerprint.
-
#
-
# "foo-0aa2105d29558f3eb790d411d7d8fb66.js"
-
# # => "0aa2105d29558f3eb790d411d7d8fb66"
-
#
-
2
def path_fingerprint(path)
-
path[/-([0-9a-f]{7,40})\.[^.]+$/, 1]
-
end
-
-
# URI.unescape is deprecated on 1.9. We need to use URI::Parser
-
# if its available.
-
2
if defined? URI::DEFAULT_PARSER
-
2
def unescape(str)
-
str = URI::DEFAULT_PARSER.unescape(str)
-
str.force_encoding(Encoding.default_internal) if Encoding.default_internal
-
str
-
end
-
else
-
def unescape(str)
-
URI.unescape(str)
-
end
-
end
-
-
# Helper to quote the assets digest for use as an ETag.
-
2
def etag(asset)
-
%("#{asset.digest}")
-
end
-
end
-
end
-
2
require 'sprockets/asset'
-
2
require 'fileutils'
-
2
require 'zlib'
-
-
2
module Sprockets
-
# `StaticAsset`s are used for files that are served verbatim without
-
# any processing or concatenation. These are typical images and
-
# other binary files.
-
2
class StaticAsset < Asset
-
# Returns file contents as its `source`.
-
2
def source
-
# File is read everytime to avoid memory bloat of large binary files
-
pathname.open('rb') { |f| f.read }
-
end
-
-
# Implemented for Rack SendFile support.
-
2
def to_path
-
pathname.to_s
-
end
-
-
# Save asset to disk.
-
2
def write_to(filename, options = {})
-
# Gzip contents if filename has '.gz'
-
options[:compress] ||= File.extname(filename) == '.gz'
-
-
FileUtils.mkdir_p File.dirname(filename)
-
-
if options[:compress]
-
# Open file and run it through `Zlib`
-
pathname.open('rb') do |rd|
-
File.open("#{filename}+", 'wb') do |wr|
-
gz = Zlib::GzipWriter.new(wr, Zlib::BEST_COMPRESSION)
-
buf = ""
-
while rd.read(16384, buf)
-
gz.write(buf)
-
end
-
gz.close
-
end
-
end
-
else
-
# If no compression needs to be done, we can just copy it into place.
-
FileUtils.cp(pathname, "#{filename}+")
-
end
-
-
# Atomic write
-
FileUtils.mv("#{filename}+", filename)
-
-
# Set mtime correctly
-
File.utime(mtime, mtime, filename)
-
-
nil
-
ensure
-
# Ensure tmp file gets cleaned up
-
FileUtils.rm("#{filename}+") if File.exist?("#{filename}+")
-
end
-
end
-
end
-
2
require 'sprockets/errors'
-
2
require 'pathname'
-
-
2
module Sprockets
-
# `Trail` is an internal mixin whose public methods are exposed on
-
# the `Environment` and `Index` classes.
-
2
module Trail
-
# Returns `Environment` root.
-
#
-
# All relative paths are expanded with root as its base. To be
-
# useful set this to your applications root directory. (`Rails.root`)
-
2
def root
-
trail.root.dup
-
end
-
-
# Returns an `Array` of path `String`s.
-
#
-
# These paths will be used for asset logical path lookups.
-
#
-
# Note that a copy of the `Array` is returned so mutating will
-
# have no affect on the environment. See `append_path`,
-
# `prepend_path`, and `clear_paths`.
-
2
def paths
-
trail.paths.dup
-
end
-
-
# Prepend a `path` to the `paths` list.
-
#
-
# Paths at the end of the `Array` have the least priority.
-
2
def prepend_path(path)
-
expire_index!
-
@trail.prepend_path(path)
-
end
-
-
# Append a `path` to the `paths` list.
-
#
-
# Paths at the beginning of the `Array` have a higher priority.
-
2
def append_path(path)
-
26
expire_index!
-
26
@trail.append_path(path)
-
end
-
-
# Clear all paths and start fresh.
-
#
-
# There is no mechanism for reordering paths, so its best to
-
# completely wipe the paths list and reappend them in the order
-
# you want.
-
2
def clear_paths
-
expire_index!
-
@trail.paths.dup.each { |path| @trail.remove_path(path) }
-
end
-
-
# Returns an `Array` of extensions.
-
#
-
# These extensions maybe omitted from logical path searches.
-
#
-
# # => [".js", ".css", ".coffee", ".sass", ...]
-
#
-
2
def extensions
-
trail.extensions.dup
-
end
-
-
# Finds the expanded real path for a given logical path by
-
# searching the environment's paths.
-
#
-
# resolve("application.js")
-
# # => "/path/to/app/javascripts/application.js.coffee"
-
#
-
# A `FileNotFound` exception is raised if the file does not exist.
-
2
def resolve(logical_path, options = {})
-
# If a block is given, preform an iterable search
-
if block_given?
-
args = attributes_for(logical_path).search_paths + [options]
-
trail.find(*args) do |path|
-
yield Pathname.new(path)
-
end
-
else
-
resolve(logical_path, options) do |pathname|
-
return pathname
-
end
-
raise FileNotFound, "couldn't find file '#{logical_path}'"
-
end
-
end
-
-
2
protected
-
2
def trail
-
@trail
-
end
-
end
-
end
-
2
module Sprockets
-
# `Utils`, we didn't know where else to put it!
-
2
module Utils
-
# If theres encoding support (aka Ruby 1.9)
-
2
if "".respond_to?(:valid_encoding?)
-
# Define UTF-8 BOM pattern matcher.
-
# Avoid using a Regexp literal because it inheirts the files
-
# encoding and we want to avoid syntax errors in other interpreters.
-
2
UTF8_BOM_PATTERN = Regexp.new("\\A\uFEFF".encode('utf-8'))
-
-
2
def self.read_unicode(pathname, external_encoding = Encoding.default_external)
-
pathname.open("r:#{external_encoding}") do |f|
-
f.read.tap do |data|
-
# Eager validate the file's encoding. In most cases we
-
# expect it to be UTF-8 unless `default_external` is set to
-
# something else. An error is usually raised if the file is
-
# saved as UTF-16 when we expected UTF-8.
-
if !data.valid_encoding?
-
raise EncodingError, "#{pathname} has a invalid " +
-
"#{data.encoding} byte sequence"
-
-
# If the file is UTF-8 and theres a BOM, strip it for safe concatenation.
-
elsif data.encoding.name == "UTF-8" && data =~ UTF8_BOM_PATTERN
-
data.sub!(UTF8_BOM_PATTERN, "")
-
end
-
end
-
end
-
end
-
-
else
-
# Define UTF-8 and UTF-16 BOM pattern matchers.
-
# Avoid using a Regexp literal to prevent syntax errors in other interpreters.
-
UTF8_BOM_PATTERN = Regexp.new("\\A\\xEF\\xBB\\xBF")
-
UTF16_BOM_PATTERN = Regexp.new("\\A(\\xFE\\xFF|\\xFF\\xFE)")
-
-
def self.read_unicode(pathname)
-
pathname.read.tap do |data|
-
# If the file is UTF-8 and theres a BOM, strip it for safe concatenation.
-
if data =~ UTF8_BOM_PATTERN
-
data.sub!(UTF8_BOM_PATTERN, "")
-
-
# If we find a UTF-16 BOM, theres nothing we can do on
-
# 1.8. Only UTF-8 is supported.
-
elsif data =~ UTF16_BOM_PATTERN
-
raise EncodingError, "#{pathname} has a UTF-16 BOM. " +
-
"Resave the file as UTF-8 or upgrade to Ruby 1.9."
-
end
-
end
-
end
-
end
-
-
# Prepends a leading "." to an extension if its missing.
-
#
-
# normalize_extension("js")
-
# # => ".js"
-
#
-
# normalize_extension(".css")
-
# # => ".css"
-
#
-
2
def self.normalize_extension(extension)
-
28
extension = extension.to_s
-
28
if extension[/^\./]
-
28
extension
-
else
-
".#{extension}"
-
end
-
end
-
end
-
end
-
2
module Sprockets
-
2
VERSION = "2.2.2"
-
end
-
# support multiple ruby version (fat binaries under windows)
-
2
begin
-
2
RUBY_VERSION =~ /(\d+\.\d+)/
-
2
require "sqlite3/#{$1}/sqlite3_native"
-
rescue LoadError
-
2
require 'sqlite3/sqlite3_native'
-
end
-
-
2
require 'sqlite3/database'
-
2
require 'sqlite3/version'
-
4
module SQLite3 ; module Constants
-
-
2
module TextRep
-
2
UTF8 = 1
-
2
UTF16LE = 2
-
2
UTF16BE = 3
-
2
UTF16 = 4
-
2
ANY = 5
-
end
-
-
2
module ColumnType
-
2
INTEGER = 1
-
2
FLOAT = 2
-
2
TEXT = 3
-
2
BLOB = 4
-
2
NULL = 5
-
end
-
-
2
module ErrorCode
-
2
OK = 0 # Successful result
-
2
ERROR = 1 # SQL error or missing database
-
2
INTERNAL = 2 # An internal logic error in SQLite
-
2
PERM = 3 # Access permission denied
-
2
ABORT = 4 # Callback routine requested an abort
-
2
BUSY = 5 # The database file is locked
-
2
LOCKED = 6 # A table in the database is locked
-
2
NOMEM = 7 # A malloc() failed
-
2
READONLY = 8 # Attempt to write a readonly database
-
2
INTERRUPT = 9 # Operation terminated by sqlite_interrupt()
-
2
IOERR = 10 # Some kind of disk I/O error occurred
-
2
CORRUPT = 11 # The database disk image is malformed
-
2
NOTFOUND = 12 # (Internal Only) Table or record not found
-
2
FULL = 13 # Insertion failed because database is full
-
2
CANTOPEN = 14 # Unable to open the database file
-
2
PROTOCOL = 15 # Database lock protocol error
-
2
EMPTY = 16 # (Internal Only) Database table is empty
-
2
SCHEMA = 17 # The database schema changed
-
2
TOOBIG = 18 # Too much data for one row of a table
-
2
CONSTRAINT = 19 # Abort due to contraint violation
-
2
MISMATCH = 20 # Data type mismatch
-
2
MISUSE = 21 # Library used incorrectly
-
2
NOLFS = 22 # Uses OS features not supported on host
-
2
AUTH = 23 # Authorization denied
-
-
2
ROW = 100 # sqlite_step() has another row ready
-
2
DONE = 101 # sqlite_step() has finished executing
-
end
-
-
end ; end
-
2
require 'sqlite3/constants'
-
2
require 'sqlite3/errors'
-
2
require 'sqlite3/pragmas'
-
2
require 'sqlite3/statement'
-
2
require 'sqlite3/translator'
-
2
require 'sqlite3/value'
-
-
2
module SQLite3
-
-
# The Database class encapsulates a single connection to a SQLite3 database.
-
# Its usage is very straightforward:
-
#
-
# require 'sqlite3'
-
#
-
# SQLite3::Database.new( "data.db" ) do |db|
-
# db.execute( "select * from table" ) do |row|
-
# p row
-
# end
-
# end
-
#
-
# It wraps the lower-level methods provides by the selected driver, and
-
# includes the Pragmas module for access to various pragma convenience
-
# methods.
-
#
-
# The Database class provides type translation services as well, by which
-
# the SQLite3 data types (which are all represented as strings) may be
-
# converted into their corresponding types (as defined in the schemas
-
# for their tables). This translation only occurs when querying data from
-
# the database--insertions and updates are all still typeless.
-
#
-
# Furthermore, the Database class has been designed to work well with the
-
# ArrayFields module from Ara Howard. If you require the ArrayFields
-
# module before performing a query, and if you have not enabled results as
-
# hashes, then the results will all be indexible by field name.
-
2
class Database
-
2
attr_reader :collations
-
-
2
include Pragmas
-
-
2
class << self
-
-
2
alias :open :new
-
-
# Quotes the given string, making it safe to use in an SQL statement.
-
# It replaces all instances of the single-quote character with two
-
# single-quote characters. The modified string is returned.
-
2
def quote( string )
-
66
string.gsub( /'/, "''" )
-
end
-
-
end
-
-
# A boolean that indicates whether rows in result sets should be returned
-
# as hashes or not. By default, rows are returned as arrays.
-
2
attr_accessor :results_as_hash
-
-
2
def type_translation= value # :nodoc:
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#type_translation=
-
SQLite3::Database#type_translation= is deprecated and will be removed
-
in version 2.0.0.
-
eowarn
-
@type_translation = value
-
end
-
2
attr_reader :type_translation # :nodoc:
-
-
# Return the type translator employed by this database instance. Each
-
# database instance has its own type translator; this allows for different
-
# type handlers to be installed in each instance without affecting other
-
# instances. Furthermore, the translators are instantiated lazily, so that
-
# if a database does not use type translation, it will not be burdened by
-
# the overhead of a useless type translator. (See the Translator class.)
-
2
def translator
-
@translator ||= Translator.new
-
end
-
-
# Installs (or removes) a block that will be invoked for every access
-
# to the database. If the block returns 0 (or +nil+), the statement
-
# is allowed to proceed. Returning 1 causes an authorization error to
-
# occur, and returning 2 causes the access to be silently denied.
-
2
def authorizer( &block )
-
self.authorizer = block
-
end
-
-
# Returns a Statement object representing the given SQL. This does not
-
# execute the statement; it merely prepares the statement for execution.
-
#
-
# The Statement can then be executed using Statement#execute.
-
#
-
2
def prepare sql
-
1546
stmt = SQLite3::Statement.new( self, sql )
-
1546
return stmt unless block_given?
-
-
630
begin
-
630
yield stmt
-
ensure
-
630
stmt.close
-
end
-
end
-
-
# Executes the given SQL statement. If additional parameters are given,
-
# they are treated as bind variables, and are bound to the placeholders in
-
# the query.
-
#
-
# Note that if any of the values passed to this are hashes, then the
-
# key/value pairs are each bound separately, with the key being used as
-
# the name of the placeholder to bind the value to.
-
#
-
# The block is optional. If given, it will be invoked for each row returned
-
# by the query. Otherwise, any results are accumulated into an array and
-
# returned wholesale.
-
#
-
# See also #execute2, #query, and #execute_batch for additional ways of
-
# executing statements.
-
2
def execute sql, bind_vars = [], *args, &block
-
# FIXME: This is a terrible hack and should be removed but is required
-
# for older versions of rails
-
630
hack = Object.const_defined?(:ActiveRecord) && sql =~ /^PRAGMA index_list/
-
-
630
if bind_vars.nil? || !args.empty?
-
if args.empty?
-
bind_vars = []
-
else
-
bind_vars = [bind_vars] + args
-
end
-
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#execute with nil or multiple bind params
-
without using an array. Please switch to passing bind parameters as an array.
-
Support for bind parameters as *args will be removed in 2.0.0.
-
eowarn
-
end
-
-
630
prepare( sql ) do |stmt|
-
630
stmt.bind_params(bind_vars)
-
630
columns = stmt.columns
-
630
stmt = ResultSet.new(self, stmt).to_a if type_translation
-
-
630
if block_given?
-
stmt.each do |row|
-
if @results_as_hash
-
yield type_translation ? row : ordered_map_for(columns, row)
-
else
-
yield row
-
end
-
end
-
else
-
630
if @results_as_hash
-
630
stmt.map { |row|
-
h = type_translation ? row : ordered_map_for(columns, row)
-
-
# FIXME UGH TERRIBLE HACK!
-
h['unique'] = h['unique'].to_s if hack
-
-
h
-
}
-
else
-
stmt.to_a
-
end
-
end
-
end
-
end
-
-
# Executes the given SQL statement, exactly as with #execute. However, the
-
# first row returned (either via the block, or in the returned array) is
-
# always the names of the columns. Subsequent rows correspond to the data
-
# from the result set.
-
#
-
# Thus, even if the query itself returns no rows, this method will always
-
# return at least one row--the names of the columns.
-
#
-
# See also #execute, #query, and #execute_batch for additional ways of
-
# executing statements.
-
2
def execute2( sql, *bind_vars )
-
prepare( sql ) do |stmt|
-
result = stmt.execute( *bind_vars )
-
if block_given?
-
yield stmt.columns
-
result.each { |row| yield row }
-
else
-
return result.inject( [ stmt.columns ] ) { |arr,row|
-
arr << row; arr }
-
end
-
end
-
end
-
-
# Executes all SQL statements in the given string. By contrast, the other
-
# means of executing queries will only execute the first statement in the
-
# string, ignoring all subsequent statements. This will execute each one
-
# in turn. The same bind parameters, if given, will be applied to each
-
# statement.
-
#
-
# This always returns +nil+, making it unsuitable for queries that return
-
# rows.
-
2
def execute_batch( sql, bind_vars = [], *args )
-
# FIXME: remove this stuff later
-
unless [Array, Hash].include?(bind_vars.class)
-
bind_vars = [bind_vars]
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#execute_batch with bind parameters
-
that are not a list of a hash. Please switch to passing bind parameters as an
-
array or hash. Support for this behavior will be removed in version 2.0.0.
-
eowarn
-
end
-
-
# FIXME: remove this stuff later
-
if bind_vars.nil? || !args.empty?
-
if args.empty?
-
bind_vars = []
-
else
-
bind_vars = [nil] + args
-
end
-
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#execute_batch with nil or multiple bind params
-
without using an array. Please switch to passing bind parameters as an array.
-
Support for this behavior will be removed in version 2.0.0.
-
eowarn
-
end
-
-
sql = sql.strip
-
until sql.empty? do
-
prepare( sql ) do |stmt|
-
# FIXME: this should probably use sqlite3's api for batch execution
-
# This implementation requires stepping over the results.
-
if bind_vars.length == stmt.bind_parameter_count
-
stmt.bind_params(bind_vars)
-
end
-
stmt.step
-
sql = stmt.remainder.strip
-
end
-
end
-
nil
-
end
-
-
# This is a convenience method for creating a statement, binding
-
# paramters to it, and calling execute:
-
#
-
# result = db.query( "select * from foo where a=?", [5])
-
# # is the same as
-
# result = db.prepare( "select * from foo where a=?" ).execute( 5 )
-
#
-
# You must be sure to call +close+ on the ResultSet instance that is
-
# returned, or you could have problems with locks on the table. If called
-
# with a block, +close+ will be invoked implicitly when the block
-
# terminates.
-
2
def query( sql, bind_vars = [], *args )
-
-
if bind_vars.nil? || !args.empty?
-
if args.empty?
-
bind_vars = []
-
else
-
bind_vars = [bind_vars] + args
-
end
-
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling SQLite3::Database#query with nil or multiple bind params
-
without using an array. Please switch to passing bind parameters as an array.
-
Support for this will be removed in version 2.0.0.
-
eowarn
-
end
-
-
result = prepare( sql ).execute( bind_vars )
-
if block_given?
-
begin
-
yield result
-
ensure
-
result.close
-
end
-
else
-
return result
-
end
-
end
-
-
# A convenience method for obtaining the first row of a result set, and
-
# discarding all others. It is otherwise identical to #execute.
-
#
-
# See also #get_first_value.
-
2
def get_first_row( sql, *bind_vars )
-
execute( sql, *bind_vars ).first
-
end
-
-
# A convenience method for obtaining the first value of the first row of a
-
# result set, and discarding all other values and rows. It is otherwise
-
# identical to #execute.
-
#
-
# See also #get_first_row.
-
2
def get_first_value( sql, *bind_vars )
-
execute( sql, *bind_vars ) { |row| return row[0] }
-
nil
-
end
-
-
2
alias :busy_timeout :busy_timeout=
-
-
# Creates a new function for use in SQL statements. It will be added as
-
# +name+, with the given +arity+. (For variable arity functions, use
-
# -1 for the arity.)
-
#
-
# The block should accept at least one parameter--the FunctionProxy
-
# instance that wraps this function invocation--and any other
-
# arguments it needs (up to its arity).
-
#
-
# The block does not return a value directly. Instead, it will invoke
-
# the FunctionProxy#result= method on the +func+ parameter and
-
# indicate the return value that way.
-
#
-
# Example:
-
#
-
# db.create_function( "maim", 1 ) do |func, value|
-
# if value.nil?
-
# func.result = nil
-
# else
-
# func.result = value.split(//).sort.join
-
# end
-
# end
-
#
-
# puts db.get_first_value( "select maim(name) from table" )
-
2
def create_function name, arity, text_rep=Constants::TextRep::ANY, &block
-
define_function(name) do |*args|
-
fp = FunctionProxy.new
-
block.call(fp, *args)
-
fp.result
-
end
-
self
-
end
-
-
# Creates a new aggregate function for use in SQL statements. Aggregate
-
# functions are functions that apply over every row in the result set,
-
# instead of over just a single row. (A very common aggregate function
-
# is the "count" function, for determining the number of rows that match
-
# a query.)
-
#
-
# The new function will be added as +name+, with the given +arity+. (For
-
# variable arity functions, use -1 for the arity.)
-
#
-
# The +step+ parameter must be a proc object that accepts as its first
-
# parameter a FunctionProxy instance (representing the function
-
# invocation), with any subsequent parameters (up to the function's arity).
-
# The +step+ callback will be invoked once for each row of the result set.
-
#
-
# The +finalize+ parameter must be a +proc+ object that accepts only a
-
# single parameter, the FunctionProxy instance representing the current
-
# function invocation. It should invoke FunctionProxy#result= to
-
# store the result of the function.
-
#
-
# Example:
-
#
-
# db.create_aggregate( "lengths", 1 ) do
-
# step do |func, value|
-
# func[ :total ] ||= 0
-
# func[ :total ] += ( value ? value.length : 0 )
-
# end
-
#
-
# finalize do |func|
-
# func.result = func[ :total ] || 0
-
# end
-
# end
-
#
-
# puts db.get_first_value( "select lengths(name) from table" )
-
#
-
# See also #create_aggregate_handler for a more object-oriented approach to
-
# aggregate functions.
-
2
def create_aggregate( name, arity, step=nil, finalize=nil,
-
text_rep=Constants::TextRep::ANY, &block )
-
-
factory = Class.new do
-
def self.step( &block )
-
define_method(:step, &block)
-
end
-
-
def self.finalize( &block )
-
define_method(:finalize, &block)
-
end
-
end
-
-
if block_given?
-
factory.instance_eval(&block)
-
else
-
factory.class_eval do
-
define_method(:step, step)
-
define_method(:finalize, finalize)
-
end
-
end
-
-
proxy = factory.new
-
proxy.extend(Module.new {
-
attr_accessor :ctx
-
-
def step( *args )
-
super(@ctx, *args)
-
end
-
-
def finalize
-
super(@ctx)
-
end
-
})
-
proxy.ctx = FunctionProxy.new
-
define_aggregator(name, proxy)
-
end
-
-
# This is another approach to creating an aggregate function (see
-
# #create_aggregate). Instead of explicitly specifying the name,
-
# callbacks, arity, and type, you specify a factory object
-
# (the "handler") that knows how to obtain all of that information. The
-
# handler should respond to the following messages:
-
#
-
# +arity+:: corresponds to the +arity+ parameter of #create_aggregate. This
-
# message is optional, and if the handler does not respond to it,
-
# the function will have an arity of -1.
-
# +name+:: this is the name of the function. The handler _must_ implement
-
# this message.
-
# +new+:: this must be implemented by the handler. It should return a new
-
# instance of the object that will handle a specific invocation of
-
# the function.
-
#
-
# The handler instance (the object returned by the +new+ message, described
-
# above), must respond to the following messages:
-
#
-
# +step+:: this is the method that will be called for each step of the
-
# aggregate function's evaluation. It should implement the same
-
# signature as the +step+ callback for #create_aggregate.
-
# +finalize+:: this is the method that will be called to finalize the
-
# aggregate function's evaluation. It should implement the
-
# same signature as the +finalize+ callback for
-
# #create_aggregate.
-
#
-
# Example:
-
#
-
# class LengthsAggregateHandler
-
# def self.arity; 1; end
-
#
-
# def initialize
-
# @total = 0
-
# end
-
#
-
# def step( ctx, name )
-
# @total += ( name ? name.length : 0 )
-
# end
-
#
-
# def finalize( ctx )
-
# ctx.result = @total
-
# end
-
# end
-
#
-
# db.create_aggregate_handler( LengthsAggregateHandler )
-
# puts db.get_first_value( "select lengths(name) from A" )
-
2
def create_aggregate_handler( handler )
-
proxy = Class.new do
-
def initialize handler
-
@handler = handler
-
@fp = FunctionProxy.new
-
end
-
-
def step( *args )
-
@handler.step(@fp, *args)
-
end
-
-
def finalize
-
@handler.finalize @fp
-
@fp.result
-
end
-
end
-
define_aggregator(handler.name, proxy.new(handler.new))
-
self
-
end
-
-
# Begins a new transaction. Note that nested transactions are not allowed
-
# by SQLite, so attempting to nest a transaction will result in a runtime
-
# exception.
-
#
-
# The +mode+ parameter may be either <tt>:deferred</tt> (the default),
-
# <tt>:immediate</tt>, or <tt>:exclusive</tt>.
-
#
-
# If a block is given, the database instance is yielded to it, and the
-
# transaction is committed when the block terminates. If the block
-
# raises an exception, a rollback will be performed instead. Note that if
-
# a block is given, #commit and #rollback should never be called
-
# explicitly or you'll get an error when the block terminates.
-
#
-
# If a block is not given, it is the caller's responsibility to end the
-
# transaction explicitly, either by calling #commit, or by calling
-
# #rollback.
-
2
def transaction( mode = :deferred )
-
147
execute "begin #{mode.to_s} transaction"
-
-
147
if block_given?
-
abort = false
-
begin
-
yield self
-
rescue ::Object
-
abort = true
-
raise
-
ensure
-
abort and rollback or commit
-
end
-
end
-
-
147
true
-
end
-
-
# Commits the current transaction. If there is no current transaction,
-
# this will cause an error to be raised. This returns +true+, in order
-
# to allow it to be used in idioms like
-
# <tt>abort? and rollback or commit</tt>.
-
2
def commit
-
2
execute "commit transaction"
-
2
true
-
end
-
-
# Rolls the current transaction back. If there is no current transaction,
-
# this will cause an error to be raised. This returns +true+, in order
-
# to allow it to be used in idioms like
-
# <tt>abort? and rollback or commit</tt>.
-
2
def rollback
-
145
execute "rollback transaction"
-
145
true
-
end
-
-
# Returns +true+ if the database has been open in readonly mode
-
# A helper to check before performing any operation
-
2
def readonly?
-
@readonly
-
end
-
-
# A helper class for dealing with custom functions (see #create_function,
-
# #create_aggregate, and #create_aggregate_handler). It encapsulates the
-
# opaque function object that represents the current invocation. It also
-
# provides more convenient access to the API functions that operate on
-
# the function object.
-
#
-
# This class will almost _always_ be instantiated indirectly, by working
-
# with the create methods mentioned above.
-
2
class FunctionProxy
-
2
attr_accessor :result
-
-
# Create a new FunctionProxy that encapsulates the given +func+ object.
-
# If context is non-nil, the functions context will be set to that. If
-
# it is non-nil, it must quack like a Hash. If it is nil, then none of
-
# the context functions will be available.
-
2
def initialize
-
@result = nil
-
@context = {}
-
end
-
-
# Set the result of the function to the given error message.
-
# The function will then return that error.
-
2
def set_error( error )
-
@driver.result_error( @func, error.to_s, -1 )
-
end
-
-
# (Only available to aggregate functions.) Returns the number of rows
-
# that the aggregate has processed so far. This will include the current
-
# row, and so will always return at least 1.
-
2
def count
-
@driver.aggregate_count( @func )
-
end
-
-
# Returns the value with the given key from the context. This is only
-
# available to aggregate functions.
-
2
def []( key )
-
@context[ key ]
-
end
-
-
# Sets the value with the given key in the context. This is only
-
# available to aggregate functions.
-
2
def []=( key, value )
-
@context[ key ] = value
-
end
-
end
-
-
2
private
-
-
2
def ordered_map_for columns, row
-
h = Hash[*columns.zip(row).flatten]
-
row.each_with_index { |r, i| h[i] = r }
-
h
-
end
-
end
-
end
-
2
require 'sqlite3/constants'
-
-
2
module SQLite3
-
2
class Exception < ::StandardError
-
2
@code = 0
-
-
# The numeric error code that this exception represents.
-
2
def self.code
-
@code
-
end
-
-
# A convenience for accessing the error code for this exception.
-
2
def code
-
self.class.code
-
end
-
end
-
-
2
class SQLException < Exception; end
-
2
class InternalException < Exception; end
-
2
class PermissionException < Exception; end
-
2
class AbortException < Exception; end
-
2
class BusyException < Exception; end
-
2
class LockedException < Exception; end
-
2
class MemoryException < Exception; end
-
2
class ReadOnlyException < Exception; end
-
2
class InterruptException < Exception; end
-
2
class IOException < Exception; end
-
2
class CorruptException < Exception; end
-
2
class NotFoundException < Exception; end
-
2
class FullException < Exception; end
-
2
class CantOpenException < Exception; end
-
2
class ProtocolException < Exception; end
-
2
class EmptyException < Exception; end
-
2
class SchemaChangedException < Exception; end
-
2
class TooBigException < Exception; end
-
2
class ConstraintException < Exception; end
-
2
class MismatchException < Exception; end
-
2
class MisuseException < Exception; end
-
2
class UnsupportedException < Exception; end
-
2
class AuthorizationException < Exception; end
-
2
class FormatException < Exception; end
-
2
class RangeException < Exception; end
-
2
class NotADatabaseException < Exception; end
-
end
-
2
require 'sqlite3/errors'
-
-
2
module SQLite3
-
-
# This module is intended for inclusion solely by the Database class. It
-
# defines convenience methods for the various pragmas supported by SQLite3.
-
#
-
# For a detailed description of these pragmas, see the SQLite3 documentation
-
# at http://sqlite.org/pragma.html.
-
2
module Pragmas
-
-
# Returns +true+ or +false+ depending on the value of the named pragma.
-
2
def get_boolean_pragma( name )
-
get_first_value( "PRAGMA #{name}" ) != "0"
-
end
-
2
private :get_boolean_pragma
-
-
# Sets the given pragma to the given boolean value. The value itself
-
# may be +true+ or +false+, or any other commonly used string or
-
# integer that represents truth.
-
2
def set_boolean_pragma( name, mode )
-
case mode
-
when String
-
case mode.downcase
-
when "on", "yes", "true", "y", "t"; mode = "'ON'"
-
when "off", "no", "false", "n", "f"; mode = "'OFF'"
-
else
-
raise Exception,
-
"unrecognized pragma parameter #{mode.inspect}"
-
end
-
when true, 1
-
mode = "ON"
-
when false, 0, nil
-
mode = "OFF"
-
else
-
raise Exception,
-
"unrecognized pragma parameter #{mode.inspect}"
-
end
-
-
execute( "PRAGMA #{name}=#{mode}" )
-
end
-
2
private :set_boolean_pragma
-
-
# Requests the given pragma (and parameters), and if the block is given,
-
# each row of the result set will be yielded to it. Otherwise, the results
-
# are returned as an array.
-
2
def get_query_pragma( name, *parms, &block ) # :yields: row
-
if parms.empty?
-
execute( "PRAGMA #{name}", &block )
-
else
-
args = "'" + parms.join("','") + "'"
-
execute( "PRAGMA #{name}( #{args} )", &block )
-
end
-
end
-
2
private :get_query_pragma
-
-
# Return the value of the given pragma.
-
2
def get_enum_pragma( name )
-
get_first_value( "PRAGMA #{name}" )
-
end
-
2
private :get_enum_pragma
-
-
# Set the value of the given pragma to +mode+. The +mode+ parameter must
-
# conform to one of the values in the given +enum+ array. Each entry in
-
# the array is another array comprised of elements in the enumeration that
-
# have duplicate values. See #synchronous, #default_synchronous,
-
# #temp_store, and #default_temp_store for usage examples.
-
2
def set_enum_pragma( name, mode, enums )
-
match = enums.find { |p| p.find { |i| i.to_s.downcase == mode.to_s.downcase } }
-
raise Exception,
-
"unrecognized #{name} #{mode.inspect}" unless match
-
execute( "PRAGMA #{name}='#{match.first.upcase}'" )
-
end
-
2
private :set_enum_pragma
-
-
# Returns the value of the given pragma as an integer.
-
2
def get_int_pragma( name )
-
get_first_value( "PRAGMA #{name}" ).to_i
-
end
-
2
private :get_int_pragma
-
-
# Set the value of the given pragma to the integer value of the +value+
-
# parameter.
-
2
def set_int_pragma( name, value )
-
execute( "PRAGMA #{name}=#{value.to_i}" )
-
end
-
2
private :set_int_pragma
-
-
# The enumeration of valid synchronous modes.
-
2
SYNCHRONOUS_MODES = [ [ 'full', 2 ], [ 'normal', 1 ], [ 'off', 0 ] ]
-
-
# The enumeration of valid temp store modes.
-
2
TEMP_STORE_MODES = [ [ 'default', 0 ], [ 'file', 1 ], [ 'memory', 2 ] ]
-
-
# Does an integrity check on the database. If the check fails, a
-
# SQLite3::Exception will be raised. Otherwise it
-
# returns silently.
-
2
def integrity_check
-
execute( "PRAGMA integrity_check" ) do |row|
-
raise Exception, row[0] if row[0] != "ok"
-
end
-
end
-
-
2
def auto_vacuum
-
get_boolean_pragma "auto_vacuum"
-
end
-
-
2
def auto_vacuum=( mode )
-
set_boolean_pragma "auto_vacuum", mode
-
end
-
-
2
def schema_cookie
-
get_int_pragma "schema_cookie"
-
end
-
-
2
def schema_cookie=( cookie )
-
set_int_pragma "schema_cookie", cookie
-
end
-
-
2
def user_cookie
-
get_int_pragma "user_cookie"
-
end
-
-
2
def user_cookie=( cookie )
-
set_int_pragma "user_cookie", cookie
-
end
-
-
2
def cache_size
-
get_int_pragma "cache_size"
-
end
-
-
2
def cache_size=( size )
-
set_int_pragma "cache_size", size
-
end
-
-
2
def default_cache_size
-
get_int_pragma "default_cache_size"
-
end
-
-
2
def default_cache_size=( size )
-
set_int_pragma "default_cache_size", size
-
end
-
-
2
def default_synchronous
-
get_enum_pragma "default_synchronous"
-
end
-
-
2
def default_synchronous=( mode )
-
set_enum_pragma "default_synchronous", mode, SYNCHRONOUS_MODES
-
end
-
-
2
def synchronous
-
get_enum_pragma "synchronous"
-
end
-
-
2
def synchronous=( mode )
-
set_enum_pragma "synchronous", mode, SYNCHRONOUS_MODES
-
end
-
-
2
def default_temp_store
-
get_enum_pragma "default_temp_store"
-
end
-
-
2
def default_temp_store=( mode )
-
set_enum_pragma "default_temp_store", mode, TEMP_STORE_MODES
-
end
-
-
2
def temp_store
-
get_enum_pragma "temp_store"
-
end
-
-
2
def temp_store=( mode )
-
set_enum_pragma "temp_store", mode, TEMP_STORE_MODES
-
end
-
-
2
def full_column_names
-
get_boolean_pragma "full_column_names"
-
end
-
-
2
def full_column_names=( mode )
-
set_boolean_pragma "full_column_names", mode
-
end
-
-
2
def parser_trace
-
get_boolean_pragma "parser_trace"
-
end
-
-
2
def parser_trace=( mode )
-
set_boolean_pragma "parser_trace", mode
-
end
-
-
2
def vdbe_trace
-
get_boolean_pragma "vdbe_trace"
-
end
-
-
2
def vdbe_trace=( mode )
-
set_boolean_pragma "vdbe_trace", mode
-
end
-
-
2
def database_list( &block ) # :yields: row
-
get_query_pragma "database_list", &block
-
end
-
-
2
def foreign_key_list( table, &block ) # :yields: row
-
get_query_pragma "foreign_key_list", table, &block
-
end
-
-
2
def index_info( index, &block ) # :yields: row
-
get_query_pragma "index_info", index, &block
-
end
-
-
2
def index_list( table, &block ) # :yields: row
-
get_query_pragma "index_list", table, &block
-
end
-
-
###
-
# Returns information about +table+. Yields each row of table information
-
# if a block is provided.
-
2
def table_info table
-
stmt = prepare "PRAGMA table_info(#{table})"
-
columns = stmt.columns
-
-
needs_tweak_default =
-
version_compare(SQLite3.libversion.to_s, "3.3.7") > 0
-
-
result = [] unless block_given?
-
stmt.each do |row|
-
new_row = Hash[columns.zip(row)]
-
-
# FIXME: This should be removed but is required for older versions
-
# of rails
-
if(Object.const_defined?(:ActiveRecord))
-
new_row['notnull'] = new_row['notnull'].to_s
-
end
-
-
tweak_default(new_row) if needs_tweak_default
-
-
if block_given?
-
yield new_row
-
else
-
result << new_row
-
end
-
end
-
stmt.close
-
-
result
-
end
-
-
2
private
-
-
# Compares two version strings
-
2
def version_compare(v1, v2)
-
v1 = v1.split(".").map { |i| i.to_i }
-
v2 = v2.split(".").map { |i| i.to_i }
-
parts = [v1.length, v2.length].max
-
v1.push 0 while v1.length < parts
-
v2.push 0 while v2.length < parts
-
v1.zip(v2).each do |a,b|
-
return -1 if a < b
-
return 1 if a > b
-
end
-
return 0
-
end
-
-
# Since SQLite 3.3.8, the table_info pragma has returned the default
-
# value of the row as a quoted SQL value. This method essentially
-
# unquotes those values.
-
2
def tweak_default(hash)
-
case hash["dflt_value"]
-
when /^null$/i
-
hash["dflt_value"] = nil
-
when /^'(.*)'$/
-
hash["dflt_value"] = $1.gsub(/''/, "'")
-
when /^"(.*)"$/
-
hash["dflt_value"] = $1.gsub(/""/, '"')
-
end
-
end
-
end
-
-
end
-
2
require 'sqlite3/constants'
-
2
require 'sqlite3/errors'
-
-
2
module SQLite3
-
-
# The ResultSet object encapsulates the enumerability of a query's output.
-
# It is a simple cursor over the data that the query returns. It will
-
# very rarely (if ever) be instantiated directly. Instead, client's should
-
# obtain a ResultSet instance via Statement#execute.
-
2
class ResultSet
-
2
include Enumerable
-
-
2
class ArrayWithTypes < Array # :nodoc:
-
2
attr_accessor :types
-
end
-
-
2
class ArrayWithTypesAndFields < Array # :nodoc:
-
2
attr_writer :types
-
2
attr_writer :fields
-
-
2
def types
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling #{self.class}#types. This method will be removed in
-
sqlite3 version 2.0.0, please call the `types` method on the SQLite3::ResultSet
-
object that created this object
-
eowarn
-
@types
-
end
-
-
2
def fields
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling #{self.class}#fields. This method will be removed in
-
sqlite3 version 2.0.0, please call the `columns` method on the SQLite3::ResultSet
-
object that created this object
-
eowarn
-
@fields
-
end
-
end
-
-
# The class of which we return an object in case we want a Hash as
-
# result.
-
2
class HashWithTypesAndFields < Hash # :nodoc:
-
2
attr_writer :types
-
2
attr_writer :fields
-
-
2
def types
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling #{self.class}#types. This method will be removed in
-
sqlite3 version 2.0.0, please call the `types` method on the SQLite3::ResultSet
-
object that created this object
-
eowarn
-
@types
-
end
-
-
2
def fields
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling #{self.class}#fields. This method will be removed in
-
sqlite3 version 2.0.0, please call the `columns` method on the SQLite3::ResultSet
-
object that created this object
-
eowarn
-
@fields
-
end
-
-
2
def [] key
-
key = fields[key] if key.is_a? Numeric
-
super key
-
end
-
end
-
-
# Create a new ResultSet attached to the given database, using the
-
# given sql text.
-
2
def initialize db, stmt
-
@db = db
-
@stmt = stmt
-
end
-
-
# Reset the cursor, so that a result set which has reached end-of-file
-
# can be rewound and reiterated.
-
2
def reset( *bind_params )
-
@stmt.reset!
-
@stmt.bind_params( *bind_params )
-
@eof = false
-
end
-
-
# Query whether the cursor has reached the end of the result set or not.
-
2
def eof?
-
@stmt.done?
-
end
-
-
# Obtain the next row from the cursor. If there are no more rows to be
-
# had, this will return +nil+. If type translation is active on the
-
# corresponding database, the values in the row will be translated
-
# according to their types.
-
#
-
# The returned value will be an array, unless Database#results_as_hash has
-
# been set to +true+, in which case the returned value will be a hash.
-
#
-
# For arrays, the column names are accessible via the +fields+ property,
-
# and the column types are accessible via the +types+ property.
-
#
-
# For hashes, the column names are the keys of the hash, and the column
-
# types are accessible via the +types+ property.
-
2
def next
-
if @db.results_as_hash
-
return next_hash
-
end
-
-
row = @stmt.step
-
return nil if @stmt.done?
-
-
if @db.type_translation
-
row = @stmt.types.zip(row).map do |type, value|
-
@db.translator.translate( type, value )
-
end
-
end
-
-
if row.respond_to?(:fields)
-
# FIXME: this can only happen if the translator returns something
-
# that responds to `fields`. Since we're removing the translator
-
# in 2.0, we can remove this branch in 2.0.
-
row = ArrayWithTypes.new(row)
-
else
-
# FIXME: the `fields` and `types` methods are deprecated on this
-
# object for version 2.0, so we can safely remove this branch
-
# as well.
-
row = ArrayWithTypesAndFields.new(row)
-
end
-
-
row.fields = @stmt.columns
-
row.types = @stmt.types
-
row
-
end
-
-
# Required by the Enumerable mixin. Provides an internal iterator over the
-
# rows of the result set.
-
2
def each
-
while node = self.next
-
yield node
-
end
-
end
-
-
# Provides an internal iterator over the rows of the result set where
-
# each row is yielded as a hash.
-
2
def each_hash
-
while node = next_hash
-
yield node
-
end
-
end
-
-
# Closes the statement that spawned this result set.
-
# <em>Use with caution!</em> Closing a result set will automatically
-
# close any other result sets that were spawned from the same statement.
-
2
def close
-
@stmt.close
-
end
-
-
# Queries whether the underlying statement has been closed or not.
-
2
def closed?
-
@stmt.closed?
-
end
-
-
# Returns the types of the columns returned by this result set.
-
2
def types
-
@stmt.types
-
end
-
-
# Returns the names of the columns returned by this result set.
-
2
def columns
-
@stmt.columns
-
end
-
-
# Return the next row as a hash
-
2
def next_hash
-
row = @stmt.step
-
return nil if @stmt.done?
-
-
# FIXME: type translation is deprecated, so this can be removed
-
# in 2.0
-
if @db.type_translation
-
row = @stmt.types.zip(row).map do |type, value|
-
@db.translator.translate( type, value )
-
end
-
end
-
-
# FIXME: this can be switched to a regular hash in 2.0
-
row = HashWithTypesAndFields[*@stmt.columns.zip(row).flatten]
-
-
# FIXME: these methods are deprecated for version 2.0, so we can remove
-
# this code in 2.0
-
row.fields = @stmt.columns
-
row.types = @stmt.types
-
row
-
end
-
end
-
end
-
2
require 'sqlite3/errors'
-
2
require 'sqlite3/resultset'
-
-
2
class String
-
2
def to_blob
-
SQLite3::Blob.new( self )
-
end
-
end
-
-
2
module SQLite3
-
# A statement represents a prepared-but-unexecuted SQL query. It will rarely
-
# (if ever) be instantiated directly by a client, and is most often obtained
-
# via the Database#prepare method.
-
2
class Statement
-
2
include Enumerable
-
-
# This is any text that followed the first valid SQL statement in the text
-
# with which the statement was initialized. If there was no trailing text,
-
# this will be the empty string.
-
2
attr_reader :remainder
-
-
# Binds the given variables to the corresponding placeholders in the SQL
-
# text.
-
#
-
# See Database#execute for a description of the valid placeholder
-
# syntaxes.
-
#
-
# Example:
-
#
-
# stmt = db.prepare( "select * from table where a=? and b=?" )
-
# stmt.bind_params( 15, "hello" )
-
#
-
# See also #execute, #bind_param, Statement#bind_param, and
-
# Statement#bind_params.
-
2
def bind_params( *bind_vars )
-
1088
index = 1
-
1088
bind_vars.flatten.each do |var|
-
3590
if Hash === var
-
var.each { |key, val| bind_param key, val }
-
else
-
3590
bind_param index, var
-
3590
index += 1
-
end
-
end
-
end
-
-
# Execute the statement. This creates a new ResultSet object for the
-
# statement's virtual machine. If a block was given, the new ResultSet will
-
# be yielded to it; otherwise, the ResultSet will be returned.
-
#
-
# Any parameters will be bound to the statement using #bind_params.
-
#
-
# Example:
-
#
-
# stmt = db.prepare( "select * from table" )
-
# stmt.execute do |result|
-
# ...
-
# end
-
#
-
# See also #bind_params, #execute!.
-
2
def execute( *bind_vars )
-
reset! if active? || done?
-
-
bind_params(*bind_vars) unless bind_vars.empty?
-
@results = ResultSet.new(@connection, self)
-
-
step if 0 == column_count
-
-
yield @results if block_given?
-
@results
-
end
-
-
# Execute the statement. If no block was given, this returns an array of
-
# rows returned by executing the statement. Otherwise, each row will be
-
# yielded to the block.
-
#
-
# Any parameters will be bound to the statement using #bind_params.
-
#
-
# Example:
-
#
-
# stmt = db.prepare( "select * from table" )
-
# stmt.execute! do |row|
-
# ...
-
# end
-
#
-
# See also #bind_params, #execute.
-
2
def execute!( *bind_vars, &block )
-
execute(*bind_vars)
-
block_given? ? each(&block) : to_a
-
end
-
-
# Returns true if the statement is currently active, meaning it has an
-
# open result set.
-
2
def active?
-
!done?
-
end
-
-
# Return an array of the column names for this statement. Note that this
-
# may execute the statement in order to obtain the metadata; this makes it
-
# a (potentially) expensive operation.
-
2
def columns
-
1546
get_metadata unless @columns
-
1546
return @columns
-
end
-
-
2
def each
-
1989
loop do
-
3105
val = step
-
3105
break self if done?
-
1116
yield val
-
end
-
end
-
-
# Return an array of the data types for each column in this statement. Note
-
# that this may execute the statement in order to obtain the metadata; this
-
# makes it a (potentially) expensive operation.
-
2
def types
-
must_be_open!
-
get_metadata unless @types
-
@types
-
end
-
-
# Performs a sanity check to ensure that the statement is not
-
# closed. If it is, an exception is raised.
-
2
def must_be_open! # :nodoc:
-
if closed?
-
raise SQLite3::Exception, "cannot use a closed statement"
-
end
-
end
-
-
2
private
-
# A convenience method for obtaining the metadata about the query. Note
-
# that this will actually execute the SQL, which means it can be a
-
# (potentially) expensive operation.
-
2
def get_metadata
-
1546
@columns = Array.new(column_count) do |column|
-
8223
column_name column
-
end
-
1546
@types = Array.new(column_count) do |column|
-
8223
column_decltype column
-
end
-
end
-
end
-
end
-
2
require 'time'
-
2
require 'date'
-
-
2
module SQLite3
-
-
# The Translator class encapsulates the logic and callbacks necessary for
-
# converting string data to a value of some specified type. Every Database
-
# instance may have a Translator instance, in order to assist in type
-
# translation (Database#type_translation).
-
#
-
# Further, applications may define their own custom type translation logic
-
# by registering translator blocks with the corresponding database's
-
# translator instance (Database#translator).
-
2
class Translator
-
-
# Create a new Translator instance. It will be preinitialized with default
-
# translators for most SQL data types.
-
2
def initialize
-
@translators = Hash.new( proc { |type,value| value } )
-
@type_name_cache = {}
-
register_default_translators
-
end
-
-
# Add a new translator block, which will be invoked to process type
-
# translations to the given type. The type should be an SQL datatype, and
-
# may include parentheses (i.e., "VARCHAR(30)"). However, any parenthetical
-
# information is stripped off and discarded, so type translation decisions
-
# are made solely on the "base" type name.
-
#
-
# The translator block itself should accept two parameters, "type" and
-
# "value". In this case, the "type" is the full type name (including
-
# parentheses), so the block itself may include logic for changing how a
-
# type is translated based on the additional data. The "value" parameter
-
# is the (string) data to convert.
-
#
-
# The block should return the translated value.
-
2
def add_translator( type, &block ) # :yields: type, value
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]} is calling `add_translator`.
-
Built in translators are deprecated and will be removed in version 2.0.0
-
eowarn
-
@translators[ type_name( type ) ] = block
-
end
-
-
# Translate the given string value to a value of the given type. In the
-
# absense of an installed translator block for the given type, the value
-
# itself is always returned. Further, +nil+ values are never translated,
-
# and are always passed straight through regardless of the type parameter.
-
2
def translate( type, value )
-
unless value.nil?
-
# FIXME: this is a hack to support Sequel
-
if type && %w{ datetime timestamp }.include?(type.downcase)
-
@translators[ type_name( type ) ].call( type, value.to_s )
-
else
-
@translators[ type_name( type ) ].call( type, value )
-
end
-
end
-
end
-
-
# A convenience method for working with type names. This returns the "base"
-
# type name, without any parenthetical data.
-
2
def type_name( type )
-
@type_name_cache[type] ||= begin
-
type = "" if type.nil?
-
type = $1 if type =~ /^(.*?)\(/
-
type.upcase
-
end
-
end
-
2
private :type_name
-
-
# Register the default translators for the current Translator instance.
-
# This includes translators for most major SQL data types.
-
2
def register_default_translators
-
[ "time",
-
"timestamp" ].each { |type| add_translator( type ) { |t, v| Time.parse( v ) } }
-
-
add_translator( "date" ) { |t,v| Date.parse(v) }
-
add_translator( "datetime" ) { |t,v| DateTime.parse(v) }
-
-
[ "decimal",
-
"float",
-
"numeric",
-
"double",
-
"real",
-
"dec",
-
"fixed" ].each { |type| add_translator( type ) { |t,v| v.to_f } }
-
-
[ "integer",
-
"smallint",
-
"mediumint",
-
"int",
-
"bigint" ].each { |type| add_translator( type ) { |t,v| v.to_i } }
-
-
[ "bit",
-
"bool",
-
"boolean" ].each do |type|
-
add_translator( type ) do |t,v|
-
!( v.strip.gsub(/00+/,"0") == "0" ||
-
v.downcase == "false" ||
-
v.downcase == "f" ||
-
v.downcase == "no" ||
-
v.downcase == "n" )
-
end
-
end
-
-
add_translator( "tinyint" ) do |type, value|
-
if type =~ /\(\s*1\s*\)/
-
value.to_i == 1
-
else
-
value.to_i
-
end
-
end
-
end
-
2
private :register_default_translators
-
-
end
-
-
end
-
2
require 'sqlite3/constants'
-
-
2
module SQLite3
-
-
2
class Value
-
2
attr_reader :handle
-
-
2
def initialize( db, handle )
-
@driver = db.driver
-
@handle = handle
-
end
-
-
2
def null?
-
type == :null
-
end
-
-
2
def to_blob
-
@driver.value_blob( @handle )
-
end
-
-
2
def length( utf16=false )
-
if utf16
-
@driver.value_bytes16( @handle )
-
else
-
@driver.value_bytes( @handle )
-
end
-
end
-
-
2
def to_f
-
@driver.value_double( @handle )
-
end
-
-
2
def to_i
-
@driver.value_int( @handle )
-
end
-
-
2
def to_int64
-
@driver.value_int64( @handle )
-
end
-
-
2
def to_s( utf16=false )
-
@driver.value_text( @handle, utf16 )
-
end
-
-
2
def type
-
case @driver.value_type( @handle )
-
when Constants::ColumnType::INTEGER then :int
-
when Constants::ColumnType::FLOAT then :float
-
when Constants::ColumnType::TEXT then :text
-
when Constants::ColumnType::BLOB then :blob
-
when Constants::ColumnType::NULL then :null
-
end
-
end
-
-
end
-
-
end
-
2
module SQLite3
-
-
2
VERSION = '1.3.8'
-
-
2
module VersionProxy
-
-
2
MAJOR = 1
-
2
MINOR = 3
-
2
TINY = 8
-
2
BUILD = nil
-
-
2
STRING = [ MAJOR, MINOR, TINY, BUILD ].compact.join( "." )
-
#:beta-tag:
-
-
2
VERSION = ::SQLite3::VERSION
-
end
-
-
2
def self.const_missing(name)
-
return super unless name == :Version
-
warn(<<-eowarn) if $VERBOSE
-
#{caller[0]}: SQLite::Version will be removed in sqlite3-ruby version 2.0.0
-
eowarn
-
VersionProxy
-
end
-
end
-
2
require "v8/version"
-
-
2
require 'v8/weak'
-
2
require 'v8/init'
-
2
require 'v8/error'
-
2
require 'v8/stack'
-
2
require 'v8/conversion/fundamental'
-
2
require 'v8/conversion/indentity'
-
2
require 'v8/conversion/reference'
-
2
require 'v8/conversion/primitive'
-
2
require 'v8/conversion/code'
-
2
require 'v8/conversion/class'
-
2
require 'v8/conversion/object'
-
2
require 'v8/conversion/time'
-
2
require 'v8/conversion/hash'
-
2
require 'v8/conversion/array'
-
2
require 'v8/conversion/proc'
-
2
require 'v8/conversion/method'
-
2
require 'v8/conversion/symbol'
-
2
require 'v8/conversion/string'
-
2
require 'v8/conversion/fixnum'
-
2
require 'v8/conversion'
-
2
require 'v8/access/names'
-
2
require 'v8/access/indices'
-
2
require 'v8/access/invocation'
-
2
require 'v8/access'
-
2
require 'v8/context'
-
2
require 'v8/object'
-
2
require 'v8/array'
-
2
require 'v8/function'
-
2
class V8::Access
-
2
include Names
-
2
include Indices
-
2
include Invocation
-
end
-
2
class V8::Access
-
2
module Indices
-
-
2
def indices(obj)
-
obj.respond_to?(:length) ? (0..obj.length).to_a : []
-
end
-
-
2
def iget(obj, index, &dontintercept)
-
if obj.respond_to?(:[])
-
obj.send(:[], index, &dontintercept)
-
else
-
yield
-
end
-
end
-
-
2
def iset(obj, index, value, &dontintercept)
-
if obj.respond_to?(:[]=)
-
obj.send(:[]=, index, value, &dontintercept)
-
else
-
yield
-
end
-
end
-
-
2
def iquery(obj, index, attributes, &dontintercept)
-
if obj.respond_to?(:[])
-
attributes.dont_delete
-
unless obj.respond_to?(:[]=)
-
attributes.read_only
-
end
-
else
-
yield
-
end
-
end
-
-
2
def idelete(obj, index, &dontintercept)
-
yield
-
end
-
-
end
-
end
-
2
class V8::Access
-
2
module Invocation
-
2
def methodcall(code, this, args)
-
158
code.methodcall this, args
-
end
-
-
2
module Aritize
-
2
def aritize(args)
-
158
arity < 0 ? args : Array.new(arity).to_enum(:each_with_index).map {|item, i| args[i]}
-
end
-
end
-
-
2
module Proc
-
2
include Aritize
-
2
def methodcall(this, args)
-
158
call *aritize([this].concat(args))
-
end
-
2
::Proc.send :include, self
-
end
-
-
2
module Method
-
2
include Aritize
-
2
def methodcall(this, args)
-
context = V8::Context.current
-
access = context.access
-
if this.equal? self.receiver
-
call *aritize(args)
-
elsif this.class <= self.receiver.class
-
access.methodcall(unbind, this, args)
-
elsif this.equal? context.scope
-
call *aritize(args)
-
else
-
fail TypeError, "cannot invoke #{self} on #{this}"
-
end
-
end
-
2
::Method.send :include, self
-
end
-
-
2
module UnboundMethod
-
2
def methodcall(this, args)
-
access = V8::Context.current.access
-
access.methodcall bind(this), this, args
-
end
-
2
::UnboundMethod.send :include, self
-
end
-
end
-
end
-
2
require 'set'
-
2
class V8::Access
-
2
module Names
-
2
def names(obj)
-
accessible_names(obj)
-
end
-
-
2
def get(obj, name, &dontintercept)
-
methods = accessible_names(obj)
-
if methods.include?(name)
-
method = obj.method(name)
-
method.arity == 0 ? method.call : method.unbind
-
elsif obj.respond_to?(:[]) && !special?(name)
-
obj.send(:[], name, &dontintercept)
-
else
-
yield
-
end
-
end
-
-
2
def set(obj, name, value, &dontintercept)
-
setter = name + "="
-
methods = accessible_names(obj, true)
-
if methods.include?(setter)
-
obj.send(setter, value)
-
elsif obj.respond_to?(:[]=) && !special?(name)
-
obj.send(:[]=, name, value, &dontintercept)
-
else
-
yield
-
end
-
end
-
-
2
def query(obj, name, attributes, &dontintercept)
-
if obj.respond_to?(name)
-
attributes.dont_delete
-
unless obj.respond_to?(name + "=")
-
attributes.read_only
-
end
-
else
-
yield
-
end
-
end
-
-
2
def delete(obj, name, &dontintercept)
-
yield
-
end
-
-
2
def accessible_names(obj, special_methods = false)
-
obj.public_methods(false).map {|m| m.to_s}.to_set.tap do |methods|
-
ancestors = obj.class.ancestors.dup
-
while ancestor = ancestors.shift
-
break if ancestor == ::Object
-
methods.merge(ancestor.public_instance_methods(false).map {|m| m.to_s})
-
end
-
methods.reject!(&special?) unless special_methods
-
end
-
end
-
-
2
private
-
-
2
def special?(name = nil)
-
@special ||= lambda {|m| m == "[]" || m == "[]=" || m =~ /=$/}
-
name.nil? ? @special : @special[name]
-
end
-
end
-
end
-
2
class V8::Array < V8::Object
-
-
2
def initialize(native_or_length = nil)
-
super do
-
if native_or_length.is_a?(Numeric)
-
V8::C::Array::New(native_or_length)
-
elsif native_or_length.is_a?(V8::C::Array)
-
native_or_length
-
else
-
V8::C::Array::New()
-
end
-
end
-
end
-
-
2
def each
-
@context.enter do
-
0.upto(@native.Length() - 1) do |i|
-
yield @context.to_ruby(@native.Get(i))
-
end
-
end
-
end
-
-
2
def length
-
@native.Length()
-
end
-
end
-
2
require 'stringio'
-
2
module V8
-
# All JavaScript must be executed in a context. This context consists of a global scope containing the
-
# standard JavaScript objects¨and functions like Object, String, Array, as well as any objects or
-
# functions from Ruby which have been embedded into it from the containing enviroment. E.g.
-
#
-
# V8::Context.new do |cxt|
-
# cxt['num'] = 5
-
# cxt.eval('num + 5') #=> 10
-
# end
-
#
-
# The same object may appear in any number of contexts, but only one context may be executing JavaScript code
-
# in any given thread. If a new context is opened in a thread in which a context is already opened, the second
-
# context will "mask" the old context e.g.
-
#
-
# six = 6
-
# Context.new do |cxt|
-
# cxt['num'] = 5
-
# cxt.eval('num') # => 5
-
# Context.new do |cxt|
-
# cxt['num'] = 10
-
# cxt.eval('num') # => 10
-
# cxt.eval('++num') # => 11
-
# end
-
# cxt.eval('num') # => 5
-
# end
-
2
class Context
-
2
include V8::Error::Try
-
-
# @!attribute [r] conversion
-
# @return [V8::Conversion] conversion behavior for this context
-
2
attr_reader :conversion
-
-
# @!attrribute [r] access
-
# @return [V8::Access] Ruby access behavior for this context
-
2
attr_reader :access
-
-
# @!attribute [r] native
-
# @return [V8::C::Context] the underlying C++ object
-
2
attr_reader :native
-
-
# Creates a new context.
-
#
-
# If passed the `:with` option, that object will be used as
-
# the global scope of the newly creating context. e.g.
-
#
-
# scope = Object.new
-
# def scope.hello; "Hi"; end
-
# V8::Context.new(:with => scope) do |cxt|
-
# cxt['hello'] #=> 'Hi'
-
# end
-
#
-
# @param [Hash<Symbol, Object>] options initial context configuration
-
# * :with scope serves as the global scope of the new context
-
# @yield [V8::Context] the newly created context
-
2
def initialize(options = {})
-
2
@conversion = Conversion.new
-
2
@access = Access.new
-
2
if global = options[:with]
-
Context.new.enter do
-
global_template = global.class.to_template.InstanceTemplate()
-
@native = V8::C::Context::New(nil, global_template)
-
end
-
enter {link global, @native.Global()}
-
else
-
2
V8::C::Locker() do
-
2
@native = V8::C::Context::New()
-
end
-
end
-
2
yield self if block_given?
-
end
-
-
# Compile and execute a string of JavaScript source.
-
#
-
# If `source` is an IO object it will be read fully before being evaluated
-
#
-
# @param [String,IO] source the source code to compile and execute
-
# @param [String] filename the name to use for this code when generating stack traces
-
# @param [Integer] line the line number to start with
-
# @return [Object] the result of the evaluation
-
2
def eval(source, filename = '<eval>', line = 1)
-
76
if IO === source || StringIO === source
-
source = source.read
-
end
-
76
enter do
-
152
script = try { V8::C::Script::New(source.to_s, filename.to_s) }
-
152
to_ruby try {script.Run()}
-
end
-
end
-
-
# Read a value from the global scope of this context
-
#
-
# @param [Object] key the name of the value to read
-
# @return [Object] value the value at `key`
-
2
def [](key)
-
76
enter do
-
76
to_ruby(@native.Global().Get(to_v8(key)))
-
end
-
end
-
-
# Binds `value` to the name `key` in the global scope of this context.
-
#
-
# @param [Object] key the name to bind to
-
# @param [Object] value the value to bind
-
2
def []=(key, value)
-
4
enter do
-
4
@native.Global().Set(to_v8(key), to_v8(value))
-
end
-
4
return value
-
end
-
-
# Destroy this context and release any internal references it may
-
# contain to embedded Ruby objects.
-
#
-
# A disposed context may never again be used for anything, and all
-
# objects created with it will become unusable.
-
2
def dispose
-
return unless @native
-
@native.Dispose()
-
@native = nil
-
V8::C::V8::ContextDisposedNotification()
-
def self.enter
-
fail "cannot enter a context which has already been disposed"
-
end
-
end
-
-
# Returns this context's global object. This will be a `V8::Object`
-
# if no scope was provided or just an `Object` if a Ruby object
-
# is serving as the global scope.
-
#
-
# @return [Object] scope the context's global scope.
-
2
def scope
-
enter { to_ruby @native.Global() }
-
end
-
-
# Converts a v8 C++ object into its ruby counterpart. This is method
-
# is used to translate all values passed to Ruby from JavaScript, either
-
# as return values or as callback parameters.
-
#
-
# @param [V8::C::Object] v8_object the native c++ object to convert.
-
# @return [Object] to pass to Ruby
-
# @see V8::Conversion for how to customize and extend this mechanism
-
2
def to_ruby(v8_object)
-
680
@conversion.to_ruby(v8_object)
-
end
-
-
# Converts a Ruby object into a native v8 C++ object. This method is
-
# used to translate all values passed to JavaScript from Ruby, either
-
# as return value or as callback parameters.
-
#
-
# @param [Object] ruby_object the Ruby object to convert
-
# @return [V8::C::Object] to pass to V8
-
# @see V8::Conversion for customizing and extending this mechanism
-
2
def to_v8(ruby_object)
-
754
@conversion.to_v8(ruby_object)
-
end
-
-
# Marks a Ruby object and a v8 C++ Object as being the same. In other
-
# words whenever `ruby_object` is passed to v8, the result of the
-
# conversion should be `v8_object`. Conversely, whenever `v8_object`
-
# is passed to Ruby, the result of the conversion should be `ruby_object`.
-
# The Ruby Racer uses this mechanism to maintain referential integrity
-
# between Ruby and JavaScript peers
-
#
-
# @param [Object] ruby_object the Ruby half of the object identity
-
# @param [V8::C::Object] v8_object the V8 half of the object identity.
-
# @see V8::Conversion::Identity
-
2
def link(ruby_object, v8_object)
-
360
@conversion.equate ruby_object, v8_object
-
end
-
-
# Links `ruby_object` and `v8_object` inside the currently entered
-
# context. This is an error if no context has been entered.
-
#
-
# @param [Object] ruby_object the Ruby half of the object identity
-
# @param [V8::C::Object] v8_object the V8 half of the object identity.
-
2
def self.link(ruby_object, v8_object)
-
114
current.link ruby_object, v8_object
-
end
-
-
# Run some Ruby code in the context of this context.
-
#
-
# This will acquire the V8 interpreter lock (possibly blocking
-
# until it is available), and prepare V8 for JavaScript execution.
-
#
-
# Only one context may be running at a time per thread.
-
#
-
# @return [Object] the result of executing `block`
-
2
def enter(&block)
-
474
if !entered?
-
102
lock_scope_and_enter(&block)
-
else
-
372
yield
-
end
-
end
-
-
# Indicates if this context is the currently entered context
-
#
-
# @return true if this context is currently entered
-
2
def entered?
-
474
Context.current == self
-
end
-
-
# Get the currently entered context.
-
#
-
# @return [V8::Context] currently entered context, nil if none entered.
-
2
def self.current
-
1182
Thread.current[:v8_context]
-
end
-
-
# Compile and execute the contents of the file with path `filename`
-
# as JavaScript code.
-
#
-
# @param [String] filename path to the file to execute.
-
# @return [Object] the result of the evaluation.
-
2
def load(filename)
-
File.open(filename) do |file|
-
self.eval file, filename
-
end
-
end
-
-
2
private
-
-
2
def self.current=(context)
-
204
Thread.current[:v8_context] = context
-
end
-
-
2
def lock_scope_and_enter
-
102
current = Context.current
-
102
Context.current = self
-
102
V8::C::Locker() do
-
102
V8::C::HandleScope() do
-
102
begin
-
102
@native.Enter()
-
102
yield if block_given?
-
ensure
-
102
@native.Exit()
-
end
-
end
-
end
-
ensure
-
102
Context.current = current
-
end
-
end
-
end
-
-
2
class V8::Conversion
-
2
include Fundamental
-
2
include Identity
-
-
2
def to_ruby(v8_object)
-
680
super v8_object
-
end
-
-
2
def to_v8(ruby_object)
-
754
super ruby_object
-
end
-
end
-
-
2
for type in [TrueClass, FalseClass, NilClass, Float] do
-
8
type.class_eval do
-
8
include V8::Conversion::Primitive
-
end
-
end
-
-
2
for type in [Class, Object, Array, Hash, String, Symbol, Time, Proc, Method, Fixnum] do
-
20
type.class_eval do
-
20
include V8::Conversion.const_get(type.name)
-
end
-
end
-
-
2
class UnboundMethod
-
2
include V8::Conversion::Method
-
end
-
-
2
for type in [:Object, :String, :Date] do
-
6
V8::C::const_get(type).class_eval do
-
6
include V8::Conversion::const_get("Native#{type}")
-
end
-
end
-
-
2
class V8::Conversion
-
2
module Array
-
2
def to_v8
-
array = V8::Array.new(length)
-
each_with_index do |item, i|
-
array[i] = item
-
end
-
return array.to_v8
-
end
-
end
-
end
-
2
class V8::Conversion
-
2
module Class
-
2
include V8::Conversion::Code
-
-
2
def to_template
-
8
weakcell(:constructor) do
-
8
template = V8::C::FunctionTemplate::New(V8::Conversion::Constructor.new(self))
-
8
prototype = template.InstanceTemplate()
-
8
prototype.SetNamedPropertyHandler(V8::Conversion::Get, V8::Conversion::Set)
-
8
prototype.SetIndexedPropertyHandler(V8::Conversion::IGet, V8::Conversion::ISet)
-
8
if self != ::Object && superclass != ::Object && superclass != ::Class
-
template.Inherit(superclass.to_template)
-
end
-
8
template
-
end
-
end
-
end
-
-
2
class Constructor
-
2
include V8::Error::Protect
-
-
2
def initialize(cls)
-
8
@class = cls
-
end
-
-
2
def call(arguments)
-
88
arguments.extend Args
-
88
protect do
-
88
if arguments.linkage_call?
-
88
arguments.link
-
else
-
arguments.construct @class
-
end
-
end
-
88
return arguments.This()
-
end
-
-
2
module Args
-
2
def linkage_call?
-
88
self.Length() == 1 && self[0].IsExternal()
-
end
-
-
2
def link
-
88
external = self[0]
-
88
This().SetHiddenValue("rr::implementation", external)
-
88
context.link external.Value(), This()
-
end
-
-
2
def construct(cls)
-
context.link cls.new(*to_args), This()
-
end
-
-
2
def context
-
88
V8::Context.current
-
end
-
-
2
def to_args
-
args = ::Array.new(Length())
-
0.upto(args.length - 1) do |i|
-
args[i] = self[i]
-
end
-
return args
-
end
-
end
-
end
-
-
2
module Accessor
-
2
include V8::Error::Protect
-
2
def intercept(info, key, &block)
-
context = V8::Context.current
-
access = context.access
-
object = context.to_ruby(info.This())
-
handles_property = true
-
dontintercept = proc do
-
handles_property = false
-
end
-
protect do
-
result = block.call(context, access, object, context.to_ruby(key), dontintercept)
-
handles_property ? context.to_v8(result) : V8::C::Value::Empty
-
end
-
end
-
end
-
-
2
class Get
-
2
extend Accessor
-
2
def self.call(property, info)
-
intercept(info, property) do |context, access, object, key, dontintercept|
-
access.get(object, key, &dontintercept)
-
end
-
end
-
end
-
-
2
class Set
-
2
extend Accessor
-
2
def self.call(property, value, info)
-
intercept(info, property) do |context, access, object, key, dontintercept|
-
access.set(object, key, context.to_ruby(value), &dontintercept)
-
end
-
end
-
end
-
-
2
class IGet
-
2
extend Accessor
-
2
def self.call(property, info)
-
intercept(info, property) do |context, access, object, key, dontintercept|
-
access.iget(object, key, &dontintercept)
-
end
-
end
-
end
-
-
2
class ISet
-
2
extend Accessor
-
2
def self.call(property, value, info)
-
intercept(info, property) do |context, access, object, key, dontintercept|
-
access.iset(object, key, context.to_ruby(value), &dontintercept)
-
end
-
end
-
end
-
end
-
2
class V8::Conversion
-
2
module Code
-
2
include V8::Weak::Cell
-
-
2
def to_v8
-
114
fn = to_template.GetFunction()
-
114
V8::Context.link self, fn
-
114
return fn
-
end
-
-
2
def to_template
-
212
weakcell(:template) {V8::C::FunctionTemplate::New(InvocationHandler.new(self))}
-
end
-
-
2
class InvocationHandler
-
2
include V8::Error::Protect
-
-
2
def initialize(code)
-
106
@code = code
-
end
-
-
2
def call(arguments)
-
158
protect do
-
158
context = V8::Context.current
-
158
access = context.access
-
158
args = ::Array.new(arguments.Length())
-
158
0.upto(args.length - 1) do |i|
-
158
if i < args.length
-
158
args[i] = context.to_ruby arguments[i]
-
end
-
end
-
158
this = context.to_ruby arguments.This()
-
158
context.to_v8 access.methodcall(@code, this, args)
-
end
-
end
-
end
-
end
-
end
-
2
class V8::Conversion
-
2
module Fixnum
-
2
def to_ruby
-
self
-
end
-
-
2
def to_v8
-
self.to_f.to_v8
-
end
-
end
-
end
-
2
class V8::Conversion
-
2
module Fundamental
-
2
def to_ruby(v8_object)
-
392
v8_object.to_ruby
-
end
-
-
2
def to_v8(ruby_object)
-
448
ruby_object.to_v8
-
end
-
end
-
end
-
2
class V8::Conversion
-
2
module Hash
-
2
def to_v8
-
object = V8::Object.new
-
each do |key, value|
-
object[key] = value
-
end
-
return object.to_v8
-
end
-
end
-
end
-
2
require 'ref'
-
-
2
class V8::Conversion
-
2
module Identity
-
2
def to_ruby(v8_object)
-
680
if v8_object.class <= V8::C::Object
-
446
v8_idmap[v8_object.GetIdentityHash()] || super(v8_object)
-
else
-
234
super(v8_object)
-
end
-
end
-
-
2
def to_v8(ruby_object)
-
754
return super(ruby_object) if ruby_object.is_a?(String) || ruby_object.is_a?(Primitive)
-
644
rb_idmap[ruby_object.object_id] || super(ruby_object)
-
end
-
-
2
def equate(ruby_object, v8_object)
-
360
v8_idmap[v8_object.GetIdentityHash()] = ruby_object
-
360
rb_idmap[ruby_object.object_id] = v8_object
-
end
-
-
2
def v8_idmap
-
806
@v8_idmap ||= V8::Weak::WeakValueMap.new
-
end
-
-
2
def rb_idmap
-
1004
@ruby_idmap ||= V8::Weak::WeakValueMap.new
-
end
-
end
-
end
-
2
class V8::Conversion
-
2
module Method
-
2
include V8::Conversion::Code
-
-
2
def to_v8
-
template = @@method_cache[self] ||= to_template
-
template.GetFunction()
-
end
-
-
2
class MethodCache
-
2
def initialize
-
2
@map = V8::Weak::WeakValueMap.new
-
end
-
-
2
def [](method)
-
@map[method.to_s]
-
end
-
-
2
def []=(method, template)
-
@map[method.to_s] = template
-
end
-
end
-
-
2
@@method_cache = MethodCache.new
-
end
-
end
-
2
class V8::Conversion
-
2
module Object
-
2
def to_v8
-
88
Reference.construct! self
-
end
-
-
2
def to_ruby
-
76
self
-
end
-
end
-
-
2
module NativeObject
-
2
def to_ruby
-
158
wrap = if IsArray()
-
::V8::Array
-
elsif IsFunction()
-
78
::V8::Function
-
else
-
80
::V8::Object
-
end
-
158
wrap.new(self)
-
end
-
-
2
def to_v8
-
76
self
-
end
-
end
-
end
-
2
class V8::Conversion
-
2
module Primitive
-
2
def to_v8
-
return self
-
end
-
end
-
end
-
2
class V8::Conversion
-
2
module Proc
-
2
include V8::Conversion::Code
-
end
-
end
-
2
class V8::Conversion
-
2
module Reference
-
-
2
def self.construct!(object)
-
88
context = V8::Context.current
-
88
constructor = context.to_v8(object.class)
-
88
reference = constructor.NewInstance([V8::C::External::New(object)])
-
88
return reference
-
end
-
-
2
def to_v8
-
Reference.construct! self
-
end
-
-
end
-
end
-
2
class V8::Conversion
-
2
module String
-
2
def to_v8
-
110
V8::C::String::New(self)
-
end
-
end
-
2
module NativeString
-
2
def to_ruby
-
158
self.Utf8Value()
-
end
-
end
-
end
-
2
class V8::Conversion
-
2
module Symbol
-
2
def to_v8
-
60
V8::C::String::NewSymbol(to_s)
-
end
-
end
-
end
-
2
class V8::Conversion
-
2
module Time
-
2
def to_v8
-
V8::C::Date::New(to_f * 1000)
-
end
-
end
-
-
2
module NativeDate
-
2
def to_ruby
-
::Time.at(self.NumberValue() / 1000)
-
end
-
end
-
end
-
2
module V8
-
# capture 99 stack frames on exception with normal details.
-
# You can adjust these values for performance or turn of stack capture entirely
-
2
V8::C::V8::SetCaptureStackTraceForUncaughtExceptions(true, 99, V8::C::StackTrace::kOverview)
-
2
class Error < StandardError
-
2
include Enumerable
-
-
# @!attribute [r] value
-
# @return [Object] the JavaScript value passed to the `throw` statement
-
2
attr_reader :value
-
-
# @!attribute [r] cause
-
# @return [Exception] the underlying error (if any) that triggered this error to be raised
-
2
attr_reader :cause
-
-
# @!attribute [r] javascript_backtrace
-
# @return [V8::StackTrace] the complete JavaScript stack at the point this error was thrown
-
2
attr_reader :javascript_backtrace
-
-
# keep an alias to the StandardError#backtrace method so that we can capture
-
# just ruby backtrace frames
-
2
alias_method :standard_error_backtrace, :backtrace
-
-
2
def initialize(message, value, javascript_backtrace, cause = nil)
-
super(message)
-
@value = value
-
@cause = cause
-
@javascript_backtrace = javascript_backtrace
-
end
-
-
2
def causes
-
[].tap do |causes|
-
current = self
-
until current.nil? do
-
causes.push current
-
current = current.respond_to?(:cause) ? current.cause : nil
-
end
-
end
-
end
-
-
2
def backtrace(*modifiers)
-
return unless super()
-
trace_framework = modifiers.include?(:framework)
-
trace_ruby = modifiers.length == 0 || modifiers.include?(:ruby)
-
trace_javascript = modifiers.length == 0 || modifiers.include?(:javascript)
-
bilingual_backtrace(trace_ruby, trace_javascript).tap do |trace|
-
trace.reject! {|frame| frame =~ %r{(lib/v8/.*\.rb|ext/v8/.*\.cc)}} unless modifiers.include?(:framework)
-
end
-
end
-
-
2
def root_cause
-
causes.last
-
end
-
-
2
def in_javascript?
-
causes.last.is_a? self.class
-
end
-
-
2
def in_ruby?
-
!in_javascript?
-
end
-
-
2
def bilingual_backtrace(trace_ruby = true, trace_javascript = true)
-
backtrace = causes.reduce(:backtrace => [], :ruby => -1, :javascript => -1) { |accumulator, cause|
-
accumulator.tap do
-
if trace_ruby
-
backtrace_selector = cause.respond_to?(:standard_error_backtrace) ? :standard_error_backtrace : :backtrace
-
ruby_frames = cause.send(backtrace_selector)[0..accumulator[:ruby]]
-
accumulator[:backtrace].unshift *ruby_frames
-
accumulator[:ruby] -= ruby_frames.length
-
end
-
if trace_javascript && cause.respond_to?(:javascript_backtrace)
-
javascript_frames = cause.javascript_backtrace.to_a[0..accumulator[:javascript]].map(&:to_s)
-
accumulator[:backtrace].unshift *javascript_frames
-
accumulator[:javascript] -= javascript_frames.length
-
end
-
end
-
}[:backtrace]
-
end
-
-
2
module Try
-
2
def try
-
304
V8::C::TryCatch() do |trycatch|
-
304
result = yield
-
304
if trycatch.HasCaught()
-
raise V8::Error(trycatch)
-
else
-
304
result
-
end
-
end
-
end
-
end
-
-
2
module Protect
-
2
def protect
-
246
yield
-
rescue Exception => e
-
error = V8::C::Exception::Error(e.message)
-
error.SetHiddenValue("rr::Cause", V8::C::External::New(e))
-
V8::C::ThrowException(error)
-
end
-
end
-
-
end
-
-
# Convert the result of a triggered JavaScript try/catch block into
-
# a V8::Error
-
#
-
# This is a bit of a yak-shave because JavaScript let's you throw all
-
# kinds of things. We do our best to make sure that the message property
-
# of the resulting V8::Error is as helpful as possible, and that it
-
# contains as much source location information as we can put onto it.
-
#
-
# For example:
-
#
-
# throw 4
-
# throw 'four'
-
# throw {number: 4}
-
#
-
# are all valid cases, none of which actually reference an exception object
-
# with a stack trace and a message. only with something like:
-
#
-
# throw new Error('fail!')
-
#
-
# do you get the a proper stacktrace and a message property. However a lot of
-
# times JavaScript library authors are lazy and do this:
-
#
-
# throw {message: 'foo', otherMetadata: 'bar'}
-
#
-
# It's common enough so we do the courtesy of having the resulting V8::Error
-
# have as its message in ruby land the 'message' property of the value object
-
#
-
# To further complicate things, SyntaxErrors do not have a JavaScript stack
-
# (even if they occur during js execution). This can make debugging a nightmare
-
# so we copy in the source location of the syntax error into the message of
-
# the resulting V8::Error
-
#
-
# @param [V8::C::TryCatch] native trycatch object that has been triggered
-
# @return [V8::Error] the error generated by this try/catch
-
2
def self.Error(trycatch)
-
exception = trycatch.Exception()
-
value = exception.to_ruby
-
cause = nil
-
javascript_backtrace = V8::StackTrace.new(trycatch.Message().GetStackTrace())
-
message = if !exception.kind_of?(V8::C::Value)
-
exception.to_s
-
elsif exception.IsNativeError()
-
if cause = exception.GetHiddenValue("rr::Cause")
-
cause = cause.Value()
-
end
-
if value['constructor'] == V8::Context.current['SyntaxError']
-
info = trycatch.Message()
-
resource_name = info.GetScriptResourceName().to_ruby
-
"#{value['message']} at #{resource_name}:#{info.GetLineNumber()}:#{info.GetStartColumn() + 1}"
-
else
-
exception.Get("message").to_ruby
-
end
-
elsif exception.IsObject()
-
value['message'] || value.to_s
-
else
-
value.to_s
-
end
-
V8::Error.new(message, value, javascript_backtrace, cause)
-
end
-
2
const_set :JSError, Error
-
end
-
2
class V8::Function < V8::Object
-
2
include V8::Error::Try
-
-
2
def initialize(native = nil)
-
78
super do
-
78
native || V8::C::FunctionTemplate::New().GetFunction()
-
end
-
end
-
-
2
def methodcall(this, *args)
-
76
@context.enter do
-
76
this ||= @context.native.Global()
-
380
@context.to_ruby try {native.Call(@context.to_v8(this), args.map {|a| @context.to_v8 a})}
-
end
-
end
-
-
2
def call(*args)
-
76
@context.enter do
-
76
methodcall @context.native.Global(), *args
-
end
-
end
-
-
2
def new(*args)
-
76
@context.enter do
-
152
@context.to_ruby try {native.NewInstance(args.map {|a| @context.to_v8 a})}
-
end
-
end
-
end
-
2
class V8::Object
-
2
include Enumerable
-
2
attr_reader :native
-
2
alias_method :to_v8, :native
-
-
2
def initialize(native = nil)
-
158
@context = V8::Context.current or fail "tried to initialize a #{self.class} without being in an entered V8::Context"
-
158
@native = block_given? ? yield : native || V8::C::Object::New()
-
158
@context.link self, @native
-
end
-
-
2
def [](key)
-
60
@context.enter do
-
60
@context.to_ruby @native.Get(@context.to_v8(key))
-
end
-
end
-
-
2
def []=(key, value)
-
30
@context.enter do
-
30
@native.Set(@context.to_v8(key), @context.to_v8(value))
-
end
-
30
return value
-
end
-
-
2
def keys
-
@context.enter do
-
names = @native.GetPropertyNames()
-
0.upto( names.Length() - 1).to_enum.map {|i| @context.to_ruby names.Get(i)}
-
end
-
end
-
-
2
def values
-
@context.enter do
-
names = @native.GetPropertyNames()
-
0.upto( names.Length() - 1).to_enum.map {|i| @context.to_ruby @native.Get(names.Get(i))}
-
end
-
end
-
-
2
def each
-
@context.enter do
-
names = @native.GetPropertyNames()
-
0.upto(names.Length() - 1) do |i|
-
name = names.Get(i)
-
yield @context.to_ruby(name), @context.to_ruby(@native.Get(name))
-
end
-
end
-
end
-
-
2
def to_s
-
@context.enter do
-
@context.to_ruby @native.ToString()
-
end
-
end
-
-
2
def respond_to?(method)
-
922
super or self[method] != nil
-
end
-
-
2
def method_missing(name, *args, &block)
-
30
if name.to_s =~ /(.*)=$/
-
if args.length > 1
-
self[$1] = args
-
return args
-
else
-
self[$1] = args.first
-
return args
-
end
-
end
-
30
return super(name, *args, &block) unless self.respond_to?(name)
-
30
property = self[name]
-
30
if property.kind_of?(V8::Function)
-
property.methodcall(self, *args)
-
30
elsif args.empty?
-
30
property
-
else
-
raise ArgumentError, "wrong number of arguments (#{args.length} for 0)" unless args.empty?
-
end
-
end
-
end
-
-
2
module V8
-
-
2
class StackTrace
-
2
include Enumerable
-
-
2
def initialize(native)
-
@context = V8::Context.current
-
@native = native
-
end
-
-
2
def length
-
@context.enter do
-
@native ? @native.GetFrameCount() : 0
-
end
-
end
-
-
2
def each
-
return unless @native
-
@context.enter do
-
for i in 0..length - 1
-
yield V8::StackFrame.new(@native.GetFrame(i), @context)
-
end
-
end
-
end
-
-
2
def to_s
-
@native ? map(&:to_s).join("\n") : ""
-
end
-
end
-
-
2
class StackFrame
-
-
2
def initialize(native, context)
-
@context = context
-
@native = native
-
end
-
-
2
def script_name
-
@context.enter do
-
@context.to_ruby(@native.GetScriptName())
-
end
-
end
-
-
2
def function_name
-
@context.enter do
-
@context.to_ruby(@native.GetFunctionName())
-
end
-
end
-
-
2
def line_number
-
@context.enter do
-
@native.GetLineNumber()
-
end
-
end
-
-
2
def column
-
@context.enter do
-
@native.GetColumn()
-
end
-
end
-
-
2
def eval?
-
@context.enter do
-
@native.IsEval()
-
end
-
end
-
-
2
def constructor?
-
@context.enter do
-
@native.IsConstructor()
-
end
-
end
-
-
2
def to_s
-
@context.enter do
-
"at " + if !function_name.empty?
-
"#{function_name} (#{script_name}:#{line_number}:#{column})"
-
else
-
"#{script_name}:#{line_number}:#{column}"
-
end
-
end
-
end
-
end
-
end
-
2
module V8
-
2
VERSION = "0.12.0"
-
end
-
2
module V8
-
2
module Weak
-
# weak refs are broken on MRI 1.9 and merely slow on 1.8
-
# so we mitigate this by using the 'ref' gem. However, this
-
# only mitigates the problem. Under heavy load, you will still
-
# get different or terminated objects being returned. bad stuff.
-
#
-
# If you are having problems with this, an upgrade to 2.0 is *highly*
-
# recommended.
-
#
-
# for other platforms we just use the stdlib 'weakref'
-
# implementation
-
2
if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'ruby' && RUBY_VERSION < '2.0.0'
-
2
require 'ref'
-
2
Ref = ::Ref::WeakReference
-
2
WeakValueMap = ::Ref::WeakValueMap
-
else
-
require 'weakref'
-
class Ref
-
def initialize(object)
-
@ref = ::WeakRef.new(object)
-
end
-
def object
-
@ref.__getobj__
-
rescue ::WeakRef::RefError
-
nil
-
end
-
end
-
-
class WeakValueMap
-
def initialize
-
@values = {}
-
end
-
-
def [](key)
-
if ref = @values[key]
-
ref.object
-
end
-
end
-
-
def []=(key, value)
-
@values[key] = V8::Weak::Ref.new(value)
-
end
-
end
-
end
-
-
2
module Cell
-
2
def weakcell(name, &block)
-
114
unless storage = instance_variable_get("@#{name}")
-
114
storage = instance_variable_set("@#{name}", Storage.new)
-
end
-
114
storage.access(&block)
-
end
-
2
class Storage
-
2
def access(&block)
-
114
if @ref
-
@ref.object || populate(block)
-
else
-
114
populate(block)
-
end
-
end
-
-
2
private
-
-
2
def populate(block)
-
114
occupant = block.call()
-
114
@ref = V8::Weak::Ref.new(occupant)
-
114
return occupant
-
end
-
end
-
end
-
end
-
end
-
2
module Tilt
-
2
VERSION = '1.4.1'
-
-
2
@preferred_mappings = Hash.new
-
64
@template_mappings = Hash.new { |h, k| h[k] = [] }
-
-
# Hash of template path pattern => template implementation class mappings.
-
2
def self.mappings
-
104
@template_mappings
-
end
-
-
2
def self.normalize(ext)
-
104
ext.to_s.downcase.sub(/^\./, '')
-
end
-
-
# Register a template implementation by file extension.
-
2
def self.register(template_class, *extensions)
-
58
if template_class.respond_to?(:to_str)
-
# Support register(ext, template_class) too
-
extensions, template_class = [template_class], extensions[0]
-
end
-
-
58
extensions.each do |ext|
-
104
ext = normalize(ext)
-
104
mappings[ext].unshift(template_class).uniq!
-
end
-
end
-
-
# Makes a template class preferred for the given file extensions. If you
-
# don't provide any extensions, it will be preferred for all its already
-
# registered extensions:
-
#
-
# # Prefer RDiscount for its registered file extensions:
-
# Tilt.prefer(Tilt::RDiscountTemplate)
-
#
-
# # Prefer RDiscount only for the .md extensions:
-
# Tilt.prefer(Tilt::RDiscountTemplate, '.md')
-
2
def self.prefer(template_class, *extensions)
-
if extensions.empty?
-
mappings.each do |ext, klasses|
-
@preferred_mappings[ext] = template_class if klasses.include? template_class
-
end
-
else
-
extensions.each do |ext|
-
ext = normalize(ext)
-
register(template_class, ext)
-
@preferred_mappings[ext] = template_class
-
end
-
end
-
end
-
-
# Returns true when a template exists on an exact match of the provided file extension
-
2
def self.registered?(ext)
-
mappings.key?(ext.downcase) && !mappings[ext.downcase].empty?
-
end
-
-
# Create a new template for the given file using the file's extension
-
# to determine the the template mapping.
-
2
def self.new(file, line=nil, options={}, &block)
-
if template_class = self[file]
-
template_class.new(file, line, options, &block)
-
else
-
fail "No template engine registered for #{File.basename(file)}"
-
end
-
end
-
-
# Lookup a template class for the given filename or file
-
# extension. Return nil when no implementation is found.
-
2
def self.[](file)
-
pattern = file.to_s.downcase
-
until pattern.empty? || registered?(pattern)
-
pattern = File.basename(pattern)
-
pattern.sub!(/^[^.]*\.?/, '')
-
end
-
-
# Try to find a preferred engine.
-
preferred_klass = @preferred_mappings[pattern]
-
return preferred_klass if preferred_klass
-
-
# Fall back to the general list of mappings.
-
klasses = @template_mappings[pattern]
-
-
# Try to find an engine which is already loaded.
-
template = klasses.detect do |klass|
-
if klass.respond_to?(:engine_initialized?)
-
klass.engine_initialized?
-
end
-
end
-
-
return template if template
-
-
# Try each of the classes until one succeeds. If all of them fails,
-
# we'll raise the error of the first class.
-
first_failure = nil
-
-
klasses.each do |klass|
-
begin
-
klass.new { '' }
-
rescue Exception => ex
-
first_failure ||= ex
-
next
-
else
-
return klass
-
end
-
end
-
-
raise first_failure if first_failure
-
end
-
-
# Deprecated module.
-
2
module CompileSite
-
end
-
-
# Extremely simple template cache implementation. Calling applications
-
# create a Tilt::Cache instance and use #fetch with any set of hashable
-
# arguments (such as those to Tilt.new):
-
# cache = Tilt::Cache.new
-
# cache.fetch(path, line, options) { Tilt.new(path, line, options) }
-
#
-
# Subsequent invocations return the already loaded template object.
-
2
class Cache
-
2
def initialize
-
@cache = {}
-
end
-
-
2
def fetch(*key)
-
@cache[key] ||= yield
-
end
-
-
2
def clear
-
@cache = {}
-
end
-
end
-
-
-
# Template Implementations ================================================
-
-
2
require 'tilt/string'
-
2
register StringTemplate, 'str'
-
-
2
require 'tilt/erb'
-
2
register ERBTemplate, 'erb', 'rhtml'
-
2
register ErubisTemplate, 'erb', 'rhtml', 'erubis'
-
-
2
require 'tilt/etanni'
-
2
register EtanniTemplate, 'etn', 'etanni'
-
-
2
require 'tilt/haml'
-
2
register HamlTemplate, 'haml'
-
-
2
require 'tilt/css'
-
2
register SassTemplate, 'sass'
-
2
register ScssTemplate, 'scss'
-
2
register LessTemplate, 'less'
-
-
2
require 'tilt/csv'
-
2
register CSVTemplate, 'rcsv'
-
-
2
require 'tilt/coffee'
-
2
register CoffeeScriptTemplate, 'coffee'
-
-
2
require 'tilt/nokogiri'
-
2
register NokogiriTemplate, 'nokogiri'
-
-
2
require 'tilt/builder'
-
2
register BuilderTemplate, 'builder'
-
-
2
require 'tilt/markaby'
-
2
register MarkabyTemplate, 'mab'
-
-
2
require 'tilt/liquid'
-
2
register LiquidTemplate, 'liquid'
-
-
2
require 'tilt/radius'
-
2
register RadiusTemplate, 'radius'
-
-
2
require 'tilt/markdown'
-
2
register MarukuTemplate, 'markdown', 'mkd', 'md'
-
2
register KramdownTemplate, 'markdown', 'mkd', 'md'
-
2
register BlueClothTemplate, 'markdown', 'mkd', 'md'
-
2
register RDiscountTemplate, 'markdown', 'mkd', 'md'
-
2
register RedcarpetTemplate::Redcarpet1, 'markdown', 'mkd', 'md'
-
2
register RedcarpetTemplate::Redcarpet2, 'markdown', 'mkd', 'md'
-
2
register RedcarpetTemplate, 'markdown', 'mkd', 'md'
-
-
2
require 'tilt/textile'
-
2
register RedClothTemplate, 'textile'
-
-
2
require 'tilt/rdoc'
-
2
register RDocTemplate, 'rdoc'
-
-
2
require 'tilt/wiki'
-
2
register CreoleTemplate, 'wiki', 'creole'
-
2
register WikiClothTemplate, 'wiki', 'mediawiki', 'mw'
-
-
2
require 'tilt/yajl'
-
2
register YajlTemplate, 'yajl'
-
-
2
require 'tilt/asciidoc'
-
2
register AsciidoctorTemplate, 'ad', 'adoc', 'asciidoc'
-
-
2
require 'tilt/plain'
-
2
register PlainTemplate, 'html'
-
end
-
2
require 'tilt/template'
-
-
# AsciiDoc see: http://asciidoc.org/
-
2
module Tilt
-
# Asciidoctor implementation for AsciiDoc see:
-
# http://asciidoctor.github.com/
-
#
-
# Asciidoctor is an open source, pure-Ruby processor for
-
# converting AsciiDoc documents or strings into HTML 5,
-
# DocBook 4.5 and other formats.
-
2
class AsciidoctorTemplate < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
defined? ::Asciidoctor::Document
-
end
-
-
2
def initialize_engine
-
require_template_library 'asciidoctor'
-
end
-
-
2
def prepare
-
options[:header_footer] = false if options[:header_footer].nil?
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= Asciidoctor.render(data, options, &block)
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Builder template implementation. See:
-
# http://builder.rubyforge.org/
-
2
class BuilderTemplate < Template
-
2
self.default_mime_type = 'text/xml'
-
-
2
def self.engine_initialized?
-
defined? ::Builder
-
end
-
-
2
def initialize_engine
-
require_template_library 'builder'
-
end
-
-
2
def prepare; end
-
-
2
def evaluate(scope, locals, &block)
-
return super(scope, locals, &block) if data.respond_to?(:to_str)
-
xml = ::Builder::XmlMarkup.new(:indent => 2)
-
data.call(xml)
-
xml.target!
-
end
-
-
2
def precompiled_preamble(locals)
-
return super if locals.include? :xml
-
"xml = ::Builder::XmlMarkup.new(:indent => 2)\n#{super}"
-
end
-
-
2
def precompiled_postamble(locals)
-
"xml.target!"
-
end
-
-
2
def precompiled_template(locals)
-
data.to_str
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# CoffeeScript template implementation. See:
-
# http://coffeescript.org/
-
#
-
# CoffeeScript templates do not support object scopes, locals, or yield.
-
2
class CoffeeScriptTemplate < Template
-
2
self.default_mime_type = 'application/javascript'
-
-
2
@@default_bare = false
-
-
2
def self.default_bare
-
@@default_bare
-
end
-
-
2
def self.default_bare=(value)
-
@@default_bare = value
-
end
-
-
# DEPRECATED
-
2
def self.default_no_wrap
-
@@default_bare
-
end
-
-
# DEPRECATED
-
2
def self.default_no_wrap=(value)
-
@@default_bare = value
-
end
-
-
2
def self.engine_initialized?
-
defined? ::CoffeeScript
-
end
-
-
2
def initialize_engine
-
require_template_library 'coffee_script'
-
end
-
-
2
def prepare
-
if !options.key?(:bare) and !options.key?(:no_wrap)
-
options[:bare] = self.class.default_bare
-
end
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= CoffeeScript.compile(data, options)
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Sass template implementation. See:
-
# http://haml.hamptoncatlin.com/
-
#
-
# Sass templates do not support object scopes, locals, or yield.
-
2
class SassTemplate < Template
-
2
self.default_mime_type = 'text/css'
-
-
2
def self.engine_initialized?
-
defined? ::Sass::Engine
-
end
-
-
2
def initialize_engine
-
require_template_library 'sass'
-
end
-
-
2
def prepare
-
@engine = ::Sass::Engine.new(data, sass_options)
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.render
-
end
-
-
2
def allows_script?
-
false
-
end
-
-
2
private
-
2
def sass_options
-
options.merge(:filename => eval_file, :line => line, :syntax => :sass)
-
end
-
end
-
-
# Sass's new .scss type template implementation.
-
2
class ScssTemplate < SassTemplate
-
2
self.default_mime_type = 'text/css'
-
-
2
private
-
2
def sass_options
-
options.merge(:filename => eval_file, :line => line, :syntax => :scss)
-
end
-
end
-
-
# Lessscss template implementation. See:
-
# http://lesscss.org/
-
#
-
# Less templates do not support object scopes, locals, or yield.
-
2
class LessTemplate < Template
-
2
self.default_mime_type = 'text/css'
-
-
2
def self.engine_initialized?
-
defined? ::Less
-
end
-
-
2
def initialize_engine
-
require_template_library 'less'
-
end
-
-
2
def prepare
-
if ::Less.const_defined? :Engine
-
@engine = ::Less::Engine.new(data)
-
else
-
parser = ::Less::Parser.new(options.merge :filename => eval_file, :line => line)
-
@engine = parser.parse(data)
-
end
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_css(options)
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
-
# CSV Template implementation. See:
-
# http://ruby-doc.org/stdlib/libdoc/csv/rdoc/CSV.html
-
#
-
# == Example
-
#
-
# # Example of csv template
-
# tpl = <<-EOS
-
# # header
-
# csv << ['NAME', 'ID']
-
#
-
# # data rows
-
# @people.each do |person|
-
# csv << [person[:name], person[:id]]
-
# end
-
# EOS
-
#
-
# @people = [
-
# {:name => "Joshua Peek", :id => 1},
-
# {:name => "Ryan Tomayko", :id => 2},
-
# {:name => "Simone Carletti", :id => 3}
-
# ]
-
#
-
# template = Tilt::CSVTemplate.new { tpl }
-
# template.render(self)
-
#
-
2
class CSVTemplate < Template
-
2
self.default_mime_type = 'text/csv'
-
-
2
def self.engine_initialized?
-
engine
-
end
-
-
2
def self.engine
-
if RUBY_VERSION >= '1.9.0' && defined? ::CSV
-
::CSV
-
elsif defined? ::FasterCSV
-
::FasterCSV
-
end
-
end
-
-
2
def initialize_engine
-
if RUBY_VERSION >= '1.9.0'
-
require_template_library 'csv'
-
else
-
require_template_library 'fastercsv'
-
end
-
end
-
-
2
def prepare
-
@code =<<-RUBY
-
#{self.class.engine}.generate do |csv|
-
#{data}
-
end
-
RUBY
-
end
-
-
2
def precompiled_template(locals)
-
@code
-
end
-
-
2
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# ERB template implementation. See:
-
# http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html
-
2
class ERBTemplate < Template
-
2
@@default_output_variable = '_erbout'
-
-
2
def self.default_output_variable
-
@@default_output_variable
-
end
-
-
2
def self.default_output_variable=(name)
-
@@default_output_variable = name
-
end
-
-
2
def self.engine_initialized?
-
defined? ::ERB
-
end
-
-
2
def initialize_engine
-
require_template_library 'erb'
-
end
-
-
2
def prepare
-
@outvar = options[:outvar] || self.class.default_output_variable
-
options[:trim] = '<>' if !(options[:trim] == false) && (options[:trim].nil? || options[:trim] == true)
-
@engine = ::ERB.new(data, options[:safe], options[:trim], @outvar)
-
end
-
-
2
def precompiled_template(locals)
-
source = @engine.src
-
source
-
end
-
-
2
def precompiled_preamble(locals)
-
<<-RUBY
-
begin
-
__original_outvar = #{@outvar} if defined?(#{@outvar})
-
#{super}
-
RUBY
-
end
-
-
2
def precompiled_postamble(locals)
-
<<-RUBY
-
#{super}
-
ensure
-
#{@outvar} = __original_outvar
-
end
-
RUBY
-
end
-
-
# ERB generates a line to specify the character coding of the generated
-
# source in 1.9. Account for this in the line offset.
-
2
if RUBY_VERSION >= '1.9.0'
-
2
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
end
-
end
-
-
# Erubis template implementation. See:
-
# http://www.kuwata-lab.com/erubis/
-
#
-
# ErubisTemplate supports the following additional options, which are not
-
# passed down to the Erubis engine:
-
#
-
# :engine_class allows you to specify a custom engine class to use
-
# instead of the default (which is ::Erubis::Eruby).
-
#
-
# :escape_html when true, ::Erubis::EscapedEruby will be used as
-
# the engine class instead of the default. All content
-
# within <%= %> blocks will be automatically html escaped.
-
2
class ErubisTemplate < ERBTemplate
-
2
def self.engine_initialized?
-
defined? ::Erubis::Eruby
-
end
-
-
2
def initialize_engine
-
require_template_library 'erubis'
-
end
-
-
2
def prepare
-
@outvar = options.delete(:outvar) || self.class.default_output_variable
-
@options.merge!(:preamble => false, :postamble => false, :bufvar => @outvar)
-
engine_class = options.delete(:engine_class)
-
engine_class = ::Erubis::EscapedEruby if options.delete(:escape_html)
-
@engine = (engine_class || ::Erubis::Eruby).new(data, options)
-
end
-
-
2
def precompiled_preamble(locals)
-
[super, "#{@outvar} = _buf = ''"].join("\n")
-
end
-
-
2
def precompiled_postamble(locals)
-
[@outvar, super].join("\n")
-
end
-
-
# Erubis doesn't have ERB's line-off-by-one under 1.9 problem.
-
# Override and adjust back.
-
2
if RUBY_VERSION >= '1.9.0'
-
2
def precompiled(locals)
-
source, offset = super
-
[source, offset - 1]
-
end
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
2
class EtanniTemplate < Template
-
2
def prepare
-
separator = data.hash.abs
-
chomp = "<<#{separator}.chomp!"
-
start = "\n_out_ << #{chomp}\n"
-
stop = "\n#{separator}\n"
-
replacement = "#{stop}\\1#{start}"
-
-
temp = data.strip
-
temp.gsub!(/<\?r\s+(.*?)\s+\?>/m, replacement)
-
-
@code = "_out_ = [<<#{separator}.chomp!]\n#{temp}#{stop}_out_.join"
-
end
-
-
2
def precompiled_template(locals)
-
@code
-
end
-
-
2
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Haml template implementation. See:
-
# http://haml.hamptoncatlin.com/
-
2
class HamlTemplate < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
defined? ::Haml::Engine
-
end
-
-
2
def initialize_engine
-
require_template_library 'haml'
-
end
-
-
2
def prepare
-
options = @options.merge(:filename => eval_file, :line => line)
-
@engine = ::Haml::Engine.new(data, options)
-
end
-
-
2
def evaluate(scope, locals, &block)
-
if @engine.respond_to?(:precompiled_method_return_value, true)
-
super
-
else
-
@engine.render(scope, locals, &block)
-
end
-
end
-
-
# Precompiled Haml source. Taken from the precompiled_with_ambles
-
# method in Haml::Precompiler:
-
# http://github.com/nex3/haml/blob/master/lib/haml/precompiler.rb#L111-126
-
2
def precompiled_template(locals)
-
@engine.precompiled
-
end
-
-
2
def precompiled_preamble(locals)
-
local_assigns = super
-
@engine.instance_eval do
-
<<-RUBY
-
begin
-
extend Haml::Helpers
-
_hamlout = @haml_buffer = Haml::Buffer.new(@haml_buffer, #{options_for_buffer.inspect})
-
_erbout = _hamlout.buffer
-
__in_erb_template = true
-
_haml_locals = locals
-
#{local_assigns}
-
RUBY
-
end
-
end
-
-
2
def precompiled_postamble(locals)
-
@engine.instance_eval do
-
<<-RUBY
-
#{precompiled_method_return_value}
-
ensure
-
@haml_buffer = @haml_buffer.upper
-
end
-
RUBY
-
end
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Liquid template implementation. See:
-
# http://liquid.rubyforge.org/
-
#
-
# Liquid is designed to be a *safe* template system and threfore
-
# does not provide direct access to execuatable scopes. In order to
-
# support a +scope+, the +scope+ must be able to represent itself
-
# as a hash by responding to #to_h. If the +scope+ does not respond
-
# to #to_h it will be ignored.
-
#
-
# LiquidTemplate does not support yield blocks.
-
#
-
# It's suggested that your program require 'liquid' at load
-
# time when using this template engine.
-
2
class LiquidTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::Liquid::Template
-
end
-
-
2
def initialize_engine
-
require_template_library 'liquid'
-
end
-
-
2
def prepare
-
@engine = ::Liquid::Template.parse(data)
-
end
-
-
2
def evaluate(scope, locals, &block)
-
locals = locals.inject({}){ |h,(k,v)| h[k.to_s] = v ; h }
-
if scope.respond_to?(:to_h)
-
scope = scope.to_h.inject({}){ |h,(k,v)| h[k.to_s] = v ; h }
-
locals = scope.merge(locals)
-
end
-
locals['yield'] = block.nil? ? '' : yield
-
locals['content'] = locals['yield']
-
@engine.render(locals)
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Markaby
-
# http://github.com/markaby/markaby
-
2
class MarkabyTemplate < Template
-
2
def self.builder_class
-
@builder_class ||= Class.new(Markaby::Builder) do
-
def __capture_markaby_tilt__(&block)
-
__run_markaby_tilt__ do
-
text capture(&block)
-
end
-
end
-
end
-
end
-
-
2
def self.engine_initialized?
-
defined? ::Markaby
-
end
-
-
2
def initialize_engine
-
require_template_library 'markaby'
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(scope, locals, &block)
-
builder = self.class.builder_class.new({}, scope)
-
builder.locals = locals
-
-
if data.kind_of? Proc
-
(class << builder; self end).send(:define_method, :__run_markaby_tilt__, &data)
-
else
-
builder.instance_eval <<-CODE, __FILE__, __LINE__
-
def __run_markaby_tilt__
-
#{data}
-
end
-
CODE
-
end
-
-
if block
-
builder.__capture_markaby_tilt__(&block)
-
else
-
builder.__run_markaby_tilt__
-
end
-
-
builder.to_s
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Discount Markdown implementation. See:
-
# http://github.com/rtomayko/rdiscount
-
#
-
# RDiscount is a simple text filter. It does not support +scope+ or
-
# +locals+. The +:smart+ and +:filter_html+ options may be set true
-
# to enable those flags on the underlying RDiscount object.
-
2
class RDiscountTemplate < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
ALIAS = {
-
:escape_html => :filter_html,
-
:smartypants => :smart
-
}
-
-
2
FLAGS = [:smart, :filter_html, :smartypants, :escape_html]
-
-
2
def flags
-
FLAGS.select { |flag| options[flag] }.map { |flag| ALIAS[flag] || flag }
-
end
-
-
2
def self.engine_initialized?
-
defined? ::RDiscount
-
end
-
-
2
def initialize_engine
-
require_template_library 'rdiscount'
-
end
-
-
2
def prepare
-
@engine = RDiscount.new(data, *flags)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
-
# Upskirt Markdown implementation. See:
-
# https://github.com/tanoku/redcarpet
-
#
-
# Supports both Redcarpet 1.x and 2.x
-
2
class RedcarpetTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::Redcarpet
-
end
-
-
2
def initialize_engine
-
require_template_library 'redcarpet'
-
end
-
-
2
def prepare
-
klass = [Redcarpet2, Redcarpet1].detect { |e| e.engine_initialized? }
-
@engine = klass.new(file, line, options) { data }
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@engine.evaluate(scope, locals, &block)
-
end
-
-
2
def allows_script?
-
false
-
end
-
-
# Compatibility mode for Redcarpet 1.x
-
2
class Redcarpet1 < RDiscountTemplate
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
defined? ::RedcarpetCompat
-
end
-
-
2
def prepare
-
@engine = RedcarpetCompat.new(data, *flags)
-
@output = nil
-
end
-
end
-
-
# Future proof mode for Redcarpet 2.x (not yet released)
-
2
class Redcarpet2 < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
defined? ::Redcarpet::Render and defined? ::Redcarpet::Markdown
-
end
-
-
2
def generate_renderer
-
renderer = options.delete(:renderer) || ::Redcarpet::Render::HTML
-
return renderer unless options.delete(:smartypants)
-
return renderer if renderer.is_a?(Class) && renderer <= ::Redcarpet::Render::SmartyPants
-
-
if renderer == ::Redcarpet::Render::XHTML
-
::Redcarpet::Render::SmartyHTML.new(:xhtml => true)
-
elsif renderer == ::Redcarpet::Render::HTML
-
::Redcarpet::Render::SmartyHTML
-
elsif renderer.is_a? Class
-
Class.new(renderer) { include ::Redcarpet::Render::SmartyPants }
-
else
-
renderer.extend ::Redcarpet::Render::SmartyPants
-
end
-
end
-
-
2
def prepare
-
# try to support the same aliases
-
RDiscountTemplate::ALIAS.each do |opt, aka|
-
next if options.key? opt or not options.key? aka
-
options[opt] = options.delete(aka)
-
end
-
-
# only raise an exception if someone is trying to enable :escape_html
-
options.delete(:escape_html) unless options[:escape_html]
-
-
@engine = ::Redcarpet::Markdown.new(generate_renderer, options)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.render(data)
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
-
# BlueCloth Markdown implementation. See:
-
# http://deveiate.org/projects/BlueCloth/
-
2
class BlueClothTemplate < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
defined? ::BlueCloth
-
end
-
-
2
def initialize_engine
-
require_template_library 'bluecloth'
-
end
-
-
2
def prepare
-
@engine = BlueCloth.new(data, options)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
-
# Maruku markdown implementation. See:
-
# http://maruku.rubyforge.org/
-
2
class MarukuTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::Maruku
-
end
-
-
2
def initialize_engine
-
require_template_library 'maruku'
-
end
-
-
2
def prepare
-
@engine = Maruku.new(data, options)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
-
# Kramdown Markdown implementation. See:
-
# http://kramdown.rubyforge.org/
-
2
class KramdownTemplate < Template
-
2
DUMB_QUOTES = [39, 39, 34, 34]
-
-
2
def self.engine_initialized?
-
defined? ::Kramdown
-
end
-
-
2
def initialize_engine
-
require_template_library 'kramdown'
-
end
-
-
2
def prepare
-
options[:smart_quotes] = DUMB_QUOTES unless options[:smartypants]
-
@engine = Kramdown::Document.new(data, options)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Nokogiri template implementation. See:
-
# http://nokogiri.org/
-
2
class NokogiriTemplate < Template
-
2
DOCUMENT_HEADER = /^<\?xml version=\"1\.0\"\?>\n?/
-
2
self.default_mime_type = 'text/xml'
-
-
2
def self.engine_initialized?
-
defined? ::Nokogiri
-
end
-
-
2
def initialize_engine
-
require_template_library 'nokogiri'
-
end
-
-
2
def prepare; end
-
-
2
def evaluate(scope, locals)
-
if data.respond_to?(:to_str)
-
wrapper = proc { yield.sub(DOCUMENT_HEADER, "") } if block_given?
-
super(scope, locals, &wrapper)
-
else
-
::Nokogiri::XML::Builder.new.tap(&data).to_xml
-
end
-
end
-
-
2
def precompiled_preamble(locals)
-
return super if locals.include? :xml
-
"xml = ::Nokogiri::XML::Builder.new { |xml| }\n#{super}"
-
end
-
-
2
def precompiled_postamble(locals)
-
"xml.to_xml"
-
end
-
-
2
def precompiled_template(locals)
-
data.to_str
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
-
2
module Tilt
-
# Raw text (no template functionality).
-
2
class PlainTemplate < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
true
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= data
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Radius Template
-
# http://github.com/jlong/radius/
-
2
class RadiusTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::Radius
-
end
-
-
2
def self.context_class
-
@context_class ||= Class.new(Radius::Context) do
-
attr_accessor :tilt_scope
-
-
def tag_missing(name, attributes)
-
tilt_scope.__send__(name)
-
end
-
-
def dup
-
i = super
-
i.tilt_scope = tilt_scope
-
i
-
end
-
end
-
end
-
-
2
def initialize_engine
-
require_template_library 'radius'
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(scope, locals, &block)
-
context = self.class.context_class.new
-
context.tilt_scope = scope
-
context.define_tag("yield") do
-
block.call
-
end
-
locals.each do |tag, value|
-
context.define_tag(tag) do
-
value
-
end
-
end
-
-
options = {:tag_prefix => 'r'}.merge(@options)
-
parser = Radius::Parser.new(context, options)
-
parser.parse(data)
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# RDoc template. See:
-
# http://rdoc.rubyforge.org/
-
#
-
# It's suggested that your program `require 'rdoc/markup'` and
-
# `require 'rdoc/markup/to_html'` at load time when using this template
-
# engine in a threaded environment.
-
2
class RDocTemplate < Template
-
2
self.default_mime_type = 'text/html'
-
-
2
def self.engine_initialized?
-
defined? ::RDoc::Markup::ToHtml
-
end
-
-
2
def initialize_engine
-
require_template_library 'rdoc'
-
require_template_library 'rdoc/markup'
-
require_template_library 'rdoc/markup/to_html'
-
end
-
-
2
def markup
-
begin
-
# RDoc 4.0
-
require 'rdoc/options'
-
RDoc::Markup::ToHtml.new(RDoc::Options.new, nil)
-
rescue ArgumentError
-
# RDoc < 4.0
-
RDoc::Markup::ToHtml.new
-
end
-
end
-
-
2
def prepare
-
@engine = markup.convert(data)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_s
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# The template source is evaluated as a Ruby string. The #{} interpolation
-
# syntax can be used to generated dynamic output.
-
2
class StringTemplate < Template
-
2
def prepare
-
hash = "TILT#{data.hash.abs}"
-
@code = "<<#{hash}.chomp\n#{data}\n#{hash}"
-
end
-
-
2
def precompiled_template(locals)
-
@code
-
end
-
-
2
def precompiled(locals)
-
source, offset = super
-
[source, offset + 1]
-
end
-
end
-
end
-
2
module Tilt
-
2
TOPOBJECT = Object.superclass || Object
-
-
# Base class for template implementations. Subclasses must implement
-
# the #prepare method and one of the #evaluate or #precompiled_template
-
# methods.
-
2
class Template
-
# Template source; loaded from a file or given directly.
-
2
attr_reader :data
-
-
# The name of the file where the template data was loaded from.
-
2
attr_reader :file
-
-
# The line number in #file where template data was loaded from.
-
2
attr_reader :line
-
-
# A Hash of template engine specific options. This is passed directly
-
# to the underlying engine and is not used by the generic template
-
# interface.
-
2
attr_reader :options
-
-
# Used to determine if this class's initialize_engine method has
-
# been called yet.
-
2
@engine_initialized = false
-
2
class << self
-
2
attr_accessor :engine_initialized
-
2
alias engine_initialized? engine_initialized
-
-
2
attr_accessor :default_mime_type
-
end
-
-
# Create a new template with the file, line, and options specified. By
-
# default, template data is read from the file. When a block is given,
-
# it should read template data and return as a String. When file is nil,
-
# a block is required.
-
#
-
# All arguments are optional.
-
2
def initialize(file=nil, line=1, options={}, &block)
-
@file, @line, @options = nil, 1, {}
-
-
[options, line, file].compact.each do |arg|
-
case
-
when arg.respond_to?(:to_str) ; @file = arg.to_str
-
when arg.respond_to?(:to_int) ; @line = arg.to_int
-
when arg.respond_to?(:to_hash) ; @options = arg.to_hash.dup
-
when arg.respond_to?(:path) ; @file = arg.path
-
else raise TypeError
-
end
-
end
-
-
raise ArgumentError, "file or block required" if (@file || block).nil?
-
-
# call the initialize_engine method if this is the very first time
-
# an instance of this class has been created.
-
if !self.class.engine_initialized?
-
initialize_engine
-
self.class.engine_initialized = true
-
end
-
-
# used to hold compiled template methods
-
@compiled_method = {}
-
-
# used on 1.9 to set the encoding if it is not set elsewhere (like a magic comment)
-
# currently only used if template compiles to ruby
-
@default_encoding = @options.delete :default_encoding
-
-
# load template data and prepare (uses binread to avoid encoding issues)
-
@reader = block || lambda { |t| read_template_file }
-
@data = @reader.call(self)
-
-
if @data.respond_to?(:force_encoding)
-
@data.force_encoding(default_encoding) if default_encoding
-
-
if !@data.valid_encoding?
-
raise Encoding::InvalidByteSequenceError, "#{eval_file} is not valid #{@data.encoding}"
-
end
-
end
-
-
prepare
-
end
-
-
# The encoding of the source data. Defaults to the
-
# default_encoding-option if present. You may override this method
-
# in your template class if you have a better hint of the data's
-
# encoding.
-
2
def default_encoding
-
@default_encoding
-
end
-
-
2
def read_template_file
-
data = File.open(file, 'rb') { |io| io.read }
-
if data.respond_to?(:force_encoding)
-
# Set it to the default external (without verifying)
-
data.force_encoding(Encoding.default_external) if Encoding.default_external
-
end
-
data
-
end
-
-
# Render the template in the given scope with the locals specified. If a
-
# block is given, it is typically available within the template via
-
# +yield+.
-
2
def render(scope=Object.new, locals={}, &block)
-
evaluate scope, locals || {}, &block
-
end
-
-
# The basename of the template file.
-
2
def basename(suffix='')
-
File.basename(file, suffix) if file
-
end
-
-
# The template file's basename with all extensions chomped off.
-
2
def name
-
basename.split('.', 2).first if basename
-
end
-
-
# The filename used in backtraces to describe the template.
-
2
def eval_file
-
file || '(__TEMPLATE__)'
-
end
-
-
# Whether or not this template engine allows executing Ruby script
-
# within the template. If this is false, +scope+ and +locals+ will
-
# generally not be used, nor will the provided block be avaiable
-
# via +yield+.
-
# This should be overridden by template subclasses.
-
2
def allows_script?
-
true
-
end
-
-
2
protected
-
# Called once and only once for each template subclass the first time
-
# the template class is initialized. This should be used to require the
-
# underlying template library and perform any initial setup.
-
2
def initialize_engine
-
end
-
-
# Like Kernel#require but issues a warning urging a manual require when
-
# running under a threaded environment.
-
2
def require_template_library(name)
-
if Thread.list.size > 1
-
warn "WARN: tilt autoloading '#{name}' in a non thread-safe way; " +
-
"explicit require '#{name}' suggested."
-
end
-
require name
-
end
-
-
# Do whatever preparation is necessary to setup the underlying template
-
# engine. Called immediately after template data is loaded. Instance
-
# variables set in this method are available when #evaluate is called.
-
#
-
# Subclasses must provide an implementation of this method.
-
2
def prepare
-
if respond_to?(:compile!)
-
# backward compat with tilt < 0.6; just in case
-
warn 'Tilt::Template#compile! is deprecated; implement #prepare instead.'
-
compile!
-
else
-
raise NotImplementedError
-
end
-
end
-
-
# Execute the compiled template and return the result string. Template
-
# evaluation is guaranteed to be performed in the scope object with the
-
# locals specified and with support for yielding to the block.
-
#
-
# This method is only used by source generating templates. Subclasses that
-
# override render() may not support all features.
-
2
def evaluate(scope, locals, &block)
-
method = compiled_method(locals.keys)
-
method.bind(scope).call(locals, &block)
-
end
-
-
# Generates all template source by combining the preamble, template, and
-
# postamble and returns a two-tuple of the form: [source, offset], where
-
# source is the string containing (Ruby) source code for the template and
-
# offset is the integer line offset where line reporting should begin.
-
#
-
# Template subclasses may override this method when they need complete
-
# control over source generation or want to adjust the default line
-
# offset. In most cases, overriding the #precompiled_template method is
-
# easier and more appropriate.
-
2
def precompiled(locals)
-
preamble = precompiled_preamble(locals)
-
template = precompiled_template(locals)
-
postamble = precompiled_postamble(locals)
-
source = ''
-
-
# Ensure that our generated source code has the same encoding as the
-
# the source code generated by the template engine.
-
if source.respond_to?(:force_encoding)
-
template_encoding = extract_encoding(template)
-
-
source.force_encoding(template_encoding)
-
template.force_encoding(template_encoding)
-
end
-
-
# https://github.com/rtomayko/tilt/issues/193
-
warn "precompiled_preamble should return String (not Array)" if preamble.is_a?(Array)
-
warn "precompiled_postamble should return String (not Array)" if postamble.is_a?(Array)
-
source << [preamble, template, postamble].join("\n")
-
-
[source, preamble.count("\n")+1]
-
end
-
-
# A string containing the (Ruby) source code for the template. The
-
# default Template#evaluate implementation requires either this
-
# method or the #precompiled method be overridden. When defined,
-
# the base Template guarantees correct file/line handling, locals
-
# support, custom scopes, proper encoding, and support for template
-
# compilation.
-
2
def precompiled_template(locals)
-
raise NotImplementedError
-
end
-
-
# Generates preamble code for initializing template state, and performing
-
# locals assignment. The default implementation performs locals
-
# assignment only. Lines included in the preamble are subtracted from the
-
# source line offset, so adding code to the preamble does not effect line
-
# reporting in Kernel::caller and backtraces.
-
2
def precompiled_preamble(locals)
-
locals.map do |k,v|
-
if k.to_s =~ /\A[a-z_][a-zA-Z_0-9]*\z/
-
"#{k} = locals[#{k.inspect}]"
-
else
-
raise "invalid locals key: #{k.inspect} (keys must be variable names)"
-
end
-
end.join("\n")
-
end
-
-
# Generates postamble code for the precompiled template source. The
-
# string returned from this method is appended to the precompiled
-
# template source.
-
2
def precompiled_postamble(locals)
-
''
-
end
-
-
# The compiled method for the locals keys provided.
-
2
def compiled_method(locals_keys)
-
@compiled_method[locals_keys] ||=
-
compile_template_method(locals_keys)
-
end
-
-
2
private
-
2
def compile_template_method(locals)
-
source, offset = precompiled(locals)
-
method_name = "__tilt_#{Thread.current.object_id.abs}"
-
method_source = ""
-
-
if method_source.respond_to?(:force_encoding)
-
method_source.force_encoding(source.encoding)
-
end
-
-
method_source << <<-RUBY
-
TOPOBJECT.class_eval do
-
def #{method_name}(locals)
-
Thread.current[:tilt_vars] = [self, locals]
-
class << self
-
this, locals = Thread.current[:tilt_vars]
-
this.instance_eval do
-
RUBY
-
offset += method_source.count("\n")
-
method_source << source
-
method_source << "\nend;end;end;end"
-
Object.class_eval method_source, eval_file, line - offset
-
unbind_compiled_method(method_name)
-
end
-
-
2
def unbind_compiled_method(method_name)
-
method = TOPOBJECT.instance_method(method_name)
-
TOPOBJECT.class_eval { remove_method(method_name) }
-
method
-
end
-
-
2
def extract_encoding(script)
-
extract_magic_comment(script) || script.encoding
-
end
-
-
2
def extract_magic_comment(script)
-
binary script do
-
script[/\A[ \t]*\#.*coding\s*[=:]\s*([[:alnum:]\-_]+).*$/n, 1]
-
end
-
end
-
-
2
def binary(string)
-
original_encoding = string.encoding
-
string.force_encoding(Encoding::BINARY)
-
yield
-
ensure
-
string.force_encoding(original_encoding)
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# RedCloth implementation. See:
-
# http://redcloth.org/
-
2
class RedClothTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::RedCloth
-
end
-
-
2
def initialize_engine
-
require_template_library 'redcloth'
-
end
-
-
2
def prepare
-
@engine = RedCloth.new(data)
-
options.each {|k, v| @engine.send("#{k}=", v) if @engine.respond_to? "#{k}="}
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
-
2
require 'tilt/template'
-
-
2
module Tilt
-
# Creole implementation. See:
-
# http://www.wikicreole.org/
-
2
class CreoleTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::Creole
-
end
-
-
2
def initialize_engine
-
require_template_library 'creole'
-
end
-
-
2
def prepare
-
opts = {}
-
[:allowed_schemes, :extensions, :no_escape].each do |k|
-
opts[k] = options[k] if options[k]
-
end
-
@engine = Creole::Parser.new(data, opts)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
-
# WikiCloth implementation. See:
-
# http://redcloth.org/
-
2
class WikiClothTemplate < Template
-
2
def self.engine_initialized?
-
defined? ::WikiCloth::Parser
-
end
-
-
2
def initialize_engine
-
require_template_library 'wikicloth'
-
end
-
-
2
def prepare
-
@parser = options.delete(:parser) || WikiCloth::Parser
-
@engine = @parser.new options.merge(:data => data)
-
@output = nil
-
end
-
-
2
def evaluate(scope, locals, &block)
-
@output ||= @engine.to_html
-
end
-
-
2
def allows_script?
-
false
-
end
-
end
-
end
-
2
require 'tilt/template'
-
-
2
module Tilt
-
-
# Yajl Template implementation
-
#
-
# Yajl is a fast JSON parsing and encoding library for Ruby
-
# See https://github.com/brianmario/yajl-ruby
-
#
-
# The template source is evaluated as a Ruby string,
-
# and the result is converted #to_json.
-
#
-
# == Example
-
#
-
# # This is a template example.
-
# # The template can contain any Ruby statement.
-
# tpl <<-EOS
-
# @counter = 0
-
#
-
# # The json variable represents the buffer
-
# # and holds the data to be serialized into json.
-
# # It defaults to an empty hash, but you can override it at any time.
-
# json = {
-
# :"user#{@counter += 1}" => { :name => "Joshua Peek", :id => @counter },
-
# :"user#{@counter += 1}" => { :name => "Ryan Tomayko", :id => @counter },
-
# :"user#{@counter += 1}" => { :name => "Simone Carletti", :id => @counter },
-
# }
-
#
-
# # Since the json variable is a Hash,
-
# # you can use conditional statements or any other Ruby statement
-
# # to populate it.
-
# json[:"user#{@counter += 1}"] = { :name => "Unknown" } if 1 == 2
-
#
-
# # The last line doesn't affect the returned value.
-
# nil
-
# EOS
-
#
-
# template = Tilt::YajlTemplate.new { tpl }
-
# template.render(self)
-
#
-
2
class YajlTemplate < Template
-
-
2
self.default_mime_type = 'application/json'
-
-
2
def self.engine_initialized?
-
defined? ::Yajl
-
end
-
-
2
def initialize_engine
-
require_template_library 'yajl'
-
end
-
-
2
def prepare
-
end
-
-
2
def evaluate(scope, locals, &block)
-
decorate super(scope, locals, &block)
-
end
-
-
2
def precompiled_preamble(locals)
-
return super if locals.include? :json
-
"json = {}\n#{super}"
-
end
-
-
2
def precompiled_postamble(locals)
-
"Yajl::Encoder.new.encode(json)"
-
end
-
-
2
def precompiled_template(locals)
-
data.to_str
-
end
-
-
-
# Decorates the +json+ input according to given +options+.
-
#
-
# json - The json String to decorate.
-
# options - The option Hash to customize the behavior.
-
#
-
# Returns the decorated String.
-
2
def decorate(json)
-
callback, variable = options[:callback], options[:variable]
-
if callback && variable
-
"var #{variable} = #{json}; #{callback}(#{variable});"
-
elsif variable
-
"var #{variable} = #{json};"
-
elsif callback
-
"#{callback}(#{json});"
-
else
-
json
-
end
-
end
-
end
-
-
end
-
2
require File.join(File.dirname(__FILE__), "timecop", "timecop")
-
2
require File.join(File.dirname(__FILE__), "timecop", "version")
-
2
require 'date'
-
2
require 'time'
-
-
2
class Time #:nodoc:
-
2
class << self
-
2
def mock_time
-
7260
mocked_time_stack_item = Timecop.top_stack_item
-
7260
mocked_time_stack_item.nil? ? nil : mocked_time_stack_item.time(self)
-
end
-
-
2
alias_method :now_without_mock_time, :now
-
-
2
def now_with_mock_time
-
7260
mock_time || now_without_mock_time
-
end
-
-
2
alias_method :now, :now_with_mock_time
-
-
2
alias_method :new_without_mock_time, :new
-
-
2
def new_with_mock_time(*args)
-
args.size <= 0 ? now : new_without_mock_time(*args)
-
end
-
-
2
alias_method :new, :new_with_mock_time
-
end
-
end
-
-
2
class Date #:nodoc:
-
2
class << self
-
2
def mock_date
-
8
mocked_time_stack_item = Timecop.top_stack_item
-
8
mocked_time_stack_item.nil? ? nil : mocked_time_stack_item.date(self)
-
end
-
-
2
alias_method :today_without_mock_date, :today
-
-
2
def today_with_mock_date
-
8
mock_date || today_without_mock_date
-
end
-
-
2
alias_method :today, :today_with_mock_date
-
-
2
alias_method :strptime_without_mock_date, :strptime
-
-
2
def strptime_with_mock_date(str = '-4712-01-01', fmt = '%F', start = Date::ITALY)
-
12
unless start == Date::ITALY
-
raise ArgumentError, "Timecop's #{self}::#{__method__} only " +
-
"supports Date::ITALY for the start argument."
-
end
-
-
12
Time.strptime(str, fmt).to_date
-
end
-
-
2
alias_method :strptime, :strptime_with_mock_date
-
end
-
end
-
-
2
class DateTime #:nodoc:
-
2
class << self
-
2
def mock_time
-
4
mocked_time_stack_item = Timecop.top_stack_item
-
4
mocked_time_stack_item.nil? ? nil : mocked_time_stack_item.datetime(self)
-
end
-
-
2
def now_without_mock_time
-
4
Time.now_without_mock_time.to_datetime
-
end
-
-
2
def now_with_mock_time
-
4
mock_time || now_without_mock_time
-
end
-
-
2
alias_method :now, :now_with_mock_time
-
end
-
end
-
2
class Timecop
-
# A data class for carrying around "time movement" objects. Makes it easy to keep track of the time
-
# movements on a simple stack.
-
2
class TimeStackItem #:nodoc:
-
2
attr_reader :mock_type
-
-
2
def initialize(mock_type, *args)
-
8
raise "Unknown mock_type #{mock_type}" unless [:freeze, :travel, :scale].include?(mock_type)
-
8
@scaling_factor = args.shift if mock_type == :scale
-
8
@mock_type = mock_type
-
8
@time = parse_time(*args)
-
8
@time_was = Time.now_without_mock_time
-
8
@travel_offset = compute_travel_offset
-
end
-
-
2
def year
-
time.year
-
end
-
-
2
def month
-
time.month
-
end
-
-
2
def day
-
time.day
-
end
-
-
2
def hour
-
time.hour
-
end
-
-
2
def min
-
time.min
-
end
-
-
2
def sec
-
time.sec
-
end
-
-
2
def utc_offset
-
time.utc_offset
-
end
-
-
2
def travel_offset
-
900
@travel_offset
-
end
-
-
2
def scaling_factor
-
446
@scaling_factor
-
end
-
-
2
def time(time_klass = Time) #:nodoc:
-
454
if @time.respond_to?(:in_time_zone)
-
454
time = time_klass.at(@time.dup.utc.to_r)
-
else
-
time = time_klass.at(@time)
-
end
-
-
454
if travel_offset.nil?
-
8
time
-
446
elsif scaling_factor.nil?
-
446
time_klass.at((Time.now_without_mock_time + travel_offset).to_f)
-
else
-
time_klass.at(scaled_time)
-
end
-
end
-
-
2
def scaled_time
-
(@time + (Time.now_without_mock_time - @time_was) * scaling_factor).to_f
-
end
-
-
2
def date(date_klass = Date)
-
date_klass.jd(time.__send__(:to_date).jd)
-
end
-
-
2
def datetime(datetime_klass = DateTime)
-
if Float.method_defined?(:to_r)
-
if !sec.zero?
-
fractions_of_a_second = time.to_f % 1
-
datetime_klass.new(year, month, day, hour, min, (fractions_of_a_second + sec), utc_offset_to_rational(utc_offset))
-
else
-
datetime_klass.new(year, month, day, hour, min, sec, utc_offset_to_rational(utc_offset))
-
end
-
else
-
datetime_klass.new(year, month, day, hour, min, sec, utc_offset_to_rational(utc_offset))
-
end
-
end
-
-
2
private
-
-
2
def rational_to_utc_offset(rational)
-
((24.0 / rational.denominator) * rational.numerator) * (60 * 60)
-
end
-
-
2
def utc_offset_to_rational(utc_offset)
-
Rational(utc_offset, 24 * 60 * 60)
-
end
-
-
2
def parse_time(*args)
-
8
arg = args.shift
-
8
if arg.is_a?(Time)
-
arg
-
8
elsif Object.const_defined?(:DateTime) && arg.is_a?(DateTime)
-
time_klass.at(arg.to_time.to_f).getlocal
-
8
elsif Object.const_defined?(:Date) && arg.is_a?(Date)
-
8
time_klass.local(arg.year, arg.month, arg.day, 0, 0, 0)
-
elsif args.empty? && arg.kind_of?(Integer)
-
Time.now + arg
-
elsif arg.nil?
-
Time.now
-
else
-
if arg.is_a?(String) && Time.respond_to?(:parse)
-
Time.parse(arg)
-
else
-
# we'll just assume it's a list of y/m/d/h/m/s
-
year = arg || 2000
-
month = args.shift || 1
-
day = args.shift || 1
-
hour = args.shift || 0
-
minute = args.shift || 0
-
second = args.shift || 0
-
time_klass.local(year, month, day, hour, minute, second)
-
end
-
end
-
end
-
-
2
def compute_travel_offset
-
8
return nil if mock_type == :freeze
-
8
time - Time.now_without_mock_time
-
end
-
-
2
def times_are_equal_within_epsilon t1, t2, epsilon_in_seconds
-
(t1 - t2).abs < epsilon_in_seconds
-
end
-
-
2
def time_klass
-
8
Time.respond_to?(:zone) && Time.zone ? Time.zone : Time
-
end
-
end
-
end
-
2
require 'singleton'
-
2
require File.join(File.dirname(__FILE__), "time_extensions")
-
2
require File.join(File.dirname(__FILE__), "time_stack_item")
-
-
# Timecop
-
# * Wrapper class for manipulating the extensions to the Time, Date, and DateTime objects
-
# * Allows us to "freeze" time in our Ruby applications.
-
# * Optionally allows time travel to simulate a running clock, such time is not technically frozen.
-
#
-
# This is very useful when your app's functionality is dependent on time (e.g.
-
# anything that might expire). This will allow us to alter the return value of
-
# Date.today, Time.now, and DateTime.now, such that our application code _never_ has to change.
-
2
class Timecop
-
2
include Singleton
-
-
2
class << self
-
# Allows you to run a block of code and "fake" a time throughout the execution of that block.
-
# This is particularly useful for writing test methods where the passage of time is critical to the business
-
# logic being tested. For example:
-
#
-
# joe = User.find(1)
-
# joe.purchase_home()
-
# assert !joe.mortgage_due?
-
# Timecop.freeze(2008, 10, 5) do
-
# assert joe.mortgage_due?
-
# end
-
#
-
# freeze and travel will respond to several different arguments:
-
# 1. Timecop.freeze(time_inst)
-
# 2. Timecop.freeze(datetime_inst)
-
# 3. Timecop.freeze(date_inst)
-
# 4. Timecop.freeze(offset_in_seconds)
-
# 5. Timecop.freeze(year, month, day, hour=0, minute=0, second=0)
-
#
-
# When a block is also passed, Time.now, DateTime.now and Date.today are all reset to their
-
# previous values after the block has finished executing. This allows us to nest multiple
-
# calls to Timecop.travel and have each block maintain it's concept of "now."
-
#
-
# * Note: Timecop.freeze will actually freeze time. This can cause unanticipated problems if
-
# benchmark or other timing calls are executed, which implicitly expect Time to actually move
-
# forward.
-
#
-
# * Rails Users: Be especially careful when setting this in your development environment in a
-
# rails project. Generators will load your environment, including the migration generator,
-
# which will lead to files being generated with the timestamp set by the Timecop.freeze call
-
# in your dev environment
-
#
-
# Returns the value of the block if one is given, or the mocked time.
-
2
def freeze(*args, &block)
-
send_travel(:freeze, *args, &block)
-
end
-
-
# Allows you to run a block of code and "fake" a time throughout the execution of that block.
-
# See Timecop#freeze for a sample of how to use (same exact usage syntax)
-
#
-
# * Note: Timecop.travel will not freeze time (as opposed to Timecop.freeze). This is a particularly
-
# good candidate for use in environment files in rails projects.
-
#
-
# Returns the value of the block if one is given, or the mocked time.
-
2
def travel(*args, &block)
-
8
send_travel(:travel, *args, &block)
-
end
-
-
# Allows you to run a block of code and "scale" a time throughout the execution of that block.
-
# The first argument is a scaling factor, for example:
-
# Timecop.scale(2) do
-
# ... time will 'go' twice as fast here
-
# end
-
# See Timecop#freeze for exact usage of the other arguments
-
#
-
# Returns the value of the block if one is given, or the mocked time.
-
2
def scale(*args, &block)
-
send_travel(:scale, *args, &block)
-
end
-
-
2
def baseline
-
instance.send(:baseline)
-
end
-
-
2
def baseline=(baseline)
-
instance.send(:baseline=, baseline)
-
end
-
-
# Reverts back to system's Time.now, Date.today and DateTime.now (if it exists) permamently when
-
# no block argument is given, or temporarily reverts back to the system's time temporarily for
-
# the given block.
-
2
def return(&block)
-
6
if block_given?
-
instance.send(:return, &block)
-
else
-
6
instance.send(:unmock!)
-
nil
-
end
-
end
-
-
2
def return_to_baseline
-
instance.send(:return_to_baseline)
-
Time.now
-
end
-
-
2
def top_stack_item #:nodoc:
-
7272
instance.instance_variable_get(:@_stack).last
-
end
-
-
2
def safe_mode=(safe)
-
@safe_mode = safe
-
end
-
-
2
def safe_mode?
-
8
false || @safe_mode
-
end
-
-
2
private
-
2
def send_travel(mock_type, *args, &block)
-
8
val = instance.send(:travel, mock_type, *args, &block)
-
8
block_given? ? val : Time.now
-
end
-
end
-
-
2
private
-
-
2
def baseline=(baseline)
-
@baseline = baseline
-
@_stack << TimeStackItem.new(:travel, baseline)
-
end
-
-
2
def initialize #:nodoc:
-
2
@_stack = []
-
end
-
-
2
def travel(mock_type, *args, &block) #:nodoc:
-
8
raise SafeModeException if Timecop.safe_mode? && !block_given?
-
-
8
stack_item = TimeStackItem.new(mock_type, *args)
-
-
8
stack_backup = @_stack.dup
-
8
@_stack << stack_item
-
-
8
if block_given?
-
begin
-
yield stack_item.time
-
ensure
-
@_stack.replace stack_backup
-
end
-
end
-
end
-
-
2
def return(&block)
-
current_stack = @_stack
-
current_baseline = @baseline
-
unmock!
-
yield
-
@_stack = current_stack
-
@baseline = current_baseline
-
end
-
-
2
def unmock! #:nodoc:
-
6
@baseline = nil
-
6
@_stack = []
-
end
-
-
2
def return_to_baseline
-
if @baseline
-
@_stack = [@_stack.shift]
-
else
-
unmock!
-
end
-
end
-
-
2
class SafeModeException < StandardError
-
2
def initialize
-
super "Safe mode is enabled, only calls passing a block are allowed."
-
end
-
end
-
end
-
2
class Timecop
-
2
VERSION = "0.7.1"
-
end
-
2
require 'treetop/ruby_extensions/string'
-
2
class String
-
2
def column_of(index)
-
return 1 if index == 0
-
newline_index = rindex("\n", index - 1)
-
if newline_index
-
index - newline_index
-
else
-
index + 1
-
end
-
end
-
-
2
def line_of(index)
-
self[0...index].count("\n") + 1
-
end
-
-
2
unless method_defined?(:blank?)
-
def blank?
-
self == ""
-
end
-
end
-
-
# The following methods are lifted from Facets 2.0.2
-
2
def tabto(n)
-
if self =~ /^( *)\S/
-
# Inlined due to collision with ActiveSupport 4.0: indent(n - $1.length)
-
m = n - $1.length
-
if m >= 0
-
gsub(/^/, ' ' * m)
-
else
-
gsub(/^ {0,#{-m}}/, "")
-
end
-
else
-
self
-
end
-
end
-
-
2
def treetop_camelize
-
to_s.gsub(/\/(.?)/){ "::" + $1.upcase }.gsub(/(^|_)(.)/){ $2.upcase }
-
end
-
end
-
2
require 'treetop/ruby_extensions'
-
-
2
require 'treetop/runtime/compiled_parser'
-
2
require 'treetop/runtime/syntax_node'
-
2
require 'treetop/runtime/terminal_parse_failure'
-
2
require 'treetop/runtime/interval_skip_list'
-
2
module Treetop
-
2
module Runtime
-
2
class CompiledParser
-
2
include Treetop::Runtime
-
-
2
attr_reader :input, :index, :max_terminal_failure_index
-
2
attr_writer :root
-
2
attr_accessor :consume_all_input
-
2
alias :consume_all_input? :consume_all_input
-
-
2
def initialize
-
40
self.consume_all_input = true
-
end
-
-
2
def parse(input, options = {})
-
40
prepare_to_parse(input)
-
40
@index = options[:index] if options[:index]
-
40
result = send("_nt_#{options[:root] || root}")
-
40
should_consume_all = options.include?(:consume_all_input) ? options[:consume_all_input] : consume_all_input?
-
40
return nil if (should_consume_all && index != input.size)
-
40
return SyntaxNode.new(input, index...(index + 1)) if result == true
-
40
return result
-
end
-
-
2
def failure_index
-
max_terminal_failure_index
-
end
-
-
2
def failure_line
-
@terminal_failures && input.line_of(failure_index)
-
end
-
-
2
def failure_column
-
@terminal_failures && input.column_of(failure_index)
-
end
-
-
2
def failure_reason
-
return nil unless (tf = terminal_failures) && tf.size > 0
-
"Expected " +
-
(tf.size == 1 ?
-
tf[0].expected_string :
-
"one of #{tf.map{|f| f.expected_string}.uniq*', '}"
-
) +
-
" at line #{failure_line}, column #{failure_column} (byte #{failure_index+1})" +
-
" after #{input[index...failure_index]}"
-
end
-
-
2
def terminal_failures
-
if @terminal_failures.empty? || @terminal_failures[0].is_a?(TerminalParseFailure)
-
@terminal_failures
-
else
-
@terminal_failures.map! {|tf_ary| TerminalParseFailure.new(*tf_ary) }
-
end
-
end
-
-
-
2
protected
-
-
2
attr_reader :node_cache, :input_length
-
2
attr_writer :index
-
-
2
def prepare_to_parse(input)
-
40
@input = input
-
40
@input_length = input.length
-
40
reset_index
-
852
@node_cache = Hash.new {|hash, key| hash[key] = Hash.new}
-
40
@regexps = {}
-
40
@terminal_failures = []
-
40
@max_terminal_failure_index = 0
-
end
-
-
2
def reset_index
-
40
@index = 0
-
end
-
-
2
def parse_anything(node_class = SyntaxNode, inline_module = nil)
-
if index < input.length
-
result = instantiate_node(node_class,input, index...(index + 1))
-
result.extend(inline_module) if inline_module
-
@index += 1
-
result
-
else
-
terminal_parse_failure("any character")
-
end
-
end
-
-
2
def instantiate_node(node_type,*args)
-
1891
if node_type.respond_to? :new
-
1891
node_type.new(*args)
-
else
-
SyntaxNode.new(*args).extend(node_type)
-
end
-
end
-
-
2
def has_terminal?(terminal, regex, index)
-
3375
if regex
-
1131
rx = @regexps[terminal] ||= Regexp.new(terminal)
-
1131
input.index(rx, index) == index
-
else
-
2244
input[index, terminal.size] == terminal
-
end
-
end
-
-
2
def terminal_parse_failure(expected_string)
-
2116
return nil if index < max_terminal_failure_index
-
1980
if index > max_terminal_failure_index
-
160
@max_terminal_failure_index = index
-
160
@terminal_failures = []
-
end
-
1980
@terminal_failures << [index, expected_string]
-
return nil
-
end
-
end
-
end
-
end
-
2
require 'treetop/runtime/interval_skip_list/interval_skip_list'
-
2
require 'treetop/runtime/interval_skip_list/head_node'
-
2
require 'treetop/runtime/interval_skip_list/node'
-
2
class IntervalSkipList
-
2
class HeadNode
-
2
attr_reader :height, :forward, :forward_markers
-
-
2
def initialize(height)
-
@height = height
-
@forward = Array.new(height, nil)
-
@forward_markers = Array.new(height) {|i| []}
-
end
-
-
2
def top_level
-
height - 1
-
end
-
end
-
end
-
2
class IntervalSkipList
-
2
attr_reader :probability
-
-
2
def initialize
-
@head = HeadNode.new(max_height)
-
@ranges = {}
-
@probability = 0.5
-
end
-
-
2
def max_height
-
3
-
end
-
-
2
def empty?
-
head.forward[0].nil?
-
end
-
-
2
def expire(range, length_change)
-
expired_markers, first_node_after_range = overlapping(range)
-
expired_markers.each { |marker| delete(marker) }
-
first_node_after_range.propagate_length_change(length_change)
-
end
-
-
2
def overlapping(range)
-
markers, first_node = containing_with_node(range.first)
-
-
cur_node = first_node
-
begin
-
markers.concat(cur_node.forward_markers.flatten)
-
cur_node = cur_node.forward[0]
-
end while cur_node.key < range.last
-
-
return markers.uniq, cur_node
-
end
-
-
2
def containing(n)
-
containing_with_node(n).first
-
end
-
-
2
def insert(range, marker)
-
ranges[marker] = range
-
first_node = insert_node(range.first)
-
first_node.endpoint_of.push(marker)
-
last_node = insert_node(range.last)
-
last_node.endpoint_of.push(marker)
-
-
cur_node = first_node
-
cur_level = first_node.top_level
-
while next_node_at_level_inside_range?(cur_node, cur_level, range)
-
while can_ascend_from?(cur_node, cur_level) && next_node_at_level_inside_range?(cur_node, cur_level + 1, range)
-
cur_level += 1
-
end
-
cur_node = mark_forward_path_at_level(cur_node, cur_level, marker)
-
end
-
-
while node_inside_range?(cur_node, range)
-
while can_descend_from?(cur_level) && next_node_at_level_outside_range?(cur_node, cur_level, range)
-
cur_level -= 1
-
end
-
cur_node = mark_forward_path_at_level(cur_node, cur_level, marker)
-
end
-
end
-
-
2
def delete(marker)
-
range = ranges[marker]
-
path_to_first_node = make_path
-
first_node = find(range.first, path_to_first_node)
-
-
cur_node = first_node
-
cur_level = first_node.top_level
-
while next_node_at_level_inside_range?(cur_node, cur_level, range)
-
while can_ascend_from?(cur_node, cur_level) && next_node_at_level_inside_range?(cur_node, cur_level + 1, range)
-
cur_level += 1
-
end
-
cur_node = unmark_forward_path_at_level(cur_node, cur_level, marker)
-
end
-
-
while node_inside_range?(cur_node, range)
-
while can_descend_from?(cur_level) && next_node_at_level_outside_range?(cur_node, cur_level, range)
-
cur_level -= 1
-
end
-
cur_node = unmark_forward_path_at_level(cur_node, cur_level, marker)
-
end
-
last_node = cur_node
-
-
first_node.endpoint_of.delete(marker)
-
if first_node.endpoint_of.empty?
-
first_node.delete(path_to_first_node)
-
end
-
-
last_node.endpoint_of.delete(marker)
-
if last_node.endpoint_of.empty?
-
path_to_last_node = make_path
-
find(range.last, path_to_last_node)
-
last_node.delete(path_to_last_node)
-
end
-
end
-
-
2
protected
-
2
attr_reader :head, :ranges
-
-
2
def insert_node(key)
-
path = make_path
-
found_node = find(key, path)
-
if found_node && found_node.key == key
-
return found_node
-
else
-
return Node.new(key, next_node_height, path)
-
end
-
end
-
-
2
def containing_with_node(n)
-
containing = []
-
cur_node = head
-
(max_height - 1).downto(0) do |cur_level|
-
while (next_node = cur_node.forward[cur_level]) && next_node.key <= n
-
cur_node = next_node
-
if cur_node.key == n
-
return containing + (cur_node.markers - cur_node.endpoint_of), cur_node
-
end
-
end
-
containing.concat(cur_node.forward_markers[cur_level])
-
end
-
-
return containing, cur_node
-
end
-
-
2
def delete_node(key)
-
path = make_path
-
found_node = find(key, path)
-
found_node.delete(path) if found_node.key == key
-
end
-
-
2
def find(key, path)
-
cur_node = head
-
(max_height - 1).downto(0) do |cur_level|
-
while (next_node = cur_node.forward[cur_level]) && next_node.key < key
-
cur_node = next_node
-
end
-
path[cur_level] = cur_node
-
end
-
cur_node.forward[0]
-
end
-
-
2
def make_path
-
Array.new(max_height, nil)
-
end
-
-
2
def next_node_height
-
height = 1
-
while rand < probability && height < max_height
-
height += 1
-
end
-
height
-
end
-
-
2
def can_ascend_from?(node, level)
-
level < node.top_level
-
end
-
-
2
def can_descend_from?(level)
-
level > 0
-
end
-
-
2
def node_inside_range?(node, range)
-
node.key < range.last
-
end
-
-
2
def next_node_at_level_inside_range?(node, level, range)
-
node.forward[level] && node.forward[level].key <= range.last
-
end
-
-
2
def next_node_at_level_outside_range?(node, level, range)
-
(node.forward[level].nil? || node.forward[level].key > range.last)
-
end
-
-
2
def mark_forward_path_at_level(node, level, marker)
-
node.forward_markers[level].push(marker)
-
next_node = node.forward[level]
-
next_node.markers.push(marker)
-
node = next_node
-
end
-
-
2
def unmark_forward_path_at_level(node, level, marker)
-
node.forward_markers[level].delete(marker)
-
next_node = node.forward[level]
-
next_node.markers.delete(marker)
-
node = next_node
-
end
-
-
2
def nodes
-
nodes = []
-
cur_node = head.forward[0]
-
until cur_node.nil?
-
nodes << cur_node
-
cur_node = cur_node.forward[0]
-
end
-
nodes
-
end
-
end
-
2
class IntervalSkipList
-
2
class Node < HeadNode
-
2
attr_accessor :key
-
2
attr_reader :markers, :endpoint_of
-
-
2
def initialize(key, height, path)
-
super(height)
-
@key = key
-
@markers = []
-
@endpoint_of = []
-
update_forward_pointers(path)
-
promote_markers(path)
-
end
-
-
2
def all_forward_markers
-
markers.flatten
-
end
-
-
2
def delete(path)
-
0.upto(top_level) do |i|
-
path[i].forward[i] = forward[i]
-
end
-
demote_markers(path)
-
end
-
-
2
def propagate_length_change(length_change)
-
cur_node = self
-
while cur_node do
-
cur_node.key += length_change
-
cur_node = cur_node.forward[0]
-
end
-
end
-
-
2
protected
-
-
2
def update_forward_pointers(path)
-
0.upto(top_level) do |i|
-
forward[i] = path[i].forward[i]
-
path[i].forward[i] = self
-
end
-
end
-
-
2
def promote_markers(path)
-
promoted = []
-
new_promoted = []
-
0.upto(top_level) do |i|
-
incoming_markers = path[i].forward_markers[i]
-
markers.concat(incoming_markers)
-
-
incoming_markers.each do |marker|
-
if can_be_promoted_higher?(marker, i)
-
new_promoted.push(marker)
-
forward[i].delete_marker_from_path(marker, i, forward[i+1])
-
else
-
forward_markers[i].push(marker)
-
end
-
end
-
-
promoted.each do |marker|
-
if can_be_promoted_higher?(marker, i)
-
new_promoted.push(marker)
-
forward[i].delete_marker_from_path(marker, i, forward[i+1])
-
else
-
forward_markers[i].push(marker)
-
end
-
end
-
-
promoted = new_promoted
-
new_promoted = []
-
end
-
end
-
-
-
2
def can_be_promoted_higher?(marker, level)
-
level < top_level && forward[level + 1] && forward[level + 1].markers.include?(marker)
-
end
-
-
2
def delete_marker_from_path(marker, level, terminus)
-
cur_node = self
-
until cur_node == terminus
-
cur_node.forward_markers[level].delete(marker)
-
cur_node.markers.delete(marker)
-
cur_node = cur_node.forward[level]
-
end
-
end
-
-
2
def demote_markers(path)
-
demote_inbound_markers(path)
-
demote_outbound_markers(path)
-
end
-
-
2
def demote_inbound_markers(path)
-
demoted = []
-
new_demoted = []
-
-
top_level.downto(0) do |i|
-
incoming_markers = path[i].forward_markers[i].dup
-
incoming_markers.each do |marker|
-
unless forward_node_with_marker_at_or_above_level?(marker, i)
-
path[i].forward_markers[i].delete(marker)
-
new_demoted.push(marker)
-
end
-
end
-
-
demoted.each do |marker|
-
path[i + 1].place_marker_on_inbound_path(marker, i, path[i])
-
-
if forward[i].markers.include?(marker)
-
path[i].forward_markers[i].push(marker)
-
else
-
new_demoted.push(marker)
-
end
-
end
-
-
demoted = new_demoted
-
new_demoted = []
-
end
-
end
-
-
2
def demote_outbound_markers(path)
-
demoted = []
-
new_demoted = []
-
-
top_level.downto(0) do |i|
-
forward_markers[i].each do |marker|
-
new_demoted.push(marker) unless path[i].forward_markers[i].include?(marker)
-
end
-
-
demoted.each do |marker|
-
forward[i].place_marker_on_outbound_path(marker, i, forward[i + 1])
-
new_demoted.push(marker) unless path[i].forward_markers[i].include?(marker)
-
end
-
-
demoted = new_demoted
-
new_demoted = []
-
end
-
end
-
-
2
def forward_node_with_marker_at_or_above_level?(marker, level)
-
level.upto(top_level) do |i|
-
return true if forward[i].markers.include?(marker)
-
end
-
false
-
end
-
-
2
def place_marker_on_outbound_path(marker, level, terminus)
-
cur_node = self
-
until cur_node == terminus
-
cur_node.forward_markers[level].push(marker)
-
cur_node.markers.push(marker)
-
cur_node = cur_node.forward[level]
-
end
-
end
-
-
2
def place_marker_on_inbound_path(marker, level, terminus)
-
cur_node = self
-
until cur_node == terminus
-
cur_node.forward_markers[level].push(marker)
-
cur_node = cur_node.forward[level]
-
cur_node.markers.push(marker)
-
end
-
end
-
end
-
end
-
2
module Treetop
-
2
module Runtime
-
2
class SyntaxNode
-
2
attr_reader :input, :interval
-
2
attr_accessor :parent
-
-
2
def initialize(input, interval, elements = nil)
-
1891
@input = input
-
1891
@interval = interval
-
1891
@elements = elements
-
end
-
-
2
def elements
-
18956
return @elements if terminal?
-
# replace the character class placeholders in the sequence (lazy instantiation)
-
12020
last_element = nil
-
@comprehensive_elements ||= @elements.map do |element|
-
512
if element == true
-
index = last_element ? last_element.interval.last : interval.first
-
element = SyntaxNode.new(input, index...(index + 1))
-
end
-
512
element.parent = self
-
512
last_element = element
-
12020
end
-
-
12020
@comprehensive_elements
-
end
-
-
2
def terminal?
-
18956
@elements.nil?
-
end
-
-
2
def nonterminal?
-
!terminal?
-
end
-
-
2
def text_value
-
252
input[interval]
-
end
-
-
2
def empty?
-
16
interval.first == interval.last && interval.exclude_end?
-
end
-
-
2
def <=>(other)
-
self.interval.first <=> other.interval.first
-
end
-
-
2
def extension_modules
-
local_extensions =
-
class <<self
-
included_modules-Object.included_modules
-
end
-
if local_extensions.size > 0
-
local_extensions
-
else
-
[] # There weren't any; must be a literal node
-
end
-
end
-
-
2
def inspect(indent="")
-
em = extension_modules
-
interesting_methods = methods-[em.last ? em.last.methods : nil]-self.class.instance_methods
-
im = interesting_methods.size > 0 ? " (#{interesting_methods.join(",")})" : ""
-
tv = text_value
-
tv = "...#{tv[-20..-1]}" if tv.size > 20
-
-
indent +
-
self.class.to_s.sub(/.*:/,'') +
-
em.map{|m| "+"+m.to_s.sub(/.*:/,'')}*"" +
-
" offset=#{interval.first}" +
-
", #{tv.inspect}" +
-
im +
-
(elements && elements.size > 0 ?
-
":" +
-
(elements||[]).map{|e|
-
begin
-
"\n"+e.inspect(indent+" ")
-
rescue # Defend against inspect not taking a parameter
-
"\n"+indent+" "+e.inspect
-
end
-
}.join("") :
-
""
-
)
-
end
-
-
2
@@dot_id_counter = 0
-
-
2
def dot_id
-
@dot_id ||= @@dot_id_counter += 1
-
end
-
-
2
def write_dot(io)
-
io.puts "node#{dot_id} [label=\"'#{text_value}'\"];"
-
if nonterminal? then
-
elements.each do
-
|x|
-
io.puts "node#{dot_id} -> node#{x.dot_id};"
-
x.write_dot(io)
-
end
-
end
-
end
-
-
2
def write_dot_file(fname)
-
File.open(fname + ".dot","w") do
-
|file|
-
file.puts "digraph G {"
-
write_dot(file)
-
file.puts "}"
-
end
-
end
-
end
-
end
-
end
-
2
module Treetop
-
2
module Runtime
-
2
class TerminalParseFailure
-
2
attr_reader :index, :expected_string
-
-
2
def initialize(index, expected_string)
-
@index = index
-
@expected_string = expected_string
-
end
-
-
2
def to_s
-
"String matching #{expected_string} expected."
-
end
-
end
-
end
-
end
-
2
module BadgeLabelHelper
-
2
def badge(*args)
-
badge_label(:badge, *args)
-
end
-
-
2
def tag_label(*args)
-
badge_label(:label, *args)
-
end
-
-
2
private
-
2
def badge_label(what, value, type = nil)
-
klass = [what]
-
klass << "#{what}-#{type}" if type.present?
-
content_tag :span, value, :class => "#{klass.join(' ')}"
-
end
-
end
-
2
module BootstrapFlashHelper
-
2
ALERT_TYPES = [:error, :info, :success, :warning]
-
-
2
def bootstrap_flash
-
flash_messages = []
-
flash.each do |type, message|
-
# Skip empty messages, e.g. for devise messages set to nothing in a locale file.
-
next if message.blank?
-
-
type = :success if type == :notice
-
type = :error if type == :alert
-
next unless ALERT_TYPES.include?(type)
-
-
Array(message).each do |msg|
-
text = content_tag(:div,
-
content_tag(:button, raw("×"), :class => "close", "data-dismiss" => "alert") +
-
msg.html_safe, :class => "alert fade in alert-#{type}")
-
flash_messages << text if msg
-
end
-
end
-
flash_messages.join("\n").html_safe
-
end
-
end
-
2
module FlashBlockHelper
-
2
def flash_block
-
output = ''
-
flash.each do |type, message|
-
output += flash_container(type, message)
-
end
-
-
raw(output)
-
end
-
-
2
def flash_container(type, message)
-
raw(content_tag(:div, :class => "alert alert-#{type}") do
-
content_tag(:a, raw("×"),:class => 'close', :data => {:dismiss => 'alert'}) +
-
message
-
end)
-
end
-
end
-
2
module GlyphHelper
-
# ==== Examples
-
# glyph(:share_alt)
-
# # => <i class="icon-share-alt"></i>
-
# glyph(:lock, :white)
-
# # => <i class="icon-lock icon-white"></i>
-
# glyph(:thumbs_up, :pull_left)
-
# # => <i class="icon-thumbs-up pull-left"></i>
-
-
2
def glyph(*names)
-
names.map! { |name| name.to_s.gsub('_','-') }
-
names.map! do |name|
-
name =~ /pull-(?:left|right)/ ? name : "icon-#{name}"
-
end
-
content_tag :i, nil, :class => names
-
end
-
end
-
2
module ModalHelper
-
-
#modals have a header, a body, a footer for options.
-
2
def modal_dialog(options = {}, &block)
-
content_tag :div, :id => options[:id], :class => "bootstrap-modal modal hide fade" do
-
modal_header(options[:header]) +
-
modal_body(options[:body]) +
-
modal_footer(options[:footer])
-
end
-
end
-
-
2
def modal_header(options = {}, &block)
-
content_tag :div, :class => 'modal-header' do
-
if options[:show_close]
-
close_button(options[:dismiss]) +
-
content_tag(:h3, options[:title], &block)
-
else
-
content_tag(:h3, options[:title], &block)
-
end
-
end
-
end
-
-
2
def modal_body(options = {}, &block)
-
content_tag :div, options, :class => 'modal-body', &block
-
end
-
-
2
def modal_footer(options = {}, &block)
-
content_tag :div, options, :class => 'modal-footer', &block
-
end
-
-
2
def close_button(dismiss)
-
#It doesn't seem to like content_tag, so we do this instead.
-
raw("<button class=\"close\" data-dismiss=\"#{dismiss}\">×</button>")
-
end
-
-
2
def modal_toggle(content_or_options = nil, options = {}, &block)
-
if block_given?
-
options = content_or_options if content_or_options.is_a?(Hash)
-
default_options = { :class => 'btn', "data-toggle" => "modal", "href" => options[:dialog] }.merge(options)
-
-
content_tag :a, nil, default_options, true, &block
-
else
-
default_options = { :class => 'btn', "data-toggle" => "modal", "href" => options[:dialog] }.merge(options)
-
content_tag :a, content_or_options, default_options, true
-
end
-
end
-
-
2
def modal_cancel_button content, options = {}
-
default_options = { :class => "btn bootstrap-modal-cancel-button" }
-
-
content_tag_string "a", content, default_options.merge(options)
-
end
-
-
end
-
-
#Credit for this goes to https://github.com/julescopeland/Rails-Bootstrap-Navbar
-
2
module NavbarHelper
-
2
def nav_bar(options={}, &block)
-
nav_bar_div(options) do
-
navbar_inner_div do
-
container_div(options[:brand], options[:brand_link], options[:responsive], options[:fluid]) do
-
yield if block_given?
-
end
-
end
-
end
-
end
-
-
2
def menu_group(options={}, &block)
-
pull_class = "pull-#{options[:pull].to_s}" if options[:pull].present?
-
content_tag(:ul, :class => "nav #{pull_class}", &block)
-
end
-
-
2
def menu_item(name=nil, path="#", *args, &block)
-
path = name || path if block_given?
-
options = args.extract_options!
-
content_tag :li, :class => is_active?(path, options) do
-
name, path = path, options if block_given?
-
link_to name, path, options, &block
-
end
-
end
-
-
2
def drop_down(name)
-
content_tag :li, :class => "dropdown" do
-
drop_down_link(name) + drop_down_list { yield }
-
end
-
end
-
-
2
def drop_down_with_submenu(name, &block)
-
content_tag :li, :class => "dropdown" do
-
drop_down_link(name) + drop_down_sublist(&block)
-
end
-
end
-
-
2
def drop_down_sublist(&block)
-
content_tag :ul, :class => "dropdown-menu", &block
-
end
-
-
2
def drop_down_submenu(name, &block)
-
content_tag :li, :class => "dropdown-submenu" do
-
link_to(name, "") + drop_down_list(&block)
-
end
-
end
-
-
2
def drop_down_divider
-
content_tag :li, "", :class => "divider"
-
end
-
-
2
def drop_down_header(text)
-
content_tag :li, text, :class => "nav-header"
-
end
-
-
2
def menu_divider
-
content_tag :li, "", :class => "divider-vertical"
-
end
-
-
2
def menu_text(text=nil, options={}, &block)
-
pull = options.delete(:pull)
-
pull_class = pull.present? ? "pull-#{pull.to_s}" : nil
-
options.append_merge!(:class, pull_class)
-
options.append_merge!(:class, "navbar-text")
-
content_tag :p, options do
-
text || yield
-
end
-
end
-
-
# Returns current url or path state (useful for buttons).
-
# Example:
-
# # Assume we'r currently at blog/categories/test
-
# uri_state('/blog/categories/test', {}) # :active
-
# uri_state('/blog/categories', {}) # :chosen
-
# uri_state('/blog/categories/test', {method: delete}) # :inactive
-
# uri_state('/blog/categories/test/3', {}) # :inactive
-
2
def uri_state(uri, options={})
-
root_url = request.host_with_port + '/'
-
root = uri == '/' || uri == root_url
-
-
request_uri = if uri.start_with?(root_url)
-
request.url
-
else
-
request.path
-
end
-
-
if !options[:method].nil? || !options["data-method"].nil?
-
:inactive
-
elsif uri == request_uri
-
:active
-
else
-
if request_uri.start_with?(uri) and not(root)
-
:chosen
-
else
-
:inactive
-
end
-
end
-
end
-
-
2
private
-
-
2
def nav_bar_div(options, &block)
-
-
position = "static-#{options[:static].to_s}" if options[:static]
-
position = "fixed-#{options[:fixed].to_s}" if options[:fixed]
-
inverse = (options[:inverse].present? && options[:inverse] == true) ? true : false
-
-
content_tag :div, :class => nav_bar_css_class(position, inverse) do
-
yield
-
end
-
end
-
-
2
def navbar_inner_div(&block)
-
content_tag :div, :class => "navbar-inner" do
-
yield
-
end
-
end
-
-
2
def container_div(brand, brand_link, responsive, fluid, &block)
-
content_tag :div, :class => "container#{"-fluid" if fluid}" do
-
container_div_with_block(brand, brand_link, responsive, &block)
-
end
-
end
-
-
2
def container_div_with_block(brand, brand_link, responsive, &block)
-
output = []
-
if responsive == true
-
output << responsive_button
-
output << brand_link(brand, brand_link)
-
output << responsive_div { capture(&block) }
-
else
-
output << brand_link(brand, brand_link)
-
output << capture(&block)
-
end
-
output.join("\n").html_safe
-
end
-
-
2
def nav_bar_css_class(position, inverse = false)
-
css_class = ["navbar"]
-
css_class << "navbar-#{position}" if position.present?
-
css_class << "navbar-inverse" if inverse
-
css_class.join(" ")
-
end
-
-
2
def brand_link(name, url)
-
return "" if name.blank?
-
url ||= root_url
-
link_to(name, url, :class => "brand")
-
end
-
-
2
def responsive_button
-
%{<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
-
<span class="icon-bar"></span>
-
<span class="icon-bar"></span>
-
<span class="icon-bar"></span>
-
</a>}
-
end
-
-
2
def responsive_div(&block)
-
content_tag(:div, :class => "nav-collapse collapse", &block)
-
end
-
-
2
def is_active?(path, options={})
-
"active" if uri_state(path, options).in?([:active, :chosen])
-
end
-
-
2
def name_and_caret(name)
-
"#{name} #{content_tag(:b, :class => "caret") {}}".html_safe
-
end
-
-
2
def drop_down_link(name)
-
link_to(name_and_caret(name), "#", :class => "dropdown-toggle", "data-toggle" => "dropdown")
-
end
-
-
2
def drop_down_list(&block)
-
content_tag :ul, :class => "dropdown-menu", &block
-
end
-
end
-
-
2
class Hash
-
# appends a string to a hash key's value after a space character (Good for merging CSS classes in options hashes)
-
2
def append_merge!(key, value)
-
# just return self if value is blank
-
return self if value.blank?
-
-
current_value = self[key]
-
# just merge if it doesn't already have that key
-
self[key] = value and return if current_value.blank?
-
# raise error if we're trying to merge into something that isn't a string
-
raise ArgumentError, "Can only merge strings" unless current_value.is_a?(String)
-
self[key] = [current_value, value].compact.join(" ")
-
end
-
end
-
2
module TwitterBreadcrumbsHelper
-
2
def render_breadcrumbs(divider = '/', &block)
-
content = render :partial => 'twitter-bootstrap/breadcrumbs', :layout => false, :locals => { :divider => divider }
-
if block_given?
-
capture(content, &block)
-
else
-
content
-
end
-
end
-
end
-
2
module Twitter
-
2
module Bootstrap
-
2
module Rails
-
2
require 'twitter/bootstrap/rails/engine' if defined?(Rails)
-
end
-
end
-
end
-
-
#require 'less-rails'
-
2
require 'twitter/bootstrap/rails/bootstrap' if defined?(Rails)
-
2
require "twitter/bootstrap/rails/engine"
-
2
require "twitter/bootstrap/rails/version"
-
2
require 'rails'
-
-
2
require File.dirname(__FILE__) + '/twitter-bootstrap-breadcrumbs.rb'
-
2
require File.dirname(__FILE__) + '/../../../../app/helpers/flash_block_helper.rb'
-
2
require File.dirname(__FILE__) + '/../../../../app/helpers/modal_helper.rb'
-
2
require File.dirname(__FILE__) + '/../../../../app/helpers/navbar_helper.rb'
-
-
2
module Twitter
-
2
module Bootstrap
-
2
module Rails
-
2
class Engine < ::Rails::Engine
-
2
initializer 'twitter-bootstrap-rails.setup',
-
:after => 'less-rails.after.load_config_initializers',
-
:group => :all do |app|
-
2
if defined?(Less)
-
2
app.config.less.paths << File.join(config.root, 'vendor', 'toolkit')
-
end
-
end
-
-
2
initializer 'twitter-bootstrap-rails.setup_helpers' do |app|
-
2
app.config.to_prepare do
-
2
ActionController::Base.send :include, BreadCrumbs
-
2
ActionController::Base.send :helper, FlashBlockHelper
-
2
ActionController::Base.send :helper, ModalHelper
-
2
ActionController::Base.send :helper, NavbarHelper
-
2
ActionController::Base.send :helper, BadgeLabelHelper
-
#ActionController::Base.send :helper_method, :render_breadcrumbs
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module Twitter
-
2
module Bootstrap
-
2
module BreadCrumbs
-
2
def self.included(base)
-
2
base.extend(ClassMethods)
-
end
-
-
2
module ClassMethods
-
2
def add_breadcrumb(name, url, options = {})
-
class_name = self.name
-
before_filter options do |controller|
-
name = controller.send :translate_breadcrumb, name, class_name if name.is_a?(Symbol)
-
controller.send :add_breadcrumb, name, url
-
end
-
end
-
end
-
-
2
protected
-
-
2
def add_breadcrumb(name, url = '', options = {})
-
@breadcrumbs ||= []
-
name = translate_breadcrumb(name, self.class.name) if name.is_a?(Symbol)
-
url = eval(url.to_s) if url =~ /_path|_url|@/
-
@breadcrumbs << {:name => name, :url => url, :options => options}
-
end
-
-
2
def translate_breadcrumb(name, class_name)
-
scope = [:breadcrumbs]
-
namespace = class_name.underscore.split('/')
-
namespace.last.sub!('_controller', '')
-
scope += namespace
-
-
I18n.t name, :scope => scope
-
end
-
-
2
def render_breadcrumbs(divider = '/')
-
s = render :partial => 'twitter-bootstrap/breadcrumbs', :locals => {:divider => divider}
-
s.first
-
end
-
end
-
end
-
end
-
2
module Twitter
-
2
module Bootstrap
-
2
module Rails
-
2
VERSION = "2.2.8"
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2005-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
# Add the directory containing this file to the start of the load path if it
-
# isn't there already.
-
$:.unshift(File.dirname(__FILE__)) unless
-
2
$:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
-
-
-
2
require 'tzinfo/ruby_core_support'
-
2
require 'tzinfo/offset_rationals'
-
2
require 'tzinfo/time_or_datetime'
-
-
2
require 'tzinfo/timezone_definition'
-
-
2
require 'tzinfo/timezone_offset_info'
-
2
require 'tzinfo/timezone_transition_info'
-
-
2
require 'tzinfo/timezone_index_definition'
-
-
2
require 'tzinfo/timezone_info'
-
2
require 'tzinfo/data_timezone_info'
-
2
require 'tzinfo/linked_timezone_info'
-
-
2
require 'tzinfo/timezone_period'
-
2
require 'tzinfo/timezone'
-
2
require 'tzinfo/info_timezone'
-
2
require 'tzinfo/data_timezone'
-
2
require 'tzinfo/linked_timezone'
-
2
require 'tzinfo/timezone_proxy'
-
-
2
require 'tzinfo/country_index_definition'
-
2
require 'tzinfo/country_info'
-
-
2
require 'tzinfo/country'
-
2
require 'tzinfo/country_timezone'
-
#--
-
# Copyright (c) 2005-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
# Thrown by Country#get if the code given is not valid.
-
2
class InvalidCountryCode < StandardError
-
end
-
-
# An ISO 3166 country. Can be used to get a list of Timezones for a country.
-
# For example:
-
#
-
# us = Country.get('US')
-
# us.zone_identifiers
-
# us.zones
-
# us.zone_info
-
2
class Country
-
2
include Comparable
-
-
# Defined countries.
-
#
-
# @!visibility private
-
2
@@countries = {}
-
-
# Whether the countries index has been loaded yet.
-
#
-
# @!visibility private
-
2
@@index_loaded = false
-
-
# Gets a Country by its ISO 3166 code. Raises an InvalidCountryCode
-
# exception if it couldn't be found.
-
2
def self.get(identifier)
-
instance = @@countries[identifier]
-
-
unless instance
-
load_index
-
info = Indexes::Countries.countries[identifier]
-
raise InvalidCountryCode.new, 'Invalid identifier' unless info
-
instance = Country.new(info)
-
@@countries[identifier] = instance
-
end
-
-
instance
-
end
-
-
# If identifier is a CountryInfo object, initializes the Country instance,
-
# otherwise calls get(identifier).
-
2
def self.new(identifier)
-
if identifier.kind_of?(CountryInfo)
-
instance = super()
-
instance.send :setup, identifier
-
instance
-
else
-
get(identifier)
-
end
-
end
-
-
# Returns an Array of all the valid country codes.
-
2
def self.all_codes
-
load_index
-
Indexes::Countries.countries.keys
-
end
-
-
# Returns an Array of all the defined Countries.
-
2
def self.all
-
load_index
-
Indexes::Countries.countries.keys.collect {|code| get(code)}
-
end
-
-
# The ISO 3166 country code.
-
2
def code
-
@info.code
-
end
-
-
# The name of the country.
-
2
def name
-
@info.name
-
end
-
-
# Alias for name.
-
2
def to_s
-
name
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #{@info.code}>"
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country. These
-
# are in an order that
-
# (1) makes some geographical sense, and
-
# (2) puts the most populous zones first, where that does not contradict (1).
-
2
def zone_identifiers
-
@info.zone_identifiers
-
end
-
2
alias zone_names zone_identifiers
-
-
# An array of all the Timezones for this country. Returns TimezoneProxy
-
# objects to avoid the overhead of loading Timezone definitions until
-
# a conversion is actually required. The Timezones are returned in an order
-
# that
-
# (1) makes some geographical sense, and
-
# (2) puts the most populous zones first, where that does not contradict (1).
-
2
def zones
-
zone_identifiers.collect {|id|
-
Timezone.get_proxy(id)
-
}
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances (containing extra information about each zone).
-
# These are in an order that
-
# (1) makes some geographical sense, and
-
# (2) puts the most populous zones first, where that does not contradict (1).
-
2
def zone_info
-
@info.zones
-
end
-
-
# Compare two Countries based on their code. Returns -1 if c is less
-
# than self, 0 if c is equal to self and +1 if c is greater than self.
-
2
def <=>(c)
-
code <=> c.code
-
end
-
-
# Returns true if and only if the code of c is equal to the code of this
-
# Country.
-
2
def eql?(c)
-
self == c
-
end
-
-
# Returns a hash value for this Country.
-
2
def hash
-
code.hash
-
end
-
-
# Dumps this Country for marshalling.
-
2
def _dump(limit)
-
code
-
end
-
-
# Loads a marshalled Country.
-
2
def self._load(data)
-
Country.get(data)
-
end
-
-
2
private
-
# Loads in the index of countries if it hasn't already been loaded.
-
2
def self.load_index
-
unless @@index_loaded
-
require 'tzinfo/indexes/countries'
-
@@index_loaded = true
-
end
-
end
-
-
# Called by Country.new to initialize a new Country instance. The info
-
# parameter is a CountryInfo that defines the country.
-
2
def setup(info)
-
@info = info
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
# The country index file includes CountryIndexDefinition which provides
-
# a country method used to define each country in the index.
-
#
-
# @private
-
2
module CountryIndexDefinition #:nodoc:
-
2
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
base.instance_eval { @countries = {} }
-
end
-
-
# Class methods for inclusion.
-
#
-
# @private
-
2
module ClassMethods #:nodoc:
-
# Defines a country with an ISO 3166 country code, name and block. The
-
# block will be evaluated to obtain all the timezones for the country.
-
# Calls Country.country_defined with the definition of each country.
-
2
def country(code, name, &block)
-
@countries[code] = CountryInfo.new(code, name, &block)
-
end
-
-
# Returns a frozen hash of all the countries that have been defined in
-
# the index.
-
2
def countries
-
@countries.freeze
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
# Class to store the data loaded from the country index. Instances of this
-
# class are passed to the blocks in the index that define timezones.
-
#
-
# @private
-
2
class CountryInfo #:nodoc:
-
2
attr_reader :code
-
2
attr_reader :name
-
-
# Constructs a new CountryInfo with an ISO 3166 country code, name and
-
# block. The block will be evaluated to obtain the timezones for the country
-
# (when they are first needed).
-
2
def initialize(code, name, &block)
-
@code = code
-
@name = name
-
@block = block
-
@zones = nil
-
@zone_identifiers = nil
-
end
-
-
# Called by the index data to define a timezone for the country.
-
2
def timezone(identifier, latitude_numerator, latitude_denominator,
-
longitude_numerator, longitude_denominator, description = nil)
-
# Currently only store the identifiers.
-
@zones << CountryTimezone.new(identifier, latitude_numerator,
-
latitude_denominator, longitude_numerator, longitude_denominator,
-
description)
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country. These
-
# are in the order they were added using the timezone method.
-
2
def zone_identifiers
-
unless @zone_identifiers
-
@zone_identifiers = zones.collect {|zone| zone.identifier}
-
@zone_identifiers.freeze
-
end
-
-
@zone_identifiers
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #@code>"
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances. These are in the order they were added using
-
# the timezone method.
-
2
def zones
-
unless @zones
-
@zones = []
-
@block.call(self) if @block
-
@block = nil
-
@zones.freeze
-
end
-
-
@zones
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
# A Timezone within a Country. This contains extra information about the
-
# Timezone that is specific to the Country (a Timezone could be used by
-
# multiple countries).
-
2
class CountryTimezone
-
# The zone identifier.
-
2
attr_reader :identifier
-
-
# A description of this timezone in relation to the country, e.g.
-
# "Eastern Time". This is usually nil for countries having only a single
-
# Timezone.
-
2
attr_reader :description
-
-
# Creates a new CountryTimezone with a timezone identifier, latitude,
-
# longitude and description. The latitude and longitude are specified as
-
# rationals - a numerator and denominator. For performance reasons, the
-
# numerators and denominators must be specified in their lowest form.
-
#
-
# CountryTimezone instances should not normally be constructed manually.
-
2
def initialize(identifier, latitude_numerator, latitude_denominator,
-
longitude_numerator, longitude_denominator, description = nil) #:nodoc:
-
@identifier = identifier
-
@latitude_numerator = latitude_numerator
-
@latitude_denominator = latitude_denominator
-
@longitude_numerator = longitude_numerator
-
@longitude_denominator = longitude_denominator
-
@description = description
-
end
-
-
# The Timezone (actually a TimezoneProxy for performance reasons).
-
2
def timezone
-
Timezone.get_proxy(@identifier)
-
end
-
-
# if description is not nil, this method returns description; otherwise it
-
# returns timezone.friendly_identifier(true).
-
2
def description_or_friendly_identifier
-
description || timezone.friendly_identifier(true)
-
end
-
-
# The latitude of this timezone in degrees as a Rational.
-
2
def latitude
-
@latitude ||= RubyCoreSupport.rational_new!(@latitude_numerator, @latitude_denominator)
-
end
-
-
# The longitude of this timezone in degrees as a Rational.
-
2
def longitude
-
@longitude ||= RubyCoreSupport.rational_new!(@longitude_numerator, @longitude_denominator)
-
end
-
-
# Returns true if and only if the given CountryTimezone is equal to the
-
# current CountryTimezone (has the same identifer, latitude, longitude
-
# and description).
-
2
def ==(ct)
-
ct.kind_of?(CountryTimezone) &&
-
identifier == ct.identifier && latitude == ct.latitude &&
-
longitude == ct.longitude && description == ct.description
-
end
-
-
# Returns true if and only if the given CountryTimezone is equal to the
-
# current CountryTimezone (has the same identifer, latitude, longitude
-
# and description).
-
2
def eql?(ct)
-
self == ct
-
end
-
-
# Returns a hash of this CountryTimezone.
-
2
def hash
-
@identifier.hash ^ @latitude_numerator.hash ^ @latitude_denominator.hash ^
-
@longitude_numerator.hash ^ @longitude_denominator.hash ^ @description.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #@identifier>"
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
-
# A Timezone based on a DataTimezoneInfo.
-
#
-
# @private
-
2
class DataTimezone < InfoTimezone #:nodoc:
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
#
-
# If no TimezonePeriod could be found, PeriodNotFound is raised.
-
2
def period_for_utc(utc)
-
1472
info.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Raises PeriodNotFound if no periods are found for the given time.
-
2
def periods_for_local(local)
-
1122
info.periods_for_local(local)
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
# Thrown if no offsets have been defined when calling period_for_utc or
-
# periods_for_local. Indicates an error in the timezone data.
-
2
class NoOffsetsDefined < StandardError
-
end
-
-
# Represents a (non-linked) timezone defined in a data module.
-
#
-
# @private
-
2
class DataTimezoneInfo < TimezoneInfo #:nodoc:
-
-
# Constructs a new TimezoneInfo with its identifier.
-
2
def initialize(identifier)
-
2
super(identifier)
-
2
@offsets = {}
-
2
@transitions = []
-
2
@previous_offset = nil
-
2
@transitions_index = nil
-
end
-
-
# Defines a offset. The id uniquely identifies this offset within the
-
# timezone. utc_offset and std_offset define the offset in seconds of
-
# standard time from UTC and daylight savings from standard time
-
# respectively. abbreviation describes the timezone offset (e.g. GMT, BST,
-
# EST or EDT).
-
#
-
# The first offset to be defined is treated as the offset that applies
-
# until the first transition. This will usually be in Local Mean Time (LMT).
-
#
-
# ArgumentError will be raised if the id is already defined.
-
2
def offset(id, utc_offset, std_offset, abbreviation)
-
10
raise ArgumentError, 'Offset already defined' if @offsets.has_key?(id)
-
-
10
offset = TimezoneOffsetInfo.new(utc_offset, std_offset, abbreviation)
-
10
@offsets[id] = offset
-
10
@previous_offset = offset unless @previous_offset
-
end
-
-
# Defines a transition. Transitions must be defined in chronological order.
-
# ArgumentError will be raised if a transition is added out of order.
-
# offset_id refers to an id defined with offset. ArgumentError will be
-
# raised if the offset_id cannot be found. numerator_or_time and
-
# denomiator specify the time the transition occurs as. See
-
# TimezoneTransitionInfo for more detail about specifying times.
-
2
def transition(year, month, offset_id, numerator_or_time, denominator = nil)
-
524
offset = @offsets[offset_id]
-
524
raise ArgumentError, 'Offset not found' unless offset
-
-
524
if @transitions_index
-
522
if year < @last_year || (year == @last_year && month < @last_month)
-
raise ArgumentError, 'Transitions must be increasing date order'
-
end
-
-
# Record the position of the first transition with this index.
-
522
index = transition_index(year, month)
-
522
@transitions_index[index] ||= @transitions.length
-
-
# Fill in any gaps
-
522
(index - 1).downto(0) do |i|
-
670
break if @transitions_index[i]
-
148
@transitions_index[i] = @transitions.length
-
end
-
else
-
2
@transitions_index = [@transitions.length]
-
2
@start_year = year
-
2
@start_month = month
-
end
-
-
@transitions << TimezoneTransitionInfo.new(offset, @previous_offset,
-
524
numerator_or_time, denominator)
-
524
@last_year = year
-
524
@last_month = month
-
524
@previous_offset = offset
-
end
-
-
# Returns the TimezonePeriod for the given UTC time.
-
# Raises NoOffsetsDefined if no offsets have been defined.
-
2
def period_for_utc(utc)
-
1472
unless @transitions.empty?
-
1472
utc = TimeOrDateTime.wrap(utc)
-
1472
index = transition_index(utc.year, utc.mon)
-
-
1472
start_transition = nil
-
1472
start = transition_before_end(index)
-
1472
if start
-
1472
start.downto(0) do |i|
-
2896
if @transitions[i].at <= utc
-
1472
start_transition = @transitions[i]
-
1472
break
-
end
-
end
-
end
-
-
1472
end_transition = nil
-
1472
start = transition_after_start(index)
-
1472
if start
-
1472
start.upto(@transitions.length - 1) do |i|
-
1520
if @transitions[i].at > utc
-
1472
end_transition = @transitions[i]
-
1472
break
-
end
-
end
-
end
-
-
1472
if start_transition || end_transition
-
1472
TimezonePeriod.new(start_transition, end_transition)
-
else
-
# Won't happen since there are transitions. Must always find one
-
# transition that is either >= or < the specified time.
-
raise 'No transitions found in search'
-
end
-
else
-
raise NoOffsetsDefined, 'No offsets have been defined' unless @previous_offset
-
TimezonePeriod.new(nil, nil, @previous_offset)
-
end
-
end
-
-
# Returns the set of TimezonePeriods for the given local time as an array.
-
# Results returned are ordered by increasing UTC start date.
-
# Returns an empty array if no periods are found for the given time.
-
# Raises NoOffsetsDefined if no offsets have been defined.
-
2
def periods_for_local(local)
-
1122
unless @transitions.empty?
-
1122
local = TimeOrDateTime.wrap(local)
-
1122
index = transition_index(local.year, local.mon)
-
-
1122
result = []
-
-
1122
start_index = transition_after_start(index - 1)
-
1122
if start_index && @transitions[start_index].local_end > local
-
if start_index > 0
-
if @transitions[start_index - 1].local_start <= local
-
result << TimezonePeriod.new(@transitions[start_index - 1], @transitions[start_index])
-
end
-
else
-
result << TimezonePeriod.new(nil, @transitions[start_index])
-
end
-
end
-
-
1122
end_index = transition_before_end(index + 1)
-
-
1122
if end_index
-
1122
start_index = end_index unless start_index
-
-
1122
start_index.upto(transition_before_end(index + 1)) do |i|
-
3366
if @transitions[i].local_start <= local
-
1165
if i + 1 < @transitions.length
-
1165
if @transitions[i + 1].local_end > local
-
1122
result << TimezonePeriod.new(@transitions[i], @transitions[i + 1])
-
end
-
else
-
result << TimezonePeriod.new(@transitions[i], nil)
-
end
-
end
-
end
-
end
-
-
1122
result
-
else
-
raise NoOffsetsDefined, 'No offsets have been defined' unless @previous_offset
-
[TimezonePeriod.new(nil, nil, @previous_offset)]
-
end
-
end
-
-
2
private
-
# Returns the index into the @transitions_index array for a given year
-
# and month.
-
2
def transition_index(year, month)
-
3116
index = (year - @start_year) * 2
-
3116
index += 1 if month > 6
-
3116
index -= 1 if @start_month > 6
-
3116
index
-
end
-
-
# Returns the index into @transitions of the first transition that occurs
-
# on or after the start of the given index into @transitions_index.
-
# Returns nil if there are no such transitions.
-
2
def transition_after_start(index)
-
2594
if index >= @transitions_index.length
-
nil
-
else
-
2594
index = 0 if index < 0
-
2594
@transitions_index[index]
-
end
-
end
-
-
# Returns the index into @transitions of the first transition that occurs
-
# before the end of the given index into @transitions_index.
-
# Returns nil if there are no such transitions.
-
2
def transition_before_end(index)
-
3716
index = index + 1
-
-
3716
if index <= 0
-
nil
-
3716
elsif index >= @transitions_index.length
-
@transitions.length - 1
-
else
-
3716
@transitions_index[index] - 1
-
end
-
end
-
end
-
end
-
2
module TZInfo
-
2
module Definitions
-
2
module America
-
2
module New_York
-
2
include TimezoneDefinition
-
-
2
timezone 'America/New_York' do |tz|
-
2
tz.offset :o0, -17762, 0, :LMT
-
2
tz.offset :o1, -18000, 0, :EST
-
2
tz.offset :o2, -18000, 3600, :EDT
-
2
tz.offset :o3, -18000, 3600, :EWT
-
2
tz.offset :o4, -18000, 3600, :EPT
-
-
2
tz.transition 1883, 11, :o1, 57819197, 24
-
2
tz.transition 1918, 3, :o2, 58120411, 24
-
2
tz.transition 1918, 10, :o1, 9687575, 4
-
2
tz.transition 1919, 3, :o2, 58129147, 24
-
2
tz.transition 1919, 10, :o1, 9689031, 4
-
2
tz.transition 1920, 3, :o2, 58137883, 24
-
2
tz.transition 1920, 10, :o1, 9690515, 4
-
2
tz.transition 1921, 4, :o2, 58147291, 24
-
2
tz.transition 1921, 9, :o1, 9691831, 4
-
2
tz.transition 1922, 4, :o2, 58156195, 24
-
2
tz.transition 1922, 9, :o1, 9693287, 4
-
2
tz.transition 1923, 4, :o2, 58164931, 24
-
2
tz.transition 1923, 9, :o1, 9694771, 4
-
2
tz.transition 1924, 4, :o2, 58173667, 24
-
2
tz.transition 1924, 9, :o1, 9696227, 4
-
2
tz.transition 1925, 4, :o2, 58182403, 24
-
2
tz.transition 1925, 9, :o1, 9697683, 4
-
2
tz.transition 1926, 4, :o2, 58191139, 24
-
2
tz.transition 1926, 9, :o1, 9699139, 4
-
2
tz.transition 1927, 4, :o2, 58199875, 24
-
2
tz.transition 1927, 9, :o1, 9700595, 4
-
2
tz.transition 1928, 4, :o2, 58208779, 24
-
2
tz.transition 1928, 9, :o1, 9702079, 4
-
2
tz.transition 1929, 4, :o2, 58217515, 24
-
2
tz.transition 1929, 9, :o1, 9703535, 4
-
2
tz.transition 1930, 4, :o2, 58226251, 24
-
2
tz.transition 1930, 9, :o1, 9704991, 4
-
2
tz.transition 1931, 4, :o2, 58234987, 24
-
2
tz.transition 1931, 9, :o1, 9706447, 4
-
2
tz.transition 1932, 4, :o2, 58243723, 24
-
2
tz.transition 1932, 9, :o1, 9707903, 4
-
2
tz.transition 1933, 4, :o2, 58252627, 24
-
2
tz.transition 1933, 9, :o1, 9709359, 4
-
2
tz.transition 1934, 4, :o2, 58261363, 24
-
2
tz.transition 1934, 9, :o1, 9710843, 4
-
2
tz.transition 1935, 4, :o2, 58270099, 24
-
2
tz.transition 1935, 9, :o1, 9712299, 4
-
2
tz.transition 1936, 4, :o2, 58278835, 24
-
2
tz.transition 1936, 9, :o1, 9713755, 4
-
2
tz.transition 1937, 4, :o2, 58287571, 24
-
2
tz.transition 1937, 9, :o1, 9715211, 4
-
2
tz.transition 1938, 4, :o2, 58296307, 24
-
2
tz.transition 1938, 9, :o1, 9716667, 4
-
2
tz.transition 1939, 4, :o2, 58305211, 24
-
2
tz.transition 1939, 9, :o1, 9718123, 4
-
2
tz.transition 1940, 4, :o2, 58313947, 24
-
2
tz.transition 1940, 9, :o1, 9719607, 4
-
2
tz.transition 1941, 4, :o2, 58322683, 24
-
2
tz.transition 1941, 9, :o1, 9721063, 4
-
2
tz.transition 1942, 2, :o3, 58329595, 24
-
2
tz.transition 1945, 8, :o4, 58360379, 24
-
2
tz.transition 1945, 9, :o1, 9726915, 4
-
2
tz.transition 1946, 4, :o2, 58366531, 24
-
2
tz.transition 1946, 9, :o1, 9728371, 4
-
2
tz.transition 1947, 4, :o2, 58375267, 24
-
2
tz.transition 1947, 9, :o1, 9729827, 4
-
2
tz.transition 1948, 4, :o2, 58384003, 24
-
2
tz.transition 1948, 9, :o1, 9731283, 4
-
2
tz.transition 1949, 4, :o2, 58392739, 24
-
2
tz.transition 1949, 9, :o1, 9732739, 4
-
2
tz.transition 1950, 4, :o2, 58401643, 24
-
2
tz.transition 1950, 9, :o1, 9734195, 4
-
2
tz.transition 1951, 4, :o2, 58410379, 24
-
2
tz.transition 1951, 9, :o1, 9735679, 4
-
2
tz.transition 1952, 4, :o2, 58419115, 24
-
2
tz.transition 1952, 9, :o1, 9737135, 4
-
2
tz.transition 1953, 4, :o2, 58427851, 24
-
2
tz.transition 1953, 9, :o1, 9738591, 4
-
2
tz.transition 1954, 4, :o2, 58436587, 24
-
2
tz.transition 1954, 9, :o1, 9740047, 4
-
2
tz.transition 1955, 4, :o2, 58445323, 24
-
2
tz.transition 1955, 10, :o1, 9741643, 4
-
2
tz.transition 1956, 4, :o2, 58454227, 24
-
2
tz.transition 1956, 10, :o1, 9743099, 4
-
2
tz.transition 1957, 4, :o2, 58462963, 24
-
2
tz.transition 1957, 10, :o1, 9744555, 4
-
2
tz.transition 1958, 4, :o2, 58471699, 24
-
2
tz.transition 1958, 10, :o1, 9746011, 4
-
2
tz.transition 1959, 4, :o2, 58480435, 24
-
2
tz.transition 1959, 10, :o1, 9747467, 4
-
2
tz.transition 1960, 4, :o2, 58489171, 24
-
2
tz.transition 1960, 10, :o1, 9748951, 4
-
2
tz.transition 1961, 4, :o2, 58498075, 24
-
2
tz.transition 1961, 10, :o1, 9750407, 4
-
2
tz.transition 1962, 4, :o2, 58506811, 24
-
2
tz.transition 1962, 10, :o1, 9751863, 4
-
2
tz.transition 1963, 4, :o2, 58515547, 24
-
2
tz.transition 1963, 10, :o1, 9753319, 4
-
2
tz.transition 1964, 4, :o2, 58524283, 24
-
2
tz.transition 1964, 10, :o1, 9754775, 4
-
2
tz.transition 1965, 4, :o2, 58533019, 24
-
2
tz.transition 1965, 10, :o1, 9756259, 4
-
2
tz.transition 1966, 4, :o2, 58541755, 24
-
2
tz.transition 1966, 10, :o1, 9757715, 4
-
2
tz.transition 1967, 4, :o2, 58550659, 24
-
2
tz.transition 1967, 10, :o1, 9759171, 4
-
2
tz.transition 1968, 4, :o2, 58559395, 24
-
2
tz.transition 1968, 10, :o1, 9760627, 4
-
2
tz.transition 1969, 4, :o2, 58568131, 24
-
2
tz.transition 1969, 10, :o1, 9762083, 4
-
2
tz.transition 1970, 4, :o2, 9961200
-
2
tz.transition 1970, 10, :o1, 25682400
-
2
tz.transition 1971, 4, :o2, 41410800
-
2
tz.transition 1971, 10, :o1, 57736800
-
2
tz.transition 1972, 4, :o2, 73465200
-
2
tz.transition 1972, 10, :o1, 89186400
-
2
tz.transition 1973, 4, :o2, 104914800
-
2
tz.transition 1973, 10, :o1, 120636000
-
2
tz.transition 1974, 1, :o2, 126687600
-
2
tz.transition 1974, 10, :o1, 152085600
-
2
tz.transition 1975, 2, :o2, 162370800
-
2
tz.transition 1975, 10, :o1, 183535200
-
2
tz.transition 1976, 4, :o2, 199263600
-
2
tz.transition 1976, 10, :o1, 215589600
-
2
tz.transition 1977, 4, :o2, 230713200
-
2
tz.transition 1977, 10, :o1, 247039200
-
2
tz.transition 1978, 4, :o2, 262767600
-
2
tz.transition 1978, 10, :o1, 278488800
-
2
tz.transition 1979, 4, :o2, 294217200
-
2
tz.transition 1979, 10, :o1, 309938400
-
2
tz.transition 1980, 4, :o2, 325666800
-
2
tz.transition 1980, 10, :o1, 341388000
-
2
tz.transition 1981, 4, :o2, 357116400
-
2
tz.transition 1981, 10, :o1, 372837600
-
2
tz.transition 1982, 4, :o2, 388566000
-
2
tz.transition 1982, 10, :o1, 404892000
-
2
tz.transition 1983, 4, :o2, 420015600
-
2
tz.transition 1983, 10, :o1, 436341600
-
2
tz.transition 1984, 4, :o2, 452070000
-
2
tz.transition 1984, 10, :o1, 467791200
-
2
tz.transition 1985, 4, :o2, 483519600
-
2
tz.transition 1985, 10, :o1, 499240800
-
2
tz.transition 1986, 4, :o2, 514969200
-
2
tz.transition 1986, 10, :o1, 530690400
-
2
tz.transition 1987, 4, :o2, 544604400
-
2
tz.transition 1987, 10, :o1, 562140000
-
2
tz.transition 1988, 4, :o2, 576054000
-
2
tz.transition 1988, 10, :o1, 594194400
-
2
tz.transition 1989, 4, :o2, 607503600
-
2
tz.transition 1989, 10, :o1, 625644000
-
2
tz.transition 1990, 4, :o2, 638953200
-
2
tz.transition 1990, 10, :o1, 657093600
-
2
tz.transition 1991, 4, :o2, 671007600
-
2
tz.transition 1991, 10, :o1, 688543200
-
2
tz.transition 1992, 4, :o2, 702457200
-
2
tz.transition 1992, 10, :o1, 719992800
-
2
tz.transition 1993, 4, :o2, 733906800
-
2
tz.transition 1993, 10, :o1, 752047200
-
2
tz.transition 1994, 4, :o2, 765356400
-
2
tz.transition 1994, 10, :o1, 783496800
-
2
tz.transition 1995, 4, :o2, 796806000
-
2
tz.transition 1995, 10, :o1, 814946400
-
2
tz.transition 1996, 4, :o2, 828860400
-
2
tz.transition 1996, 10, :o1, 846396000
-
2
tz.transition 1997, 4, :o2, 860310000
-
2
tz.transition 1997, 10, :o1, 877845600
-
2
tz.transition 1998, 4, :o2, 891759600
-
2
tz.transition 1998, 10, :o1, 909295200
-
2
tz.transition 1999, 4, :o2, 923209200
-
2
tz.transition 1999, 10, :o1, 941349600
-
2
tz.transition 2000, 4, :o2, 954658800
-
2
tz.transition 2000, 10, :o1, 972799200
-
2
tz.transition 2001, 4, :o2, 986108400
-
2
tz.transition 2001, 10, :o1, 1004248800
-
2
tz.transition 2002, 4, :o2, 1018162800
-
2
tz.transition 2002, 10, :o1, 1035698400
-
2
tz.transition 2003, 4, :o2, 1049612400
-
2
tz.transition 2003, 10, :o1, 1067148000
-
2
tz.transition 2004, 4, :o2, 1081062000
-
2
tz.transition 2004, 10, :o1, 1099202400
-
2
tz.transition 2005, 4, :o2, 1112511600
-
2
tz.transition 2005, 10, :o1, 1130652000
-
2
tz.transition 2006, 4, :o2, 1143961200
-
2
tz.transition 2006, 10, :o1, 1162101600
-
2
tz.transition 2007, 3, :o2, 1173596400
-
2
tz.transition 2007, 11, :o1, 1194156000
-
2
tz.transition 2008, 3, :o2, 1205046000
-
2
tz.transition 2008, 11, :o1, 1225605600
-
2
tz.transition 2009, 3, :o2, 1236495600
-
2
tz.transition 2009, 11, :o1, 1257055200
-
2
tz.transition 2010, 3, :o2, 1268550000
-
2
tz.transition 2010, 11, :o1, 1289109600
-
2
tz.transition 2011, 3, :o2, 1299999600
-
2
tz.transition 2011, 11, :o1, 1320559200
-
2
tz.transition 2012, 3, :o2, 1331449200
-
2
tz.transition 2012, 11, :o1, 1352008800
-
2
tz.transition 2013, 3, :o2, 1362898800
-
2
tz.transition 2013, 11, :o1, 1383458400
-
2
tz.transition 2014, 3, :o2, 1394348400
-
2
tz.transition 2014, 11, :o1, 1414908000
-
2
tz.transition 2015, 3, :o2, 1425798000
-
2
tz.transition 2015, 11, :o1, 1446357600
-
2
tz.transition 2016, 3, :o2, 1457852400
-
2
tz.transition 2016, 11, :o1, 1478412000
-
2
tz.transition 2017, 3, :o2, 1489302000
-
2
tz.transition 2017, 11, :o1, 1509861600
-
2
tz.transition 2018, 3, :o2, 1520751600
-
2
tz.transition 2018, 11, :o1, 1541311200
-
2
tz.transition 2019, 3, :o2, 1552201200
-
2
tz.transition 2019, 11, :o1, 1572760800
-
2
tz.transition 2020, 3, :o2, 1583650800
-
2
tz.transition 2020, 11, :o1, 1604210400
-
2
tz.transition 2021, 3, :o2, 1615705200
-
2
tz.transition 2021, 11, :o1, 1636264800
-
2
tz.transition 2022, 3, :o2, 1647154800
-
2
tz.transition 2022, 11, :o1, 1667714400
-
2
tz.transition 2023, 3, :o2, 1678604400
-
2
tz.transition 2023, 11, :o1, 1699164000
-
2
tz.transition 2024, 3, :o2, 1710054000
-
2
tz.transition 2024, 11, :o1, 1730613600
-
2
tz.transition 2025, 3, :o2, 1741503600
-
2
tz.transition 2025, 11, :o1, 1762063200
-
2
tz.transition 2026, 3, :o2, 1772953200
-
2
tz.transition 2026, 11, :o1, 1793512800
-
2
tz.transition 2027, 3, :o2, 1805007600
-
2
tz.transition 2027, 11, :o1, 1825567200
-
2
tz.transition 2028, 3, :o2, 1836457200
-
2
tz.transition 2028, 11, :o1, 1857016800
-
2
tz.transition 2029, 3, :o2, 1867906800
-
2
tz.transition 2029, 11, :o1, 1888466400
-
2
tz.transition 2030, 3, :o2, 1899356400
-
2
tz.transition 2030, 11, :o1, 1919916000
-
2
tz.transition 2031, 3, :o2, 1930806000
-
2
tz.transition 2031, 11, :o1, 1951365600
-
2
tz.transition 2032, 3, :o2, 1962860400
-
2
tz.transition 2032, 11, :o1, 1983420000
-
2
tz.transition 2033, 3, :o2, 1994310000
-
2
tz.transition 2033, 11, :o1, 2014869600
-
2
tz.transition 2034, 3, :o2, 2025759600
-
2
tz.transition 2034, 11, :o1, 2046319200
-
2
tz.transition 2035, 3, :o2, 2057209200
-
2
tz.transition 2035, 11, :o1, 2077768800
-
2
tz.transition 2036, 3, :o2, 2088658800
-
2
tz.transition 2036, 11, :o1, 2109218400
-
2
tz.transition 2037, 3, :o2, 2120108400
-
2
tz.transition 2037, 11, :o1, 2140668000
-
2
tz.transition 2038, 3, :o2, 59171923, 24
-
2
tz.transition 2038, 11, :o1, 9862939, 4
-
2
tz.transition 2039, 3, :o2, 59180659, 24
-
2
tz.transition 2039, 11, :o1, 9864395, 4
-
2
tz.transition 2040, 3, :o2, 59189395, 24
-
2
tz.transition 2040, 11, :o1, 9865851, 4
-
2
tz.transition 2041, 3, :o2, 59198131, 24
-
2
tz.transition 2041, 11, :o1, 9867307, 4
-
2
tz.transition 2042, 3, :o2, 59206867, 24
-
2
tz.transition 2042, 11, :o1, 9868763, 4
-
2
tz.transition 2043, 3, :o2, 59215603, 24
-
2
tz.transition 2043, 11, :o1, 9870219, 4
-
2
tz.transition 2044, 3, :o2, 59224507, 24
-
2
tz.transition 2044, 11, :o1, 9871703, 4
-
2
tz.transition 2045, 3, :o2, 59233243, 24
-
2
tz.transition 2045, 11, :o1, 9873159, 4
-
2
tz.transition 2046, 3, :o2, 59241979, 24
-
2
tz.transition 2046, 11, :o1, 9874615, 4
-
2
tz.transition 2047, 3, :o2, 59250715, 24
-
2
tz.transition 2047, 11, :o1, 9876071, 4
-
2
tz.transition 2048, 3, :o2, 59259451, 24
-
2
tz.transition 2048, 11, :o1, 9877527, 4
-
2
tz.transition 2049, 3, :o2, 59268355, 24
-
2
tz.transition 2049, 11, :o1, 9879011, 4
-
2
tz.transition 2050, 3, :o2, 59277091, 24
-
2
tz.transition 2050, 11, :o1, 9880467, 4
-
end
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
-
# A Timezone based on a TimezoneInfo.
-
#
-
# @private
-
2
class InfoTimezone < Timezone #:nodoc:
-
-
# Constructs a new InfoTimezone with a TimezoneInfo instance.
-
2
def self.new(info)
-
2
tz = super()
-
2
tz.send(:setup, info)
-
2
tz
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
2
def identifier
-
2
@info.identifier
-
end
-
-
2
protected
-
# The TimezoneInfo for this Timezone.
-
2
def info
-
2594
@info
-
end
-
-
2
def setup(info)
-
2
@info = info
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
-
# A Timezone based on a LinkedTimezoneInfo.
-
#
-
# @private
-
2
class LinkedTimezone < InfoTimezone #:nodoc:
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
#
-
# If no TimezonePeriod could be found, PeriodNotFound is raised.
-
2
def period_for_utc(utc)
-
@linked_timezone.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Raises PeriodNotFound if no periods are found for the given time.
-
2
def periods_for_local(local)
-
@linked_timezone.periods_for_local(local)
-
end
-
-
2
protected
-
2
def setup(info)
-
super(info)
-
@linked_timezone = Timezone.get(info.link_to_identifier)
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
# Represents a linked timezone defined in a data module.
-
#
-
# @private
-
2
class LinkedTimezoneInfo < TimezoneInfo #:nodoc:
-
-
# The zone that provides the data (that this zone is an alias for).
-
2
attr_reader :link_to_identifier
-
-
# Constructs a new TimezoneInfo with an identifier and the identifier
-
# of the zone linked to.
-
2
def initialize(identifier, link_to_identifier)
-
super(identifier)
-
@link_to_identifier = link_to_identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #@identifier,#@link_to_identifier>"
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
require 'rational' unless defined?(Rational)
-
-
2
module TZInfo
-
-
# Provides a method for getting Rationals for a timezone offset in seconds.
-
# Pre-reduced rationals are returned for all the half-hour intervals between
-
# -14 and +14 hours to avoid having to call gcd at runtime.
-
#
-
# @private
-
2
module OffsetRationals #:nodoc:
-
2
@@rational_cache = {
-
-50400 => RubyCoreSupport.rational_new!(-7,12),
-
-48600 => RubyCoreSupport.rational_new!(-9,16),
-
-46800 => RubyCoreSupport.rational_new!(-13,24),
-
-45000 => RubyCoreSupport.rational_new!(-25,48),
-
-43200 => RubyCoreSupport.rational_new!(-1,2),
-
-41400 => RubyCoreSupport.rational_new!(-23,48),
-
-39600 => RubyCoreSupport.rational_new!(-11,24),
-
-37800 => RubyCoreSupport.rational_new!(-7,16),
-
-36000 => RubyCoreSupport.rational_new!(-5,12),
-
-34200 => RubyCoreSupport.rational_new!(-19,48),
-
-32400 => RubyCoreSupport.rational_new!(-3,8),
-
-30600 => RubyCoreSupport.rational_new!(-17,48),
-
-28800 => RubyCoreSupport.rational_new!(-1,3),
-
-27000 => RubyCoreSupport.rational_new!(-5,16),
-
-25200 => RubyCoreSupport.rational_new!(-7,24),
-
-23400 => RubyCoreSupport.rational_new!(-13,48),
-
-21600 => RubyCoreSupport.rational_new!(-1,4),
-
-19800 => RubyCoreSupport.rational_new!(-11,48),
-
-18000 => RubyCoreSupport.rational_new!(-5,24),
-
-16200 => RubyCoreSupport.rational_new!(-3,16),
-
-14400 => RubyCoreSupport.rational_new!(-1,6),
-
-12600 => RubyCoreSupport.rational_new!(-7,48),
-
-10800 => RubyCoreSupport.rational_new!(-1,8),
-
-9000 => RubyCoreSupport.rational_new!(-5,48),
-
-7200 => RubyCoreSupport.rational_new!(-1,12),
-
-5400 => RubyCoreSupport.rational_new!(-1,16),
-
-3600 => RubyCoreSupport.rational_new!(-1,24),
-
-1800 => RubyCoreSupport.rational_new!(-1,48),
-
0 => RubyCoreSupport.rational_new!(0,1),
-
1800 => RubyCoreSupport.rational_new!(1,48),
-
3600 => RubyCoreSupport.rational_new!(1,24),
-
5400 => RubyCoreSupport.rational_new!(1,16),
-
7200 => RubyCoreSupport.rational_new!(1,12),
-
9000 => RubyCoreSupport.rational_new!(5,48),
-
10800 => RubyCoreSupport.rational_new!(1,8),
-
12600 => RubyCoreSupport.rational_new!(7,48),
-
14400 => RubyCoreSupport.rational_new!(1,6),
-
16200 => RubyCoreSupport.rational_new!(3,16),
-
18000 => RubyCoreSupport.rational_new!(5,24),
-
19800 => RubyCoreSupport.rational_new!(11,48),
-
21600 => RubyCoreSupport.rational_new!(1,4),
-
23400 => RubyCoreSupport.rational_new!(13,48),
-
25200 => RubyCoreSupport.rational_new!(7,24),
-
27000 => RubyCoreSupport.rational_new!(5,16),
-
28800 => RubyCoreSupport.rational_new!(1,3),
-
30600 => RubyCoreSupport.rational_new!(17,48),
-
32400 => RubyCoreSupport.rational_new!(3,8),
-
34200 => RubyCoreSupport.rational_new!(19,48),
-
36000 => RubyCoreSupport.rational_new!(5,12),
-
37800 => RubyCoreSupport.rational_new!(7,16),
-
39600 => RubyCoreSupport.rational_new!(11,24),
-
41400 => RubyCoreSupport.rational_new!(23,48),
-
43200 => RubyCoreSupport.rational_new!(1,2),
-
45000 => RubyCoreSupport.rational_new!(25,48),
-
46800 => RubyCoreSupport.rational_new!(13,24),
-
48600 => RubyCoreSupport.rational_new!(9,16),
-
50400 => RubyCoreSupport.rational_new!(7,12)}
-
-
# Returns a Rational expressing the fraction of a day that offset in
-
# seconds represents (i.e. equivalent to Rational(offset, 86400)).
-
2
def rational_for_offset(offset)
-
@@rational_cache[offset] || Rational(offset, 86400)
-
end
-
2
module_function :rational_for_offset
-
end
-
end
-
#--
-
# Copyright (c) 2008-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
require 'date'
-
2
require 'rational' unless defined?(Rational)
-
-
2
module TZInfo
-
-
# Methods to support different versions of Ruby.
-
#
-
# @private
-
2
module RubyCoreSupport #:nodoc:
-
-
# Use Rational.new! for performance reasons in Ruby 1.8.
-
# This has been removed from 1.9, but Rational performs better.
-
2
if Rational.respond_to? :new!
-
def self.rational_new!(numerator, denominator = 1)
-
Rational.new!(numerator, denominator)
-
end
-
else
-
2
def self.rational_new!(numerator, denominator = 1)
-
116
Rational(numerator, denominator)
-
end
-
end
-
-
# Ruby 1.8.6 introduced new! and deprecated new0.
-
# Ruby 1.9.0 removed new0.
-
# Ruby trunk revision 31668 removed the new! method.
-
# Still support new0 for better performance on older versions of Ruby (new0 indicates
-
# that the rational has already been reduced to its lowest terms).
-
# Fallback to jd with conversion from ajd if new! and new0 are unavailable.
-
2
if DateTime.respond_to? :new!
-
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
DateTime.new!(ajd, of, sg)
-
end
-
elsif DateTime.respond_to? :new0
-
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
DateTime.new0(ajd, of, sg)
-
end
-
else
-
2
HALF_DAYS_IN_DAY = rational_new!(1, 2)
-
-
2
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
# Convert from an Astronomical Julian Day number to a civil Julian Day number.
-
jd = ajd + of + HALF_DAYS_IN_DAY
-
-
# Ruby trunk revision 31862 changed the behaviour of DateTime.jd so that it will no
-
# longer accept a fractional civil Julian Day number if further arguments are specified.
-
# Calculate the hours, minutes and seconds to pass to jd.
-
-
jd_i = jd.to_i
-
jd_i -= 1 if jd < 0
-
hours = (jd - jd_i) * 24
-
hours_i = hours.to_i
-
minutes = (hours - hours_i) * 60
-
minutes_i = minutes.to_i
-
seconds = (minutes - minutes_i) * 60
-
-
DateTime.jd(jd_i, hours_i, minutes_i, seconds, of, sg)
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
require 'date'
-
2
require 'time'
-
-
2
module TZInfo
-
# Used by TZInfo internally to represent either a Time, DateTime or integer
-
# timestamp (seconds since 1970-01-01 00:00:00).
-
#
-
# @private
-
2
class TimeOrDateTime #:nodoc:
-
2
include Comparable
-
-
# Constructs a new TimeOrDateTime. timeOrDateTime can be a Time, DateTime
-
# or an integer. If using a Time or DateTime, any time zone information is
-
# ignored.
-
2
def initialize(timeOrDateTime)
-
8377
@time = nil
-
8377
@datetime = nil
-
8377
@timestamp = nil
-
-
8377
if timeOrDateTime.is_a?(Time)
-
8357
@time = timeOrDateTime
-
8357
@time = Time.utc(@time.year, @time.mon, @time.mday, @time.hour, @time.min, @time.sec) unless @time.zone == 'UTC'
-
8357
@orig = @time
-
20
elsif timeOrDateTime.is_a?(DateTime)
-
@datetime = timeOrDateTime
-
@datetime = @datetime.new_offset(0) unless @datetime.offset == 0
-
@orig = @datetime
-
else
-
20
@timestamp = timeOrDateTime.to_i
-
20
@orig = @timestamp
-
end
-
end
-
-
# Returns the time as a Time.
-
2
def to_time
-
23115
unless @time
-
20
if @timestamp
-
20
@time = Time.at(@timestamp).utc
-
else
-
@time = Time.utc(year, mon, mday, hour, min, sec)
-
end
-
end
-
-
23115
@time
-
end
-
-
# Returns the time as a DateTime.
-
2
def to_datetime
-
unless @datetime
-
@datetime = DateTime.new(year, mon, mday, hour, min, sec)
-
end
-
-
@datetime
-
end
-
-
# Returns the time as an integer timestamp.
-
2
def to_i
-
12
unless @timestamp
-
@timestamp = to_time.to_i
-
end
-
-
12
@timestamp
-
end
-
-
# Returns the time as the original time passed to new.
-
2
def to_orig
-
10069
@orig
-
end
-
-
# Returns a string representation of the TimeOrDateTime.
-
2
def to_s
-
if @orig.is_a?(Time)
-
"Time: #{@orig.to_s}"
-
elsif @orig.is_a?(DateTime)
-
"DateTime: #{@orig.to_s}"
-
else
-
"Timestamp: #{@orig.to_s}"
-
end
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #{@orig.inspect}>"
-
end
-
-
# Returns the year.
-
2
def year
-
2594
if @time
-
2594
@time.year
-
elsif @datetime
-
@datetime.year
-
else
-
to_time.year
-
end
-
end
-
-
# Returns the month of the year (1..12).
-
2
def mon
-
2594
if @time
-
2594
@time.mon
-
elsif @datetime
-
@datetime.mon
-
else
-
to_time.mon
-
end
-
end
-
2
alias :month :mon
-
-
# Returns the day of the month (1..n).
-
2
def mday
-
if @time
-
@time.mday
-
elsif @datetime
-
@datetime.mday
-
else
-
to_time.mday
-
end
-
end
-
2
alias :day :mday
-
-
# Returns the hour of the day (0..23).
-
2
def hour
-
if @time
-
@time.hour
-
elsif @datetime
-
@datetime.hour
-
else
-
to_time.hour
-
end
-
end
-
-
# Returns the minute of the hour (0..59).
-
2
def min
-
if @time
-
@time.min
-
elsif @datetime
-
@datetime.min
-
else
-
to_time.min
-
end
-
end
-
-
# Returns the second of the minute (0..60). (60 for a leap second).
-
2
def sec
-
if @time
-
@time.sec
-
elsif @datetime
-
@datetime.sec
-
else
-
to_time.sec
-
end
-
end
-
-
# Compares this TimeOrDateTime with another Time, DateTime, integer
-
# timestamp or TimeOrDateTime. Returns -1, 0 or +1 depending whether the
-
# receiver is less than, equal to, or greater than timeOrDateTime.
-
#
-
# Milliseconds and smaller units are ignored in the comparison.
-
2
def <=>(timeOrDateTime)
-
10069
if timeOrDateTime.is_a?(TimeOrDateTime)
-
10069
orig = timeOrDateTime.to_orig
-
-
10069
if @orig.is_a?(DateTime) || orig.is_a?(DateTime)
-
# If either is a DateTime, assume it is there for a reason
-
# (i.e. for range).
-
to_datetime <=> timeOrDateTime.to_datetime
-
10069
elsif orig.is_a?(Time)
-
10069
to_time <=> timeOrDateTime.to_time
-
else
-
to_i <=> timeOrDateTime.to_i
-
end
-
elsif @orig.is_a?(DateTime) || timeOrDateTime.is_a?(DateTime)
-
# If either is a DateTime, assume it is there for a reason
-
# (i.e. for range).
-
to_datetime <=> TimeOrDateTime.wrap(timeOrDateTime).to_datetime
-
elsif timeOrDateTime.is_a?(Time)
-
to_time <=> timeOrDateTime
-
else
-
to_i <=> timeOrDateTime.to_i
-
end
-
end
-
-
# Adds a number of seconds to the TimeOrDateTime. Returns a new
-
# TimeOrDateTime, preserving what the original constructed type was.
-
# If the original type is a Time and the resulting calculation goes out of
-
# range for Times, then an exception will be raised by the Time class.
-
2
def +(seconds)
-
2977
if seconds == 0
-
self
-
else
-
2977
if @orig.is_a?(DateTime)
-
TimeOrDateTime.new(@orig + OffsetRationals.rational_for_offset(seconds))
-
else
-
# + defined for Time and integer timestamps
-
2977
TimeOrDateTime.new(@orig + seconds)
-
end
-
end
-
end
-
-
# Subtracts a number of seconds from the TimeOrDateTime. Returns a new
-
# TimeOrDateTime, preserving what the original constructed type was.
-
# If the original type is a Time and the resulting calculation goes out of
-
# range for Times, then an exception will be raised by the Time class.
-
2
def -(seconds)
-
1533
self + (-seconds)
-
end
-
-
# Similar to the + operator, but for cases where adding would cause a
-
# timestamp or time to go out of the allowed range, converts to a DateTime
-
# based TimeOrDateTime.
-
2
def add_with_convert(seconds)
-
12
if seconds == 0
-
self
-
else
-
12
if @orig.is_a?(DateTime)
-
TimeOrDateTime.new(@orig + OffsetRationals.rational_for_offset(seconds))
-
else
-
# A Time or timestamp.
-
12
result = to_i + seconds
-
-
12
if result < 0 || result > 2147483647
-
result = TimeOrDateTime.new(to_datetime + OffsetRationals.rational_for_offset(seconds))
-
else
-
12
result = TimeOrDateTime.new(@orig + seconds)
-
end
-
end
-
end
-
end
-
-
# Returns true if todt represents the same time and was originally
-
# constructed with the same type (DateTime, Time or timestamp) as this
-
# TimeOrDateTime.
-
2
def eql?(todt)
-
todt.kind_of?(TimeOrDateTime) && to_orig.eql?(todt.to_orig)
-
end
-
-
# Returns a hash of this TimeOrDateTime.
-
2
def hash
-
@orig.hash
-
end
-
-
# If no block is given, returns a TimeOrDateTime wrapping the given
-
# timeOrDateTime. If a block is specified, a TimeOrDateTime is constructed
-
# and passed to the block. The result of the block must be a TimeOrDateTime.
-
# to_orig will be called on the result and the result of to_orig will be
-
# returned.
-
#
-
# timeOrDateTime can be a Time, DateTime, integer timestamp or TimeOrDateTime.
-
# If a TimeOrDateTime is passed in, no new TimeOrDateTime will be constructed,
-
# the passed in value will be used.
-
2
def self.wrap(timeOrDateTime)
-
5762
t = timeOrDateTime.is_a?(TimeOrDateTime) ? timeOrDateTime : TimeOrDateTime.new(timeOrDateTime)
-
-
5762
if block_given?
-
3168
t = yield t
-
-
3168
if timeOrDateTime.is_a?(TimeOrDateTime)
-
191
t
-
2977
elsif timeOrDateTime.is_a?(Time)
-
2977
t.to_time
-
elsif timeOrDateTime.is_a?(DateTime)
-
t.to_datetime
-
else
-
t.to_i
-
end
-
else
-
2594
t
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2005-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
require 'date'
-
-
2
module TZInfo
-
# Indicate a specified time in a local timezone has more than one
-
# possible time in UTC. This happens when switching from daylight savings time
-
# to normal time where the clocks are rolled back. Thrown by period_for_local
-
# and local_to_utc when using an ambiguous time and not specifying any
-
# means to resolve the ambiguity.
-
2
class AmbiguousTime < StandardError
-
end
-
-
# Thrown to indicate that no TimezonePeriod matching a given time could be found.
-
2
class PeriodNotFound < StandardError
-
end
-
-
# Thrown by Timezone#get if the identifier given is not valid.
-
2
class InvalidTimezoneIdentifier < StandardError
-
end
-
-
# Thrown if an attempt is made to use a timezone created with Timezone.new(nil).
-
2
class UnknownTimezone < StandardError
-
end
-
-
# Timezone is the base class of all timezones. It provides a factory method
-
# get to access timezones by identifier. Once a specific Timezone has been
-
# retrieved, DateTimes, Times and timestamps can be converted between the UTC
-
# and the local time for the zone. For example:
-
#
-
# tz = TZInfo::Timezone.get('America/New_York')
-
# puts tz.utc_to_local(DateTime.new(2005,8,29,15,35,0)).to_s
-
# puts tz.local_to_utc(Time.utc(2005,8,29,11,35,0)).to_s
-
# puts tz.utc_to_local(1125315300).to_s
-
#
-
# Each time conversion method returns an object of the same type it was
-
# passed.
-
#
-
# The timezone information all comes from the tz database
-
# (see http://www.twinsun.com/tz/tz-link.htm)
-
2
class Timezone
-
2
include Comparable
-
-
# Cache of loaded zones by identifier to avoid using require if a zone
-
# has already been loaded.
-
#
-
# @!visibility private
-
2
@@loaded_zones = {}
-
-
# Whether the timezones index has been loaded yet.
-
#
-
# @!visibility private
-
2
@@index_loaded = false
-
-
# Default value of the dst parameter of the local_to_utc and
-
# period_for_local methods.
-
#
-
# @!visibility private
-
2
@@default_dst = nil
-
-
# Sets the default value of the optional dst parameter of the
-
# local_to_utc and period_for_local methods. Can be set to nil, true or
-
# false.
-
#
-
# The value of default_dst defaults to nil if unset.
-
2
def self.default_dst=(value)
-
@@default_dst = value.nil? ? nil : !!value
-
end
-
-
# Gets the default value of the optional dst parameter of the
-
# local_to_utc and period_for_local methods. Can be set to nil, true or
-
# false.
-
2
def self.default_dst
-
@@default_dst
-
end
-
-
# Returns a timezone by its identifier (e.g. "Europe/London",
-
# "America/Chicago" or "UTC").
-
#
-
# Raises InvalidTimezoneIdentifier if the timezone couldn't be found.
-
2
def self.get(identifier)
-
2
instance = @@loaded_zones[identifier]
-
2
unless instance
-
2
raise InvalidTimezoneIdentifier, 'Invalid identifier' if identifier !~ /^[A-Za-z0-9\+\-_]+(\/[A-Za-z0-9\+\-_]+)*$/
-
2
identifier = identifier.gsub(/-/, '__m__').gsub(/\+/, '__p__')
-
2
begin
-
# Use a temporary variable to avoid an rdoc warning
-
2
file = "tzinfo/definitions/#{identifier}".untaint
-
2
require file
-
-
2
m = Definitions
-
2
identifier.split(/\//).each {|part|
-
4
m = m.const_get(part)
-
}
-
-
2
info = m.get
-
-
# Could make Timezone subclasses register an interest in an info
-
# type. Since there are currently only two however, there isn't
-
# much point.
-
2
if info.kind_of?(DataTimezoneInfo)
-
2
instance = DataTimezone.new(info)
-
elsif info.kind_of?(LinkedTimezoneInfo)
-
instance = LinkedTimezone.new(info)
-
else
-
raise InvalidTimezoneIdentifier, "No handler for info type #{info.class}"
-
end
-
-
2
@@loaded_zones[instance.identifier] = instance
-
rescue LoadError, NameError => e
-
raise InvalidTimezoneIdentifier, e.message
-
end
-
end
-
-
2
instance
-
end
-
-
# Returns a proxy for the Timezone with the given identifier. The proxy
-
# will cause the real timezone to be loaded when an attempt is made to
-
# find a period or convert a time. get_proxy will not validate the
-
# identifier. If an invalid identifier is specified, no exception will be
-
# raised until the proxy is used.
-
2
def self.get_proxy(identifier)
-
TimezoneProxy.new(identifier)
-
end
-
-
# If identifier is nil calls super(), otherwise calls get. An identfier
-
# should always be passed in when called externally.
-
2
def self.new(identifier = nil)
-
4
if identifier
-
get(identifier)
-
else
-
4
super()
-
end
-
end
-
-
# Returns an array containing all the available Timezones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
2
def self.all
-
get_proxies(all_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones.
-
2
def self.all_identifiers
-
load_index
-
Indexes::Timezones.timezones
-
end
-
-
# Returns an array containing all the available Timezones that are based
-
# on data (are not links to other Timezones).
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
2
def self.all_data_zones
-
get_proxies(all_data_zone_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones that are based on data (are not links to other Timezones)..
-
2
def self.all_data_zone_identifiers
-
load_index
-
Indexes::Timezones.data_timezones
-
end
-
-
# Returns an array containing all the available Timezones that are links
-
# to other Timezones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
2
def self.all_linked_zones
-
get_proxies(all_linked_zone_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones that are links to other Timezones.
-
2
def self.all_linked_zone_identifiers
-
load_index
-
Indexes::Timezones.linked_timezones
-
end
-
-
# Returns all the Timezones defined for all Countries. This is not the
-
# complete set of Timezones as some are not country specific (e.g.
-
# 'Etc/GMT').
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
2
def self.all_country_zones
-
Country.all_codes.inject([]) {|zones,country|
-
zones += Country.get(country).zones
-
}
-
end
-
-
# Returns all the zone identifiers defined for all Countries. This is not the
-
# complete set of zone identifiers as some are not country specific (e.g.
-
# 'Etc/GMT'). You can obtain a Timezone instance for a given identifier
-
# with the get method.
-
2
def self.all_country_zone_identifiers
-
Country.all_codes.inject([]) {|zones,country|
-
zones += Country.get(country).zone_identifiers
-
}
-
end
-
-
# Returns all US Timezone instances. A shortcut for
-
# TZInfo::Country.get('US').zones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
2
def self.us_zones
-
Country.get('US').zones
-
end
-
-
# Returns all US zone identifiers. A shortcut for
-
# TZInfo::Country.get('US').zone_identifiers.
-
2
def self.us_zone_identifiers
-
Country.get('US').zone_identifiers
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
2
def identifier
-
raise UnknownTimezone, 'TZInfo::Timezone constructed directly'
-
end
-
-
# An alias for identifier.
-
2
def name
-
# Don't use alias, as identifier gets overridden.
-
identifier
-
end
-
-
# Returns a friendlier version of the identifier.
-
2
def to_s
-
friendly_identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #{identifier}>"
-
end
-
-
# Returns a friendlier version of the identifier. Set skip_first_part to
-
# omit the first part of the identifier (typically a region name) where
-
# there is more than one part.
-
#
-
# For example:
-
#
-
# Timezone.get('Europe/Paris').friendly_identifier(false) #=> "Europe - Paris"
-
# Timezone.get('Europe/Paris').friendly_identifier(true) #=> "Paris"
-
# Timezone.get('America/Indiana/Knox').friendly_identifier(false) #=> "America - Knox, Indiana"
-
# Timezone.get('America/Indiana/Knox').friendly_identifier(true) #=> "Knox, Indiana"
-
2
def friendly_identifier(skip_first_part = false)
-
parts = identifier.split('/')
-
if parts.empty?
-
# shouldn't happen
-
identifier
-
elsif parts.length == 1
-
parts[0]
-
else
-
if skip_first_part
-
result = ''
-
else
-
result = parts[0] + ' - '
-
end
-
-
parts[1, parts.length - 1].reverse_each {|part|
-
part.gsub!(/_/, ' ')
-
-
if part.index(/[a-z]/)
-
# Missing a space if a lower case followed by an upper case and the
-
# name isn't McXxxx.
-
part.gsub!(/([^M][a-z])([A-Z])/, '\1 \2')
-
part.gsub!(/([M][a-bd-z])([A-Z])/, '\1 \2')
-
-
# Missing an apostrophe if two consecutive upper case characters.
-
part.gsub!(/([A-Z])([A-Z])/, '\1\'\2')
-
end
-
-
result << part
-
result << ', '
-
}
-
-
result.slice!(result.length - 2, 2)
-
result
-
end
-
end
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
2
def period_for_utc(utc)
-
raise UnknownTimezone, 'TZInfo::Timezone constructed directly'
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how ambiguities should be resolved.
-
# Returns an empty array if no periods are found for the given time.
-
2
def periods_for_local(local)
-
raise UnknownTimezone, 'TZInfo::Timezone constructed directly'
-
end
-
-
# Returns the TimezonePeriod for the given local time. local can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in local is ignored (it is treated as a time in the current
-
# timezone).
-
#
-
# Warning: There are local times that have no equivalent UTC times (e.g.
-
# in the transition from standard time to daylight savings time). There are
-
# also local times that have more than one UTC equivalent (e.g. in the
-
# transition from daylight savings time to standard time).
-
#
-
# In the first case (no equivalent UTC time), a PeriodNotFound exception
-
# will be raised.
-
#
-
# In the second case (more than one equivalent UTC time), an AmbiguousTime
-
# exception will be raised unless the optional dst parameter or block
-
# handles the ambiguity.
-
#
-
# If the ambiguity is due to a transition from daylight savings time to
-
# standard time, the dst parameter can be used to select whether the
-
# daylight savings time or local time is used. For example,
-
#
-
# Timezone.get('America/New_York').period_for_local(DateTime.new(2004,10,31,1,30,0))
-
#
-
# would raise an AmbiguousTime exception.
-
#
-
# Specifying dst=true would the daylight savings period from April to
-
# October 2004. Specifying dst=false would return the standard period
-
# from October 2004 to April 2005.
-
#
-
# If the dst parameter does not resolve the ambiguity, and a block is
-
# specified, it is called. The block must take a single parameter - an
-
# array of the periods that need to be resolved. The block can select and
-
# return a single period or return nil or an empty array
-
# to cause an AmbiguousTime exception to be raised.
-
#
-
# The default value of the dst parameter can be specified by setting
-
# Timezone.default_dst. If default_dst is not set, or is set to nil, then
-
# an AmbiguousTime exception will be raised in ambiguous situations unless
-
# a block is given to resolve the ambiguity.
-
2
def period_for_local(local, dst = Timezone.default_dst)
-
1122
results = periods_for_local(local)
-
-
1122
if results.empty?
-
raise PeriodNotFound
-
1122
elsif results.size < 2
-
1122
results.first
-
else
-
# ambiguous result try to resolve
-
-
if !dst.nil?
-
matches = results.find_all {|period| period.dst? == dst}
-
results = matches if !matches.empty?
-
end
-
-
if results.size < 2
-
results.first
-
else
-
# still ambiguous, try the block
-
-
if block_given?
-
results = yield results
-
end
-
-
if results.is_a?(TimezonePeriod)
-
results
-
elsif results && results.size == 1
-
results.first
-
else
-
raise AmbiguousTime, "#{local} is an ambiguous local time."
-
end
-
end
-
end
-
end
-
-
# Converts a time in UTC to the local timezone. utc can either be
-
# a DateTime, Time or timestamp (Time.to_i). The returned time has the same
-
# type as utc. Any timezone information in utc is ignored (it is treated as
-
# a UTC time).
-
2
def utc_to_local(utc)
-
191
TimeOrDateTime.wrap(utc) {|wrapped|
-
191
period_for_utc(wrapped).to_local(wrapped)
-
}
-
end
-
-
# Converts a time in the local timezone to UTC. local can either be
-
# a DateTime, Time or timestamp (Time.to_i). The returned time has the same
-
# type as local. Any timezone information in local is ignored (it is treated
-
# as a local time).
-
#
-
# Warning: There are local times that have no equivalent UTC times (e.g.
-
# in the transition from standard time to daylight savings time). There are
-
# also local times that have more than one UTC equivalent (e.g. in the
-
# transition from daylight savings time to standard time).
-
#
-
# In the first case (no equivalent UTC time), a PeriodNotFound exception
-
# will be raised.
-
#
-
# In the second case (more than one equivalent UTC time), an AmbiguousTime
-
# exception will be raised unless the optional dst parameter or block
-
# handles the ambiguity.
-
#
-
# If the ambiguity is due to a transition from daylight savings time to
-
# standard time, the dst parameter can be used to select whether the
-
# daylight savings time or local time is used. For example,
-
#
-
# Timezone.get('America/New_York').local_to_utc(DateTime.new(2004,10,31,1,30,0))
-
#
-
# would raise an AmbiguousTime exception.
-
#
-
# Specifying dst=true would return 2004-10-31 5:30:00. Specifying dst=false
-
# would return 2004-10-31 6:30:00.
-
#
-
# If the dst parameter does not resolve the ambiguity, and a block is
-
# specified, it is called. The block must take a single parameter - an
-
# array of the periods that need to be resolved. The block can return a
-
# single period to use to convert the time or return nil or an empty array
-
# to cause an AmbiguousTime exception to be raised.
-
#
-
# The default value of the dst parameter can be specified by setting
-
# Timezone.default_dst. If default_dst is not set, or is set to nil, then
-
# an AmbiguousTime exception will be raised in ambiguous situations unless
-
# a block is given to resolve the ambiguity.
-
2
def local_to_utc(local, dst = Timezone.default_dst)
-
TimeOrDateTime.wrap(local) {|wrapped|
-
if block_given?
-
period = period_for_local(wrapped, dst) {|periods| yield periods }
-
else
-
period = period_for_local(wrapped, dst)
-
end
-
-
period.to_utc(wrapped)
-
}
-
end
-
-
# Returns the current time in the timezone as a Time.
-
2
def now
-
191
utc_to_local(Time.now.utc)
-
end
-
-
# Returns the TimezonePeriod for the current time.
-
2
def current_period
-
period_for_utc(Time.now.utc)
-
end
-
-
# Returns the current Time and TimezonePeriod as an array. The first element
-
# is the time, the second element is the period.
-
2
def current_period_and_time
-
utc = Time.now.utc
-
period = period_for_utc(utc)
-
[period.to_local(utc), period]
-
end
-
-
2
alias :current_time_and_period :current_period_and_time
-
-
# Converts a time in UTC to local time and returns it as a string
-
# according to the given format. The formatting is identical to
-
# Time.strftime and DateTime.strftime, except %Z is replaced with the
-
# timezone abbreviation for the specified time (for example, EST or EDT).
-
2
def strftime(format, utc = Time.now.utc)
-
period = period_for_utc(utc)
-
local = period.to_local(utc)
-
local = Time.at(local).utc unless local.kind_of?(Time) || local.kind_of?(DateTime)
-
abbreviation = period.abbreviation.to_s.gsub(/%/, '%%')
-
-
format = format.gsub(/(.?)%Z/) do
-
if $1 == '%'
-
# return %%Z so the real strftime treats it as a literal %Z too
-
'%%Z'
-
else
-
"#$1#{abbreviation}"
-
end
-
end
-
-
local.strftime(format)
-
end
-
-
# Compares two Timezones based on their identifier. Returns -1 if tz is less
-
# than self, 0 if tz is equal to self and +1 if tz is greater than self.
-
2
def <=>(tz)
-
identifier <=> tz.identifier
-
end
-
-
# Returns true if and only if the identifier of tz is equal to the
-
# identifier of this Timezone.
-
2
def eql?(tz)
-
self == tz
-
end
-
-
# Returns a hash of this Timezone.
-
2
def hash
-
identifier.hash
-
end
-
-
# Dumps this Timezone for marshalling.
-
2
def _dump(limit)
-
identifier
-
end
-
-
# Loads a marshalled Timezone.
-
2
def self._load(data)
-
Timezone.get(data)
-
end
-
-
2
private
-
# Loads in the index of timezones if it hasn't already been loaded.
-
2
def self.load_index
-
unless @@index_loaded
-
require 'tzinfo/indexes/timezones'
-
@@index_loaded = true
-
end
-
end
-
-
# Returns an array of proxies corresponding to the given array of
-
# identifiers.
-
2
def self.get_proxies(identifiers)
-
identifiers.collect {|identifier| get_proxy(identifier)}
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
-
# TimezoneDefinition is included into Timezone definition modules.
-
# TimezoneDefinition provides the methods for defining timezones.
-
#
-
# @private
-
2
module TimezoneDefinition #:nodoc:
-
# Add class methods to the includee.
-
2
def self.append_features(base)
-
2
super
-
2
base.extend(ClassMethods)
-
end
-
-
# Class methods for inclusion.
-
#
-
# @private
-
2
module ClassMethods #:nodoc:
-
# Returns and yields a DataTimezoneInfo object to define a timezone.
-
2
def timezone(identifier)
-
2
yield @timezone = DataTimezoneInfo.new(identifier)
-
end
-
-
# Defines a linked timezone.
-
2
def linked_timezone(identifier, link_to_identifier)
-
@timezone = LinkedTimezoneInfo.new(identifier, link_to_identifier)
-
end
-
-
# Returns the last TimezoneInfo to be defined with timezone or
-
# linked_timezone.
-
2
def get
-
2
@timezone
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
# The timezone index file includes TimezoneIndexDefinition which provides
-
# methods used to define timezones in the index.
-
#
-
# @private
-
2
module TimezoneIndexDefinition #:nodoc:
-
2
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
base.instance_eval do
-
@timezones = []
-
@data_timezones = []
-
@linked_timezones = []
-
end
-
end
-
-
# Class methods for inclusion.
-
#
-
# @private
-
2
module ClassMethods #:nodoc:
-
# Defines a timezone based on data.
-
2
def timezone(identifier)
-
@timezones << identifier
-
@data_timezones << identifier
-
end
-
-
# Defines a timezone which is a link to another timezone.
-
2
def linked_timezone(identifier)
-
@timezones << identifier
-
@linked_timezones << identifier
-
end
-
-
# Returns a frozen array containing the identifiers of all the timezones.
-
# Identifiers appear in the order they were defined in the index.
-
2
def timezones
-
@timezones.freeze
-
end
-
-
# Returns a frozen array containing the identifiers of all data timezones.
-
# Identifiers appear in the order they were defined in the index.
-
2
def data_timezones
-
@data_timezones.freeze
-
end
-
-
# Returns a frozen array containing the identifiers of all linked
-
# timezones. Identifiers appear in the order they were defined in
-
# the index.
-
2
def linked_timezones
-
@linked_timezones.freeze
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
# Represents a timezone defined in a data module.
-
#
-
# @private
-
2
class TimezoneInfo #:nodoc:
-
-
# The timezone identifier.
-
2
attr_reader :identifier
-
-
# Constructs a new TimezoneInfo with an identifier.
-
2
def initialize(identifier)
-
2
@identifier = identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #@identifier>"
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
# Represents an offset defined in a Timezone data file.
-
#
-
# @private
-
2
class TimezoneOffsetInfo #:nodoc:
-
# The base offset of the timezone from UTC in seconds.
-
2
attr_reader :utc_offset
-
-
# The offset from standard time for the zone in seconds (i.e. non-zero if
-
# daylight savings is being observed).
-
2
attr_reader :std_offset
-
-
# The total offset of this observance from UTC in seconds
-
# (utc_offset + std_offset).
-
2
attr_reader :utc_total_offset
-
-
# The abbreviation that identifies this observance, e.g. "GMT"
-
# (Greenwich Mean Time) or "BST" (British Summer Time) for "Europe/London". The returned identifier is a
-
# symbol.
-
2
attr_reader :abbreviation
-
-
# Constructs a new TimezoneOffsetInfo. utc_offset and std_offset are
-
# specified in seconds.
-
2
def initialize(utc_offset, std_offset, abbreviation)
-
10
@utc_offset = utc_offset
-
10
@std_offset = std_offset
-
10
@abbreviation = abbreviation
-
-
10
@utc_total_offset = @utc_offset + @std_offset
-
end
-
-
# True if std_offset is non-zero.
-
2
def dst?
-
@std_offset != 0
-
end
-
-
# Converts a UTC DateTime to local time based on the offset of this period.
-
2
def to_local(utc)
-
1444
TimeOrDateTime.wrap(utc) {|wrapped|
-
1444
wrapped + @utc_total_offset
-
}
-
end
-
-
# Converts a local DateTime to UTC based on the offset of this period.
-
2
def to_utc(local)
-
1533
TimeOrDateTime.wrap(local) {|wrapped|
-
1533
wrapped - @utc_total_offset
-
}
-
end
-
-
# Returns true if and only if toi has the same utc_offset, std_offset
-
# and abbreviation as this TimezoneOffsetInfo.
-
2
def ==(toi)
-
toi.kind_of?(TimezoneOffsetInfo) &&
-
utc_offset == toi.utc_offset && std_offset == toi.std_offset && abbreviation == toi.abbreviation
-
end
-
-
# Returns true if and only if toi has the same utc_offset, std_offset
-
# and abbreviation as this TimezoneOffsetInfo.
-
2
def eql?(toi)
-
self == toi
-
end
-
-
# Returns a hash of this TimezoneOffsetInfo.
-
2
def hash
-
utc_offset.hash ^ std_offset.hash ^ abbreviation.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #@utc_offset,#@std_offset,#@abbreviation>"
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2005-2012 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
# A period of time in a timezone where the same offset from UTC applies.
-
#
-
# All the methods that take times accept instances of Time, DateTime or
-
# integer timestamps.
-
2
class TimezonePeriod
-
# The TimezoneTransitionInfo that defines the start of this TimezonePeriod
-
# (may be nil if unbounded).
-
2
attr_reader :start_transition
-
-
# The TimezoneTransitionInfo that defines the end of this TimezonePeriod
-
# (may be nil if unbounded).
-
2
attr_reader :end_transition
-
-
# The TimezoneOffsetInfo for this period.
-
2
attr_reader :offset
-
-
# Initializes a new TimezonePeriod.
-
2
def initialize(start_transition, end_transition, offset = nil)
-
2594
@start_transition = start_transition
-
2594
@end_transition = end_transition
-
-
2594
if offset
-
raise ArgumentError, 'Offset specified with transitions' if @start_transition || @end_transition
-
@offset = offset
-
else
-
2594
if @start_transition
-
2594
@offset = @start_transition.offset
-
elsif @end_transition
-
@offset = @end_transition.previous_offset
-
else
-
raise ArgumentError, 'No offset specified and no transitions to determine it from'
-
end
-
end
-
-
2594
@utc_total_offset_rational = nil
-
end
-
-
# Base offset of the timezone from UTC (seconds).
-
2
def utc_offset
-
@offset.utc_offset
-
end
-
-
# Offset from the local time where daylight savings is in effect (seconds).
-
# E.g.: utc_offset could be -5 hours. Normally, std_offset would be 0.
-
# During daylight savings, std_offset would typically become +1 hours.
-
2
def std_offset
-
@offset.std_offset
-
end
-
-
# The identifier of this period, e.g. "GMT" (Greenwich Mean Time) or "BST"
-
# (British Summer Time) for "Europe/London". The returned identifier is a
-
# symbol.
-
2
def abbreviation
-
1217
@offset.abbreviation
-
end
-
2
alias :zone_identifier :abbreviation
-
-
# Total offset from UTC (seconds). Equal to utc_offset + std_offset.
-
2
def utc_total_offset
-
1259
@offset.utc_total_offset
-
end
-
-
# Total offset from UTC (days). Result is a Rational.
-
2
def utc_total_offset_rational
-
unless @utc_total_offset_rational
-
@utc_total_offset_rational = OffsetRationals.rational_for_offset(utc_total_offset)
-
end
-
@utc_total_offset_rational
-
end
-
-
# The start time of the period in UTC as a DateTime. May be nil if unbounded.
-
2
def utc_start
-
@start_transition ? @start_transition.at.to_datetime : nil
-
end
-
-
# The end time of the period in UTC as a DateTime. May be nil if unbounded.
-
2
def utc_end
-
@end_transition ? @end_transition.at.to_datetime : nil
-
end
-
-
# The start time of the period in local time as a DateTime. May be nil if
-
# unbounded.
-
2
def local_start
-
@start_transition ? @start_transition.local_start.to_datetime : nil
-
end
-
-
# The end time of the period in local time as a DateTime. May be nil if
-
# unbounded.
-
2
def local_end
-
@end_transition ? @end_transition.local_end.to_datetime : nil
-
end
-
-
# true if daylight savings is in effect for this period; otherwise false.
-
2
def dst?
-
@offset.dst?
-
end
-
-
# true if this period is valid for the given UTC DateTime; otherwise false.
-
2
def valid_for_utc?(utc)
-
utc_after_start?(utc) && utc_before_end?(utc)
-
end
-
-
# true if the given UTC DateTime is after the start of the period
-
# (inclusive); otherwise false.
-
2
def utc_after_start?(utc)
-
!@start_transition || @start_transition.at <= utc
-
end
-
-
# true if the given UTC DateTime is before the end of the period
-
# (exclusive); otherwise false.
-
2
def utc_before_end?(utc)
-
!@end_transition || @end_transition.at > utc
-
end
-
-
# true if this period is valid for the given local DateTime; otherwise false.
-
2
def valid_for_local?(local)
-
local_after_start?(local) && local_before_end?(local)
-
end
-
-
# true if the given local DateTime is after the start of the period
-
# (inclusive); otherwise false.
-
2
def local_after_start?(local)
-
!@start_transition || @start_transition.local_start <= local
-
end
-
-
# true if the given local DateTime is before the end of the period
-
# (exclusive); otherwise false.
-
2
def local_before_end?(local)
-
!@end_transition || @end_transition.local_end > local
-
end
-
-
# Converts a UTC DateTime to local time based on the offset of this period.
-
2
def to_local(utc)
-
1444
@offset.to_local(utc)
-
end
-
-
# Converts a local DateTime to UTC based on the offset of this period.
-
2
def to_utc(local)
-
1533
@offset.to_utc(local)
-
end
-
-
# Returns true if this TimezonePeriod is equal to p. This compares the
-
# start_transition, end_transition and offset using ==.
-
2
def ==(p)
-
p.kind_of?(TimezonePeriod) &&
-
start_transition == p.start_transition &&
-
end_transition == p.end_transition &&
-
offset == p.offset
-
end
-
-
# Returns true if this TimezonePeriods is equal to p. This compares the
-
# start_transition, end_transition and offset using eql?
-
2
def eql?(p)
-
p.kind_of?(TimezonePeriod) &&
-
start_transition.eql?(p.start_transition) &&
-
end_transition.eql?(p.end_transition) &&
-
offset.eql?(p.offset)
-
end
-
-
# Returns a hash of this TimezonePeriod.
-
2
def hash
-
result = @start_transition.hash ^ @end_transition.hash
-
result ^= @offset.hash unless @start_transition || @end_transition
-
result
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
result = "#<#{self.class}: #{@start_transition.inspect},#{@end_transition.inspect}"
-
result << ",#{@offset.inspect}>" unless @start_transition || @end_transition
-
result + '>'
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2005-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
module TZInfo
-
-
# A proxy class representing a timezone with a given identifier. TimezoneProxy
-
# inherits from Timezone and can be treated like any Timezone loaded with
-
# Timezone.get.
-
#
-
# The first time an attempt is made to access the data for the timezone, the
-
# real Timezone is loaded. If the proxy's identifier was not valid, then an
-
# exception will be raised at this point.
-
2
class TimezoneProxy < Timezone
-
# Construct a new TimezoneProxy for the given identifier. The identifier
-
# is not checked when constructing the proxy. It will be validated on the
-
# when the real Timezone is loaded.
-
2
def self.new(identifier)
-
# Need to override new to undo the behaviour introduced in Timezone#new.
-
2
tzp = super()
-
2
tzp.send(:setup, identifier)
-
2
tzp
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
2
def identifier
-
@real_timezone ? @real_timezone.identifier : @identifier
-
end
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
2
def period_for_utc(utc)
-
1472
real_timezone.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Returns an empty array if no periods are found for the given time.
-
2
def periods_for_local(local)
-
1122
real_timezone.periods_for_local(local)
-
end
-
-
# Dumps this TimezoneProxy for marshalling.
-
2
def _dump(limit)
-
identifier
-
end
-
-
# Loads a marshalled TimezoneProxy.
-
2
def self._load(data)
-
TimezoneProxy.new(data)
-
end
-
-
2
private
-
2
def setup(identifier)
-
2
@identifier = identifier
-
2
@real_timezone = nil
-
end
-
-
2
def real_timezone
-
2594
@real_timezone ||= Timezone.get(@identifier)
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2013 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
2
require 'date'
-
-
2
module TZInfo
-
# Represents an offset defined in a Timezone data file.
-
#
-
# @private
-
2
class TimezoneTransitionInfo #:nodoc:
-
# The offset this transition changes to (a TimezoneOffsetInfo instance).
-
2
attr_reader :offset
-
-
# The offset this transition changes from (a TimezoneOffsetInfo instance).
-
2
attr_reader :previous_offset
-
-
# The numerator of the DateTime if the transition time is defined as a
-
# DateTime, otherwise the transition time as a timestamp.
-
2
attr_reader :numerator_or_time
-
2
protected :numerator_or_time
-
-
# Either the denominotor of the DateTime if the transition time is defined
-
# as a DateTime, otherwise nil.
-
2
attr_reader :denominator
-
2
protected :denominator
-
-
# Creates a new TimezoneTransitionInfo with the given offset,
-
# previous_offset (both TimezoneOffsetInfo instances) and UTC time.
-
# if denominator is nil, numerator_or_time is treated as a number of
-
# seconds since the epoch. If denominator is specified numerator_or_time
-
# and denominator are used to create a DateTime as follows:
-
#
-
# DateTime.new!(Rational.send(:new!, numerator_or_time, denominator), 0, Date::ITALY)
-
#
-
# For performance reasons, the numerator and denominator must be specified
-
# in their lowest form.
-
2
def initialize(offset, previous_offset, numerator_or_time, denominator = nil)
-
524
@offset = offset
-
524
@previous_offset = previous_offset
-
524
@numerator_or_time = numerator_or_time
-
524
@denominator = denominator
-
-
524
@at = nil
-
524
@local_end = nil
-
524
@local_start = nil
-
end
-
-
# A TimeOrDateTime instance representing the UTC time when this transition
-
# occurs.
-
2
def at
-
4428
unless @at
-
8
unless @denominator
-
8
@at = TimeOrDateTime.new(@numerator_or_time)
-
else
-
r = RubyCoreSupport.rational_new!(@numerator_or_time, @denominator)
-
dt = RubyCoreSupport.datetime_new!(r, 0, Date::ITALY)
-
@at = TimeOrDateTime.new(dt)
-
end
-
end
-
-
4428
@at
-
end
-
-
# A TimeOrDateTime instance representing the local time when this transition
-
# causes the previous observance to end (calculated from at using
-
# previous_offset).
-
2
def local_end
-
2287
@local_end = at.add_with_convert(@previous_offset.utc_total_offset) unless @local_end
-
2287
@local_end
-
end
-
-
# A TimeOrDateTime instance representing the local time when this transition
-
# causes the next observance to start (calculated from at using offset).
-
2
def local_start
-
3366
@local_start = at.add_with_convert(@offset.utc_total_offset) unless @local_start
-
3366
@local_start
-
end
-
-
# Returns true if this TimezoneTransitionInfo is equal to the given
-
# TimezoneTransitionInfo. Two TimezoneTransitionInfo instances are
-
# considered to be equal by == if offset, previous_offset and at are all
-
# equal.
-
2
def ==(tti)
-
tti.kind_of?(TimezoneTransitionInfo) &&
-
offset == tti.offset && previous_offset == tti.previous_offset && at == tti.at
-
end
-
-
# Returns true if this TimezoneTransitionInfo is equal to the given
-
# TimezoneTransitionInfo. Two TimezoneTransitionInfo instances are
-
# considered to be equal by eql? if offset, previous_offset,
-
# numerator_or_time and denominator are all equal. This is stronger than ==,
-
# which just requires the at times to be equal regardless of how they were
-
# originally specified.
-
2
def eql?(tti)
-
tti.kind_of?(TimezoneTransitionInfo) &&
-
offset == tti.offset && previous_offset == tti.previous_offset &&
-
numerator_or_time == tti.numerator_or_time && denominator == tti.denominator
-
end
-
-
# Returns a hash of this TimezoneTransitionInfo instance.
-
2
def hash
-
@offset.hash ^ @previous_offset.hash ^ @numerator_or_time.hash ^ @denominator.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
2
def inspect
-
"#<#{self.class}: #{at.inspect},#{@offset.inspect}>"
-
end
-
end
-
end
-
# encoding: UTF-8
-
-
2
require "execjs"
-
2
require "json"
-
2
require "uglifier/version"
-
-
2
class Uglifier
-
2
Error = ExecJS::Error
-
-
# Default options for compilation
-
2
DEFAULTS = {
-
:output => {
-
:ascii_only => false, # Escape non-ASCII characterss
-
:comments => :copyright, # Preserve comments (:all, :jsdoc, :copyright, :none)
-
:inline_script => false, # Escape occurrences of </script in strings
-
:quote_keys => false, # Quote keys in object literals
-
:max_line_len => 32 * 1024, # Maximum line length in minified code
-
:bracketize => false, # Bracketize if, for, do, while or with statements, even if their body is a single statement
-
:semicolons => true, # Separate statements with semicolons
-
:preserve_line => false, # Preserve line numbers in outputs
-
:beautify => false, # Beautify output
-
:indent_level => 4, # Indent level in spaces
-
:indent_start => 0, # Starting indent level
-
:space_colon => false, # Insert space before colons (only with beautifier)
-
:width => 80, # Specify line width when beautifier is used (only with beautifier)
-
:preamble => nil # Preamble for the generated JS file. Can be used to insert any code or comment.
-
},
-
:mangle => {
-
:eval => false, # Mangle names when eval of when is used in scope
-
:except => ["$super"], # Argument names to be excluded from mangling
-
:sort => false, # Assign shorter names to most frequently used variables. Often results in bigger output after gzip.
-
:toplevel => false # Mangle names declared in the toplevel scope
-
}, # Mangle variable and function names, set to false to skip mangling
-
:compress => {
-
:sequences => true, # Allow statements to be joined by commas
-
:properties => true, # Rewrite property access using the dot notation
-
:dead_code => true, # Remove unreachable code
-
:drop_debugger => true, # Remove debugger; statements
-
:unsafe => false, # Apply "unsafe" transformations
-
:conditionals => true, # Optimize for if-s and conditional expressions
-
:comparisons => true, # Apply binary node optimizations for comparisons
-
:evaluate => true, # Attempt to evaluate constant expressions
-
:booleans => true, # Various optimizations to boolean contexts
-
:loops => true, # Optimize loops when condition can be statically determined
-
:unused => true, # Drop unreferenced functions and variables
-
:hoist_funs => true, # Hoist function declarations
-
:hoist_vars => false, # Hoist var declarations
-
:if_return => true, # Optimizations for if/return and if/continue
-
:join_vars => true, # Join consecutive var statements
-
:cascade => true, # Cascade sequences
-
:negate_iife => true, # Negate immediately invoked function expressions to avoid extra parens
-
:pure_getters => false, # Assume that object property access does not have any side-effects
-
:pure_funcs => nil, # List of functions without side-effects. Can safely discard function calls when the result value is not used
-
:drop_console => false # Drop calls to console.* functions
-
}, # Apply transformations to code, set to false to skip
-
:define => {}, # Define values for symbol replacement
-
:enclose => false, # Enclose in output function wrapper, define replacements as key-value pairs
-
:source_filename => nil, # The filename of the input file
-
:source_root => nil, # The URL of the directory which contains :source_filename
-
:output_filename => nil, # The filename or URL where the minified output can be found
-
:input_source_map => nil, # The contents of the source map describing the input
-
:screw_ie8 => false # Don't bother to generate safe code for IE8
-
}
-
-
2
SourcePath = File.expand_path("../uglify.js", __FILE__)
-
2
ES5FallbackPath = File.expand_path("../es5.js", __FILE__)
-
2
SplitFallbackPath = File.expand_path("../split.js", __FILE__)
-
-
# Minifies JavaScript code using implicit context.
-
#
-
# source should be a String or IO object containing valid JavaScript.
-
# options contain optional overrides to Uglifier::DEFAULTS
-
#
-
# Returns minified code as String
-
2
def self.compile(source, options = {})
-
self.new(options).compile(source)
-
end
-
-
# Minifies JavaScript code and generates a source map using implicit context.
-
#
-
# source should be a String or IO object containing valid JavaScript.
-
# options contain optional overrides to Uglifier::DEFAULTS
-
#
-
# Returns a pair of [minified code as String, source map as a String]
-
2
def self.compile_with_map(source, options = {})
-
self.new(options).compile_with_map(source)
-
end
-
-
# Initialize new context for Uglifier with given options
-
#
-
# options - Hash of options to override Uglifier::DEFAULTS
-
2
def initialize(options = {})
-
(options.keys - DEFAULTS.keys - [:comments, :squeeze, :copyright])[0..1].each do |missing|
-
raise ArgumentError.new("Invalid option: #{missing}")
-
end
-
@options = options
-
@context = ExecJS.compile(File.open(ES5FallbackPath, "r:UTF-8").read +
-
File.open(SplitFallbackPath, "r:UTF-8").read +
-
File.open(SourcePath, "r:UTF-8").read)
-
end
-
-
# Minifies JavaScript code
-
#
-
# source should be a String or IO object containing valid JavaScript.
-
#
-
# Returns minified code as String
-
2
def compile(source)
-
really_compile(source, false)
-
end
-
2
alias_method :compress, :compile
-
-
# Minifies JavaScript code and generates a source map
-
#
-
# source should be a String or IO object containing valid JavaScript.
-
#
-
# Returns a pair of [minified code as String, source map as a String]
-
2
def compile_with_map(source)
-
really_compile(source, true)
-
end
-
-
2
private
-
-
# Minifies JavaScript code
-
#
-
# source should be a String or IO object containing valid JavaScript.
-
2
def really_compile(source, generate_map)
-
source = source.respond_to?(:read) ? source.read : source.to_s
-
-
js = <<-JS
-
function comments(option) {
-
if (Object.prototype.toString.call(option) === '[object Array]') {
-
return new RegExp(option[0], option[1]);
-
} else if (option == "jsdoc") {
-
return function(node, comment) {
-
if (comment.type == "comment2") {
-
return /@preserve|@license|@cc_on/i.test(comment.value);
-
} else {
-
return false;
-
}
-
}
-
} else {
-
return option;
-
}
-
}
-
-
var options = %s;
-
var source = options.source;
-
var ast = UglifyJS.parse(source, options.parse_options);
-
ast.figure_out_scope();
-
-
if (options.compress) {
-
var compressor = UglifyJS.Compressor(options.compress);
-
ast = ast.transform(compressor);
-
ast.figure_out_scope();
-
}
-
-
if (options.mangle) {
-
ast.compute_char_frequency();
-
ast.mangle_names(options.mangle);
-
}
-
-
if (options.enclose) {
-
ast = ast.wrap_enclose(options.enclose);
-
}
-
-
var gen_code_options = options.output;
-
gen_code_options.comments = comments(options.output.comments);
-
-
if (options.generate_map) {
-
var source_map = UglifyJS.SourceMap(options.source_map_options);
-
gen_code_options.source_map = source_map;
-
}
-
-
var stream = UglifyJS.OutputStream(gen_code_options);
-
-
ast.print(stream);
-
if (options.generate_map) {
-
return [stream.toString(), source_map.toString()];
-
} else {
-
return stream.toString();
-
}
-
JS
-
-
@context.exec(js % json_encode(
-
:source => source,
-
:output => output_options,
-
:compress => compressor_options,
-
:mangle => mangle_options,
-
:parse_options => parse_options,
-
:source_map_options => source_map_options,
-
:generate_map => (!!generate_map),
-
:enclose => enclose_options
-
))
-
end
-
-
2
def mangle_options
-
conditional_option(@options[:mangle], DEFAULTS[:mangle])
-
end
-
-
2
def compressor_options
-
defaults = conditional_option(DEFAULTS[:compress],
-
:global_defs => @options[:define] || {},
-
:screw_ie8 => @options[:screw_ie8] || DEFAULTS[:screw_ie8]
-
)
-
conditional_option(@options[:compress] || @options[:squeeze], defaults)
-
end
-
-
2
def comment_options
-
val = if @options.has_key?(:output) && @options[:output].has_key?(:comments)
-
@options[:output][:comments]
-
elsif @options.has_key?(:comments)
-
@options[:comments]
-
elsif @options[:copyright] == false
-
:none
-
else
-
DEFAULTS[:output][:comments]
-
end
-
-
case val
-
when :all, true
-
true
-
when :jsdoc
-
"jsdoc"
-
when :copyright
-
encode_regexp(/Copyright/i)
-
when Regexp
-
encode_regexp(val)
-
else
-
false
-
end
-
end
-
-
2
def output_options
-
screw_ie8 = if (@options[:output] || {}).has_key?(:ie_proof)
-
false
-
else
-
@options[:screw_ie8] || DEFAULTS[:screw_ie8]
-
end
-
-
DEFAULTS[:output].merge(@options[:output] || {}).merge(
-
:comments => comment_options,
-
:screw_ie8 => screw_ie8
-
).reject { |key,value| key == :ie_proof}
-
end
-
-
2
def source_map_options
-
{
-
:file => @options[:output_filename],
-
:root => @options[:source_root],
-
:orig => @options[:input_source_map]
-
}
-
end
-
-
2
def parse_options
-
{:filename => @options[:source_filename]}
-
end
-
-
2
def enclose_options
-
if @options[:enclose]
-
@options[:enclose].map do |pair|
-
pair.first + ':' + pair.last
-
end
-
else
-
false
-
end
-
end
-
-
2
def json_encode(obj)
-
JSON.dump(obj)
-
end
-
-
2
def encode_regexp(regexp)
-
modifiers = if regexp.casefold?
-
"i"
-
else
-
""
-
end
-
-
[regexp.source, modifiers]
-
end
-
-
2
def conditional_option(value, defaults)
-
if value == true || value == nil
-
defaults
-
elsif value
-
defaults.merge(value)
-
else
-
false
-
end
-
end
-
end
-
2
class Uglifier
-
2
VERSION = "2.4.0"
-
end
-
# You will paginate!
-
2
module WillPaginate
-
end
-
-
2
if defined?(Rails::Railtie)
-
2
require 'will_paginate/railtie'
-
elsif defined?(Rails::Initializer)
-
raise "will_paginate 3.0 is not compatible with Rails 2.3 or older"
-
end
-
-
2
if defined?(Merb::AbstractController)
-
require 'will_paginate/view_helpers/merb'
-
-
Merb::BootLoader.before_app_loads do
-
adapters = { :datamapper => 'data_mapper', :activerecord => 'active_record', :sequel => 'sequel' }
-
# auto-load the right ORM adapter
-
if adapter = adapters[Merb.orm]
-
require "will_paginate/#{adapter}"
-
end
-
end
-
end
-
-
2
if defined?(Sinatra) and Sinatra.respond_to? :register
-
require 'will_paginate/view_helpers/sinatra'
-
end
-
2
require 'will_paginate/per_page'
-
2
require 'will_paginate/page_number'
-
2
require 'will_paginate/collection'
-
2
require 'active_record'
-
-
2
module WillPaginate
-
# = Paginating finders for ActiveRecord models
-
#
-
# WillPaginate adds +paginate+, +per_page+ and other methods to
-
# ActiveRecord::Base class methods and associations.
-
#
-
# In short, paginating finders are equivalent to ActiveRecord finders; the
-
# only difference is that we start with "paginate" instead of "find" and
-
# that <tt>:page</tt> is required parameter:
-
#
-
# @posts = Post.paginate :all, :page => params[:page], :order => 'created_at DESC'
-
#
-
2
module ActiveRecord
-
# makes a Relation look like WillPaginate::Collection
-
2
module RelationMethods
-
2
include WillPaginate::CollectionMethods
-
-
2
attr_accessor :current_page
-
2
attr_writer :total_entries, :wp_count_options
-
-
2
def per_page(value = nil)
-
if value.nil? then limit_value
-
else limit(value)
-
end
-
end
-
-
# TODO: solve with less relation clones and code dups
-
2
def limit(num)
-
rel = super
-
if rel.current_page
-
rel.offset rel.current_page.to_offset(rel.limit_value).to_i
-
else
-
rel
-
end
-
end
-
-
# dirty hack to enable `first` after `limit` behavior above
-
2
def first(*args)
-
if current_page
-
rel = clone
-
rel.current_page = nil
-
rel.first(*args)
-
else
-
super
-
end
-
end
-
-
# fix for Rails 3.0
-
2
def find_last
-
if !loaded? and offset_value || limit_value
-
@last ||= to_a.last
-
else
-
super
-
end
-
end
-
-
2
def offset(value = nil)
-
if value.nil? then offset_value
-
else super(value)
-
end
-
end
-
-
2
def total_entries
-
@total_entries ||= begin
-
if loaded? and size < limit_value and (current_page == 1 or size > 0)
-
offset_value + size
-
else
-
@total_entries_queried = true
-
result = count
-
result = result.size if result.respond_to?(:size) and !result.is_a?(Integer)
-
result
-
end
-
end
-
end
-
-
2
def count
-
if limit_value
-
excluded = [:order, :limit, :offset, :reorder]
-
excluded << :includes unless eager_loading?
-
rel = self.except(*excluded)
-
# TODO: hack. decide whether to keep
-
rel = rel.apply_finder_options(@wp_count_options) if defined? @wp_count_options
-
rel.count
-
else
-
super
-
end
-
end
-
-
# workaround for Active Record 3.0
-
2
def size
-
if !loaded? and limit_value and group_values.empty?
-
[super, limit_value].min
-
else
-
super
-
end
-
end
-
-
# overloaded to be pagination-aware
-
2
def empty?
-
if !loaded? and offset_value
-
result = count
-
result = result.size if result.respond_to?(:size) and !result.is_a?(Integer)
-
result <= offset_value
-
else
-
super
-
end
-
end
-
-
2
def clone
-
copy_will_paginate_data super
-
end
-
-
# workaround for Active Record 3.0
-
2
def scoped(options = nil)
-
copy_will_paginate_data super
-
end
-
-
2
def to_a
-
if current_page.nil? then super # workaround for Active Record 3.0
-
else
-
::WillPaginate::Collection.create(current_page, limit_value) do |col|
-
col.replace super
-
col.total_entries ||= total_entries
-
end
-
end
-
end
-
-
2
private
-
-
2
def copy_will_paginate_data(other)
-
other.current_page = current_page unless other.current_page
-
other.total_entries = nil if defined? @total_entries_queried
-
other.wp_count_options = @wp_count_options if defined? @wp_count_options
-
other
-
end
-
end
-
-
2
module Pagination
-
2
def paginate(options)
-
options = options.dup
-
pagenum = options.fetch(:page) { raise ArgumentError, ":page parameter required" }
-
per_page = options.delete(:per_page) || self.per_page
-
total = options.delete(:total_entries)
-
-
count_options = options.delete(:count)
-
options.delete(:page)
-
-
rel = limit(per_page.to_i).page(pagenum)
-
rel = rel.apply_finder_options(options) if options.any?
-
rel.wp_count_options = count_options if count_options
-
rel.total_entries = total.to_i unless total.blank?
-
rel
-
end
-
-
2
def page(num)
-
rel = if ::ActiveRecord::Relation === self
-
self
-
elsif !defined?(::ActiveRecord::Scoping) or ::ActiveRecord::Scoping::ClassMethods.method_defined? :with_scope
-
# Active Record 3
-
scoped
-
else
-
# Active Record 4
-
all
-
end
-
-
rel = rel.extending(RelationMethods)
-
pagenum = ::WillPaginate::PageNumber(num.nil? ? 1 : num)
-
per_page = rel.limit_value || self.per_page
-
rel = rel.offset(pagenum.to_offset(per_page).to_i)
-
rel = rel.limit(per_page) unless rel.limit_value
-
rel.current_page = pagenum
-
rel
-
end
-
end
-
-
2
module BaseMethods
-
# Wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string
-
# based on the params otherwise used by paginating finds: +page+ and
-
# +per_page+.
-
#
-
# Example:
-
#
-
# @developers = Developer.paginate_by_sql ['select * from developers where salary > ?', 80000],
-
# :page => params[:page], :per_page => 3
-
#
-
# A query for counting rows will automatically be generated if you don't
-
# supply <tt>:total_entries</tt>. If you experience problems with this
-
# generated SQL, you might want to perform the count manually in your
-
# application.
-
#
-
2
def paginate_by_sql(sql, options)
-
pagenum = options.fetch(:page) { raise ArgumentError, ":page parameter required" } || 1
-
per_page = options[:per_page] || self.per_page
-
total = options[:total_entries]
-
-
WillPaginate::Collection.create(pagenum, per_page, total) do |pager|
-
query = sanitize_sql(sql.dup)
-
original_query = query.dup
-
oracle = self.connection.adapter_name =~ /^(oracle|oci$)/i
-
-
# add limit, offset
-
if oracle
-
query = <<-SQL
-
SELECT * FROM (
-
SELECT rownum rnum, a.* FROM (#{query}) a
-
WHERE rownum <= #{pager.offset + pager.per_page}
-
) WHERE rnum >= #{pager.offset}
-
SQL
-
else
-
query << " LIMIT #{pager.per_page} OFFSET #{pager.offset}"
-
end
-
-
# perfom the find
-
pager.replace find_by_sql(query)
-
-
unless pager.total_entries
-
count_query = original_query.sub /\bORDER\s+BY\s+[\w`,\s.]+$/mi, ''
-
count_query = "SELECT COUNT(*) FROM (#{count_query})"
-
count_query << ' AS count_table' unless oracle
-
# perform the count query
-
pager.total_entries = count_by_sql(count_query)
-
end
-
end
-
end
-
end
-
-
# mix everything into Active Record
-
2
::ActiveRecord::Base.extend PerPage
-
2
::ActiveRecord::Base.extend Pagination
-
2
::ActiveRecord::Base.extend BaseMethods
-
-
2
klasses = [::ActiveRecord::Relation]
-
2
if defined? ::ActiveRecord::Associations::CollectionProxy
-
2
klasses << ::ActiveRecord::Associations::CollectionProxy
-
else
-
klasses << ::ActiveRecord::Associations::AssociationCollection
-
end
-
-
# support pagination on associations and scopes
-
6
klasses.each { |klass| klass.send(:include, Pagination) }
-
end
-
end
-
2
require 'will_paginate/per_page'
-
2
require 'will_paginate/page_number'
-
-
2
module WillPaginate
-
# Any will_paginate-compatible collection should have these methods:
-
#
-
# current_page, per_page, offset, total_entries, total_pages
-
#
-
# It can also define some of these optional methods:
-
#
-
# out_of_bounds?, previous_page, next_page
-
#
-
# This module provides few of these methods.
-
2
module CollectionMethods
-
2
def total_pages
-
total_entries.zero? ? 1 : (total_entries / per_page.to_f).ceil
-
end
-
-
# current_page - 1 or nil if there is no previous page
-
2
def previous_page
-
current_page > 1 ? (current_page - 1) : nil
-
end
-
-
# current_page + 1 or nil if there is no next page
-
2
def next_page
-
current_page < total_pages ? (current_page + 1) : nil
-
end
-
-
# Helper method that is true when someone tries to fetch a page with a
-
# larger number than the last page. Can be used in combination with flashes
-
# and redirecting.
-
2
def out_of_bounds?
-
current_page > total_pages
-
end
-
end
-
-
# = The key to pagination
-
# Arrays returned from paginating finds are, in fact, instances of this little
-
# class. You may think of WillPaginate::Collection as an ordinary array with
-
# some extra properties. Those properties are used by view helpers to generate
-
# correct page links.
-
#
-
# WillPaginate::Collection also assists in rolling out your own pagination
-
# solutions: see +create+.
-
#
-
# If you are writing a library that provides a collection which you would like
-
# to conform to this API, you don't have to copy these methods over; simply
-
# make your plugin/gem dependant on this library and do:
-
#
-
# require 'will_paginate/collection'
-
# # WillPaginate::Collection is now available for use
-
2
class Collection < Array
-
2
include CollectionMethods
-
-
2
attr_reader :current_page, :per_page, :total_entries
-
-
# Arguments to the constructor are the current page number, per-page limit
-
# and the total number of entries. The last argument is optional because it
-
# is best to do lazy counting; in other words, count *conditionally* after
-
# populating the collection using the +replace+ method.
-
2
def initialize(page, per_page = WillPaginate.per_page, total = nil)
-
@current_page = WillPaginate::PageNumber(page)
-
@per_page = per_page.to_i
-
self.total_entries = total if total
-
end
-
-
# Just like +new+, but yields the object after instantiation and returns it
-
# afterwards. This is very useful for manual pagination:
-
#
-
# @entries = WillPaginate::Collection.create(1, 10) do |pager|
-
# result = Post.find(:all, :limit => pager.per_page, :offset => pager.offset)
-
# # inject the result array into the paginated collection:
-
# pager.replace(result)
-
#
-
# unless pager.total_entries
-
# # the pager didn't manage to guess the total count, do it manually
-
# pager.total_entries = Post.count
-
# end
-
# end
-
#
-
# The possibilities with this are endless. For another example, here is how
-
# WillPaginate used to define pagination for Array instances:
-
#
-
# Array.class_eval do
-
# def paginate(page = 1, per_page = 15)
-
# WillPaginate::Collection.create(page, per_page, size) do |pager|
-
# pager.replace self[pager.offset, pager.per_page].to_a
-
# end
-
# end
-
# end
-
#
-
# The Array#paginate API has since then changed, but this still serves as a
-
# fine example of WillPaginate::Collection usage.
-
2
def self.create(page, per_page, total = nil)
-
pager = new(page, per_page, total)
-
yield pager
-
pager
-
end
-
-
# Current offset of the paginated collection. If we're on the first page,
-
# it is always 0. If we're on the 2nd page and there are 30 entries per page,
-
# the offset is 30. This property is useful if you want to render ordinals
-
# side by side with records in the view: simply start with offset + 1.
-
2
def offset
-
current_page.to_offset(per_page).to_i
-
end
-
-
2
def total_entries=(number)
-
@total_entries = number.to_i
-
end
-
-
# This is a magic wrapper for the original Array#replace method. It serves
-
# for populating the paginated collection after initialization.
-
#
-
# Why magic? Because it tries to guess the total number of entries judging
-
# by the size of given array. If it is shorter than +per_page+ limit, then we
-
# know we're on the last page. This trick is very useful for avoiding
-
# unnecessary hits to the database to do the counting after we fetched the
-
# data for the current page.
-
#
-
# However, after using +replace+ you should always test the value of
-
# +total_entries+ and set it to a proper value if it's +nil+. See the example
-
# in +create+.
-
2
def replace(array)
-
result = super
-
-
# The collection is shorter then page limit? Rejoice, because
-
# then we know that we are on the last page!
-
if total_entries.nil? and length < per_page and (current_page == 1 or length > 0)
-
self.total_entries = offset + length
-
end
-
-
result
-
end
-
end
-
end
-
2
require 'set'
-
-
# copied from ActiveSupport so we don't depend on it
-
-
2
unless Hash.method_defined? :except
-
Hash.class_eval do
-
# Returns a new hash without the given keys.
-
def except(*keys)
-
rejected = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
-
reject { |key,| rejected.include?(key) }
-
end
-
-
# Replaces the hash without only the given keys.
-
def except!(*keys)
-
replace(except(*keys))
-
end
-
end
-
end
-
-
2
unless String.method_defined? :underscore
-
String.class_eval do
-
def underscore
-
self.to_s.gsub(/::/, '/').
-
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
-
gsub(/([a-z\d])([A-Z])/,'\1_\2').
-
tr("-", "_").
-
downcase
-
end
-
end
-
end
-
2
module WillPaginate::Deprecation
-
2
class << self
-
2
def warn(message, stack = caller)
-
offending_line = origin_of_call(stack)
-
full_message = "DEPRECATION WARNING: #{message} (called from #{offending_line})"
-
logger = rails_logger || Kernel
-
logger.warn full_message
-
end
-
-
2
private
-
-
2
def rails_logger
-
defined?(Rails) && Rails.logger
-
end
-
-
2
def origin_of_call(stack)
-
lib_root = File.expand_path('../../..', __FILE__)
-
stack.find { |line| line.index(lib_root) != 0 } || stack.first
-
end
-
end
-
-
2
class Hash < ::Hash
-
2
def initialize(values = {})
-
2
super()
-
2
update values
-
2
@deprecated = {}
-
end
-
-
2
def []=(key, value)
-
check_deprecated(key, value)
-
super
-
end
-
-
2
def deprecate_key(*keys)
-
4
message = block_given? ? Proc.new : keys.pop
-
10
Array(keys).each { |key| @deprecated[key] = message }
-
end
-
-
2
def merge(another)
-
to_hash.update(another)
-
end
-
-
2
def to_hash
-
::Hash.new.update(self)
-
end
-
-
2
private
-
-
2
def check_deprecated(key, value)
-
if msg = @deprecated[key] and (!msg.respond_to?(:call) or (msg = msg.call(key, value)))
-
WillPaginate::Deprecation.warn(msg)
-
end
-
end
-
end
-
end
-
2
module WillPaginate
-
2
module I18n
-
2
def self.locale_dir
-
2
File.expand_path('../locale', __FILE__)
-
end
-
-
2
def self.load_path
-
2
Dir["#{locale_dir}/*.{rb,yml}"]
-
end
-
-
2
def will_paginate_translate(keys, options = {})
-
if defined? ::I18n
-
defaults = Array(keys).dup
-
defaults << Proc.new if block_given?
-
::I18n.translate(defaults.shift, options.merge(:default => defaults, :scope => :will_paginate))
-
else
-
key = Array === keys ? keys.first : keys
-
yield key, options
-
end
-
end
-
end
-
end
-
2
require 'delegate'
-
2
require 'forwardable'
-
-
2
module WillPaginate
-
# a module that page number exceptions are tagged with
-
2
module InvalidPage; end
-
-
# integer representing a page number
-
2
class PageNumber < DelegateClass(Integer)
-
# a value larger than this is not supported in SQL queries
-
2
BIGINT = 9223372036854775807
-
-
2
extend Forwardable
-
-
2
def initialize(value, name)
-
value = Integer(value)
-
if 'offset' == name ? (value < 0 or value > BIGINT) : value < 1
-
raise RangeError, "invalid #{name}: #{value.inspect}"
-
end
-
@name = name
-
super(value)
-
rescue ArgumentError, TypeError, RangeError => error
-
error.extend InvalidPage
-
raise error
-
end
-
-
2
alias_method :to_i, :__getobj__
-
-
2
def inspect
-
"#{@name} #{to_i}"
-
end
-
-
2
def to_offset(per_page)
-
PageNumber.new((to_i - 1) * per_page.to_i, 'offset')
-
end
-
-
2
def kind_of?(klass)
-
super || to_i.kind_of?(klass)
-
end
-
2
alias is_a? kind_of?
-
end
-
-
# Ultrahax: makes `Fixnum === current_page` checks pass
-
2
Numeric.extend Module.new {
-
2
def ===(obj)
-
10396
obj.instance_of? PageNumber or super
-
end
-
}
-
-
# An idemptotent coercion method
-
2
def self.PageNumber(value, name = 'page')
-
case value
-
when PageNumber then value
-
else PageNumber.new(value, name)
-
end
-
end
-
end
-
2
module WillPaginate
-
2
module PerPage
-
2
def per_page
-
44
defined?(@per_page) ? @per_page : WillPaginate.per_page
-
end
-
-
2
def per_page=(limit)
-
24
@per_page = limit.to_i
-
end
-
-
2
def self.extended(base)
-
4
base.extend Inheritance if base.is_a? Class
-
end
-
-
2
module Inheritance
-
2
def inherited(subclass)
-
22
super
-
22
subclass.per_page = self.per_page
-
end
-
end
-
end
-
-
2
extend PerPage
-
-
# default number of items per page
-
2
self.per_page = 30
-
end
-
2
require 'will_paginate'
-
2
require 'will_paginate/page_number'
-
2
require 'will_paginate/collection'
-
2
require 'will_paginate/i18n'
-
-
2
module WillPaginate
-
2
class Railtie < Rails::Railtie
-
2
initializer "will_paginate" do |app|
-
2
ActiveSupport.on_load :active_record do
-
2
require 'will_paginate/active_record'
-
end
-
-
2
ActiveSupport.on_load :action_controller do
-
2
WillPaginate::Railtie.setup_actioncontroller
-
end
-
-
2
ActiveSupport.on_load :action_view do
-
2
require 'will_paginate/view_helpers/action_view'
-
end
-
-
2
self.class.add_locale_path config
-
-
# early access to ViewHelpers.pagination_options
-
2
require 'will_paginate/view_helpers'
-
end
-
-
2
def self.setup_actioncontroller
-
2
( defined?(ActionDispatch::ExceptionWrapper) ?
-
ActionDispatch::ExceptionWrapper : ActionDispatch::ShowExceptions
-
).send :include, ShowExceptionsPatch
-
2
ActionController::Base.extend ControllerRescuePatch
-
end
-
-
2
def self.add_locale_path(config)
-
2
config.i18n.railties_load_path.unshift(*WillPaginate::I18n.load_path)
-
end
-
-
# Extending the exception handler middleware so it properly detects
-
# WillPaginate::InvalidPage regardless of it being a tag module.
-
2
module ShowExceptionsPatch
-
2
extend ActiveSupport::Concern
-
4
included { alias_method_chain :status_code, :paginate }
-
2
def status_code_with_paginate(exception = @exception)
-
if exception.is_a?(WillPaginate::InvalidPage) or
-
(exception.respond_to?(:original_exception) &&
-
exception.original_exception.is_a?(WillPaginate::InvalidPage))
-
Rack::Utils.status_code(:not_found)
-
else
-
original_method = method(:status_code_without_paginate)
-
if original_method.arity != 0
-
original_method.call(exception)
-
else
-
original_method.call()
-
end
-
end
-
end
-
end
-
-
2
module ControllerRescuePatch
-
2
def rescue_from(*args, &block)
-
2
if idx = args.index(WillPaginate::InvalidPage)
-
args[idx] = args[idx].name
-
end
-
2
super(*args, &block)
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
2
require 'will_paginate/core_ext'
-
2
require 'will_paginate/i18n'
-
2
require 'will_paginate/deprecation'
-
-
2
module WillPaginate
-
# = Will Paginate view helpers
-
#
-
# The main view helper is +will_paginate+. It renders the pagination links
-
# for the given collection. The helper itself is lightweight and serves only
-
# as a wrapper around LinkRenderer instantiation; the renderer then does
-
# all the hard work of generating the HTML.
-
2
module ViewHelpers
-
2
class << self
-
# Write to this hash to override default options on the global level:
-
#
-
# WillPaginate::ViewHelpers.pagination_options[:page_links] = false
-
#
-
2
attr_accessor :pagination_options
-
end
-
-
# default view options
-
2
self.pagination_options = Deprecation::Hash.new \
-
:class => 'pagination',
-
:previous_label => nil,
-
:next_label => nil,
-
:inner_window => 4, # links around the current page
-
:outer_window => 1, # links around beginning and end
-
:link_separator => ' ', # single space is friendly to spiders and non-graphic browsers
-
:param_name => :page,
-
:params => nil,
-
:page_links => true,
-
:container => true
-
-
2
label_deprecation = Proc.new { |key, value|
-
"set the 'will_paginate.#{key}' key in your i18n locale instead of editing pagination_options" if defined? Rails
-
}
-
2
pagination_options.deprecate_key(:previous_label, :next_label, &label_deprecation)
-
2
pagination_options.deprecate_key(:renderer) { |key, _| "pagination_options[#{key.inspect}] shouldn't be set globally" }
-
-
2
include WillPaginate::I18n
-
-
# Returns HTML representing page links for a WillPaginate::Collection-like object.
-
# In case there is no more than one page in total, nil is returned.
-
#
-
# ==== Options
-
# * <tt>:class</tt> -- CSS class name for the generated DIV (default: "pagination")
-
# * <tt>:previous_label</tt> -- default: "« Previous"
-
# * <tt>:next_label</tt> -- default: "Next »"
-
# * <tt>:inner_window</tt> -- how many links are shown around the current page (default: 4)
-
# * <tt>:outer_window</tt> -- how many links are around the first and the last page (default: 1)
-
# * <tt>:link_separator</tt> -- string separator for page HTML elements (default: single space)
-
# * <tt>:param_name</tt> -- parameter name for page number in URLs (default: <tt>:page</tt>)
-
# * <tt>:params</tt> -- additional parameters when generating pagination links
-
# (eg. <tt>:controller => "foo", :action => nil</tt>)
-
# * <tt>:renderer</tt> -- class name, class or instance of a link renderer (default in Rails:
-
# <tt>WillPaginate::ActionView::LinkRenderer</tt>)
-
# * <tt>:page_links</tt> -- when false, only previous/next links are rendered (default: true)
-
# * <tt>:container</tt> -- toggles rendering of the DIV container for pagination links, set to
-
# false only when you are rendering your own pagination markup (default: true)
-
#
-
# All options not recognized by will_paginate will become HTML attributes on the container
-
# element for pagination links (the DIV). For example:
-
#
-
# <%= will_paginate @posts, :style => 'color:blue' %>
-
#
-
# will result in:
-
#
-
# <div class="pagination" style="color:blue"> ... </div>
-
#
-
2
def will_paginate(collection, options = {})
-
# early exit if there is nothing to render
-
return nil unless collection.total_pages > 1
-
-
options = WillPaginate::ViewHelpers.pagination_options.merge(options)
-
-
options[:previous_label] ||= will_paginate_translate(:previous_label) { '← Previous' }
-
options[:next_label] ||= will_paginate_translate(:next_label) { 'Next →' }
-
-
# get the renderer instance
-
renderer = case options[:renderer]
-
when nil
-
raise ArgumentError, ":renderer not specified"
-
when String
-
klass = if options[:renderer].respond_to? :constantize then options[:renderer].constantize
-
else Object.const_get(options[:renderer]) # poor man's constantize
-
end
-
klass.new
-
when Class then options[:renderer].new
-
else options[:renderer]
-
end
-
# render HTML for pagination
-
renderer.prepare collection, options, self
-
output = renderer.to_html
-
output = output.html_safe if output.respond_to?(:html_safe)
-
output
-
end
-
-
# Renders a message containing number of displayed vs. total entries.
-
#
-
# <%= page_entries_info @posts %>
-
# #-> Displaying posts 6 - 12 of 26 in total
-
#
-
# The default output contains HTML. Use ":html => false" for plain text.
-
2
def page_entries_info(collection, options = {})
-
model = options[:model]
-
model = collection.first.class unless model or collection.empty?
-
model ||= 'entry'
-
model_key = if model.respond_to? :model_name
-
model.model_name.i18n_key # ActiveModel::Naming
-
else
-
model.to_s.underscore
-
end
-
-
if options.fetch(:html, true)
-
b, eb = '<b>', '</b>'
-
sp = ' '
-
html_key = '_html'
-
else
-
b = eb = html_key = ''
-
sp = ' '
-
end
-
-
model_count = collection.total_pages > 1 ? 5 : collection.size
-
defaults = ["models.#{model_key}"]
-
defaults << Proc.new { |_, opts|
-
if model.respond_to? :model_name
-
model.model_name.human(:count => opts[:count])
-
else
-
name = model_key.to_s.tr('_', ' ')
-
raise "can't pluralize model name: #{model.inspect}" unless name.respond_to? :pluralize
-
opts[:count] == 1 ? name : name.pluralize
-
end
-
}
-
model_name = will_paginate_translate defaults, :count => model_count
-
-
if collection.total_pages < 2
-
i18n_key = :"page_entries_info.single_page#{html_key}"
-
keys = [:"#{model_key}.#{i18n_key}", i18n_key]
-
-
will_paginate_translate keys, :count => collection.total_entries, :model => model_name do |_, opts|
-
case opts[:count]
-
when 0; "No #{opts[:model]} found"
-
when 1; "Displaying #{b}1#{eb} #{opts[:model]}"
-
else "Displaying #{b}all#{sp}#{opts[:count]}#{eb} #{opts[:model]}"
-
end
-
end
-
else
-
i18n_key = :"page_entries_info.multi_page#{html_key}"
-
keys = [:"#{model_key}.#{i18n_key}", i18n_key]
-
params = {
-
:model => model_name, :count => collection.total_entries,
-
:from => collection.offset + 1, :to => collection.offset + collection.length
-
}
-
will_paginate_translate keys, params do |_, opts|
-
%{Displaying %s #{b}%d#{sp}-#{sp}%d#{eb} of #{b}%d#{eb} in total} %
-
[ opts[:model], opts[:from], opts[:to], opts[:count] ]
-
end
-
end
-
end
-
end
-
end
-
2
require 'will_paginate/view_helpers'
-
2
require 'will_paginate/view_helpers/link_renderer'
-
-
2
module WillPaginate
-
# = ActionView helpers
-
#
-
# This module serves for availability in ActionView templates. It also adds a new
-
# view helper: +paginated_section+.
-
#
-
# == Using the helper without arguments
-
# If the helper is called without passing in the collection object, it will
-
# try to read from the instance variable inferred by the controller name.
-
# For example, calling +will_paginate+ while the current controller is
-
# PostsController will result in trying to read from the <tt>@posts</tt>
-
# variable. Example:
-
#
-
# <%= will_paginate :id => true %>
-
#
-
# ... will result in <tt>@post</tt> collection getting paginated:
-
#
-
# <div class="pagination" id="posts_pagination"> ... </div>
-
#
-
2
module ActionView
-
2
include ViewHelpers
-
-
2
def will_paginate(collection = nil, options = {}) #:nodoc:
-
options, collection = collection, nil if collection.is_a? Hash
-
collection ||= infer_collection_from_controller
-
-
options = options.symbolize_keys
-
options[:renderer] ||= LinkRenderer
-
-
super(collection, options)
-
end
-
-
2
def page_entries_info(collection = nil, options = {}) #:nodoc:
-
options, collection = collection, nil if collection.is_a? Hash
-
collection ||= infer_collection_from_controller
-
-
super(collection, options.symbolize_keys)
-
end
-
-
# Wrapper for rendering pagination links at both top and bottom of a block
-
# of content.
-
#
-
# <% paginated_section @posts do %>
-
# <ol id="posts">
-
# <% for post in @posts %>
-
# <li> ... </li>
-
# <% end %>
-
# </ol>
-
# <% end %>
-
#
-
# will result in:
-
#
-
# <div class="pagination"> ... </div>
-
# <ol id="posts">
-
# ...
-
# </ol>
-
# <div class="pagination"> ... </div>
-
#
-
# Arguments are passed to a <tt>will_paginate</tt> call, so the same options
-
# apply. Don't use the <tt>:id</tt> option; otherwise you'll finish with two
-
# blocks of pagination links sharing the same ID (which is invalid HTML).
-
2
def paginated_section(*args, &block)
-
pagination = will_paginate(*args)
-
if pagination
-
pagination + capture(&block) + pagination
-
else
-
capture(&block)
-
end
-
end
-
-
2
def will_paginate_translate(keys, options = {})
-
if respond_to? :translate
-
if Array === keys
-
defaults = keys.dup
-
key = defaults.shift
-
else
-
defaults = nil
-
key = keys
-
end
-
translate(key, options.merge(:default => defaults, :scope => :will_paginate))
-
else
-
super
-
end
-
end
-
-
2
protected
-
-
2
def infer_collection_from_controller
-
collection_name = "@#{controller.controller_name}"
-
collection = instance_variable_get(collection_name)
-
raise ArgumentError, "The #{collection_name} variable appears to be empty. Did you " +
-
"forget to pass the collection object for will_paginate?" if collection.nil?
-
collection
-
end
-
-
2
class LinkRenderer < ViewHelpers::LinkRenderer
-
2
protected
-
-
2
def default_url_params
-
{}
-
end
-
-
2
def url(page)
-
@base_url_params ||= begin
-
url_params = merge_get_params(default_url_params)
-
url_params[:only_path] = true
-
merge_optional_params(url_params)
-
end
-
-
url_params = @base_url_params.dup
-
add_current_page_param(url_params, page)
-
-
@template.url_for(url_params)
-
end
-
-
2
def merge_get_params(url_params)
-
if @template.respond_to? :request and @template.request and @template.request.get?
-
symbolized_update(url_params, @template.params)
-
end
-
url_params
-
end
-
-
2
def merge_optional_params(url_params)
-
symbolized_update(url_params, @options[:params]) if @options[:params]
-
url_params
-
end
-
-
2
def add_current_page_param(url_params, page)
-
unless param_name.index(/[^\w-]/)
-
url_params[param_name.to_sym] = page
-
else
-
page_param = parse_query_parameters("#{param_name}=#{page}")
-
symbolized_update(url_params, page_param)
-
end
-
end
-
-
2
private
-
-
2
def parse_query_parameters(params)
-
Rack::Utils.parse_nested_query(params)
-
end
-
end
-
-
2
::ActionView::Base.send :include, self
-
end
-
end
-
2
require 'cgi'
-
2
require 'will_paginate/core_ext'
-
2
require 'will_paginate/view_helpers'
-
2
require 'will_paginate/view_helpers/link_renderer_base'
-
-
2
module WillPaginate
-
2
module ViewHelpers
-
# This class does the heavy lifting of actually building the pagination
-
# links. It is used by +will_paginate+ helper internally.
-
2
class LinkRenderer < LinkRendererBase
-
-
# * +collection+ is a WillPaginate::Collection instance or any other object
-
# that conforms to that API
-
# * +options+ are forwarded from +will_paginate+ view helper
-
# * +template+ is the reference to the template being rendered
-
2
def prepare(collection, options, template)
-
super(collection, options)
-
@template = template
-
@container_attributes = @base_url_params = nil
-
end
-
-
# Process it! This method returns the complete HTML string which contains
-
# pagination links. Feel free to subclass LinkRenderer and change this
-
# method as you see fit.
-
2
def to_html
-
html = pagination.map do |item|
-
item.is_a?(Fixnum) ?
-
page_number(item) :
-
send(item)
-
end.join(@options[:link_separator])
-
-
@options[:container] ? html_container(html) : html
-
end
-
-
# Returns the subset of +options+ this instance was initialized with that
-
# represent HTML attributes for the container element of pagination links.
-
2
def container_attributes
-
@container_attributes ||= @options.except(*(ViewHelpers.pagination_options.keys + [:renderer] - [:class]))
-
end
-
-
2
protected
-
-
2
def page_number(page)
-
unless page == current_page
-
link(page, page, :rel => rel_value(page))
-
else
-
tag(:em, page, :class => 'current')
-
end
-
end
-
-
2
def gap
-
text = @template.will_paginate_translate(:page_gap) { '…' }
-
%(<span class="gap">#{text}</span>)
-
end
-
-
2
def previous_page
-
num = @collection.current_page > 1 && @collection.current_page - 1
-
previous_or_next_page(num, @options[:previous_label], 'previous_page')
-
end
-
-
2
def next_page
-
num = @collection.current_page < total_pages && @collection.current_page + 1
-
previous_or_next_page(num, @options[:next_label], 'next_page')
-
end
-
-
2
def previous_or_next_page(page, text, classname)
-
if page
-
link(text, page, :class => classname)
-
else
-
tag(:span, text, :class => classname + ' disabled')
-
end
-
end
-
-
2
def html_container(html)
-
tag(:div, html, container_attributes)
-
end
-
-
# Returns URL params for +page_link_or_span+, taking the current GET params
-
# and <tt>:params</tt> option into account.
-
2
def url(page)
-
raise NotImplementedError
-
end
-
-
2
private
-
-
2
def param_name
-
@options[:param_name].to_s
-
end
-
-
2
def link(text, target, attributes = {})
-
if target.is_a? Fixnum
-
attributes[:rel] = rel_value(target)
-
target = url(target)
-
end
-
attributes[:href] = target
-
tag(:a, text, attributes)
-
end
-
-
2
def tag(name, value, attributes = {})
-
string_attributes = attributes.inject('') do |attrs, pair|
-
unless pair.last.nil?
-
attrs << %( #{pair.first}="#{CGI::escapeHTML(pair.last.to_s)}")
-
end
-
attrs
-
end
-
"<#{name}#{string_attributes}>#{value}</#{name}>"
-
end
-
-
2
def rel_value(page)
-
case page
-
when @collection.current_page - 1; 'prev' + (page == 1 ? ' start' : '')
-
when @collection.current_page + 1; 'next'
-
when 1; 'start'
-
end
-
end
-
-
2
def symbolized_update(target, other)
-
other.each do |key, value|
-
key = key.to_sym
-
existing = target[key]
-
-
if value.is_a?(Hash) and (existing.is_a?(Hash) or existing.nil?)
-
symbolized_update(existing || (target[key] = {}), value)
-
else
-
target[key] = value
-
end
-
end
-
end
-
end
-
end
-
end
-
2
module WillPaginate
-
2
module ViewHelpers
-
# This class does the heavy lifting of actually building the pagination
-
# links. It is used by +will_paginate+ helper internally.
-
2
class LinkRendererBase
-
-
# * +collection+ is a WillPaginate::Collection instance or any other object
-
# that conforms to that API
-
# * +options+ are forwarded from +will_paginate+ view helper
-
2
def prepare(collection, options)
-
@collection = collection
-
@options = options
-
-
# reset values in case we're re-using this instance
-
@total_pages = nil
-
end
-
-
2
def pagination
-
items = @options[:page_links] ? windowed_page_numbers : []
-
items.unshift :previous_page
-
items.push :next_page
-
end
-
-
2
protected
-
-
# Calculates visible page numbers using the <tt>:inner_window</tt> and
-
# <tt>:outer_window</tt> options.
-
2
def windowed_page_numbers
-
inner_window, outer_window = @options[:inner_window].to_i, @options[:outer_window].to_i
-
window_from = current_page - inner_window
-
window_to = current_page + inner_window
-
-
# adjust lower or upper limit if other is out of bounds
-
if window_to > total_pages
-
window_from -= window_to - total_pages
-
window_to = total_pages
-
end
-
if window_from < 1
-
window_to += 1 - window_from
-
window_from = 1
-
window_to = total_pages if window_to > total_pages
-
end
-
-
# these are always visible
-
middle = window_from..window_to
-
-
# left window
-
if outer_window + 3 < middle.first # there's a gap
-
left = (1..(outer_window + 1)).to_a
-
left << :gap
-
else # runs into visible pages
-
left = 1...middle.first
-
end
-
-
# right window
-
if total_pages - outer_window - 2 > middle.last # again, gap
-
right = ((total_pages - outer_window)..total_pages).to_a
-
right.unshift :gap
-
else # runs into visible pages
-
right = (middle.last + 1)..total_pages
-
end
-
-
left.to_a + middle.to_a + right.to_a
-
end
-
-
2
private
-
-
2
def current_page
-
@collection.current_page
-
end
-
-
2
def total_pages
-
@total_pages ||= @collection.total_pages
-
end
-
end
-
end
-
end
-
2
require 'ostruct'
-
-
#
-
# Wirble: A collection of useful Irb features.
-
#
-
# To use, add the following to your ~/.irbrc:
-
#
-
# require 'rubygems'
-
# require 'wirble'
-
# Wirble.init
-
#
-
# If you want color in Irb, add this to your ~/.irbrc as well:
-
#
-
# Wirble.colorize
-
#
-
# Note: I spent a fair amount of time documenting this code in the
-
# README. If you've installed via RubyGems, root around your cache a
-
# little bit (or fire up gem_server) and read it before you tear your
-
# hair out sifting through the code below.
-
#
-
2
module Wirble
-
2
VERSION = '0.1.3'
-
-
#
-
# Load internal Ruby features, including pp, tab-completion,
-
# and a simple prompt.
-
#
-
2
module Internals
-
# list of internal libraries to automatically load
-
2
LIBRARIES = %w{pp irb/completion}
-
-
#
-
# load libraries
-
#
-
2
def self.init_libraries
-
LIBRARIES.each do |lib|
-
begin
-
require lib
-
rescue LoadError
-
nil
-
end
-
end
-
end
-
-
#
-
# Set a simple prompt, unless a custom one has been specified.
-
#
-
2
def self.init_prompt
-
# set the prompt
-
if IRB.conf[:PROMPT_MODE] == :DEFAULT
-
IRB.conf[:PROMPT_MODE] = :SIMPLE
-
end
-
end
-
-
#
-
# Load all Ruby internal features.
-
#
-
2
def self.init(opt = nil)
-
init_libraries unless opt && opt[:skip_libraries]
-
init_prompt unless opt && opt[:skip_prompt]
-
end
-
end
-
-
#
-
# Basic IRB history support. This is based on the tips from
-
# http://wiki.rubygarden.org/Ruby/page/show/Irb/TipsAndTricks
-
#
-
2
class History
-
2
DEFAULTS = {
-
:history_path => ENV['IRB_HISTORY_FILE'] || "~/.irb_history",
-
2
:history_size => (ENV['IRB_HISTORY_SIZE'] || 1000).to_i,
-
:history_perms => File::WRONLY | File::CREAT | File::TRUNC,
-
}
-
-
2
private
-
-
2
def say(*args)
-
puts(*args) if @verbose
-
end
-
-
2
def cfg(key)
-
@opt["history_#{key}".intern]
-
end
-
-
2
def save_history
-
path, max_size, perms = %w{path size perms}.map { |v| cfg(v) }
-
-
# read lines from history, and truncate the list (if necessary)
-
lines = Readline::HISTORY.to_a.uniq
-
lines = lines[-max_size, -1] if lines.size > max_size
-
-
# write the history file
-
real_path = File.expand_path(path)
-
File.open(real_path, perms) { |fh| fh.puts lines }
-
say 'Saved %d lines to history file %s.' % [lines.size, path]
-
end
-
-
2
def load_history
-
# expand history file and make sure it exists
-
real_path = File.expand_path(cfg('path'))
-
unless File.exist?(real_path)
-
say "History file #{real_path} doesn't exist."
-
return
-
end
-
-
# read lines from file and add them to history
-
lines = File.readlines(real_path).map { |line| line.chomp }
-
Readline::HISTORY.push(*lines)
-
-
say 'Read %d lines from history file %s' % [lines.size, cfg('path')]
-
end
-
-
2
public
-
-
2
def initialize(opt = nil)
-
@opt = DEFAULTS.merge(opt || {})
-
return unless defined? Readline::HISTORY
-
load_history
-
Kernel.at_exit { save_history }
-
end
-
end
-
-
#
-
# Add color support to IRB.
-
#
-
2
module Colorize
-
#
-
# Tokenize an inspection string.
-
#
-
2
module Tokenizer
-
2
def self.tokenize(str)
-
raise 'missing block' unless block_given?
-
chars = str.split(//)
-
-
# $stderr.puts "DEBUG: chars = #{chars.join(',')}"
-
-
state, val, i, lc = [], '', 0, nil
-
while i <= chars.size
-
repeat = false
-
c = chars[i]
-
-
# $stderr.puts "DEBUG: state = #{state}"
-
-
case state[-1]
-
when nil
-
case c
-
when ':'
-
state << :symbol
-
when '"'
-
state << :string
-
when '#'
-
state << :object
-
when /[a-z]/i
-
state << :keyword
-
repeat = true
-
when /[0-9-]/
-
state << :number
-
repeat = true
-
when '{'
-
yield :open_hash, '{'
-
when '['
-
yield :open_array, '['
-
when ']'
-
yield :close_array, ']'
-
when '}'
-
yield :close_hash, '}'
-
when /\s/
-
yield :whitespace, c
-
when ','
-
yield :comma, ','
-
when '>'
-
yield :refers, '=>' if lc == '='
-
when '.'
-
yield :range, '..' if lc == '.'
-
when '='
-
# ignore these, they're used elsewhere
-
nil
-
else
-
# $stderr.puts "DEBUG: ignoring char #{c}"
-
end
-
when :symbol
-
case c
-
# XXX: should have =, but that messes up foo=>bar
-
when /[a-z0-9_!?]/
-
val << c
-
else
-
yield :symbol_prefix, ':'
-
yield state[-1], val
-
state.pop; val = ''
-
repeat = true
-
end
-
when :string
-
case c
-
when '"'
-
if lc == "\\"
-
val[-1] = ?"
-
else
-
yield :open_string, '"'
-
yield state[-1], val
-
state.pop; val = ''
-
yield :close_string, '"'
-
end
-
else
-
val << c
-
end
-
when :keyword
-
case c
-
when /[a-z0-9_]/i
-
val << c
-
else
-
# is this a class?
-
st = val =~ /^[A-Z]/ ? :class : state[-1]
-
-
yield st, val
-
state.pop; val = ''
-
repeat = true
-
end
-
when :number
-
case c
-
when /[0-9e-]/
-
val << c
-
when '.'
-
if lc == '.'
-
val[/\.$/] = ''
-
yield state[-1], val
-
state.pop; val = ''
-
yield :range, '..'
-
else
-
val << c
-
end
-
else
-
yield state[-1], val
-
state.pop; val = ''
-
repeat = true
-
end
-
when :object
-
case c
-
when '<'
-
yield :open_object, '#<'
-
state << :object_class
-
when ':'
-
state << :object_addr
-
when '@'
-
state << :object_line
-
when '>'
-
yield :close_object, '>'
-
state.pop; val = ''
-
end
-
when :object_class
-
case c
-
when ':'
-
yield state[-1], val
-
state.pop; val = ''
-
repeat = true
-
else
-
val << c
-
end
-
when :object_addr
-
case c
-
when '>'
-
when '@'
-
yield :object_addr_prefix, ':'
-
yield state[-1], val
-
state.pop; val = ''
-
repeat = true
-
else
-
val << c
-
end
-
when :object_line
-
case c
-
when '>'
-
yield :object_line_prefix, '@'
-
yield state[-1], val
-
state.pop; val = ''
-
repeat = true
-
else
-
val << c
-
end
-
else
-
raise "unknown state #{state}"
-
end
-
-
unless repeat
-
i += 1
-
lc = c
-
end
-
end
-
end
-
end
-
-
#
-
# Terminal escape codes for colors.
-
#
-
2
module Color
-
2
COLORS = {
-
:nothing => '0;0',
-
:black => '0;30',
-
:red => '0;31',
-
:green => '0;32',
-
:brown => '0;33',
-
:blue => '0;34',
-
:cyan => '0;36',
-
:purple => '0;35',
-
:light_gray => '0;37',
-
:dark_gray => '1;30',
-
:light_red => '1;31',
-
:light_green => '1;32',
-
:yellow => '1;33',
-
:light_blue => '1;34',
-
:light_cyan => '1;36',
-
:light_purple => '1;35',
-
:white => '1;37',
-
}
-
-
#
-
# Return the escape code for a given color.
-
#
-
2
def self.escape(key)
-
COLORS.key?(key) && "\033[#{COLORS[key]}m"
-
end
-
end
-
-
#
-
# Default Wirble color scheme.
-
#
-
2
DEFAULT_COLORS = {
-
# delimiter colors
-
:comma => :blue,
-
:refers => :blue,
-
-
# container colors (hash and array)
-
:open_hash => :green,
-
:close_hash => :green,
-
:open_array => :green,
-
:close_array => :green,
-
-
# object colors
-
:open_object => :light_red,
-
:object_class => :white,
-
:object_addr_prefix => :blue,
-
:object_line_prefix => :blue,
-
:close_object => :light_red,
-
-
# symbol colors
-
:symbol => :yellow,
-
:symbol_prefix => :yellow,
-
-
# string colors
-
:open_string => :red,
-
:string => :cyan,
-
:close_string => :red,
-
-
# misc colors
-
:number => :cyan,
-
:keyword => :green,
-
:class => :light_green,
-
:range => :red,
-
}
-
-
#
-
# Fruity testing colors.
-
#
-
2
TESTING_COLORS = {
-
:comma => :red,
-
:refers => :red,
-
:open_hash => :blue,
-
:close_hash => :blue,
-
:open_array => :green,
-
:close_array => :green,
-
:open_object => :light_red,
-
:object_class => :light_green,
-
:object_addr => :purple,
-
:object_line => :light_purple,
-
:close_object => :light_red,
-
:symbol => :yellow,
-
:symbol_prefix => :yellow,
-
:number => :cyan,
-
:string => :cyan,
-
:keyword => :white,
-
:range => :light_blue,
-
}
-
-
#
-
# Set color map to hash
-
#
-
2
def self.colors=(hash)
-
@colors = hash
-
end
-
-
#
-
# Get current color map
-
#
-
2
def self.colors
-
@colors ||= {}.update(DEFAULT_COLORS)
-
end
-
-
#
-
# Return a string with the given color.
-
#
-
2
def self.colorize_string(str, color)
-
col, nocol = [color, :nothing].map { |key| Color.escape(key) }
-
col ? "#{col}#{str}#{nocol}" : str
-
end
-
-
#
-
# Colorize the results of inspect
-
#
-
2
def self.colorize(str)
-
begin
-
ret, nocol = '', Color.escape(:nothing)
-
Tokenizer.tokenize(str) do |tok, val|
-
# c = Color.escape(colors[tok])
-
ret << colorize_string(val, colors[tok])
-
end
-
ret
-
rescue
-
# catch any errors from the tokenizer (just in case)
-
str
-
end
-
end
-
-
#
-
# Enable colorized IRB results.
-
#
-
2
def self.enable(custom_colors = nil)
-
# if there's a better way to do this, I'm all ears.
-
::IRB::Irb.class_eval do
-
alias :non_color_output_value :output_value
-
-
def output_value
-
if @context.inspect?
-
val = Colorize.colorize(@context.last_value.inspect)
-
printf @context.return_format, val
-
else
-
printf @context.return_format, @context.last_value
-
end
-
end
-
end
-
-
colors = custom_colors if custom_colors
-
end
-
-
#
-
# Disable colorized IRB results.
-
#
-
2
def self.disable
-
::IRB::Irb.class_eval do
-
alias :output_value :non_color_output_value
-
end
-
end
-
end
-
-
#
-
# Convenient shortcut methods.
-
#
-
2
module Shortcuts
-
#
-
# Print object methods, sorted by name. (excluding methods that
-
# exist in the class Object) .
-
#
-
2
def po(o)
-
o.methods.sort - Object.methods
-
end
-
-
#
-
# Print object constants, sorted by name.
-
#
-
2
def poc(o)
-
o.constants.sort
-
end
-
end
-
-
#
-
# Convenient shortcut for ri
-
#
-
2
module RiShortcut
-
2
def self.init
-
Kernel.class_eval {
-
def ri(arg)
-
puts `ri '#{arg}'`
-
end
-
}
-
-
Module.instance_eval {
-
def ri(meth=nil)
-
if meth
-
if instance_methods(false).include? meth.to_s
-
puts `ri #{self}##{meth}`
-
else
-
super
-
end
-
else
-
puts `ri #{self}`
-
end
-
end
-
}
-
end
-
end
-
-
-
-
#
-
# Enable color results.
-
#
-
2
def self.colorize(custom_colors = nil)
-
Colorize.enable(custom_colors)
-
end
-
-
#
-
# Load everything except color.
-
#
-
2
def self.init(opt = nil)
-
# make sure opt isn't nil
-
opt ||= {}
-
-
# load internal irb/ruby features
-
Internals.init(opt) unless opt && opt[:skip_internals]
-
-
# load the history
-
History.new(opt) unless opt && opt[:skip_history]
-
-
# load shortcuts
-
unless opt && opt[:skip_shortcuts]
-
# load ri shortcuts
-
RiShortcut.init
-
-
# include common shortcuts
-
Object.class_eval { include Shortcuts }
-
end
-
-
colorize(opt[:colors]) if opt && opt[:init_colors]
-
end
-
end
-
-
2
module SerializationHelper
-
-
2
class Base
-
2
attr_reader :extension
-
-
2
def initialize(helper)
-
@dumper = helper.dumper
-
@loader = helper.loader
-
@extension = helper.extension
-
end
-
-
2
def dump(filename)
-
disable_logger
-
@dumper.dump(File.new(filename, "w"))
-
reenable_logger
-
end
-
-
2
def dump_to_dir(dirname)
-
Dir.mkdir(dirname)
-
tables = @dumper.tables
-
tables.each do |table|
-
io = File.new "#{dirname}/#{table}.#{@extension}", "w"
-
@dumper.before_table(io, table)
-
@dumper.dump_table io, table
-
@dumper.after_table(io, table)
-
end
-
end
-
-
2
def load(filename, truncate = true)
-
disable_logger
-
@loader.load(File.new(filename, "r"), truncate)
-
reenable_logger
-
end
-
-
2
def load_from_dir(dirname, truncate = true)
-
Dir.entries(dirname).each do |filename|
-
if filename =~ /^[.]/
-
next
-
end
-
@loader.load(File.new("#{dirname}/#{filename}", "r"), truncate)
-
end
-
end
-
-
2
def disable_logger
-
@@old_logger = ActiveRecord::Base.logger
-
ActiveRecord::Base.logger = nil
-
end
-
-
2
def reenable_logger
-
ActiveRecord::Base.logger = @@old_logger
-
end
-
end
-
-
2
class Load
-
2
def self.load(io, truncate = true)
-
ActiveRecord::Base.connection.transaction do
-
load_documents(io, truncate)
-
end
-
end
-
-
2
def self.truncate_table(table)
-
begin
-
ActiveRecord::Base.connection.execute("TRUNCATE #{SerializationHelper::Utils.quote_table(table)}")
-
rescue Exception
-
ActiveRecord::Base.connection.execute("DELETE FROM #{SerializationHelper::Utils.quote_table(table)}")
-
end
-
end
-
-
2
def self.load_table(table, data, truncate = true)
-
column_names = data['columns']
-
if truncate
-
truncate_table(table)
-
end
-
load_records(table, column_names, data['records'])
-
reset_pk_sequence!(table)
-
end
-
-
2
def self.load_records(table, column_names, records)
-
if column_names.nil?
-
return
-
end
-
columns = column_names.map{|cn| ActiveRecord::Base.connection.columns(table).detect{|c| c.name == cn}}
-
quoted_column_names = column_names.map { |column| ActiveRecord::Base.connection.quote_column_name(column) }.join(',')
-
quoted_table_name = SerializationHelper::Utils.quote_table(table)
-
records.each do |record|
-
quoted_values = record.zip(columns).map{|c| ActiveRecord::Base.connection.quote(c.first, c.last)}.join(',')
-
ActiveRecord::Base.connection.execute("INSERT INTO #{quoted_table_name} (#{quoted_column_names}) VALUES (#{quoted_values})")
-
end
-
end
-
-
2
def self.reset_pk_sequence!(table_name)
-
if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!)
-
ActiveRecord::Base.connection.reset_pk_sequence!(table_name)
-
end
-
end
-
-
-
end
-
-
2
module Utils
-
-
2
def self.unhash(hash, keys)
-
keys.map { |key| hash[key] }
-
end
-
-
2
def self.unhash_records(records, keys)
-
records.each_with_index do |record, index|
-
records[index] = unhash(record, keys)
-
end
-
-
records
-
end
-
-
2
def self.convert_booleans(records, columns)
-
records.each do |record|
-
columns.each do |column|
-
next if is_boolean(record[column])
-
record[column] = convert_boolean(record[column])
-
end
-
end
-
records
-
end
-
-
2
def self.convert_boolean(value)
-
['t', '1', true, 1].include?(value)
-
end
-
-
2
def self.boolean_columns(table)
-
columns = ActiveRecord::Base.connection.columns(table).reject { |c| silence_warnings { c.type != :boolean } }
-
columns.map { |c| c.name }
-
end
-
-
2
def self.is_boolean(value)
-
value.kind_of?(TrueClass) or value.kind_of?(FalseClass)
-
end
-
-
2
def self.quote_table(table)
-
ActiveRecord::Base.connection.quote_table_name(table)
-
end
-
-
end
-
-
2
class Dump
-
2
def self.before_table(io, table)
-
-
end
-
-
2
def self.dump(io)
-
tables.each do |table|
-
before_table(io, table)
-
dump_table(io, table)
-
after_table(io, table)
-
end
-
end
-
-
2
def self.after_table(io, table)
-
-
end
-
-
2
def self.tables
-
ActiveRecord::Base.connection.tables.reject { |table| ['schema_info', 'schema_migrations'].include?(table) }
-
end
-
-
2
def self.dump_table(io, table)
-
return if table_record_count(table).zero?
-
-
dump_table_columns(io, table)
-
dump_table_records(io, table)
-
end
-
-
2
def self.table_column_names(table)
-
ActiveRecord::Base.connection.columns(table).map { |c| c.name }
-
end
-
-
-
2
def self.each_table_page(table, records_per_page=1000)
-
total_count = table_record_count(table)
-
pages = (total_count.to_f / records_per_page).ceil - 1
-
id = table_column_names(table).first
-
boolean_columns = SerializationHelper::Utils.boolean_columns(table)
-
quoted_table_name = SerializationHelper::Utils.quote_table(table)
-
-
(0..pages).to_a.each do |page|
-
query = Arel::Table.new(table).order(id).skip(records_per_page*page).take(records_per_page).project(Arel.sql('*'))
-
records = ActiveRecord::Base.connection.select_all(query)
-
records = SerializationHelper::Utils.convert_booleans(records, boolean_columns)
-
yield records
-
end
-
end
-
-
2
def self.table_record_count(table)
-
ActiveRecord::Base.connection.select_one("SELECT COUNT(*) FROM #{SerializationHelper::Utils.quote_table(table)}").values.first.to_i
-
end
-
-
end
-
-
end
-
2
require 'rubygems'
-
2
require 'yaml'
-
2
require 'active_record'
-
2
require 'serialization_helper'
-
2
require 'active_support/core_ext/kernel/reporting'
-
2
require 'rails/railtie'
-
-
2
module YamlDb
-
2
module Helper
-
2
def self.loader
-
YamlDb::Load
-
end
-
-
2
def self.dumper
-
YamlDb::Dump
-
end
-
-
2
def self.extension
-
"yml"
-
end
-
end
-
-
-
2
module Utils
-
2
def self.chunk_records(records)
-
yaml = [ records ].to_yaml
-
yaml.sub!(/---\s\n|---\n/, '')
-
yaml.sub!('- - -', ' - -')
-
yaml
-
end
-
-
end
-
-
2
class Dump < SerializationHelper::Dump
-
-
2
def self.dump_table_columns(io, table)
-
io.write("\n")
-
io.write({ table => { 'columns' => table_column_names(table) } }.to_yaml)
-
end
-
-
2
def self.dump_table_records(io, table)
-
table_record_header(io)
-
-
column_names = table_column_names(table)
-
-
each_table_page(table) do |records|
-
rows = SerializationHelper::Utils.unhash_records(records, column_names)
-
io.write(YamlDb::Utils.chunk_records(records))
-
end
-
end
-
-
2
def self.table_record_header(io)
-
io.write(" records: \n")
-
end
-
-
end
-
-
2
class Load < SerializationHelper::Load
-
2
def self.load_documents(io, truncate = true)
-
YAML.load_documents(io) do |ydoc|
-
ydoc.keys.each do |table_name|
-
next if ydoc[table_name].nil?
-
load_table(table_name, ydoc[table_name], truncate)
-
end
-
end
-
end
-
end
-
-
2
class Railtie < Rails::Railtie
-
2
rake_tasks do
-
load File.expand_path('../tasks/yaml_db_tasks.rake',
-
__FILE__)
-
end
-
end
-
-
end