announcement-test/temp_file/config/application.rb

378 lines
14 KiB
Ruby

require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
require "mongoid"
require "mongoid/config"
require "mongoid/railtie"
require "bson"
require 'rails'
if Rails.version.to_i>4
module AbstractController
module Callbacks
module ClassMethods
alias_method :prepend_before_filter, :prepend_before_action
alias_method :before_filter, :before_action
end
end
end
module ActionView::Helpers::AssetTagHelper
alias_method :org_image_tag, :image_tag
def image_tag(source, options={})
tmp_source = path_to_image(source)
org_image_tag(tmp_source, options)
end
end
class ActionController::Parameters
BSON_TYPE = Hash.new.bson_type
def bson_type
BSON_TYPE
end
def method_missing(method_sym, *args, &block)
if @parameters.respond_to?(method_sym)
message = <<-DEPRECATE.squish
Method #{method_sym} is deprecated and will be removed in Rails 5.1,
as `ActionController::Parameters` no longer inherits from
hash. Using this deprecated behavior exposes potential security
problems. If you continue to use this method you may be creating
a security vulnerability in your app that can be exploited. Instead,
consider using one of these documented methods which are not
deprecated: http://api.rubyonrails.org/v#{ActionPack.version}/classes/ActionController/Parameters.html
DEPRECATE
ActiveSupport::Deprecation.warn(message)
@parameters.public_send(method_sym, *args, &block)
else
super
end
end
def to_h #Migrate from rails 4 to rails 5, avoid unpermitted parameters
to_unsafe_hash
end
def update_values(&block)
each_pair do |key, value|
store(key, block[value])
end
end
def to_bson_key(validating_keys = BSON::Config.validating_keys?)
self.to_s
end
end
end
if RUBY_VERSION.to_f > 2.1
if RUBY_VERSION.to_f>2.4
module Psych
def self.load(yaml, permitted_classes: [Symbol], permitted_symbols: [], aliases: false, filename: nil, fallback: nil, symbolize_names: false, freeze: false, strict_integer: false)
return self.unsafe_load(yaml, filename: filename, fallback: fallback, symbolize_names: symbolize_names, freeze: freeze, strict_integer: strict_integer)
end
end
end
class Time
def new_offset(offset)
DateTime.new(self.to_i).new_offset(offset)
end
end
class ActionController::Parameters
def any?(&block)
self.permit!.to_h.any?(&block)
end
end
module URI
def self.escape(uri)
self::DEFAULT_PARSER.escape(uri)
end
def self.unescape(uri)
self::DEFAULT_PARSER.unescape(uri)
end
def self.parse(uri)
uri = uri.strip
self::DEFAULT_PARSER.parse(uri)
end
class <<self
alias_method :encode, :escape
alias_method :decode, :unescape
end
end
end
if Mongoid::VERSION.to_i < 5
require "moped"
Moped::BSON = BSON
else
if Mongoid::Config.respond_to?(:belongs_to_required_by_default)
Mongoid::Config.belongs_to_required_by_default = false
end
Mongoid::Sessions = Mongoid::Clients
Mongoid::Clients::StorageOptions::ClassMethods.module_eval do
def store_in(options)
options[:client] = options.delete(:session) if options && options[:session]
Mongoid::Clients::Validators::Storage.validate(self, options)
storage_options.merge!(options)
end
end
#monkey the behavier as before(mongoid 4)
if Mongoid::VERSION.to_i==5
module Mongoid
module Contextual
class Mongo
def add_default_sort_options
if !criteria.options.key?(:sort)
criteria.options[:sort] = {:_id => 1}
apply_option(:sort)
end
end
def first
add_default_sort_options
return documents.first if cached? && cache_loaded?
try_cache(:first) do
if raw_doc = view.limit(-1).first
doc = Factory.from_db(klass, raw_doc, criteria.options[:fields])
eager_load([doc]).first
end
end
end
def last
add_default_sort_options
try_cache(:last) do
with_inverse_sorting do
if raw_doc = view.limit(-1).first
doc = Factory.from_db(klass, raw_doc, criteria.options[:fields])
eager_load([doc]).first
end
end
end
end
def documents_for_iteration
add_default_sort_options
return documents if cached? && !documents.empty?
return view unless eager_loadable?
docs = view.map{ |doc| Factory.from_db(klass, doc, criteria.options[:fields]) }
eager_load(docs)
end
end
end
end
else
Boolean = Mongoid::Boolean
class Mongoid::Criteria::Queryable::Key
def to_bson_key(validating_keys = BSON::Config.validating_keys?)
self.to_s
end
end
end
BSON::Int64.class_eval do
def bson_int64?
self.to_bson_key.bson_int64?
end
end
end
module Mongoid
module Findable
def and_any_of(conditions)
self.or(conditions)
end
end
end
module Mongoid
class Criteria
def and_any_of(conditions)
if self.selector.count==0
tmp = self.or(conditions)
else
all_selector = self.selector
self.selector = {}
tmp = self.and([all_selector,{"$or"=>conditions}])
end
tmp
end
end
end
module ActionView::Helpers::AssetTagHelper
self.included do
def stylesheet_link_tag(*sources)
options = sources.extract_options!.stringify_keys
super(*sources,{media: :all}.merge(options))
end
end
end
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
already_required = Bundler.require.map{|b| b.name}
if Thread.current[:dependency_gems].nil?
require File.expand_path('../set_global_variable.rb', __FILE__)
end
dependency_gems = Thread.current[:dependency_gems]
if dependency_gems.nil?
built_in_ext_lines = File.readlines('built_in_extensions.rb').map{|s| s.split("#")[0].to_s} rescue []
downloaded_ext_lines = File.readlines('downloaded_extensions.rb').map{|s| s.split("#")[0].to_s} rescue []
extras_ext_lines = File.readlines('extra_gems.rb').map{|s| s.split("#")[0].to_s} rescue []
orbit_ext_lines = (built_in_ext_lines + downloaded_ext_lines + extras_ext_lines)
orbit_ext_gems = orbit_ext_lines.map{|l| l.match(/gem\s+['"](\w+)['"]/)[1] rescue nil}.select{|s| s.present?}.uniq
orbit_gem_specs = Gem::Specification.find_all.select{|g| orbit_ext_gems.include?(g.name) & (g.source.class != Bundler::Source::Rubygems)}
dependency_gems = orbit_gem_specs.flat_map{|spec| spec.dependent_specs.map{|s| s.name}}.uniq
end
dependency_gems.each{|gem_name| Bundler.require.push(Bundler::Dependency.new(gem_name,:runtime)) unless already_required.include?(gem_name)}
Bundler.require(:default, Rails.env)
class CssPostProcessor
def call(input)
d = input[:data]
[[':hover','.hover-class'],[':hover',':focus-within'],['\.ad-overlay','.banner-overlay']].each do |s,t|
d = d.gsub(/((?:(?!{|}).)*#{s}(?:(?!{|}).)*){/) do |v|
v1 = $1
v1 = v1.gsub(/((?:(?!,|\t).)*#{s}(?:(?!,|\t).)*)/) do |c|
c1 = c.gsub(/#{s}/,t)
"#{c}, #{c1}"
end
"#{v1}{"
end
end
return {data: d}
end
end
module Orbit
class ExceptionController < ActionDispatch::PublicExceptions
require 'action_dispatch/http/request'
require 'action_dispatch/middleware/exception_wrapper'
require 'action_dispatch/routing/inspector'
require 'action_dispatch/middleware/debug_exceptions'
RESCUES_TEMPLATE_PATH = ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH
Is_Rails5 = (Rails.version.to_i>4)
alias_method :org_call, :call
def call(env)
request = ActionDispatch::Request.new(env)
request_path = env["REQUEST_PATH"].to_s.sub(/^\/#{I18n.locale}\//, '/')
session = env["rack.session"]
if (Site::DEBUG rescue false) || (Rails.env != "production" && request_path.start_with?('/admin') && (@current_user = (session[:user_id] ? User.find(session[:user_id]) : nil) rescue nil))
exception = env['action_dispatch.exception']
@routes_app = env["action_dispatch.routes"]
if Is_Rails5
backtrace_cleaner = request.get_header("action_dispatch.backtrace_cleaner")
wrapper = ActionDispatch::ExceptionWrapper.new(backtrace_cleaner, exception)
traces = wrapper.traces
trace_to_show = "Application Trace"
if traces[trace_to_show].empty? && wrapper.rescue_template != "routing_error"
trace_to_show = "Full Trace"
end
if source_to_show = traces[trace_to_show].first
source_to_show_id = source_to_show[:id]
end
template = ActionDispatch::DebugExceptions::DebugView.new([RESCUES_TEMPLATE_PATH],
request: request,
exception: wrapper.exception,
traces: traces,
show_source_idx: source_to_show_id,
trace_to_show: trace_to_show,
routes_inspector: routes_inspector(wrapper.exception),
source_extracts: wrapper.source_extracts,
line_number: wrapper.line_number,
file: wrapper.file
)
else
wrapper = ActionDispatch::ExceptionWrapper.new(env, exception)
template = ActionView::Base.new([RESCUES_TEMPLATE_PATH],
request: request,
exception: wrapper.exception,
application_trace: wrapper.application_trace,
framework_trace: wrapper.framework_trace,
full_trace: wrapper.full_trace,
routes_inspector: routes_inspector(exception),
source_extract: wrapper.source_extract,
line_number: wrapper.line_number,
file: wrapper.file
)
end
file = "rescues/#{wrapper.rescue_template}"
if request.xhr?
body = template.render(template: file, layout: false, formats: [:text])
format = "text/plain"
else
body = template.render(template: file, layout: 'rescues/layout')
format = "text/html"
end
render_body(wrapper.status_code, body, format)
else
org_call(env)
end
end
def render_html(status, override_public_path=nil)
override_public_path = public_path if override_public_path.nil?
path = "#{public_path}/#{status}.#{I18n.locale}.html"
path = "#{public_path}/#{status}.html" unless (found = File.exist?(path))
if found || File.exist?(path)
render_format(status, 'text/html', File.read(path))
else
[404, { "X-Cascade" => "pass" }, []]
end
end
def render_body(status, body, format)
[status, {'Content-Type' => "#{format}; charset=#{ActionDispatch::Response.default_charset}", 'Content-Length' => body.bytesize.to_s}, [body]]
end
def routes_inspector(exception)
if @routes_app && @routes_app.respond_to?(:routes) && (exception.is_a?(ActionController::RoutingError) || exception.is_a?(ActionView::Template::Error))
ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes)
end
end
end
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.
# tell the I18n library where to find your translations
if Rails.version.to_i>=6
config.hosts.clear
end
I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]
I18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}')]
I18n.load_path += Gem::Specification.select{|v| v.source.class!=Bundler::Source::Rubygems}.map{|v| Dir[File.expand_path('../config/locales/*.yml',v.loaded_from)]}.flatten
# set default locale to something other than :en
config.i18n.enforce_available_locales = true
config.i18n.default_locale = :en
extra_lang = File.read('config/extra_lang.txt').scan(/.*extra_.*/).select{|v| v.exclude? '#'}[0].to_s.split(/extra_language.*:|,| /).select{|v| !v.empty?}.map{|v| v.to_sym} rescue []
all_locales = [:en, :zh_tw] + extra_lang
I18n.available_locales = config.i18n.available_locales = all_locales
require "i18n/backend/fallbacks"
I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)
fallbacks = {}
all_locales.each do |locale|
fallbacks[locale] = [locale,:en].uniq #all_locales.sort_by{|v| v == locale ? 0 : 1}
end
I18n.fallbacks = fallbacks
config.autoload_paths += %W(#{config.root}/lib)
#reload_gems = %w(impressionist) # names of gems which should autoreload
#config.autoload_paths += Gem.loaded_specs.values.inject([]){ |a,gem| a += gem.load_paths if reload_gems.include? gem.name; a }
#require 'active_support/dependencies'
#ActiveSupport::Dependencies.explicitly_unloadable_constants += reload_gems.map { |gem| gem.classify }
# config.paths["app/views"].unshift("#{Rails.root}/app/templates")
# 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.
config.time_zone = 'Asia/Taipei'
# 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
if Rails.version.to_i>=5
config.eager_load_paths << Rails.root.join('lib')
config.mongoid.belongs_to_required_by_default = false
end
# config.mongoid.observers = :orbit_observer
config.assets.configure do |env|
env.cache = ActiveSupport::Cache.lookup_store(:memory_store,{ size: 128.megabytes })
env.register_postprocessor 'text/css', CssPostProcessor.new
end
config.exceptions_app = ExceptionController.new("#{Rails.root}/app/views/errors")
end
end