CombinedText stringlengths 4 3.42M |
|---|
#encoding: utf-8
require 'mods'
module Bplmodels
class ModsDescMetadata < ActiveFedora::OmDatastream
#include Hydra::Datastream::CommonModsIndexMethods
# MODS XML constants.
def self.default_attributes
super.merge(:mimeType => 'application/xml')
end
MODS_NS = 'http://www.loc.gov/mods/v3'
MODS_SCHEMA = 'http://www.loc.gov/standards/mods/v3/mods-3-5.xsd'
MODS_PARAMS = {
"version" => "3.5",
"xmlns:xlink" => "http://www.w3.org/1999/xlink",
"xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
#"xmlns" => MODS_NS,
"xsi:schemaLocation" => "#{MODS_NS} #{MODS_SCHEMA}",
"xmlns:mods" => "http://www.loc.gov/mods/v3"
}
# OM terminology.
set_terminology do |t|
indexer = Solrizer::Descriptor.new(:string, :indexed, :stored, :searchable)
indexer_single = Solrizer::Descriptor.new(:text, :indexed, :stored, :searchable)
indexer_multiple = Solrizer::Descriptor.new(:text, :indexed, :stored, :searchable, :multivalued)
t.root :path => 'mods', :xmlns => MODS_NS
t.originInfo do
t.dateOther
end
#t.abstract(:path=>"abstract", :index_as=>[indexer_single])
# ABSTRACT -------------------------------------------------------------------------------
#t.abstract(:path=>"mods/oxns:abstract") {
t.abstract(:path=>"abstract") {
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.type_at :path=>{:attribute=>"type"}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
# GENRE ----------------------------------------------------------------------------------
t.genre(:path => 'genre') {
t.displayLabel :path => {:attribute=>'displayLabel'}
t.type_at :path=>{:attribute=>"type"}
t.usage :path=>{:attribute=>'usage'}
::Mods::AUTHORITY_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
# IDENTIIER ------------------------------------------------------------------------------
t.identifier(:path => 'identifier') {
#t.identifier(:path=>"identifier[not(@type=uri)]")
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.invalid :path=>{:attribute=>'invalid'}
t.type_at :path=>{:attribute=>'type'}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
# ACCESS_CONDITION -----------------------------------------------------------------------
t.accessCondition(:path => 'accessCondition') {
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.type_at :path=>{:attribute=>"type"}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
#CLASSIFICATION--------------------------------------------------------
t.classification(:path => 'classification') {
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.edition :path =>{:attribute=>"edition"}
::Mods::AUTHORITY_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
=begin
# CLASSIFICATION -------------------------------------------------------------------------
t.classification(:path => 'mods/oxns:classification') {
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.edition :path =>{:attribute=>"edition"}
::Mods::AUTHORITY_ATTRIBS.each { |attr_name|
t.send attr_name, :path => {:attribute=>"#{attr_name}"}
}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
# EXTENSION ------------------------------------------------------------------------------
t.extension(:path => 'mods/oxns:extension') {
t.displayLabel :path=>{:attribute=>'displayLabel'}
}
# LANGUAGE -------------------------------------------------------------------------------
t.language(:path => 'mods/oxns:language') {
# attributes
t.displayLabel :path=>{:attribute=>'displayLabel'}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
# child elements
t.languageTerm :path => 'languageTerm'
t.code_term :path => 'languageTerm', :attributes => { :type => "code" }
t.text_term :path => 'languageTerm', :attributes => { :type => "text" }
t.scriptTerm :path => 'scriptTerm'
}
t.languageTerm(:path => 'languageTerm') {
t.type_at :path=>{:attribute=>'type'}
::Mods::AUTHORITY_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
} # t.language
# LOCATION -------------------------------------------------------------------------------
t.location(:path => 'mods/oxns:location') {
# attributes
t.displayLabel :path=>{:attribute=>'displayLabel'}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
# child elements
t.physicalLocation(:path => 'physicalLocation') {
t.displayLabel :path=>{:attribute=>'displayLabel'}
::Mods::AUTHORITY_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
t.shelfLocator :path => 'shelfLocator'
t.url(:path => 'url') {
t.dateLastAccessed :path=>{:attribute=>'dateLastAccessed'}
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.note :path=>{:attribute=>'note'}
t.access :path=>{:attribute=>'access'}
t.usage :path=>{:attribute=>'usage'}
}
t.holdingSimple :path => 'holdingSimple'
t.holdingExternal :path => 'holdingExternal'
} # t.location
:path => 'languageTerm', :attributes => { :type => "text" }
# NAME ------------------------------------------------------------------------------------
t.plain_name(:path => 'mods/oxns:name') {
::Mods::Name::ATTRIBUTES.each { |attr_name|
if attr_name != 'type'
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
else
t.type_at :path =>{:attribute=>"#{attr_name}"}
end
}
# elements
t.namePart(:path => 'namePart') {
t.type_at :path =>{:attribute=>"type"}
}
t.family_name :path => 'namePart', :attributes => {:type=>"family"}
t.given_name :path => 'namePart', :attributes => {:type=>"given"}
t.termsOfAddress :path => 'namePart', :attributes => {:type=>"termsOfAddress"}
t.date :path => 'namePart', :attributes => {:type=>"date"}
t.displayForm :path => 'displayForm'
t.affiliation :path => 'affiliation'
t.description_el :path => 'description' # description is used by Nokogiri
t.role(:path => 'role') {
t.roleTerm(:path => 'roleTerm') {
t.type_at :path =>{:attribute=> "type"}
::Mods::AUTHORITY_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
# FIXME - not sure how to do this stuff
# role convenience method
t.authority :path => '.', :accessor => lambda { |role_node|
a = nil
role_node.roleTerm.each { |role_t|
# role_t.authority will be [] if it is missing from an earlier roleTerm
if role_t.authority && (!a || a.size == 0)
a = role_t.authority
end
}
a
}
# role convenience method
r.code :path => '.', :accessor => lambda { |role_node|
c = nil
role_node.roleTerm.each { |role_t|
if role_t.type_at == 'code'
c ||= role_t.text
end
}
c
}
# role convenience method
r.value :path => '.', :accessor => lambda { |role_node|
val = nil
role_node.roleTerm.each { |role_t|
if role_t.type_at == 'text'
val ||= role_t.text
end
}
# FIXME: this is broken if there are multiple role codes and some of them are not marcrelator
if !val && role_node.code && role_node.authority.first =~ /marcrelator/
val = MARC_RELATOR[role_node.code.first]
end
val
}
} # role node
#END FIXME
# name convenience method
# uses the displayForm of a name if present
# if no displayForm, try to make a string from family, given and terms of address
# otherwise, return all non-date nameParts concatenated together
n.display_value :path => '.', :single => true, :accessor => lambda {|name_node|
dv = ''
if name_node.displayForm && name_node.displayForm.text.size > 0
dv = name_node.displayForm.text
end
if dv.blank?
if name_node.type_at == 'personal'
if name_node.family_name.size > 0
dv = name_node.given_name.size > 0 ? "#{name_node.family_name.text}, #{name_node.given_name.text}" : name_node.family_name.text
elsif name_node.given_name.size > 0
dv = name_node.given_name.text
end
if !dv.blank?
first = true
name_node.namePart.each { |np|
if np.type_at == 'termsOfAddress' && !np.text.blank?
if first
dv = dv + " " + np.text
first = false
else
dv = dv + ", " + np.text
end
end
}
else # no family or given name
dv = name_node.namePart.select {|np| np.type_at != 'date' && !np.text.blank?}.join(" ")
end
else # not a personal name
dv = name_node.namePart.select {|np| np.type_at != 'date' && !np.text.blank?}.join(" ")
end
end
dv.strip.blank? ? nil : dv.strip
}
# name convenience method
n.display_value_w_date :path => '.', :single => true, :accessor => lambda {|name_node|
dv = ''
dv = dv + name_node.display_value if name_node.display_value
name_node.namePart.each { |np|
if np.type_at == 'date' && !np.text.blank? && !dv.end_with?(np.text)
dv = dv + ", #{np.text}"
end
}
if dv.start_with?(', ')
dv.sub(', ', '')
end
dv.strip.blank? ? nil : dv.strip
}
} # t._plain_name
t.personal_name :path => '/m:mods/m:name[@type="personal"]'
t._personal_name :path => '//m:name[@type="personal"]'
t.corporate_name :path => '/m:mods/m:name[@type="corporate"]'
t._corporate_name :path => '//m:name[@type="corporate"]'
t.conference_name :path => '/m:mods/m:name[@type="conference"]'
t._conference_name :path => '//m:name[@type="conference"]'
=end
t.title_info(:path=>'titleInfo') {
t.usage(:path=>{:attribute=>"usage"})
t.display_label(:path=>{:attribute=>"displayLabel"})
t.nonSort(:path=>"nonSort", :index_as=>[:searchable, :displayable])
t.main_title(:path=>"title", :label=>"title")
t.language(:index_as=>[:facetable],:path=>{:attribute=>"lang"})
t.supplied(:path=>{:attribute=>"supplied"})
t.type(:path=>{:attribute=>"type"})
t.authority(:path=>{:attribute=>"authority"})
t.authorityURI(:path=>{:attribute=>"authorityURI"})
t.valueURI(:path=>{:attribute=>"valueURI"})
t.subtitle(:path=>"subTitle", :label=>"subtitle")
t.part_number(:path=>"partNumber", :label=>"partNumber")
t.part_name(:path=>"partName", :label=>"partName")
}
t.title(:proxy=>[:title_info, :main_title])
t.name(:path=>'name') {
# this is a namepart
t.usage(:path=>{:attribute=>"usage"})
t.namePart(:type=>:string, :label=>"generic name")
t.type(:path=>{:attribute=>"type"})
t.authority(:path=>{:attribute=>"authority"})
t.authorityURI(:path=>{:attribute=>"authorityURI"})
t.valueURI(:path=>{:attribute=>"valueURI"})
t.role(:ref=>[:role])
t.date(:path=>"namePart", :attributes=>{:type=>"date"})
}
t.type_of_resource(:path=>"typeOfResource") {
t.manuscript(:path=>{:attribute=>"manuscript"})
}
t.genre_basic(:path=>"genre", :attributes=>{:displayLabel => "general"})
t.genre_specific(:path=>"genre", :attributes=>{:displayLabel => "specific"})
t.origin_info(:path=>"originInfo") {
t.publisher(:path=>"publisher")
t.place(:path=>"place") {
t.place_term(:path=>"placeTerm", :attributes=>{:type=>'text'})
}
t.issuance(:path=>"issuance")
t.edition(:path=>"edition")
t.event_type(:path=>{:attribute=>"eventType"})
t.frequency(:path=>"frequency") {
t.authority(:path=>{:attribute=>"authority"})
}
}
t.target_audience(:path=>"targetAudience") {
t.authority(:path=>{:attribute=>"authority"})
t.display_label(:path=>{:attribute=>"displayLabel"})
}
t.item_location(:path=>"location") {
t.physical_location(:path=>"physicalLocation") {
t.type(:path=>{:attribute=>"type"})
}
t.holding_simple(:path=>"holdingSimple") {
t.copy_information(:path=>"copyInformation") {
t.sub_location(:path=>"subLocation")
t.shelf_locator(:path=>"shelfLocator")
}
}
t.url(:path=>"url") {
t.usage(:path=>{:attribute=>"usage"})
t.access(:path=>{:attribute=>"access"})
t.note(:path=>{:attribute=>"note"})
}
}
t.identifier_accession :path => 'identifier', :attributes => { :type => "accession number" }
t.identifier_barcode :path => 'identifier', :attributes => { :type => "barcode" }
t.identifier_bpldc :path => 'identifier', :attributes => { :type => "bpldc number" }
t.identifier_other :path => 'identifier', :attributes => { :type => "other" }
t.isbn :path => 'identifier', :attributes => { :type => "isbn" }
t.local_other :path => 'identifier', :attributes => { :type => "local-other" }
t.lccn :path => 'identifier', :attributes => { :type => "lccn" }
t.local_accession :path => 'identifier', :attributes => { :type => "local-accession" }
t.local_call :path => 'identifier', :attributes => { :type => "local-call" }
t.local_barcode :path => 'identifier', :attributes => { :type => "local-barcode" }
t.ia_id :path => 'identifier', :attributes => { :type => "internet-archive" }
t.identifier_uri :path => 'identifier', :attributes => { :type => "uri" }
t.physical_description(:path=>"physicalDescription") {
t.internet_media_type(:path=>"internetMediaType")
t.digital_origin(:path=>"digitalOrigin")
t.extent(:path=>"extent")
t.note(:path=>'note')
}
t.note(:path=>"note") {
t.type_at(:path=>{:attribute=>"type"})
}
t.personal_name(:path=>'mods/oxns:subject/oxns:name', :attributes=>{:type => "personal"}) {
t.name_part(:path=>"namePart[not(@type)]")
t.date(:path=>"namePart", :attributes=>{:type=>"date"})
}
t.corporate_name(:path=>'mods/oxns:subject/oxns:name', :attributes=>{:type => "corporate"}) {
t.name_part(:path=>"namePart[not(@type)]")
t.date(:path=>"namePart", :attributes=>{:type=>"date"})
}
t.subject do
t.topic
t.geographic(:path=>'geographic') {
t.display_label(:path=>{:attribute=>"displayLabel"})
}
t.authority(:path=>{:attribute=>"authority"})
t.valueURI(:path=>{:attribute=>"valueURI"})
t.authorityURI(:path=>{:attribute=>"authorityURI"})
t.personal_name(:path=>'name', :attributes=>{:type => "personal"}) {
t.name_part(:path=>"namePart[not(@type)]")
t.date(:path=>"namePart", :attributes=>{:type=>"date"})
}
t.corporate_name(:path=>'name', :attributes=>{:type => "corporate"}) {
t.name_part(:path=>"namePart[not(@type)]")
t.date(:path=>"namePart", :attributes=>{:type=>"date"})
}
t.conference_name(:path=>'name', :attributes=>{:type => "conference"}) {
t.name_part(:path=>"namePart[not(@type)]")
}
t.name(:path=>'name') {
t.name_part(:path=>"namePart[not(@type)]")
t.date(:path=>"namePart", :attributes=>{:type=>"date"})
t.name_part_actual(:path=>"namePart") {
t.type(:path=>{:attribute=>"type"})
}
t.type(:path=>{:attribute=>"type"})
t.authority(:path=>{:attribute=>"authority"})
t.authority_uri(:path=>{:attribute=>"authorityURI"})
t.value_uri(:path=>{:attribute=>"valueURI"})
}
t.hierarchical_geographic(:path=>"hierarchicalGeographic") {
t.continent
t.country
t.region
t.province
t.state
t.territory
t.county
t.island
t.city
t.city_section(:path=>"citySection")
t.area
t.extarea(:path=>"extraterrestrialArea")
}
t.cartographics {
t.coordinates
t.scale
t.projection
}
t.temporal(:path=>'temporal', :attributes=>{:encoding => "w3cdtf"}) {
t.point(:path=>{:attribute=>"point"})
}
t.title_info(:ref=>[:title_info]) {
t.title
}
t.genre {
t.authority(:path=>{:attribute=>"authority"})
t.authority_uri(:path=>{:attribute=>"authorityURI"})
t.value_uri(:path=>{:attribute=>"valueURI"})
}
end
t.related_item(:path=>"relatedItem") {
t.type(:path=>{:attribute=>"type"})
t.href(:path=>{:attribute=>'xlink:href'})
t.title_info(:path=>"titleInfo") {
t.title
t.nonSort(:path=>"nonSort")
}
t.identifier
t.location(:path=>'location') {
t.url(:path=>'url')
}
t.related_item(:ref=>[:related_series_item]) {
t.related_item(:ref=>[:related_series_item]) {
t.related_item(:ref=>[:related_series_item]) {
t.related_item(:ref=>[:related_series_item])
}
}
}
t.subseries(:path=>'relatedItem', :attributes=>{:type => "series"}) {
t.title_info(:path=>"titleInfo") {
t.title
t.nonSort(:path=>"nonSort")
}
t.subsubseries(:path=>'relatedItem', :attributes=>{:type => "series"}) {
t.title_info(:path=>"titleInfo") {
t.title
t.nonSort(:path=>"nonSort")
}
}
}
}
t.related_series_item(:path=>'relatedItem') {
t.type(:path=>{:attribute=>"type"})
t.title_info(:path=>"titleInfo") {
t.title
t.nonSort(:path=>"nonSort")
}
}
#t.subseries(:path=>'mods/oxns:relatedItem/oxns:relatedItem', :attributes=>{:type => "series"}) {
# t.title_info(:path=>"titleInfo") {
# t.title
# t.nonSort(:path=>"nonSort")
# }
#}
t.use_and_reproduction(:path=>"accessCondition", :attributes=>{:type=>"use and reproduction"}) {
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.type(:path=>{:attribute=>"type"})
}
t.restriction_on_access(:path=>"accessCondition", :attributes=>{:type=>"restriction on access"}) {
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.type(:path=>{:attribute=>"type"})
}
t.date(:path=>"originInfo") {
t.date_other(:path=>"dateOther") {
t.encoding(:path=>{:attribute=>"encoding"})
t.key_date(:path=>{:attribute=>"keyDate"})
t.type(:path=>{:attribute=>"type"})
t.qualifier(:path=>{:attribute=>"qualifier"})
}
t.dates_created(:path=>"dateCreated") {
t.encoding(:path=>{:attribute=>"encoding"})
t.key_date(:path=>{:attribute=>"keyDate"})
t.point(:path=>{:attribute=>"point"})
t.qualifier(:path=>{:attribute=>"qualifier"})
}
t.dates_issued(:path=>"dateIssued") {
t.encoding(:path=>{:attribute=>"encoding"})
t.key_date(:path=>{:attribute=>"keyDate"})
t.point(:path=>{:attribute=>"point"})
t.qualifier(:path=>{:attribute=>"qualifier"})
}
t.dates_copyright(:path=>"copyrightDate") {
t.encoding(:path=>{:attribute=>"encoding"})
t.key_date(:path=>{:attribute=>"keyDate"})
t.point(:path=>{:attribute=>"point"})
t.qualifier(:path=>{:attribute=>"qualifier"})
}
}
t.role {
t.text(:path=>'roleTerm',:attributes=>{:type=>'text', :authority=>'marcrelator', :authorityURI=>'http://id.loc.gov/vocabulary/relators'}) {
t.valueURI(:path=>{:attribute=>'valueURI'})
}
t.code(:path=>'roleTerm',:attributes=>{:type=>'code'})
}
t.language(:path=>"language") {
t.language_term(:path=>"languageTerm") {
t.lang_val_uri(:path=>{:attribute=>"valueURI"})
}
}
t.record_info(:path=>'recordInfo') {
t.description_standard(:path=>'descriptionStandard', :attributes=>{:authority=>"marcdescription"})
t.record_content_source(:path=>'recordContentSource') {
t.authority(:path=>{:attribute=>"authority"})
}
t.record_origin(:path=>'recordOrigin')
t.language_of_cataloging(:path=>'languageOfCataloging') {
t.language_term(:path=>'languageTerm', :attributes => { :authority => 'iso639-2b',:authorityURI=> 'http://id.loc.gov/vocabulary/iso639-2', :type=>'text', :valueURI=>'http://id.loc.gov/vocabulary/iso639-2/eng' })
}
}
t.table_of_contents(:path=>'tableOfContents') {
t.href(:path=>{:attribute=>'xlink:href'})
}
end
# Blocks to pass into Nokogiri::XML::Builder.new()
=begin
define_template :name do |xml|
xml.name {
xml.namePart
xml.role {
xml.roleTerm(:authority => "marcrelator", :type => "text")
}
}
end
define_template :relatedItem do |xml|
xml.relatedItem {
xml.titleInfo {
xml.title
}
xml.location {
xml.url
}
}
end
define_template :related_citation do |xml|
xml.note(:type => "citation/reference")
end
=end
def self.xml_template
builder = Nokogiri::XML::Builder.new(:encoding => "UTF-8") do |xml|
xml.mods(MODS_PARAMS) {
xml.parent.namespace = xml.parent.namespace_definitions.find{|ns|ns.prefix=="mods"}
}
end
return builder.doc
end
def to_xml(xml = nil)
xml = self.ng_xml if xml.nil?
ng_xml = self.ng_xml
if ng_xml.respond_to?(:root) && ng_xml.root.nil? && self.class.respond_to?(:root_property_ref) && !self.class.root_property_ref.nil?
ng_xml = self.class.generate(self.class.root_property_ref, "")
if xml.root.nil?
xml = ng_xml
end
end
unless xml == ng_xml || ng_xml.root.nil?
if xml.kind_of?(Nokogiri::XML::Document)
xml.root.add_child(ng_xml.root)
elsif xml.kind_of?(Nokogiri::XML::Node)
xml.add_child(ng_xml.root)
else
raise "You can only pass instances of Nokogiri::XML::Node into this method. You passed in #{xml}"
end
end
return xml.to_xml(:encoding=>'UTF-8').strip
end
#Required for Active Fedora 9
def prefix(path=nil)
return ''
end
=begin
def identifier=(values)
ng_xml.search(identifier.xpath, {oxns:"http://www.loc.gov/mods/v3"}).each do |n|
n.remove
end
super(values)
end
=end
#def insert_physical_description(media_type=nil, digital_origin=nil, media_type2=nil, note=nil)
def insert_digital_origin(digital_origin=nil)
physical_description_index = 0
origin_index = self.mods(0).physical_description(physical_description_index).digital_origin.count
self.mods(0).physical_description(physical_description_index).digital_origin(origin_index, digital_origin) unless digital_origin.blank?
end
def insert_physical_note(note=nil)
physical_description_index = 0
note_index = self.mods(0).physical_description(physical_description_index).note.count
self.mods(0).physical_description(physical_description_index).note(note_index, note) unless note.blank?
end
def remove_physical_description(index)
self.find_by_terms(:physical_description).slice(index.to_i).remove
end
def insert_media_type(media_type=nil)
physical_description_index = 0
media_type_index = self.mods(0).physical_description(physical_description_index).internet_media_type.count
self.mods(0).physical_description(physical_description_index).internet_media_type(media_type_index, media_type) unless media_type.blank? || self.mods(0).physical_description(physical_description_index).internet_media_type.include?(media_type)
end
define_template :language do |xml, value, code|
xml.language {
xml.languageTerm(:type=>"text", :authority=>"iso639-2b", :authorityURI=>"http://id.loc.gov/vocabulary/iso639-2", :valueURI=>code) {
xml.text value
}
}
end
def insert_language(value=nil, code='eng')
code = "http://id.loc.gov/vocabulary/iso639-2/#{code}" unless code.include?('http')
add_child_node(ng_xml.root, :language, value, code)
end
def remove_language(index)
self.find_by_terms(:language).slice(index.to_i).remove
end
def insert_rights(value=nil, type=nil, displayLabel=nil)
access_index = self.mods(0).accessCondition.count
self.mods(0).accessCondition(access_index, value) unless value.blank?
self.mods(0).accessCondition(access_index).type_at = type unless type.blank?
self.mods(0).accessCondition(access_index).displayLabel = displayLabel unless displayLabel.blank?
end
def insert_target_audience(value=nil, authority=nil, display_label=nil)
audience_index = self.mods(0).target_audience.count
self.mods(0).target_audience(audience_index, value) unless value.blank?
self.mods(0).target_audience(audience_index).authority = authority unless authority.blank?
self.mods(0).target_audience(audience_index).display_label = display_label unless display_label.blank?
end
def insert_type_of_resource(value=nil, manuscript=nil)
resource_index = self.mods(0).type_of_resource.count
if !self.mods(0).type_of_resource.include?(value)
self.mods(0).type_of_resource(resource_index, value) unless value.blank?
self.mods(0).type_of_resource(resource_index).manuscript = 'yes' unless manuscript.blank?
end
end
def remove_type_of_resource(index)
self.find_by_terms(:type_of_resource).slice(index.to_i).remove
end
def insert_publisher(publisher=nil, place=nil)
origin_index = 0
publisher_index = self.mods(0).origin_info(origin_index).publisher.count
place_index = self.mods(0).origin_info(origin_index).place.count
self.mods(0).origin_info(origin_index).publisher(publisher_index, publisher) unless publisher.blank?
self.mods(0).origin_info(origin_index).place(place_index).place_term = place unless place.blank?
end
def remove_publisher(index)
self.find_by_terms(:mods, :publisher).slice(index.to_i).remove
end
def insert_issuance(issuance=nil)
origin_index = 0
issuance_index = self.mods(0).origin_info(origin_index).issuance.count
self.mods(0).origin_info(origin_index).issuance(issuance_index, issuance) unless issuance.blank?
end
def insert_edition(edition=nil)
origin_index = 0
edition_index = self.mods(0).origin_info(origin_index).edition.count
self.mods(0).origin_info(origin_index).edition(edition_index, edition) unless edition.blank?
end
def insert_genre(value=nil, value_uri=nil, authority=nil, display_label='specific')
#Prevent duplicates
if value.present? && !self.mods(0).genre.any?{ |genre| genre == value}
genre_index = self.mods(0).genre.count
self.mods(0).genre(genre_index, value) unless value.blank?
unless authority.blank?
self.mods(0).genre(genre_index).authority = authority
self.mods(0).genre(genre_index).authorityURI = BplEnrich::Authorities.authority_uri(authority)
end
if value_uri.present? && value_uri.match(/^http/).blank?
value_uri = "#{BplEnrich::Authorities.authority_uri(authority)}/#{value_uri}"
end
self.mods(0).genre(genre_index).valueURI = value_uri unless value_uri.blank?
self.mods(0).genre(genre_index).displayLabel = display_label unless display_label.blank?
end
end
def remove_genre(index)
self.find_by_terms(:genre).slice(index.to_i).remove
end
define_template :access_links do |xml, preview, primary|
xml.location {
if preview != nil && preview.length > 0
xml.url(:access=>"preview") {
xml.text preview
}
end
xml.url(:usage=>"primary", :access=>"object in context") {
xml.text primary
}
}
end
def insert_access_links(preview=nil, primary=nil)
add_child_node(ng_xml.root, :access_links, preview, primary)
end
def remove_access_links(index)
self.find_by_terms(:access_links).slice(index.to_i).remove
end
def insert_geonames(geonames_id)
puts 'Geonames ID is: ' + geonames_id
#Duplicate Geonames value?
if self.subject.valueURI.include?(geonames_id)
return false
end
api_result = Geomash::Geonames.get_geonames_data(geonames_id)
puts 'API Result is: ' + api_result.to_s
subject_index = self.mods(0).subject.count
self.mods(0).subject(subject_index).authority = "geonames"
self.mods(0).subject(subject_index).valueURI = "http://sws.geonames.org/#{geonames_id}"
self.mods(0).subject(subject_index).authorityURI = 'http://sws.geonames.org'
self.mods(0).subject(subject_index).geographic = api_result[:hier_geo].values[-1]
#Insert Coordinates
if api_result[:coords] != nil
self.mods(0).subject(subject_index).cartographics.coordinates = api_result[:coords][:latitude] + "," + api_result[:coords][:longitude]
end
end
def insert_origin_event(event_type)
#Currently only supporting one elements...
origin_index = 0
self.mods(0).origin_info(origin_index).event_type = event_type unless event_type.blank?
end
def insert_origin_frequency(frequency, authority)
#Currently only supporting one elements...
origin_index = 0
self.mods(0).origin_info(origin_index).frequency = frequency unless frequency.blank?
self.mods(0).origin_info(origin_index).frequency.authority = authority unless authority.blank?
end
def insert_tgn(tgn_id)
puts 'TGN ID is: ' + tgn_id
# check for duplicate TGN value
return false if self.subject.valueURI.include?(tgn_id)
api_result = Geomash::TGN.get_tgn_data(tgn_id)
puts 'API Result is: ' + api_result.to_s
#FIXME: Only works for hier_geo places....
if api_result[:hier_geo].present? && self.subject.hierarchical_geographic.present?
self.mods(0).subject.each_with_index do |_ignored, subject_index|
if self.mods(0).subject(subject_index).authority == ['tgn']
if api_result[:hier_geo][:city_section].present?
# Get rid of less specific matches... city_section level info should trump city
if self.mods(0).subject(subject_index).hierarchical_geographic(0).city_section.blank? &&
self.mods(0).subject(subject_index).hierarchical_geographic(0).city == [api_result[:hier_geo][:city]]
# Check to not remove non-hier geo cases
if self.mods(0).subject(subject_index).geographic(0).blank?
self.mods(0).subject(subject_index, nil)
end
end
elsif api_result[:hier_geo][:city].present?
# Get rid of less specific matches... city level info should trump state
if self.mods(0).subject(subject_index).hierarchical_geographic(0).city.blank? &&
self.mods(0).subject(subject_index).hierarchical_geographic(0).state == [api_result[:hier_geo][:state]]
#Check to not remove non-hier geo cases... as actually more specific than just a state
if self.mods(0).subject(subject_index).geographic(0).blank?
self.mods(0).subject(subject_index, nil)
end
# Exit if same city match
elsif self.mods(0).subject(subject_index).hierarchical_geographic(0).city == [api_result[:hier_geo][:city]]
#Case of more specific in non_hier_geo...
if self.mods(0).subject(subject_index).geographic(0).blank? && api_result[:non_hier_geo].present?
self.mods(0).subject(subject_index, nil)
else
return false
end
end
elsif api_result[:hier_geo][:city].blank?
# Exit check if trying to insert same state twice with no city
if api_result[:hier_geo][:state].present?
if self.mods(0).subject(subject_index).hierarchical_geographic(0).state == [api_result[:hier_geo][:state]]
#Case of more specific in non_hier_geo...
if self.mods(0).subject(subject_index).geographic(0).blank? && api_result[:non_hier_geo].present?
self.mods(0).subject(subject_index, nil)
else
return false
end
end
# Exit check if trying to insert the same area...
elsif api_result[:hier_geo][:area].present?
if self.mods(0).subject(subject_index).hierarchical_geographic(0).area == [api_result[:hier_geo][:area]]
#Case of more specific in non_hier_geo...
if self.mods(0).subject(subject_index).geographic(0).blank? && api_result[:non_hier_geo].present?
self.mods(0).subject(subject_index, nil)
else
return false
end
end
# Finally exit if inserting the same country...
elsif api_result[:hier_geo][:state].blank? &&
api_result[:hier_geo][:area].blank? &&
api_result[:hier_geo][:country].present?
if self.mods(0).subject(subject_index).hierarchical_geographic(0).country == [api_result[:hier_geo][:country]]
#Case of more specific in non_hier_geo...
if self.mods(0).subject(subject_index).geographic(0).blank? && api_result[:non_hier_geo].present?
self.mods(0).subject(subject_index, nil)
else
return false
end
end
end
end
end
end
end
if api_result[:non_hier_geo].present?
#Exit if same place match currently....
self.mods(0).subject.each_with_index do |_ignored, subject_index|
if self.mods(0).subject(subject_index).authority == ['tgn']
if self.mods(0).subject(subject_index).geographic == [api_result[:non_hier_geo][:value]]
return false
end
end
end
end
subject_index = self.mods(0).subject.count
self.mods(0).subject(subject_index).authority = "tgn"
self.mods(0).subject(subject_index).valueURI = "http://vocab.getty.edu/tgn/#{tgn_id}"
self.mods(0).subject(subject_index).authorityURI = 'http://vocab.getty.edu/tgn/'
#Insert geographic text
if api_result[:non_hier_geo].present?
self.mods(0).subject(subject_index).geographic = api_result[:non_hier_geo][:value]
self.mods(0).subject(subject_index).geographic.display_label = api_result[:non_hier_geo][:qualifier] unless api_result[:non_hier_geo][:qualifier].blank?
end
#Insert hierarchicalGeographic text
if api_result[:hier_geo] != nil
api_result[:hier_geo].keys.reverse.each do |key|
key_with_equal = key.to_s + "="
self.mods(0).subject(subject_index).hierarchical_geographic.send(key_with_equal.to_sym, Bplmodels::DatastreamInputFuncs.utf8Encode(api_result[:hier_geo][key]))
end
end
#Insert Coordinates
if api_result[:coords] != nil
self.mods(0).subject(subject_index).cartographics.coordinates = api_result[:coords][:latitude] + "," + api_result[:coords][:longitude]
end
end
#usage=nil, supplied=nil, subtitle=nil, language=nil, type=nil, authority=nil, authorityURI=nil, valueURI=nil
def insert_title(nonSort=nil, main_title=nil, usage=nil, supplied=nil, type=nil, subtitle=nil, language=nil,
display_label=nil, part_number=nil, part_name=nil, authority=nil, value_uri=nil, args={})
title_index = self.mods(0).title_info.count
self.mods(0).title_info(title_index).nonSort = nonSort unless nonSort.blank?
self.mods(0).title_info(title_index).main_title = main_title unless main_title.blank?
self.mods(0).title_info(title_index).usage = usage unless usage.blank?
self.mods(0).title_info(title_index).supplied = 'yes' unless supplied.blank? || supplied == 'no'
self.mods(0).title_info(title_index).type = type unless type.blank?
#Need to update previous titles to be translated now as well....
if type == 'translated' && usage == 'primary'
0.upto title_index-1 do |pos|
if self.mods(0).title_info(pos).usage[0] == 'primary'
self.mods(0).title_info(pos).type = type
end
end
#Currently only main title has a blank type.... may want to pass this instead eventually if that changes.
elsif type.blank?
self.mods(0).title_info(title_index).display_label = 'primary_display'
end
self.mods(0).title_info(title_index).subtitle = subtitle unless subtitle.blank?
self.mods(0).title_info(title_index).language = language unless language.blank?
self.mods(0).title_info(title_index).display_label = display_label unless display_label.blank?
self.mods(0).title_info(title_index).part_number = part_number unless part_number.blank?
self.mods(0).title_info(title_index).part_name = part_name unless part_name.blank?
unless authority.blank?
self.mods(0).title_info(title_index).authority = authority
self.mods(0).title_info(title_index).authorityURI = BplEnrich::Authorities.authority_uri(authority)
end
self.mods(0).title_info(title_index).valueURI = value_uri unless value_uri.blank?
if args.present?
raise 'broken args in Active Fedora 7'
end
args.each do |key, value|
self.mods(0).title_info(title_index).send(key, Bplmodels::DatastreamInputFuncs.utf8Encode(value)) unless value.blank?
end
end
def remove_title(index)
self.find_by_terms(:mods, :title_info).slice(index.to_i).remove
end
#image.descMetadata.find_by_terms(:name).slice(0).set_attribute("new", "true")
def insert_name(name=nil, type=nil, authority=nil, value_uri=nil, role=nil, role_uri=nil, date=nil, args={})
name_index = self.mods(0).name.count
self.mods(0).name(name_index).type = type unless type.blank?
unless authority.blank?
self.mods(0).name(name_index).authority = authority
self.mods(0).name(name_index).authorityURI = BplEnrich::Authorities.authority_uri(authority)
end
self.mods(0).name(name_index).valueURI = value_uri unless value_uri.blank?
if role.present?
role_split = role.split('{|}') #new split var - see Arnold ticket
role_uri = '{|}{|}{|}{|}{|}' if role_uri.nil? #Very hackish...
role_uri_split = role_uri.split('{|}') #new split var - see Arnold ticket
role_split.each_with_index do |single_role, role_index|
self.mods(0).name(name_index).role(role_index).text = single_role unless single_role.blank?
self.mods(0).name(name_index).role(role_index).text.valueURI = role_uri_split[role_index] unless role_uri_split[role_index].blank?
end
end
if type == 'corporate'
name_array = Bplmodels::DatastreamInputFuncs.corpNamePartSplitter(name)
name_array.each_with_index do |name_value, array_pos|
self.mods(0).name(name_index).namePart(array_pos, name_value)
end
elsif type=='personal' && date.blank?
name_hash = Bplmodels::DatastreamInputFuncs.persNamePartSplitter(name)
self.mods(0).name(name_index).namePart = name_hash[:namePart]
self.mods(0).name(name_index).date = name_hash[:datePart] unless name_hash[:datePart].blank?
elsif date.present?
self.mods(0).name(name_index).namePart = name
self.mods(0).name(name_index).date = date
else
self.mods(0).name(name_index).namePart = name
end
args.each do |key, value|
self.mods(0).name(name_index).send(key, Bplmodels::DatastreamInputFuncs.utf8Encode(value)) unless value.blank?
end
end
def remove_name(index)
self.find_by_terms(:mods, :name).slice(index.to_i).remove
end
#test = ["test1", "test2"]
#test.each do |k|
#define_method "current_#{k.underscore}" do
#puts k.underscore
#end
#end
def insert_oai_date(date)
#converted = Bplmodels::DatastreamInputFuncs.convert_to_mods_date(date)
converted = BplEnrich::Dates.standardize(date)
#date_index = self.date.length
date_index = 0
dup_found = false
#Prevent duplicate entries... Using a flag as keep the potential note?
(self.mods(0).date(date_index).dates_created.length-1).times do |index|
if converted.has_key?(:single_date)
if self.mods(0).date(date_index).dates_created(index).point.blank? && self.mods(0).date(date_index).dates_created(index).first == converted[:single_date]
dup_found = true
end
elsif converted.has_key?(:date_range)
if self.mods(0).date(date_index).dates_created(index).point == 'start' && self.mods(0).date(date_index).dates_created(index).first == converted[:date_range][:start]
if self.mods(0).date(date_index).dates_created(index+1).point == 'end' && self.mods(0).date(date_index).dates_created(index+1).first == converted[:date_range][:end]
dup_found = true
end
end
end
end
if !dup_found
if converted.has_key?(:single_date) && !self.date.dates_created.include?(converted[:single_date])
date_created_index = self.date(date_index).dates_created.length
self.date(date_index).dates_created(date_created_index, converted[:single_date])
self.date(date_index).dates_created(date_created_index).encoding = 'w3cdtf'
if date_created_index == 0
self.date(date_index).dates_created(date_created_index).key_date = 'yes'
end
if converted.has_key?(:date_qualifier)
self.date(date_index).dates_created(date_created_index).qualifier = converted[:date_qualifier]
end
elsif converted.has_key?(:date_range)
date_created_index = self.date(date_index).dates_created.length
self.date(date_index).dates_created(date_created_index, converted[:date_range][:start])
self.date(date_index).dates_created(date_created_index).encoding = 'w3cdtf'
if date_created_index == 0
self.date(date_index).dates_created(date_created_index).key_date = 'yes'
end
self.date(date_index).dates_created(date_created_index).point = 'start'
self.date(date_index).dates_created(date_created_index).qualifier = converted[:date_qualifier]
date_created_index = self.date(date_index).dates_created.length
self.date(date_index).dates_created(date_created_index, converted[:date_range][:end])
self.date(date_index).dates_created(date_created_index).encoding = 'w3cdtf'
self.date(date_index).dates_created(date_created_index).point = 'end'
self.date(date_index).dates_created(date_created_index).qualifier = converted[:date_qualifier]
end
end
self.insert_note(converted[:date_note],"date") unless !converted.has_key?(:date_note)
end
def insert_oai_date_copyright(date)
#converted = Bplmodels::DatastreamInputFuncs.convert_to_mods_date(date)
converted = BplEnrich::Dates.standardize(date)
#date_index = self.date.length
date_index = 0
dup_found = false
#Prevent duplicate entries... Using a flag as keep the potential note?
(self.mods(0).date(date_index).dates_copyright.length-1).times do |index|
if converted.has_key?(:single_date)
if self.mods(0).date(date_index).dates_copyright(index).point.blank? && self.mods(0).date(date_index).dates_copyright(index).first == converted[:single_date]
dup_found = true
end
elsif converted.has_key?(:date_range)
if self.mods(0).date(date_index).dates_copyright(index).point == 'start' && self.mods(0).date(date_index).dates_copyright(index).first == converted[:date_range][:start]
if self.mods(0).date(date_index).dates_copyright(index+1).point == 'end' && self.mods(0).date(date_index).dates_copyright(index+1).first == converted[:date_range][:end]
dup_found = true
end
end
end
end
if !dup_found
if converted.has_key?(:single_date) && !self.date.dates_copyright.include?(converted[:single_date])
date_created_index = self.date(date_index).dates_copyright.length
self.date(date_index).dates_copyright(date_created_index, converted[:single_date])
self.date(date_index).dates_copyright(date_created_index).encoding = 'w3cdtf'
if date_created_index == 0
self.date(date_index).dates_copyright(date_created_index).key_date = 'yes'
end
if converted.has_key?(:date_qualifier)
self.date(date_index).dates_copyright(date_created_index).qualifier = converted[:date_qualifier]
end
elsif converted.has_key?(:date_range)
date_created_index = self.date(date_index).dates_copyright.length
self.date(date_index).dates_copyright(date_created_index, converted[:date_range][:start])
self.date(date_index).dates_copyright(date_created_index).encoding = 'w3cdtf'
if date_created_index == 0
self.date(date_index).dates_copyright(date_created_index).key_date = 'yes'
end
self.date(date_index).dates_copyright(date_created_index).point = 'start'
self.date(date_index).dates_copyright(date_created_index).qualifier = converted[:date_qualifier]
date_created_index = self.date(date_index).dates_copyright.length
self.date(date_index).dates_copyright(date_created_index, converted[:date_range][:end])
self.date(date_index).dates_copyright(date_created_index).encoding = 'w3cdtf'
self.date(date_index).dates_copyright(date_created_index).point = 'end'
self.date(date_index).dates_copyright(date_created_index).qualifier = converted[:date_qualifier]
end
end
self.insert_note(converted[:date_note],"date") unless !converted.has_key?(:date_note)
end
def insert_oai_date_issued(date)
#converted = Bplmodels::DatastreamInputFuncs.convert_to_mods_date(date)
converted = BplEnrich::Dates.standardize(date)
#date_index = self.date.length
date_index = 0
if converted.has_key?(:single_date)
date_created_index = self.date(date_index).dates_issued.length
self.date(date_index).dates_issued(date_created_index, converted[:single_date])
self.date(date_index).dates_issued(date_created_index).encoding = 'w3cdtf'
if date_created_index == 0
self.date(date_index).dates_issued(date_created_index).key_date = 'yes'
end
if converted.has_key?(:date_qualifier)
self.date(date_index).dates_issued(date_created_index).qualifier = converted[:date_qualifier]
end
elsif converted.has_key?(:date_range)
date_created_index = self.date(date_index).dates_issued.length
self.date(date_index).dates_issued(date_created_index, converted[:date_range][:start])
self.date(date_index).dates_issued(date_created_index).encoding = 'w3cdtf'
if date_created_index == 0
self.date(date_index).dates_issued(date_created_index).key_date = 'yes'
end
self.date(date_index).dates_issued(date_created_index).point = 'start'
self.date(date_index).dates_issued(date_created_index).qualifier = converted[:date_qualifier]
date_created_index = self.date(date_index).dates_issued.length
self.date(date_index).dates_issued(date_created_index, converted[:date_range][:end])
self.date(date_index).dates_issued(date_created_index).encoding = 'w3cdtf'
self.date(date_index).dates_issued(date_created_index).point = 'end'
self.date(date_index).dates_issued(date_created_index).qualifier = converted[:date_qualifier]
end
self.insert_note(converted[:date_note],"date") unless !converted.has_key?(:date_note)
end
def insert_date(date_type, dateStarted=nil, dateEnding=nil, dateQualifier=nil, dateOther=nil, keydate=nil)
#begin
#date_index = self.mods(0).date.count
date_index = 0
#This is horrid. Can't use count as other elements use origin_info at the same depth....
if keydate.blank?
keydate = true if (self.mods(0).date.dates_created.key_date.blank? and self.mods(0).date.dates_issued.key_date.blank? and self.mods(0).date.dates_copyright.key_date.blank? and self.mods(0).date.date_other.key_date.blank?)
keydate ||= false
end
date_type = 'dates_created' if date_type == 'dateCreated'
date_type = 'dates_copyright' if date_type == 'copyrightDate'
date_type = 'dates_issued' if date_type == 'dateIssued'
date_type = 'date_other' if date_type == 'dateOther'
date_type_with_equal = date_type + '='
#Range case - broken...fixme ... under same mods:originInfo ?
if dateStarted.present? and dateEnding.present?
self.mods(0).date(date_index).send(date_type.to_sym, 0).point = 'start'
self.mods(0).date(date_index).send(date_type.to_sym, 0).encoding = 'w3cdtf'
self.mods(0).date(date_index).send(date_type.to_sym, 0).qualifier = dateQualifier unless dateQualifier.blank?
self.mods(0).date(date_index).send(date_type.to_sym, 0).key_date = "yes" unless keydate == false
self.mods(0).date(date_index).send(date_type.to_sym, 1).point = 'end'
self.mods(0).date(date_index).send(date_type.to_sym, 1).encoding = 'w3cdtf'
self.mods(0).date(date_index).send(date_type.to_sym, 1).qualifier = dateQualifier unless dateQualifier.blank?
#Hackish way to set the node values....
self.mods(0).date(date_index).send(date_type_with_equal.to_sym, [dateStarted, dateEnding])
elsif dateStarted.present?
self.mods(0).date(date_index).send(date_type.to_sym, 0).encoding = 'w3cdtf'
self.mods(0).date(date_index).send(date_type.to_sym, 0).qualifier = dateQualifier unless dateQualifier.blank?
self.mods(0).date(date_index).send(date_type.to_sym, 0).key_date = "yes" unless keydate == false
self.mods(0).date(date_index).send(date_type_with_equal.to_sym, dateStarted)
elsif dateOther.present?
self.mods(0).date(date_index).send(date_type_with_equal.to_sym, dateOther)
end
end
define_template :date_issued do |xml, dateStarted, dateEnding, dateQualifier|
if dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.originInfo {
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start", :qualifier=>dateQualifier) {
xml.text dateStarted
}
xml.dateIssued(:encoding=>"w3cdtf", :point=>"end", :qualifier=>dateQualifier) {
xml.text dateEnding
}
}
elsif dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0
xml.originInfo {
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start") {
xml.text dateStarted
}
xml.dateIssued(:encoding=>"w3cdtf", :point=>"end") {
xml.text dateEnding
}
}
elsif dateStarted != nil && dateStarted.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.originInfo {
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes", :qualifier=>dateQualifier) {
xml.text dateStarted
}
}
elsif dateStarted != nil && dateStarted.length > 0
xml.originInfo {
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes") {
xml.text dateStarted
}
}
else
#puts "error in dates?"
end
end
define_template :date_issued_partial do |xml, dateStarted, dateEnding, dateQualifier|
if dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start", :qualifier=>dateQualifier) {
xml.text dateStarted
}
xml.dateIssued(:encoding=>"w3cdtf", :point=>"end", :qualifier=>dateQualifier) {
xml.text dateEnding
}
elsif dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start") {
xml.text dateStarted
}
xml.dateIssued(:encoding=>"w3cdtf", :point=>"end") {
xml.text dateEnding
}
elsif dateStarted != nil && dateStarted.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes", :qualifier=>dateQualifier) {
xml.text dateStarted
}
elsif dateStarted != nil && dateStarted.length > 0
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes") {
xml.text dateStarted
}
else
#puts "error in dates?"
end
end
def insert_date_issued(dateStarted=nil, dateEnding=nil, dateQualifier=nil)
#begin
if self.find_by_terms(:origin_info) != nil && self.find_by_terms(:origin_info).slice(0) != nil
add_child_node(self.find_by_terms(:origin_info).slice(0), :date_issued_partial, dateStarted, dateEnding, dateQualifier)
else
add_child_node(ng_xml.root, :date_issued, dateStarted, dateEnding, dateQualifier)
end
#rescue OM::XML::Terminology::BadPointerError
#add_child_node(ng_xml.root, :date, dateStarted, dateEnding, dateQualifier, dateOther)
#end
end
define_template :date_copyright do |xml, dateStarted, dateEnding, dateQualifier|
if dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.originInfo {
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start", :qualifier=>dateQualifier) {
xml.text dateStarted
}
xml.copyrightDate(:encoding=>"w3cdtf", :point=>"end", :qualifier=>dateQualifier) {
xml.text dateEnding
}
}
elsif dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0
xml.originInfo {
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start") {
xml.text dateStarted
}
xml.copyrightDate(:encoding=>"w3cdtf", :point=>"end") {
xml.text dateEnding
}
}
elsif dateStarted != nil && dateStarted.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.originInfo {
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes", :qualifier=>dateQualifier) {
xml.text dateStarted
}
}
elsif dateStarted != nil && dateStarted.length > 0
xml.originInfo {
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes") {
xml.text dateStarted
}
}
else
#puts "error in dates?"
end
end
define_template :date_copyright_partial do |xml, dateStarted, dateEnding, dateQualifier|
if dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start", :qualifier=>dateQualifier) {
xml.text dateStarted
}
xml.copyrightDate(:encoding=>"w3cdtf", :point=>"end", :qualifier=>dateQualifier) {
xml.text dateEnding
}
elsif dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start") {
xml.text dateStarted
}
xml.copyrightDate(:encoding=>"w3cdtf", :point=>"end") {
xml.text dateEnding
}
elsif dateStarted != nil && dateStarted.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes", :qualifier=>dateQualifier) {
xml.text dateStarted
}
elsif dateStarted != nil && dateStarted.length > 0
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes") {
xml.text dateStarted
}
else
#puts "error in dates?"
end
end
def insert_date_copyright(dateStarted=nil, dateEnding=nil, dateQualifier=nil)
#begin
if self.find_by_terms(:origin_info) != nil && self.find_by_terms(:origin_info).slice(0) != nil
add_child_node(self.find_by_terms(:origin_info).slice(0), :date_copyright_partial, dateStarted, dateEnding, dateQualifier)
else
add_child_node(ng_xml.root, :date_copyright, dateStarted, dateEnding, dateQualifier)
end
end
=begin
define_template :internet_media do |xml, value|
xml.internetMediaType(value)
end
def insert_internet_media(value=nil)
if(value != nil && value.length > 1 && value != "image/jpeg")
add_child_node(self.find_by_terms(:physical_description).slice(0), :internet_media, value)
end
end
def remove_value(index)
self.find_by_terms(:internet_media).slice(index.to_i).remove
end
=end
define_template :extent do |xml, extent|
xml.extent(extent)
end
def insert_extent(extent=nil)
self.mods(0).physical_description(0).extent(0, extent) unless extent.blank?
end
def remove_extent(index)
self.find_by_terms(:extent).slice(index.to_i).remove
end
def insert_note(note=nil, noteQualifier=nil)
note_index = self.mods(0).note.count
self.mods(0).note(note_index, note) unless note.blank?
self.mods(0).note(note_index).type_at = noteQualifier unless noteQualifier.blank?
end
def remove_note(index)
self.find_by_terms(:note).slice(index.to_i).remove
end
#usage=nil, supplied=nil, subtitle=nil, language=nil, type=nil, authority=nil, authorityURI=nil, valueURI=nil
def insert_subject_title(main_title=nil, authority=nil, valueURI=nil, type=nil)
if main_title.present?
subject_index = self.mods(0).subject.count
sorted_title = Bplmodels::DatastreamInputFuncs.getProperTitle(main_title)
title = sorted_title[1]
nonSort = sorted_title[0]
self.mods(0).subject(subject_index).title_info(0).nonSort = nonSort unless nonSort.blank?
self.mods(0).subject(subject_index).title_info(0).main_title = title unless title.blank?
self.mods(0).subject(subject_index).title_info(0).type = type unless type.blank?
unless authority.blank?
self.mods(0).subject(subject_index).title_info(0).authority = authority
self.mods(0).subject(subject_index).title_info(0).authorityURI = BplEnrich::Authorities.authority_uri(authority)
end
self.mods(0).subject(subject_index).title_info(0).valueURI = valueURI unless valueURI.blank?
end
end
def insert_subject_topic(topic=nil, valueURI=nil, authority=nil)
if topic.present? && !self.mods(0).subject.topic.any?{ |top| top == topic }
subject_index = self.mods(0).subject.count
self.mods(0).subject(subject_index).topic = topic unless topic.blank?
self.mods(0).subject(subject_index).valueURI = valueURI unless valueURI.blank?
unless authority.blank?
self.mods(0).subject(subject_index).authority = authority
self.mods(0).subject(subject_index).authorityURI = BplEnrich::Authorities.authority_uri(authority)
end
end
end
def remove_subject_topic(index)
self.find_by_terms(:mods, :subject_topic).slice(index.to_i).remove
end
def insert_series(series)
if series.present?
top_level_insert_position = self.mods(0).related_item.length
0.upto self.mods(0).related_item.length-1 do |pos|
if self.mods(0).related_item(pos).type == ['series']
top_level_insert_position = pos
end
end
if self.mods(0).related_item(top_level_insert_position).blank?
self.mods(0).related_item(top_level_insert_position).type = 'series'
self.mods(0).related_item(top_level_insert_position).title_info.title = series
elsif self.mods(0).related_item(top_level_insert_position).related_item(0).blank?
self.mods(0).related_item(top_level_insert_position).related_item(0).type = 'series'
self.mods(0).related_item(top_level_insert_position).related_item(0).title_info.title = series
elsif self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).blank?
self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).type = 'series'
self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).title_info.title = series
elsif self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).related_item(0).blank?
self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).related_item(0).type = 'series'
self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).related_item(0).title_info.title = series
elsif self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).related_item(0).related_item(0).blank?
self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).related_item(0).related_item(0).type = 'series'
self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).related_item(0).related_item(0).title_info.title = series
end
end
end
def insert_subject_temporal(date)
#converted = Bplmodels::DatastreamInputFuncs.convert_to_mods_date(date)
duplicate = false
converted = BplEnrich::Dates.standardize(date)
subject_index = self.mods(0).subject.count
if converted.has_key?(:single_date)
#Check for duplicates
(0..self.mods(0).subject.length-1).each do |index|
if self.mods(0).subject(index).temporal == [converted[:single_date]]
duplicate = true
end
end
temporal_index = self.mods(0).subject(subject_index).temporal.length
self.mods(0).subject(subject_index).temporal(temporal_index, converted[:single_date]) unless converted[:single_date].blank? || duplicate
elsif converted.has_key?(:date_range)
#Check for duplicates, FIXME: Is there case this doesn't work?
(0..self.mods(0).subject.length-1).each do |index|
if self.mods(0).subject(index).temporal == [converted[:date_range][:start], converted[:date_range][:end]]
duplicate = true
end
end
temporal_index = self.mods(0).subject(subject_index).temporal.length
self.mods(0).subject(subject_index).temporal(temporal_index, converted[:date_range][:start]) unless converted[:date_range][:start].blank? || duplicate
self.mods(0).subject(subject_index).temporal(temporal_index).point = 'start' unless converted[:date_range][:start].blank? || duplicate
temporal_index = self.mods(0).subject(subject_index).temporal.length
self.mods(0).subject(subject_index).temporal(temporal_index, converted[:date_range][:end]) unless converted[:date_range][:end].blank? || duplicate
self.mods(0).subject(subject_index).temporal(temporal_index).point = 'end' unless converted[:date_range][:end].blank? || duplicate
end
end
def insert_subject_date_fix_me(date_start, date_end)
subject_index = self.mods(0).subject.count
temporal_index = self.mods(0).subject(subject_index).temporal.length
self.mods(0).subject(subject_index).temporal(temporal_index, date_start) unless date_start.blank?
self.mods(0).subject(subject_index).temporal(temporal_index).point = 'start' unless date_start.blank?
temporal_index = self.mods(0).subject(subject_index).temporal.length
self.mods(0).subject(subject_index).temporal(temporal_index, date_end) unless date_end.blank?
self.mods(0).subject(subject_index).temporal(temporal_index).point = 'end' unless date_end.blank?
end
def insert_abstract(abstract=nil)
abstract_index = self.mods(0).abstract.count
self.mods(0).abstract(abstract_index, abstract) unless abstract.blank?
end
def insert_subject_name(name=nil, type=nil, authority=nil, valueURI=nil, date=nil)
subject_index = self.mods(0).subject.count
if name.is_a?String
self.mods(0).subject(subject_index).name(0).name_part_actual(0, name)
#Date
self.mods(0).subject(subject_index).name(0).name_part_actual(1, date) unless date.blank?
self.mods(0).subject(subject_index).name(0).name_part_actual(1).type = 'date' unless date.blank?
elsif name.is_a?Array
name.each_with_index do |name_part, index|
self.mods(0).subject(subject_index).name(0).name_part_actual(index,
Bplmodels::DatastreamInputFuncs.utf8Encode(name_part))
end
end
unless authority.blank?
self.mods(0).subject(subject_index).name(0).authority = authority
self.mods(0).subject(subject_index).name(0).authority_uri = BplEnrich::Authorities.authority_uri(authority)
end
self.mods(0).subject(subject_index).name(0).value_uri = valueURI unless valueURI.blank?
self.mods(0).subject(subject_index).name(0).type = type unless type.blank?
end
define_template :subject_geographic do |xml, geographic, authority|
if authority != nil and authority.length > 0
xml.subject(:authority=>authority) {
xml.geographic(geographic)
}
else
xml.subject {
xml.geographic(geographic)
}
end
end
def insert_subject_geographic(geographic=nil, valueURI=nil, authority=nil, coordinates=nil)
if geographic.present? && !self.mods(0).subject.geographic.any? {|geo| geo==geographic}
subject_index = self.mods(0).subject.count
self.mods(0).subject(subject_index).geographic = geographic unless geographic.blank?
self.mods(0).subject(subject_index).valueURI = valueURI unless valueURI.blank?
unless authority.blank?
self.mods(0).subject(subject_index).authority = authority
self.mods(0).subject(subject_index).authorityURI = BplEnrich::Authorities.authority_uri(authority)
end
self.mods(0).subject(subject_index).cartographics(0).coordinates = coordinates unless coordinates.blank?
end
end
def remove_subject_geographic(index)
self.find_by_terms(:subject_geographic).slice(index.to_i).remove
end
def insert_subject_cartographic(coordinates=nil, scale=nil, projection=nil)
subject_index = self.mods(0).subject.count
if coordinates.split(' ').length >= 3
coordinates.scan(/([NSWE])([\d\.]+) *([NSWE])([\d\.]+) *([NSWE])([\d\.]+) *([NSWE])([\d\.]+)/).map do |dir1,deg1,dir2,deg2,dir3,deg3,dir4,deg4|
deg1 = Float(deg1)
deg2 = Float(deg2)
deg3 = Float(deg3)
deg4 = Float(deg4)
deg1 = deg1 * -1 if dir1 == 'S' || dir1 == 'W'
deg2 = deg2 * -1 if dir2 == 'S' || dir2 == 'W'
deg3 = deg3 * -1 if dir3 == 'S' || dir3 == 'W'
deg4 = deg4 * -1 if dir4 == 'S' || dir4 == 'W'
if deg1 == deg2 && deg3 == deg4
self.mods(0).subject(subject_index).cartographics(0).coordinates = deg3.to_s + ',' + deg1.to_s
else
self.mods(0).subject(subject_index).cartographics(0).coordinates = deg1.to_s + ' ' + deg4.to_s + ' ' + deg2.to_s + ' ' + deg3.to_s
end
end
else
#Remove spaces around the comma
coordinates = coordinates.gsub(/ *, */, ',')
self.mods(0).subject(subject_index).cartographics(0).coordinates = coordinates unless coordinates.blank?
end
#FIXME: self.mods(0).subject(subject_index).cartographics(0).scale = scale unless scale.blank?
#FIXME: self.mods(0).subject(subject_index).cartographics(0).projection = projection unless projection.blank?
end
def insert_subject_scale(scale=nil, projection=nil)
subject_index = self.mods(0).subject.count
self.mods(0).subject(subject_index).cartographics(0).scale = scale unless scale.blank?
self.mods(0).subject(subject_index).cartographics(0).projection = projection unless projection.blank?
end
def remove_subject_cartographic(index)
self.find_by_terms(:subject_cartographic).slice(index.to_i).remove
end
def insert_table_of_contents(text_value, url=nil)
contents_index = self.mods(0).table_of_contents.count
self.mods(0).table_of_contents(contents_index, text_value) unless text_value.blank?
self.mods(0).table_of_contents(contents_index).href = url unless url.blank?
end
def remove_table_of_contents(index)
self.find_by_terms(:table_of_contents).slice(index.to_i).remove
end
def insert_host(nonSort=nil, main_title=nil, identifier=nil, args={})
related_index = self.mods(0).related_item.count
self.mods(0).related_item(related_index).type = 'host' unless main_title.blank? && identifier.blank?
self.mods(0).related_item(related_index).title_info(0).nonSort = nonSort unless nonSort.blank?
self.mods(0).related_item(related_index).title_info(0).title = main_title unless main_title.blank?
self.mods(0).related_item(related_index).identifier = identifier unless identifier.blank?
args.each do |key, value|
self.mods(0).related_item(related_index).send(key, Bplmodels::DatastreamInputFuncs.utf8Encode(value)) unless value.blank?
end
end
def remove_host(index)
self.find_by_terms(:mods, :host).slice(index.to_i).remove
end
define_template :related_item do |xml, value, qualifier|
xml.relatedItem(:type=>qualifier) {
xml.titleInfo {
xml.title {
xml.text value
}
}
}
end
def insert_related_item(value=nil, qualifier=nil)
if value != nil && value.length > 0
add_child_node(ng_xml.root, :related_item, value, qualifier)
end
end
def remove_related_item(index)
self.find_by_terms(:related_item).slice(index.to_i).remove
end
define_template :related_item_xref do |xml, value|
xml.relatedItem(:type=>"isReferencedBy", 'xlink:href'=>value)
end
def insert_related_item_xref(value=nil)
puts 'told to insert related item xref'
if value != nil && value.length > 0
add_child_node(ng_xml.root, :related_item_xref, value)
end
end
def related_item_xref(index)
self.find_by_terms(:related_item_xref).slice(index.to_i).remove
end
def insert_related_item_url(value=nil)
related_index = self.mods(0).related_item.count
self.mods(0).related_item(related_index).location(0).url = value unless value.blank?
end
def remove_physical_location(index)
self.find_by_terms(:physical_location).slice(index.to_i).remove
end
def insert_physical_location(location=nil, sublocation=nil,shelf_locator=nil, location_type=nil)
#Create a new tag unless there is a non-url tag already...
location_index = self.mods(0).item_location.count
for index in 0..self.mods(0).item_location.count-1
if self.mods(0).item_location(index).url.blank?
location_index = index
end
end
physical_location_index = 0
self.mods(0).item_location(location_index).physical_location(physical_location_index, location) unless location.blank?
self.mods(0).item_location(location_index).physical_location(physical_location_index).type = location_type unless location.blank?
self.mods(0).item_location(location_index).holding_simple(0).copy_information(0).sub_location = sublocation unless sublocation.blank?
self.mods(0).item_location(location_index).holding_simple(0).copy_information(0).shelf_locator = shelf_locator unless shelf_locator.blank?
end
def insert_location_url(url=nil, access=nil, usage=nil, note=nil)
location_index = self.mods(0).item_location.count
for index in 0..self.mods(0).item_location.count-1
if self.mods(0).item_location(index).url.present?
location_index = index
end
end
url_index = self.mods(0).item_location(location_index).url.count
self.mods(0).item_location(location_index).url(url_index, url) unless url.blank?
self.mods(0).item_location(location_index).url(url_index).usage = usage unless usage.blank?
self.mods(0).item_location(location_index).url(url_index).access = access unless access.blank?
self.mods(0).item_location(location_index).url(url_index).note = note unless note.blank?
end
def insert_identifier(identifier=nil, type=nil, display_label=nil, invalid=nil)
identifier_index = self.mods(0).identifier.count
if identifier.present?
self.mods(0).identifier(identifier_index, identifier) unless identifier.blank?
self.mods(0).identifier(identifier_index).type_at = type unless type.blank?
self.mods(0).identifier(identifier_index).displayLabel = display_label unless display_label.blank?
self.mods(0).identifier(identifier_index).invalid = 'yes' if (invalid.present? && invalid == 'yes')
end
end
def remove_identifier(index)
self.find_by_terms(:identifier).slice(index.to_i).remove
end
def insert_classification(value=nil, edition=nil, authority=nil, display_label=nil)
classification_index = self.mods(0).classification.count
if value.present?
self.mods(0).classification(classification_index, value)
self.mods(0).classification(classification_index).edition = edition unless edition.blank?
self.mods(0).classification(classification_index).authority = authority unless authority.blank?
self.mods(0).classification(classification_index).displayLabel = display_label unless display_label.blank?
end
end
define_template :mcgreevy do |xml|
xml.recordInfo {
xml.recordContentSource {
xml.text "Boston Public Library"
}
xml.recordOrigin {
xml.text "human prepared"
}
xml.languageOfCataloging {
xml.languageTerm(:authority=>"iso639-2b", :authorityURI=>"http://id.loc.gov/vocabulary/iso639-2", :type=>'text', :valueURI=>"http://id.loc.gov/vocabulary/iso639-2/eng") {
xml.text "English"
}
}
}
end
def insert_mcgreevy
add_child_node(ng_xml.root, :mcgreevy)
end
def remove_mcgreevy(index)
self.find_by_terms(:mcgreevy).slice(index.to_i).remove
end
def insert_record_information(record_content_source, record_content_authority=nil)
self.mods(0).record_info(0).record_content_source = record_content_source unless record_content_source.blank?
self.mods(0).record_info(0).record_content_source(0).authority = record_content_authority unless record_content_authority.blank?
self.mods(0).record_info(0).record_origin = 'human prepared'
self.mods(0).record_info(0).language_of_cataloging(0).language_term = 'English'
end
def insert_new_node(term)
add_child_node(ng_xml.root, term)
end
def remove_node(term, index)
node = self.find_by_terms(term.to_sym => index.to_i).first
unless node.nil?
node.remove
self.dirty = true
end
end
end
end
fix bug where non_hier_geo TGN subjects overwrite existing TGN subjects
See https://trac.bpl.org/Repository/ticket/802
#encoding: utf-8
require 'mods'
module Bplmodels
class ModsDescMetadata < ActiveFedora::OmDatastream
#include Hydra::Datastream::CommonModsIndexMethods
# MODS XML constants.
def self.default_attributes
super.merge(:mimeType => 'application/xml')
end
MODS_NS = 'http://www.loc.gov/mods/v3'
MODS_SCHEMA = 'http://www.loc.gov/standards/mods/v3/mods-3-5.xsd'
MODS_PARAMS = {
"version" => "3.5",
"xmlns:xlink" => "http://www.w3.org/1999/xlink",
"xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
#"xmlns" => MODS_NS,
"xsi:schemaLocation" => "#{MODS_NS} #{MODS_SCHEMA}",
"xmlns:mods" => "http://www.loc.gov/mods/v3"
}
# OM terminology.
set_terminology do |t|
indexer = Solrizer::Descriptor.new(:string, :indexed, :stored, :searchable)
indexer_single = Solrizer::Descriptor.new(:text, :indexed, :stored, :searchable)
indexer_multiple = Solrizer::Descriptor.new(:text, :indexed, :stored, :searchable, :multivalued)
t.root :path => 'mods', :xmlns => MODS_NS
t.originInfo do
t.dateOther
end
#t.abstract(:path=>"abstract", :index_as=>[indexer_single])
# ABSTRACT -------------------------------------------------------------------------------
#t.abstract(:path=>"mods/oxns:abstract") {
t.abstract(:path=>"abstract") {
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.type_at :path=>{:attribute=>"type"}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
# GENRE ----------------------------------------------------------------------------------
t.genre(:path => 'genre') {
t.displayLabel :path => {:attribute=>'displayLabel'}
t.type_at :path=>{:attribute=>"type"}
t.usage :path=>{:attribute=>'usage'}
::Mods::AUTHORITY_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
# IDENTIIER ------------------------------------------------------------------------------
t.identifier(:path => 'identifier') {
#t.identifier(:path=>"identifier[not(@type=uri)]")
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.invalid :path=>{:attribute=>'invalid'}
t.type_at :path=>{:attribute=>'type'}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
# ACCESS_CONDITION -----------------------------------------------------------------------
t.accessCondition(:path => 'accessCondition') {
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.type_at :path=>{:attribute=>"type"}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
#CLASSIFICATION--------------------------------------------------------
t.classification(:path => 'classification') {
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.edition :path =>{:attribute=>"edition"}
::Mods::AUTHORITY_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
=begin
# CLASSIFICATION -------------------------------------------------------------------------
t.classification(:path => 'mods/oxns:classification') {
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.edition :path =>{:attribute=>"edition"}
::Mods::AUTHORITY_ATTRIBS.each { |attr_name|
t.send attr_name, :path => {:attribute=>"#{attr_name}"}
}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
# EXTENSION ------------------------------------------------------------------------------
t.extension(:path => 'mods/oxns:extension') {
t.displayLabel :path=>{:attribute=>'displayLabel'}
}
# LANGUAGE -------------------------------------------------------------------------------
t.language(:path => 'mods/oxns:language') {
# attributes
t.displayLabel :path=>{:attribute=>'displayLabel'}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
# child elements
t.languageTerm :path => 'languageTerm'
t.code_term :path => 'languageTerm', :attributes => { :type => "code" }
t.text_term :path => 'languageTerm', :attributes => { :type => "text" }
t.scriptTerm :path => 'scriptTerm'
}
t.languageTerm(:path => 'languageTerm') {
t.type_at :path=>{:attribute=>'type'}
::Mods::AUTHORITY_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
} # t.language
# LOCATION -------------------------------------------------------------------------------
t.location(:path => 'mods/oxns:location') {
# attributes
t.displayLabel :path=>{:attribute=>'displayLabel'}
::Mods::LANG_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
# child elements
t.physicalLocation(:path => 'physicalLocation') {
t.displayLabel :path=>{:attribute=>'displayLabel'}
::Mods::AUTHORITY_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
t.shelfLocator :path => 'shelfLocator'
t.url(:path => 'url') {
t.dateLastAccessed :path=>{:attribute=>'dateLastAccessed'}
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.note :path=>{:attribute=>'note'}
t.access :path=>{:attribute=>'access'}
t.usage :path=>{:attribute=>'usage'}
}
t.holdingSimple :path => 'holdingSimple'
t.holdingExternal :path => 'holdingExternal'
} # t.location
:path => 'languageTerm', :attributes => { :type => "text" }
# NAME ------------------------------------------------------------------------------------
t.plain_name(:path => 'mods/oxns:name') {
::Mods::Name::ATTRIBUTES.each { |attr_name|
if attr_name != 'type'
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
else
t.type_at :path =>{:attribute=>"#{attr_name}"}
end
}
# elements
t.namePart(:path => 'namePart') {
t.type_at :path =>{:attribute=>"type"}
}
t.family_name :path => 'namePart', :attributes => {:type=>"family"}
t.given_name :path => 'namePart', :attributes => {:type=>"given"}
t.termsOfAddress :path => 'namePart', :attributes => {:type=>"termsOfAddress"}
t.date :path => 'namePart', :attributes => {:type=>"date"}
t.displayForm :path => 'displayForm'
t.affiliation :path => 'affiliation'
t.description_el :path => 'description' # description is used by Nokogiri
t.role(:path => 'role') {
t.roleTerm(:path => 'roleTerm') {
t.type_at :path =>{:attribute=> "type"}
::Mods::AUTHORITY_ATTRIBS.each { |attr_name|
t.send attr_name, :path =>{:attribute=>"#{attr_name}"}
}
}
# FIXME - not sure how to do this stuff
# role convenience method
t.authority :path => '.', :accessor => lambda { |role_node|
a = nil
role_node.roleTerm.each { |role_t|
# role_t.authority will be [] if it is missing from an earlier roleTerm
if role_t.authority && (!a || a.size == 0)
a = role_t.authority
end
}
a
}
# role convenience method
r.code :path => '.', :accessor => lambda { |role_node|
c = nil
role_node.roleTerm.each { |role_t|
if role_t.type_at == 'code'
c ||= role_t.text
end
}
c
}
# role convenience method
r.value :path => '.', :accessor => lambda { |role_node|
val = nil
role_node.roleTerm.each { |role_t|
if role_t.type_at == 'text'
val ||= role_t.text
end
}
# FIXME: this is broken if there are multiple role codes and some of them are not marcrelator
if !val && role_node.code && role_node.authority.first =~ /marcrelator/
val = MARC_RELATOR[role_node.code.first]
end
val
}
} # role node
#END FIXME
# name convenience method
# uses the displayForm of a name if present
# if no displayForm, try to make a string from family, given and terms of address
# otherwise, return all non-date nameParts concatenated together
n.display_value :path => '.', :single => true, :accessor => lambda {|name_node|
dv = ''
if name_node.displayForm && name_node.displayForm.text.size > 0
dv = name_node.displayForm.text
end
if dv.blank?
if name_node.type_at == 'personal'
if name_node.family_name.size > 0
dv = name_node.given_name.size > 0 ? "#{name_node.family_name.text}, #{name_node.given_name.text}" : name_node.family_name.text
elsif name_node.given_name.size > 0
dv = name_node.given_name.text
end
if !dv.blank?
first = true
name_node.namePart.each { |np|
if np.type_at == 'termsOfAddress' && !np.text.blank?
if first
dv = dv + " " + np.text
first = false
else
dv = dv + ", " + np.text
end
end
}
else # no family or given name
dv = name_node.namePart.select {|np| np.type_at != 'date' && !np.text.blank?}.join(" ")
end
else # not a personal name
dv = name_node.namePart.select {|np| np.type_at != 'date' && !np.text.blank?}.join(" ")
end
end
dv.strip.blank? ? nil : dv.strip
}
# name convenience method
n.display_value_w_date :path => '.', :single => true, :accessor => lambda {|name_node|
dv = ''
dv = dv + name_node.display_value if name_node.display_value
name_node.namePart.each { |np|
if np.type_at == 'date' && !np.text.blank? && !dv.end_with?(np.text)
dv = dv + ", #{np.text}"
end
}
if dv.start_with?(', ')
dv.sub(', ', '')
end
dv.strip.blank? ? nil : dv.strip
}
} # t._plain_name
t.personal_name :path => '/m:mods/m:name[@type="personal"]'
t._personal_name :path => '//m:name[@type="personal"]'
t.corporate_name :path => '/m:mods/m:name[@type="corporate"]'
t._corporate_name :path => '//m:name[@type="corporate"]'
t.conference_name :path => '/m:mods/m:name[@type="conference"]'
t._conference_name :path => '//m:name[@type="conference"]'
=end
t.title_info(:path=>'titleInfo') {
t.usage(:path=>{:attribute=>"usage"})
t.display_label(:path=>{:attribute=>"displayLabel"})
t.nonSort(:path=>"nonSort", :index_as=>[:searchable, :displayable])
t.main_title(:path=>"title", :label=>"title")
t.language(:index_as=>[:facetable],:path=>{:attribute=>"lang"})
t.supplied(:path=>{:attribute=>"supplied"})
t.type(:path=>{:attribute=>"type"})
t.authority(:path=>{:attribute=>"authority"})
t.authorityURI(:path=>{:attribute=>"authorityURI"})
t.valueURI(:path=>{:attribute=>"valueURI"})
t.subtitle(:path=>"subTitle", :label=>"subtitle")
t.part_number(:path=>"partNumber", :label=>"partNumber")
t.part_name(:path=>"partName", :label=>"partName")
}
t.title(:proxy=>[:title_info, :main_title])
t.name(:path=>'name') {
# this is a namepart
t.usage(:path=>{:attribute=>"usage"})
t.namePart(:type=>:string, :label=>"generic name")
t.type(:path=>{:attribute=>"type"})
t.authority(:path=>{:attribute=>"authority"})
t.authorityURI(:path=>{:attribute=>"authorityURI"})
t.valueURI(:path=>{:attribute=>"valueURI"})
t.role(:ref=>[:role])
t.date(:path=>"namePart", :attributes=>{:type=>"date"})
}
t.type_of_resource(:path=>"typeOfResource") {
t.manuscript(:path=>{:attribute=>"manuscript"})
}
t.genre_basic(:path=>"genre", :attributes=>{:displayLabel => "general"})
t.genre_specific(:path=>"genre", :attributes=>{:displayLabel => "specific"})
t.origin_info(:path=>"originInfo") {
t.publisher(:path=>"publisher")
t.place(:path=>"place") {
t.place_term(:path=>"placeTerm", :attributes=>{:type=>'text'})
}
t.issuance(:path=>"issuance")
t.edition(:path=>"edition")
t.event_type(:path=>{:attribute=>"eventType"})
t.frequency(:path=>"frequency") {
t.authority(:path=>{:attribute=>"authority"})
}
}
t.target_audience(:path=>"targetAudience") {
t.authority(:path=>{:attribute=>"authority"})
t.display_label(:path=>{:attribute=>"displayLabel"})
}
t.item_location(:path=>"location") {
t.physical_location(:path=>"physicalLocation") {
t.type(:path=>{:attribute=>"type"})
}
t.holding_simple(:path=>"holdingSimple") {
t.copy_information(:path=>"copyInformation") {
t.sub_location(:path=>"subLocation")
t.shelf_locator(:path=>"shelfLocator")
}
}
t.url(:path=>"url") {
t.usage(:path=>{:attribute=>"usage"})
t.access(:path=>{:attribute=>"access"})
t.note(:path=>{:attribute=>"note"})
}
}
t.identifier_accession :path => 'identifier', :attributes => { :type => "accession number" }
t.identifier_barcode :path => 'identifier', :attributes => { :type => "barcode" }
t.identifier_bpldc :path => 'identifier', :attributes => { :type => "bpldc number" }
t.identifier_other :path => 'identifier', :attributes => { :type => "other" }
t.isbn :path => 'identifier', :attributes => { :type => "isbn" }
t.local_other :path => 'identifier', :attributes => { :type => "local-other" }
t.lccn :path => 'identifier', :attributes => { :type => "lccn" }
t.local_accession :path => 'identifier', :attributes => { :type => "local-accession" }
t.local_call :path => 'identifier', :attributes => { :type => "local-call" }
t.local_barcode :path => 'identifier', :attributes => { :type => "local-barcode" }
t.ia_id :path => 'identifier', :attributes => { :type => "internet-archive" }
t.identifier_uri :path => 'identifier', :attributes => { :type => "uri" }
t.physical_description(:path=>"physicalDescription") {
t.internet_media_type(:path=>"internetMediaType")
t.digital_origin(:path=>"digitalOrigin")
t.extent(:path=>"extent")
t.note(:path=>'note')
}
t.note(:path=>"note") {
t.type_at(:path=>{:attribute=>"type"})
}
t.personal_name(:path=>'mods/oxns:subject/oxns:name', :attributes=>{:type => "personal"}) {
t.name_part(:path=>"namePart[not(@type)]")
t.date(:path=>"namePart", :attributes=>{:type=>"date"})
}
t.corporate_name(:path=>'mods/oxns:subject/oxns:name', :attributes=>{:type => "corporate"}) {
t.name_part(:path=>"namePart[not(@type)]")
t.date(:path=>"namePart", :attributes=>{:type=>"date"})
}
t.subject do
t.topic
t.geographic(:path=>'geographic') {
t.display_label(:path=>{:attribute=>"displayLabel"})
}
t.authority(:path=>{:attribute=>"authority"})
t.valueURI(:path=>{:attribute=>"valueURI"})
t.authorityURI(:path=>{:attribute=>"authorityURI"})
t.personal_name(:path=>'name', :attributes=>{:type => "personal"}) {
t.name_part(:path=>"namePart[not(@type)]")
t.date(:path=>"namePart", :attributes=>{:type=>"date"})
}
t.corporate_name(:path=>'name', :attributes=>{:type => "corporate"}) {
t.name_part(:path=>"namePart[not(@type)]")
t.date(:path=>"namePart", :attributes=>{:type=>"date"})
}
t.conference_name(:path=>'name', :attributes=>{:type => "conference"}) {
t.name_part(:path=>"namePart[not(@type)]")
}
t.name(:path=>'name') {
t.name_part(:path=>"namePart[not(@type)]")
t.date(:path=>"namePart", :attributes=>{:type=>"date"})
t.name_part_actual(:path=>"namePart") {
t.type(:path=>{:attribute=>"type"})
}
t.type(:path=>{:attribute=>"type"})
t.authority(:path=>{:attribute=>"authority"})
t.authority_uri(:path=>{:attribute=>"authorityURI"})
t.value_uri(:path=>{:attribute=>"valueURI"})
}
t.hierarchical_geographic(:path=>"hierarchicalGeographic") {
t.continent
t.country
t.region
t.province
t.state
t.territory
t.county
t.island
t.city
t.city_section(:path=>"citySection")
t.area
t.extarea(:path=>"extraterrestrialArea")
}
t.cartographics {
t.coordinates
t.scale
t.projection
}
t.temporal(:path=>'temporal', :attributes=>{:encoding => "w3cdtf"}) {
t.point(:path=>{:attribute=>"point"})
}
t.title_info(:ref=>[:title_info]) {
t.title
}
t.genre {
t.authority(:path=>{:attribute=>"authority"})
t.authority_uri(:path=>{:attribute=>"authorityURI"})
t.value_uri(:path=>{:attribute=>"valueURI"})
}
end
t.related_item(:path=>"relatedItem") {
t.type(:path=>{:attribute=>"type"})
t.href(:path=>{:attribute=>'xlink:href'})
t.title_info(:path=>"titleInfo") {
t.title
t.nonSort(:path=>"nonSort")
}
t.identifier
t.location(:path=>'location') {
t.url(:path=>'url')
}
t.related_item(:ref=>[:related_series_item]) {
t.related_item(:ref=>[:related_series_item]) {
t.related_item(:ref=>[:related_series_item]) {
t.related_item(:ref=>[:related_series_item])
}
}
}
t.subseries(:path=>'relatedItem', :attributes=>{:type => "series"}) {
t.title_info(:path=>"titleInfo") {
t.title
t.nonSort(:path=>"nonSort")
}
t.subsubseries(:path=>'relatedItem', :attributes=>{:type => "series"}) {
t.title_info(:path=>"titleInfo") {
t.title
t.nonSort(:path=>"nonSort")
}
}
}
}
t.related_series_item(:path=>'relatedItem') {
t.type(:path=>{:attribute=>"type"})
t.title_info(:path=>"titleInfo") {
t.title
t.nonSort(:path=>"nonSort")
}
}
#t.subseries(:path=>'mods/oxns:relatedItem/oxns:relatedItem', :attributes=>{:type => "series"}) {
# t.title_info(:path=>"titleInfo") {
# t.title
# t.nonSort(:path=>"nonSort")
# }
#}
t.use_and_reproduction(:path=>"accessCondition", :attributes=>{:type=>"use and reproduction"}) {
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.type(:path=>{:attribute=>"type"})
}
t.restriction_on_access(:path=>"accessCondition", :attributes=>{:type=>"restriction on access"}) {
t.displayLabel :path=>{:attribute=>'displayLabel'}
t.type(:path=>{:attribute=>"type"})
}
t.date(:path=>"originInfo") {
t.date_other(:path=>"dateOther") {
t.encoding(:path=>{:attribute=>"encoding"})
t.key_date(:path=>{:attribute=>"keyDate"})
t.type(:path=>{:attribute=>"type"})
t.qualifier(:path=>{:attribute=>"qualifier"})
}
t.dates_created(:path=>"dateCreated") {
t.encoding(:path=>{:attribute=>"encoding"})
t.key_date(:path=>{:attribute=>"keyDate"})
t.point(:path=>{:attribute=>"point"})
t.qualifier(:path=>{:attribute=>"qualifier"})
}
t.dates_issued(:path=>"dateIssued") {
t.encoding(:path=>{:attribute=>"encoding"})
t.key_date(:path=>{:attribute=>"keyDate"})
t.point(:path=>{:attribute=>"point"})
t.qualifier(:path=>{:attribute=>"qualifier"})
}
t.dates_copyright(:path=>"copyrightDate") {
t.encoding(:path=>{:attribute=>"encoding"})
t.key_date(:path=>{:attribute=>"keyDate"})
t.point(:path=>{:attribute=>"point"})
t.qualifier(:path=>{:attribute=>"qualifier"})
}
}
t.role {
t.text(:path=>'roleTerm',:attributes=>{:type=>'text', :authority=>'marcrelator', :authorityURI=>'http://id.loc.gov/vocabulary/relators'}) {
t.valueURI(:path=>{:attribute=>'valueURI'})
}
t.code(:path=>'roleTerm',:attributes=>{:type=>'code'})
}
t.language(:path=>"language") {
t.language_term(:path=>"languageTerm") {
t.lang_val_uri(:path=>{:attribute=>"valueURI"})
}
}
t.record_info(:path=>'recordInfo') {
t.description_standard(:path=>'descriptionStandard', :attributes=>{:authority=>"marcdescription"})
t.record_content_source(:path=>'recordContentSource') {
t.authority(:path=>{:attribute=>"authority"})
}
t.record_origin(:path=>'recordOrigin')
t.language_of_cataloging(:path=>'languageOfCataloging') {
t.language_term(:path=>'languageTerm', :attributes => { :authority => 'iso639-2b',:authorityURI=> 'http://id.loc.gov/vocabulary/iso639-2', :type=>'text', :valueURI=>'http://id.loc.gov/vocabulary/iso639-2/eng' })
}
}
t.table_of_contents(:path=>'tableOfContents') {
t.href(:path=>{:attribute=>'xlink:href'})
}
end
# Blocks to pass into Nokogiri::XML::Builder.new()
=begin
define_template :name do |xml|
xml.name {
xml.namePart
xml.role {
xml.roleTerm(:authority => "marcrelator", :type => "text")
}
}
end
define_template :relatedItem do |xml|
xml.relatedItem {
xml.titleInfo {
xml.title
}
xml.location {
xml.url
}
}
end
define_template :related_citation do |xml|
xml.note(:type => "citation/reference")
end
=end
def self.xml_template
builder = Nokogiri::XML::Builder.new(:encoding => "UTF-8") do |xml|
xml.mods(MODS_PARAMS) {
xml.parent.namespace = xml.parent.namespace_definitions.find{|ns|ns.prefix=="mods"}
}
end
return builder.doc
end
def to_xml(xml = nil)
xml = self.ng_xml if xml.nil?
ng_xml = self.ng_xml
if ng_xml.respond_to?(:root) && ng_xml.root.nil? && self.class.respond_to?(:root_property_ref) && !self.class.root_property_ref.nil?
ng_xml = self.class.generate(self.class.root_property_ref, "")
if xml.root.nil?
xml = ng_xml
end
end
unless xml == ng_xml || ng_xml.root.nil?
if xml.kind_of?(Nokogiri::XML::Document)
xml.root.add_child(ng_xml.root)
elsif xml.kind_of?(Nokogiri::XML::Node)
xml.add_child(ng_xml.root)
else
raise "You can only pass instances of Nokogiri::XML::Node into this method. You passed in #{xml}"
end
end
return xml.to_xml(:encoding=>'UTF-8').strip
end
#Required for Active Fedora 9
def prefix(path=nil)
return ''
end
=begin
def identifier=(values)
ng_xml.search(identifier.xpath, {oxns:"http://www.loc.gov/mods/v3"}).each do |n|
n.remove
end
super(values)
end
=end
#def insert_physical_description(media_type=nil, digital_origin=nil, media_type2=nil, note=nil)
def insert_digital_origin(digital_origin=nil)
physical_description_index = 0
origin_index = self.mods(0).physical_description(physical_description_index).digital_origin.count
self.mods(0).physical_description(physical_description_index).digital_origin(origin_index, digital_origin) unless digital_origin.blank?
end
def insert_physical_note(note=nil)
physical_description_index = 0
note_index = self.mods(0).physical_description(physical_description_index).note.count
self.mods(0).physical_description(physical_description_index).note(note_index, note) unless note.blank?
end
def remove_physical_description(index)
self.find_by_terms(:physical_description).slice(index.to_i).remove
end
def insert_media_type(media_type=nil)
physical_description_index = 0
media_type_index = self.mods(0).physical_description(physical_description_index).internet_media_type.count
self.mods(0).physical_description(physical_description_index).internet_media_type(media_type_index, media_type) unless media_type.blank? || self.mods(0).physical_description(physical_description_index).internet_media_type.include?(media_type)
end
define_template :language do |xml, value, code|
xml.language {
xml.languageTerm(:type=>"text", :authority=>"iso639-2b", :authorityURI=>"http://id.loc.gov/vocabulary/iso639-2", :valueURI=>code) {
xml.text value
}
}
end
def insert_language(value=nil, code='eng')
code = "http://id.loc.gov/vocabulary/iso639-2/#{code}" unless code.include?('http')
add_child_node(ng_xml.root, :language, value, code)
end
def remove_language(index)
self.find_by_terms(:language).slice(index.to_i).remove
end
def insert_rights(value=nil, type=nil, displayLabel=nil)
access_index = self.mods(0).accessCondition.count
self.mods(0).accessCondition(access_index, value) unless value.blank?
self.mods(0).accessCondition(access_index).type_at = type unless type.blank?
self.mods(0).accessCondition(access_index).displayLabel = displayLabel unless displayLabel.blank?
end
def insert_target_audience(value=nil, authority=nil, display_label=nil)
audience_index = self.mods(0).target_audience.count
self.mods(0).target_audience(audience_index, value) unless value.blank?
self.mods(0).target_audience(audience_index).authority = authority unless authority.blank?
self.mods(0).target_audience(audience_index).display_label = display_label unless display_label.blank?
end
def insert_type_of_resource(value=nil, manuscript=nil)
resource_index = self.mods(0).type_of_resource.count
if !self.mods(0).type_of_resource.include?(value)
self.mods(0).type_of_resource(resource_index, value) unless value.blank?
self.mods(0).type_of_resource(resource_index).manuscript = 'yes' unless manuscript.blank?
end
end
def remove_type_of_resource(index)
self.find_by_terms(:type_of_resource).slice(index.to_i).remove
end
def insert_publisher(publisher=nil, place=nil)
origin_index = 0
publisher_index = self.mods(0).origin_info(origin_index).publisher.count
place_index = self.mods(0).origin_info(origin_index).place.count
self.mods(0).origin_info(origin_index).publisher(publisher_index, publisher) unless publisher.blank?
self.mods(0).origin_info(origin_index).place(place_index).place_term = place unless place.blank?
end
def remove_publisher(index)
self.find_by_terms(:mods, :publisher).slice(index.to_i).remove
end
def insert_issuance(issuance=nil)
origin_index = 0
issuance_index = self.mods(0).origin_info(origin_index).issuance.count
self.mods(0).origin_info(origin_index).issuance(issuance_index, issuance) unless issuance.blank?
end
def insert_edition(edition=nil)
origin_index = 0
edition_index = self.mods(0).origin_info(origin_index).edition.count
self.mods(0).origin_info(origin_index).edition(edition_index, edition) unless edition.blank?
end
def insert_genre(value=nil, value_uri=nil, authority=nil, display_label='specific')
#Prevent duplicates
if value.present? && !self.mods(0).genre.any?{ |genre| genre == value}
genre_index = self.mods(0).genre.count
self.mods(0).genre(genre_index, value) unless value.blank?
unless authority.blank?
self.mods(0).genre(genre_index).authority = authority
self.mods(0).genre(genre_index).authorityURI = BplEnrich::Authorities.authority_uri(authority)
end
if value_uri.present? && value_uri.match(/^http/).blank?
value_uri = "#{BplEnrich::Authorities.authority_uri(authority)}/#{value_uri}"
end
self.mods(0).genre(genre_index).valueURI = value_uri unless value_uri.blank?
self.mods(0).genre(genre_index).displayLabel = display_label unless display_label.blank?
end
end
def remove_genre(index)
self.find_by_terms(:genre).slice(index.to_i).remove
end
define_template :access_links do |xml, preview, primary|
xml.location {
if preview != nil && preview.length > 0
xml.url(:access=>"preview") {
xml.text preview
}
end
xml.url(:usage=>"primary", :access=>"object in context") {
xml.text primary
}
}
end
def insert_access_links(preview=nil, primary=nil)
add_child_node(ng_xml.root, :access_links, preview, primary)
end
def remove_access_links(index)
self.find_by_terms(:access_links).slice(index.to_i).remove
end
def insert_geonames(geonames_id)
puts 'Geonames ID is: ' + geonames_id
#Duplicate Geonames value?
if self.subject.valueURI.include?(geonames_id)
return false
end
api_result = Geomash::Geonames.get_geonames_data(geonames_id)
puts 'API Result is: ' + api_result.to_s
subject_index = self.mods(0).subject.count
self.mods(0).subject(subject_index).authority = "geonames"
self.mods(0).subject(subject_index).valueURI = "http://sws.geonames.org/#{geonames_id}"
self.mods(0).subject(subject_index).authorityURI = 'http://sws.geonames.org'
self.mods(0).subject(subject_index).geographic = api_result[:hier_geo].values[-1]
#Insert Coordinates
if api_result[:coords] != nil
self.mods(0).subject(subject_index).cartographics.coordinates = api_result[:coords][:latitude] + "," + api_result[:coords][:longitude]
end
end
def insert_origin_event(event_type)
#Currently only supporting one elements...
origin_index = 0
self.mods(0).origin_info(origin_index).event_type = event_type unless event_type.blank?
end
def insert_origin_frequency(frequency, authority)
#Currently only supporting one elements...
origin_index = 0
self.mods(0).origin_info(origin_index).frequency = frequency unless frequency.blank?
self.mods(0).origin_info(origin_index).frequency.authority = authority unless authority.blank?
end
def insert_tgn(tgn_id)
puts 'TGN ID is: ' + tgn_id
# check for duplicate TGN value
return false if self.subject.valueURI.include?(tgn_id)
api_result = Geomash::TGN.get_tgn_data(tgn_id)
puts 'API Result is: ' + api_result.to_s
#FIXME: Only works for hier_geo places....
if api_result[:hier_geo].present? && self.subject.hierarchical_geographic.present?
self.mods(0).subject.each_with_index do |_ignored, subject_index|
if self.mods(0).subject(subject_index).authority == ['tgn']
if api_result[:hier_geo][:city_section].present?
# Get rid of less specific matches... city_section level info should trump city
if self.mods(0).subject(subject_index).hierarchical_geographic(0).city_section.blank? &&
self.mods(0).subject(subject_index).hierarchical_geographic(0).city == [api_result[:hier_geo][:city]]
# Check to not remove non-hier geo cases
if self.mods(0).subject(subject_index).geographic(0).blank?
self.mods(0).subject(subject_index, nil)
end
end
elsif api_result[:hier_geo][:city].present?
# Get rid of less specific matches... city level info should trump state
if self.mods(0).subject(subject_index).hierarchical_geographic(0).city.blank? &&
self.mods(0).subject(subject_index).hierarchical_geographic(0).state == [api_result[:hier_geo][:state]]
# Check to not remove non-hier geo cases... as actually more specific than just a state
if self.mods(0).subject(subject_index).geographic(0).blank?
self.mods(0).subject(subject_index, nil)
end
# Exit if same city match
elsif self.mods(0).subject(subject_index).hierarchical_geographic(0).city == [api_result[:hier_geo][:city]]
# Case of more specific in non_hier_geo...
if self.mods(0).subject(subject_index).geographic(0).blank? && api_result[:non_hier_geo].present?
self.mods(0).subject(subject_index, nil)
else
return false
end
end
elsif api_result[:hier_geo][:city].blank?
# Exit check if trying to insert same state twice with no city
if api_result[:hier_geo][:state].present?
if self.mods(0).subject(subject_index).hierarchical_geographic(0).state == [api_result[:hier_geo][:state]]
# Case of more specific in non_hier_geo or area...
if api_result[:non_hier_geo].present? || api_result[:hier_geo][:area].present?
if self.mods(0).subject(subject_index).geographic(0).blank? &&
self.mods(0).subject(subject_index).hierarchical_geographic(0).area.blank?
self.mods(0).subject(subject_index, nil)
end
else
return false
end
end
# Exit check if trying to insert the same area...
elsif api_result[:hier_geo][:area].present?
if self.mods(0).subject(subject_index).hierarchical_geographic(0).area == [api_result[:hier_geo][:area]]
# Case of more specific in non_hier_geo...
if api_result[:non_hier_geo].present?
if self.mods(0).subject(subject_index).geographic(0).blank?
self.mods(0).subject(subject_index, nil)
end
else
return false
end
end
# Finally exit if inserting the same country...
elsif api_result[:hier_geo][:country].present?
if self.mods(0).subject(subject_index).hierarchical_geographic(0).country == [api_result[:hier_geo][:country]]
# Case of more specific in non_hier_geo, but don't overwrite existing city/state
if api_result[:non_hier_geo].present?
if self.mods(0).subject(subject_index).geographic(0).blank?
unless self.mods(0).subject(subject_index).hierarchical_geographic(0).city.present? ||
self.mods(0).subject(subject_index).hierarchical_geographic(0).state.present?
self.mods(0).subject(subject_index, nil)
end
end
else
return false
end
end
end
end
end
end
end
if api_result[:non_hier_geo].present?
#Exit if same place match currently....
self.mods(0).subject.each_with_index do |_ignored, subject_index|
if self.mods(0).subject(subject_index).authority == ['tgn']
if self.mods(0).subject(subject_index).geographic == [api_result[:non_hier_geo][:value]]
return false
end
end
end
end
subject_index = self.mods(0).subject.count
self.mods(0).subject(subject_index).authority = "tgn"
self.mods(0).subject(subject_index).valueURI = "http://vocab.getty.edu/tgn/#{tgn_id}"
self.mods(0).subject(subject_index).authorityURI = 'http://vocab.getty.edu/tgn/'
#Insert geographic text
if api_result[:non_hier_geo].present?
self.mods(0).subject(subject_index).geographic = api_result[:non_hier_geo][:value]
self.mods(0).subject(subject_index).geographic.display_label = api_result[:non_hier_geo][:qualifier] unless api_result[:non_hier_geo][:qualifier].blank?
end
#Insert hierarchicalGeographic text
if api_result[:hier_geo] != nil
api_result[:hier_geo].keys.reverse.each do |key|
key_with_equal = key.to_s + "="
self.mods(0).subject(subject_index).hierarchical_geographic.send(key_with_equal.to_sym, Bplmodels::DatastreamInputFuncs.utf8Encode(api_result[:hier_geo][key]))
end
end
#Insert Coordinates
if api_result[:coords] != nil
self.mods(0).subject(subject_index).cartographics.coordinates = api_result[:coords][:latitude] + "," + api_result[:coords][:longitude]
end
end
#usage=nil, supplied=nil, subtitle=nil, language=nil, type=nil, authority=nil, authorityURI=nil, valueURI=nil
def insert_title(nonSort=nil, main_title=nil, usage=nil, supplied=nil, type=nil, subtitle=nil, language=nil,
display_label=nil, part_number=nil, part_name=nil, authority=nil, value_uri=nil, args={})
title_index = self.mods(0).title_info.count
self.mods(0).title_info(title_index).nonSort = nonSort unless nonSort.blank?
self.mods(0).title_info(title_index).main_title = main_title unless main_title.blank?
self.mods(0).title_info(title_index).usage = usage unless usage.blank?
self.mods(0).title_info(title_index).supplied = 'yes' unless supplied.blank? || supplied == 'no'
self.mods(0).title_info(title_index).type = type unless type.blank?
#Need to update previous titles to be translated now as well....
if type == 'translated' && usage == 'primary'
0.upto title_index-1 do |pos|
if self.mods(0).title_info(pos).usage[0] == 'primary'
self.mods(0).title_info(pos).type = type
end
end
#Currently only main title has a blank type.... may want to pass this instead eventually if that changes.
elsif type.blank?
self.mods(0).title_info(title_index).display_label = 'primary_display'
end
self.mods(0).title_info(title_index).subtitle = subtitle unless subtitle.blank?
self.mods(0).title_info(title_index).language = language unless language.blank?
self.mods(0).title_info(title_index).display_label = display_label unless display_label.blank?
self.mods(0).title_info(title_index).part_number = part_number unless part_number.blank?
self.mods(0).title_info(title_index).part_name = part_name unless part_name.blank?
unless authority.blank?
self.mods(0).title_info(title_index).authority = authority
self.mods(0).title_info(title_index).authorityURI = BplEnrich::Authorities.authority_uri(authority)
end
self.mods(0).title_info(title_index).valueURI = value_uri unless value_uri.blank?
if args.present?
raise 'broken args in Active Fedora 7'
end
args.each do |key, value|
self.mods(0).title_info(title_index).send(key, Bplmodels::DatastreamInputFuncs.utf8Encode(value)) unless value.blank?
end
end
def remove_title(index)
self.find_by_terms(:mods, :title_info).slice(index.to_i).remove
end
#image.descMetadata.find_by_terms(:name).slice(0).set_attribute("new", "true")
def insert_name(name=nil, type=nil, authority=nil, value_uri=nil, role=nil, role_uri=nil, date=nil, args={})
name_index = self.mods(0).name.count
self.mods(0).name(name_index).type = type unless type.blank?
unless authority.blank?
self.mods(0).name(name_index).authority = authority
self.mods(0).name(name_index).authorityURI = BplEnrich::Authorities.authority_uri(authority)
end
self.mods(0).name(name_index).valueURI = value_uri unless value_uri.blank?
if role.present?
role_split = role.split('{|}') #new split var - see Arnold ticket
role_uri = '{|}{|}{|}{|}{|}' if role_uri.nil? #Very hackish...
role_uri_split = role_uri.split('{|}') #new split var - see Arnold ticket
role_split.each_with_index do |single_role, role_index|
self.mods(0).name(name_index).role(role_index).text = single_role unless single_role.blank?
self.mods(0).name(name_index).role(role_index).text.valueURI = role_uri_split[role_index] unless role_uri_split[role_index].blank?
end
end
if type == 'corporate'
name_array = Bplmodels::DatastreamInputFuncs.corpNamePartSplitter(name)
name_array.each_with_index do |name_value, array_pos|
self.mods(0).name(name_index).namePart(array_pos, name_value)
end
elsif type=='personal' && date.blank?
name_hash = Bplmodels::DatastreamInputFuncs.persNamePartSplitter(name)
self.mods(0).name(name_index).namePart = name_hash[:namePart]
self.mods(0).name(name_index).date = name_hash[:datePart] unless name_hash[:datePart].blank?
elsif date.present?
self.mods(0).name(name_index).namePart = name
self.mods(0).name(name_index).date = date
else
self.mods(0).name(name_index).namePart = name
end
args.each do |key, value|
self.mods(0).name(name_index).send(key, Bplmodels::DatastreamInputFuncs.utf8Encode(value)) unless value.blank?
end
end
def remove_name(index)
self.find_by_terms(:mods, :name).slice(index.to_i).remove
end
#test = ["test1", "test2"]
#test.each do |k|
#define_method "current_#{k.underscore}" do
#puts k.underscore
#end
#end
def insert_oai_date(date)
#converted = Bplmodels::DatastreamInputFuncs.convert_to_mods_date(date)
converted = BplEnrich::Dates.standardize(date)
#date_index = self.date.length
date_index = 0
dup_found = false
#Prevent duplicate entries... Using a flag as keep the potential note?
(self.mods(0).date(date_index).dates_created.length-1).times do |index|
if converted.has_key?(:single_date)
if self.mods(0).date(date_index).dates_created(index).point.blank? && self.mods(0).date(date_index).dates_created(index).first == converted[:single_date]
dup_found = true
end
elsif converted.has_key?(:date_range)
if self.mods(0).date(date_index).dates_created(index).point == 'start' && self.mods(0).date(date_index).dates_created(index).first == converted[:date_range][:start]
if self.mods(0).date(date_index).dates_created(index+1).point == 'end' && self.mods(0).date(date_index).dates_created(index+1).first == converted[:date_range][:end]
dup_found = true
end
end
end
end
if !dup_found
if converted.has_key?(:single_date) && !self.date.dates_created.include?(converted[:single_date])
date_created_index = self.date(date_index).dates_created.length
self.date(date_index).dates_created(date_created_index, converted[:single_date])
self.date(date_index).dates_created(date_created_index).encoding = 'w3cdtf'
if date_created_index == 0
self.date(date_index).dates_created(date_created_index).key_date = 'yes'
end
if converted.has_key?(:date_qualifier)
self.date(date_index).dates_created(date_created_index).qualifier = converted[:date_qualifier]
end
elsif converted.has_key?(:date_range)
date_created_index = self.date(date_index).dates_created.length
self.date(date_index).dates_created(date_created_index, converted[:date_range][:start])
self.date(date_index).dates_created(date_created_index).encoding = 'w3cdtf'
if date_created_index == 0
self.date(date_index).dates_created(date_created_index).key_date = 'yes'
end
self.date(date_index).dates_created(date_created_index).point = 'start'
self.date(date_index).dates_created(date_created_index).qualifier = converted[:date_qualifier]
date_created_index = self.date(date_index).dates_created.length
self.date(date_index).dates_created(date_created_index, converted[:date_range][:end])
self.date(date_index).dates_created(date_created_index).encoding = 'w3cdtf'
self.date(date_index).dates_created(date_created_index).point = 'end'
self.date(date_index).dates_created(date_created_index).qualifier = converted[:date_qualifier]
end
end
self.insert_note(converted[:date_note],"date") unless !converted.has_key?(:date_note)
end
def insert_oai_date_copyright(date)
#converted = Bplmodels::DatastreamInputFuncs.convert_to_mods_date(date)
converted = BplEnrich::Dates.standardize(date)
#date_index = self.date.length
date_index = 0
dup_found = false
#Prevent duplicate entries... Using a flag as keep the potential note?
(self.mods(0).date(date_index).dates_copyright.length-1).times do |index|
if converted.has_key?(:single_date)
if self.mods(0).date(date_index).dates_copyright(index).point.blank? && self.mods(0).date(date_index).dates_copyright(index).first == converted[:single_date]
dup_found = true
end
elsif converted.has_key?(:date_range)
if self.mods(0).date(date_index).dates_copyright(index).point == 'start' && self.mods(0).date(date_index).dates_copyright(index).first == converted[:date_range][:start]
if self.mods(0).date(date_index).dates_copyright(index+1).point == 'end' && self.mods(0).date(date_index).dates_copyright(index+1).first == converted[:date_range][:end]
dup_found = true
end
end
end
end
if !dup_found
if converted.has_key?(:single_date) && !self.date.dates_copyright.include?(converted[:single_date])
date_created_index = self.date(date_index).dates_copyright.length
self.date(date_index).dates_copyright(date_created_index, converted[:single_date])
self.date(date_index).dates_copyright(date_created_index).encoding = 'w3cdtf'
if date_created_index == 0
self.date(date_index).dates_copyright(date_created_index).key_date = 'yes'
end
if converted.has_key?(:date_qualifier)
self.date(date_index).dates_copyright(date_created_index).qualifier = converted[:date_qualifier]
end
elsif converted.has_key?(:date_range)
date_created_index = self.date(date_index).dates_copyright.length
self.date(date_index).dates_copyright(date_created_index, converted[:date_range][:start])
self.date(date_index).dates_copyright(date_created_index).encoding = 'w3cdtf'
if date_created_index == 0
self.date(date_index).dates_copyright(date_created_index).key_date = 'yes'
end
self.date(date_index).dates_copyright(date_created_index).point = 'start'
self.date(date_index).dates_copyright(date_created_index).qualifier = converted[:date_qualifier]
date_created_index = self.date(date_index).dates_copyright.length
self.date(date_index).dates_copyright(date_created_index, converted[:date_range][:end])
self.date(date_index).dates_copyright(date_created_index).encoding = 'w3cdtf'
self.date(date_index).dates_copyright(date_created_index).point = 'end'
self.date(date_index).dates_copyright(date_created_index).qualifier = converted[:date_qualifier]
end
end
self.insert_note(converted[:date_note],"date") unless !converted.has_key?(:date_note)
end
def insert_oai_date_issued(date)
#converted = Bplmodels::DatastreamInputFuncs.convert_to_mods_date(date)
converted = BplEnrich::Dates.standardize(date)
#date_index = self.date.length
date_index = 0
if converted.has_key?(:single_date)
date_created_index = self.date(date_index).dates_issued.length
self.date(date_index).dates_issued(date_created_index, converted[:single_date])
self.date(date_index).dates_issued(date_created_index).encoding = 'w3cdtf'
if date_created_index == 0
self.date(date_index).dates_issued(date_created_index).key_date = 'yes'
end
if converted.has_key?(:date_qualifier)
self.date(date_index).dates_issued(date_created_index).qualifier = converted[:date_qualifier]
end
elsif converted.has_key?(:date_range)
date_created_index = self.date(date_index).dates_issued.length
self.date(date_index).dates_issued(date_created_index, converted[:date_range][:start])
self.date(date_index).dates_issued(date_created_index).encoding = 'w3cdtf'
if date_created_index == 0
self.date(date_index).dates_issued(date_created_index).key_date = 'yes'
end
self.date(date_index).dates_issued(date_created_index).point = 'start'
self.date(date_index).dates_issued(date_created_index).qualifier = converted[:date_qualifier]
date_created_index = self.date(date_index).dates_issued.length
self.date(date_index).dates_issued(date_created_index, converted[:date_range][:end])
self.date(date_index).dates_issued(date_created_index).encoding = 'w3cdtf'
self.date(date_index).dates_issued(date_created_index).point = 'end'
self.date(date_index).dates_issued(date_created_index).qualifier = converted[:date_qualifier]
end
self.insert_note(converted[:date_note],"date") unless !converted.has_key?(:date_note)
end
def insert_date(date_type, dateStarted=nil, dateEnding=nil, dateQualifier=nil, dateOther=nil, keydate=nil)
#begin
#date_index = self.mods(0).date.count
date_index = 0
#This is horrid. Can't use count as other elements use origin_info at the same depth....
if keydate.blank?
keydate = true if (self.mods(0).date.dates_created.key_date.blank? and self.mods(0).date.dates_issued.key_date.blank? and self.mods(0).date.dates_copyright.key_date.blank? and self.mods(0).date.date_other.key_date.blank?)
keydate ||= false
end
date_type = 'dates_created' if date_type == 'dateCreated'
date_type = 'dates_copyright' if date_type == 'copyrightDate'
date_type = 'dates_issued' if date_type == 'dateIssued'
date_type = 'date_other' if date_type == 'dateOther'
date_type_with_equal = date_type + '='
#Range case - broken...fixme ... under same mods:originInfo ?
if dateStarted.present? and dateEnding.present?
self.mods(0).date(date_index).send(date_type.to_sym, 0).point = 'start'
self.mods(0).date(date_index).send(date_type.to_sym, 0).encoding = 'w3cdtf'
self.mods(0).date(date_index).send(date_type.to_sym, 0).qualifier = dateQualifier unless dateQualifier.blank?
self.mods(0).date(date_index).send(date_type.to_sym, 0).key_date = "yes" unless keydate == false
self.mods(0).date(date_index).send(date_type.to_sym, 1).point = 'end'
self.mods(0).date(date_index).send(date_type.to_sym, 1).encoding = 'w3cdtf'
self.mods(0).date(date_index).send(date_type.to_sym, 1).qualifier = dateQualifier unless dateQualifier.blank?
#Hackish way to set the node values....
self.mods(0).date(date_index).send(date_type_with_equal.to_sym, [dateStarted, dateEnding])
elsif dateStarted.present?
self.mods(0).date(date_index).send(date_type.to_sym, 0).encoding = 'w3cdtf'
self.mods(0).date(date_index).send(date_type.to_sym, 0).qualifier = dateQualifier unless dateQualifier.blank?
self.mods(0).date(date_index).send(date_type.to_sym, 0).key_date = "yes" unless keydate == false
self.mods(0).date(date_index).send(date_type_with_equal.to_sym, dateStarted)
elsif dateOther.present?
self.mods(0).date(date_index).send(date_type_with_equal.to_sym, dateOther)
end
end
define_template :date_issued do |xml, dateStarted, dateEnding, dateQualifier|
if dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.originInfo {
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start", :qualifier=>dateQualifier) {
xml.text dateStarted
}
xml.dateIssued(:encoding=>"w3cdtf", :point=>"end", :qualifier=>dateQualifier) {
xml.text dateEnding
}
}
elsif dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0
xml.originInfo {
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start") {
xml.text dateStarted
}
xml.dateIssued(:encoding=>"w3cdtf", :point=>"end") {
xml.text dateEnding
}
}
elsif dateStarted != nil && dateStarted.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.originInfo {
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes", :qualifier=>dateQualifier) {
xml.text dateStarted
}
}
elsif dateStarted != nil && dateStarted.length > 0
xml.originInfo {
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes") {
xml.text dateStarted
}
}
else
#puts "error in dates?"
end
end
define_template :date_issued_partial do |xml, dateStarted, dateEnding, dateQualifier|
if dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start", :qualifier=>dateQualifier) {
xml.text dateStarted
}
xml.dateIssued(:encoding=>"w3cdtf", :point=>"end", :qualifier=>dateQualifier) {
xml.text dateEnding
}
elsif dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start") {
xml.text dateStarted
}
xml.dateIssued(:encoding=>"w3cdtf", :point=>"end") {
xml.text dateEnding
}
elsif dateStarted != nil && dateStarted.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes", :qualifier=>dateQualifier) {
xml.text dateStarted
}
elsif dateStarted != nil && dateStarted.length > 0
xml.dateIssued(:encoding=>"w3cdtf", :keyDate=>"yes") {
xml.text dateStarted
}
else
#puts "error in dates?"
end
end
def insert_date_issued(dateStarted=nil, dateEnding=nil, dateQualifier=nil)
#begin
if self.find_by_terms(:origin_info) != nil && self.find_by_terms(:origin_info).slice(0) != nil
add_child_node(self.find_by_terms(:origin_info).slice(0), :date_issued_partial, dateStarted, dateEnding, dateQualifier)
else
add_child_node(ng_xml.root, :date_issued, dateStarted, dateEnding, dateQualifier)
end
#rescue OM::XML::Terminology::BadPointerError
#add_child_node(ng_xml.root, :date, dateStarted, dateEnding, dateQualifier, dateOther)
#end
end
define_template :date_copyright do |xml, dateStarted, dateEnding, dateQualifier|
if dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.originInfo {
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start", :qualifier=>dateQualifier) {
xml.text dateStarted
}
xml.copyrightDate(:encoding=>"w3cdtf", :point=>"end", :qualifier=>dateQualifier) {
xml.text dateEnding
}
}
elsif dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0
xml.originInfo {
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start") {
xml.text dateStarted
}
xml.copyrightDate(:encoding=>"w3cdtf", :point=>"end") {
xml.text dateEnding
}
}
elsif dateStarted != nil && dateStarted.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.originInfo {
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes", :qualifier=>dateQualifier) {
xml.text dateStarted
}
}
elsif dateStarted != nil && dateStarted.length > 0
xml.originInfo {
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes") {
xml.text dateStarted
}
}
else
#puts "error in dates?"
end
end
define_template :date_copyright_partial do |xml, dateStarted, dateEnding, dateQualifier|
if dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start", :qualifier=>dateQualifier) {
xml.text dateStarted
}
xml.copyrightDate(:encoding=>"w3cdtf", :point=>"end", :qualifier=>dateQualifier) {
xml.text dateEnding
}
elsif dateStarted != nil && dateStarted.length > 0 && dateEnding != nil && dateEnding.length > 0
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes", :point=>"start") {
xml.text dateStarted
}
xml.copyrightDate(:encoding=>"w3cdtf", :point=>"end") {
xml.text dateEnding
}
elsif dateStarted != nil && dateStarted.length > 0 && dateQualifier!= nil && dateQualifier.length > 0
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes", :qualifier=>dateQualifier) {
xml.text dateStarted
}
elsif dateStarted != nil && dateStarted.length > 0
xml.copyrightDate(:encoding=>"w3cdtf", :keyDate=>"yes") {
xml.text dateStarted
}
else
#puts "error in dates?"
end
end
def insert_date_copyright(dateStarted=nil, dateEnding=nil, dateQualifier=nil)
#begin
if self.find_by_terms(:origin_info) != nil && self.find_by_terms(:origin_info).slice(0) != nil
add_child_node(self.find_by_terms(:origin_info).slice(0), :date_copyright_partial, dateStarted, dateEnding, dateQualifier)
else
add_child_node(ng_xml.root, :date_copyright, dateStarted, dateEnding, dateQualifier)
end
end
=begin
define_template :internet_media do |xml, value|
xml.internetMediaType(value)
end
def insert_internet_media(value=nil)
if(value != nil && value.length > 1 && value != "image/jpeg")
add_child_node(self.find_by_terms(:physical_description).slice(0), :internet_media, value)
end
end
def remove_value(index)
self.find_by_terms(:internet_media).slice(index.to_i).remove
end
=end
define_template :extent do |xml, extent|
xml.extent(extent)
end
def insert_extent(extent=nil)
self.mods(0).physical_description(0).extent(0, extent) unless extent.blank?
end
def remove_extent(index)
self.find_by_terms(:extent).slice(index.to_i).remove
end
def insert_note(note=nil, noteQualifier=nil)
note_index = self.mods(0).note.count
self.mods(0).note(note_index, note) unless note.blank?
self.mods(0).note(note_index).type_at = noteQualifier unless noteQualifier.blank?
end
def remove_note(index)
self.find_by_terms(:note).slice(index.to_i).remove
end
#usage=nil, supplied=nil, subtitle=nil, language=nil, type=nil, authority=nil, authorityURI=nil, valueURI=nil
def insert_subject_title(main_title=nil, authority=nil, valueURI=nil, type=nil)
if main_title.present?
subject_index = self.mods(0).subject.count
sorted_title = Bplmodels::DatastreamInputFuncs.getProperTitle(main_title)
title = sorted_title[1]
nonSort = sorted_title[0]
self.mods(0).subject(subject_index).title_info(0).nonSort = nonSort unless nonSort.blank?
self.mods(0).subject(subject_index).title_info(0).main_title = title unless title.blank?
self.mods(0).subject(subject_index).title_info(0).type = type unless type.blank?
unless authority.blank?
self.mods(0).subject(subject_index).title_info(0).authority = authority
self.mods(0).subject(subject_index).title_info(0).authorityURI = BplEnrich::Authorities.authority_uri(authority)
end
self.mods(0).subject(subject_index).title_info(0).valueURI = valueURI unless valueURI.blank?
end
end
def insert_subject_topic(topic=nil, valueURI=nil, authority=nil)
if topic.present? && !self.mods(0).subject.topic.any?{ |top| top == topic }
subject_index = self.mods(0).subject.count
self.mods(0).subject(subject_index).topic = topic unless topic.blank?
self.mods(0).subject(subject_index).valueURI = valueURI unless valueURI.blank?
unless authority.blank?
self.mods(0).subject(subject_index).authority = authority
self.mods(0).subject(subject_index).authorityURI = BplEnrich::Authorities.authority_uri(authority)
end
end
end
def remove_subject_topic(index)
self.find_by_terms(:mods, :subject_topic).slice(index.to_i).remove
end
def insert_series(series)
if series.present?
top_level_insert_position = self.mods(0).related_item.length
0.upto self.mods(0).related_item.length-1 do |pos|
if self.mods(0).related_item(pos).type == ['series']
top_level_insert_position = pos
end
end
if self.mods(0).related_item(top_level_insert_position).blank?
self.mods(0).related_item(top_level_insert_position).type = 'series'
self.mods(0).related_item(top_level_insert_position).title_info.title = series
elsif self.mods(0).related_item(top_level_insert_position).related_item(0).blank?
self.mods(0).related_item(top_level_insert_position).related_item(0).type = 'series'
self.mods(0).related_item(top_level_insert_position).related_item(0).title_info.title = series
elsif self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).blank?
self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).type = 'series'
self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).title_info.title = series
elsif self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).related_item(0).blank?
self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).related_item(0).type = 'series'
self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).related_item(0).title_info.title = series
elsif self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).related_item(0).related_item(0).blank?
self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).related_item(0).related_item(0).type = 'series'
self.mods(0).related_item(top_level_insert_position).related_item(0).related_item(0).related_item(0).related_item(0).title_info.title = series
end
end
end
def insert_subject_temporal(date)
#converted = Bplmodels::DatastreamInputFuncs.convert_to_mods_date(date)
duplicate = false
converted = BplEnrich::Dates.standardize(date)
subject_index = self.mods(0).subject.count
if converted.has_key?(:single_date)
#Check for duplicates
(0..self.mods(0).subject.length-1).each do |index|
if self.mods(0).subject(index).temporal == [converted[:single_date]]
duplicate = true
end
end
temporal_index = self.mods(0).subject(subject_index).temporal.length
self.mods(0).subject(subject_index).temporal(temporal_index, converted[:single_date]) unless converted[:single_date].blank? || duplicate
elsif converted.has_key?(:date_range)
#Check for duplicates, FIXME: Is there case this doesn't work?
(0..self.mods(0).subject.length-1).each do |index|
if self.mods(0).subject(index).temporal == [converted[:date_range][:start], converted[:date_range][:end]]
duplicate = true
end
end
temporal_index = self.mods(0).subject(subject_index).temporal.length
self.mods(0).subject(subject_index).temporal(temporal_index, converted[:date_range][:start]) unless converted[:date_range][:start].blank? || duplicate
self.mods(0).subject(subject_index).temporal(temporal_index).point = 'start' unless converted[:date_range][:start].blank? || duplicate
temporal_index = self.mods(0).subject(subject_index).temporal.length
self.mods(0).subject(subject_index).temporal(temporal_index, converted[:date_range][:end]) unless converted[:date_range][:end].blank? || duplicate
self.mods(0).subject(subject_index).temporal(temporal_index).point = 'end' unless converted[:date_range][:end].blank? || duplicate
end
end
def insert_subject_date_fix_me(date_start, date_end)
subject_index = self.mods(0).subject.count
temporal_index = self.mods(0).subject(subject_index).temporal.length
self.mods(0).subject(subject_index).temporal(temporal_index, date_start) unless date_start.blank?
self.mods(0).subject(subject_index).temporal(temporal_index).point = 'start' unless date_start.blank?
temporal_index = self.mods(0).subject(subject_index).temporal.length
self.mods(0).subject(subject_index).temporal(temporal_index, date_end) unless date_end.blank?
self.mods(0).subject(subject_index).temporal(temporal_index).point = 'end' unless date_end.blank?
end
def insert_abstract(abstract=nil)
abstract_index = self.mods(0).abstract.count
self.mods(0).abstract(abstract_index, abstract) unless abstract.blank?
end
def insert_subject_name(name=nil, type=nil, authority=nil, valueURI=nil, date=nil)
subject_index = self.mods(0).subject.count
if name.is_a?String
self.mods(0).subject(subject_index).name(0).name_part_actual(0, name)
#Date
self.mods(0).subject(subject_index).name(0).name_part_actual(1, date) unless date.blank?
self.mods(0).subject(subject_index).name(0).name_part_actual(1).type = 'date' unless date.blank?
elsif name.is_a?Array
name.each_with_index do |name_part, index|
self.mods(0).subject(subject_index).name(0).name_part_actual(index,
Bplmodels::DatastreamInputFuncs.utf8Encode(name_part))
end
end
unless authority.blank?
self.mods(0).subject(subject_index).name(0).authority = authority
self.mods(0).subject(subject_index).name(0).authority_uri = BplEnrich::Authorities.authority_uri(authority)
end
self.mods(0).subject(subject_index).name(0).value_uri = valueURI unless valueURI.blank?
self.mods(0).subject(subject_index).name(0).type = type unless type.blank?
end
define_template :subject_geographic do |xml, geographic, authority|
if authority != nil and authority.length > 0
xml.subject(:authority=>authority) {
xml.geographic(geographic)
}
else
xml.subject {
xml.geographic(geographic)
}
end
end
def insert_subject_geographic(geographic=nil, valueURI=nil, authority=nil, coordinates=nil)
if geographic.present? && !self.mods(0).subject.geographic.any? {|geo| geo==geographic}
subject_index = self.mods(0).subject.count
self.mods(0).subject(subject_index).geographic = geographic unless geographic.blank?
self.mods(0).subject(subject_index).valueURI = valueURI unless valueURI.blank?
unless authority.blank?
self.mods(0).subject(subject_index).authority = authority
self.mods(0).subject(subject_index).authorityURI = BplEnrich::Authorities.authority_uri(authority)
end
self.mods(0).subject(subject_index).cartographics(0).coordinates = coordinates unless coordinates.blank?
end
end
def remove_subject_geographic(index)
self.find_by_terms(:subject_geographic).slice(index.to_i).remove
end
def insert_subject_cartographic(coordinates=nil, scale=nil, projection=nil)
subject_index = self.mods(0).subject.count
if coordinates.split(' ').length >= 3
coordinates.scan(/([NSWE])([\d\.]+) *([NSWE])([\d\.]+) *([NSWE])([\d\.]+) *([NSWE])([\d\.]+)/).map do |dir1,deg1,dir2,deg2,dir3,deg3,dir4,deg4|
deg1 = Float(deg1)
deg2 = Float(deg2)
deg3 = Float(deg3)
deg4 = Float(deg4)
deg1 = deg1 * -1 if dir1 == 'S' || dir1 == 'W'
deg2 = deg2 * -1 if dir2 == 'S' || dir2 == 'W'
deg3 = deg3 * -1 if dir3 == 'S' || dir3 == 'W'
deg4 = deg4 * -1 if dir4 == 'S' || dir4 == 'W'
if deg1 == deg2 && deg3 == deg4
self.mods(0).subject(subject_index).cartographics(0).coordinates = deg3.to_s + ',' + deg1.to_s
else
self.mods(0).subject(subject_index).cartographics(0).coordinates = deg1.to_s + ' ' + deg4.to_s + ' ' + deg2.to_s + ' ' + deg3.to_s
end
end
else
#Remove spaces around the comma
coordinates = coordinates.gsub(/ *, */, ',')
self.mods(0).subject(subject_index).cartographics(0).coordinates = coordinates unless coordinates.blank?
end
#FIXME: self.mods(0).subject(subject_index).cartographics(0).scale = scale unless scale.blank?
#FIXME: self.mods(0).subject(subject_index).cartographics(0).projection = projection unless projection.blank?
end
def insert_subject_scale(scale=nil, projection=nil)
subject_index = self.mods(0).subject.count
self.mods(0).subject(subject_index).cartographics(0).scale = scale unless scale.blank?
self.mods(0).subject(subject_index).cartographics(0).projection = projection unless projection.blank?
end
def remove_subject_cartographic(index)
self.find_by_terms(:subject_cartographic).slice(index.to_i).remove
end
def insert_table_of_contents(text_value, url=nil)
contents_index = self.mods(0).table_of_contents.count
self.mods(0).table_of_contents(contents_index, text_value) unless text_value.blank?
self.mods(0).table_of_contents(contents_index).href = url unless url.blank?
end
def remove_table_of_contents(index)
self.find_by_terms(:table_of_contents).slice(index.to_i).remove
end
def insert_host(nonSort=nil, main_title=nil, identifier=nil, args={})
related_index = self.mods(0).related_item.count
self.mods(0).related_item(related_index).type = 'host' unless main_title.blank? && identifier.blank?
self.mods(0).related_item(related_index).title_info(0).nonSort = nonSort unless nonSort.blank?
self.mods(0).related_item(related_index).title_info(0).title = main_title unless main_title.blank?
self.mods(0).related_item(related_index).identifier = identifier unless identifier.blank?
args.each do |key, value|
self.mods(0).related_item(related_index).send(key, Bplmodels::DatastreamInputFuncs.utf8Encode(value)) unless value.blank?
end
end
def remove_host(index)
self.find_by_terms(:mods, :host).slice(index.to_i).remove
end
define_template :related_item do |xml, value, qualifier|
xml.relatedItem(:type=>qualifier) {
xml.titleInfo {
xml.title {
xml.text value
}
}
}
end
def insert_related_item(value=nil, qualifier=nil)
if value != nil && value.length > 0
add_child_node(ng_xml.root, :related_item, value, qualifier)
end
end
def remove_related_item(index)
self.find_by_terms(:related_item).slice(index.to_i).remove
end
define_template :related_item_xref do |xml, value|
xml.relatedItem(:type=>"isReferencedBy", 'xlink:href'=>value)
end
def insert_related_item_xref(value=nil)
puts 'told to insert related item xref'
if value != nil && value.length > 0
add_child_node(ng_xml.root, :related_item_xref, value)
end
end
def related_item_xref(index)
self.find_by_terms(:related_item_xref).slice(index.to_i).remove
end
def insert_related_item_url(value=nil)
related_index = self.mods(0).related_item.count
self.mods(0).related_item(related_index).location(0).url = value unless value.blank?
end
def remove_physical_location(index)
self.find_by_terms(:physical_location).slice(index.to_i).remove
end
def insert_physical_location(location=nil, sublocation=nil,shelf_locator=nil, location_type=nil)
#Create a new tag unless there is a non-url tag already...
location_index = self.mods(0).item_location.count
for index in 0..self.mods(0).item_location.count-1
if self.mods(0).item_location(index).url.blank?
location_index = index
end
end
physical_location_index = 0
self.mods(0).item_location(location_index).physical_location(physical_location_index, location) unless location.blank?
self.mods(0).item_location(location_index).physical_location(physical_location_index).type = location_type unless location.blank?
self.mods(0).item_location(location_index).holding_simple(0).copy_information(0).sub_location = sublocation unless sublocation.blank?
self.mods(0).item_location(location_index).holding_simple(0).copy_information(0).shelf_locator = shelf_locator unless shelf_locator.blank?
end
def insert_location_url(url=nil, access=nil, usage=nil, note=nil)
location_index = self.mods(0).item_location.count
for index in 0..self.mods(0).item_location.count-1
if self.mods(0).item_location(index).url.present?
location_index = index
end
end
url_index = self.mods(0).item_location(location_index).url.count
self.mods(0).item_location(location_index).url(url_index, url) unless url.blank?
self.mods(0).item_location(location_index).url(url_index).usage = usage unless usage.blank?
self.mods(0).item_location(location_index).url(url_index).access = access unless access.blank?
self.mods(0).item_location(location_index).url(url_index).note = note unless note.blank?
end
def insert_identifier(identifier=nil, type=nil, display_label=nil, invalid=nil)
identifier_index = self.mods(0).identifier.count
if identifier.present?
self.mods(0).identifier(identifier_index, identifier) unless identifier.blank?
self.mods(0).identifier(identifier_index).type_at = type unless type.blank?
self.mods(0).identifier(identifier_index).displayLabel = display_label unless display_label.blank?
self.mods(0).identifier(identifier_index).invalid = 'yes' if (invalid.present? && invalid == 'yes')
end
end
def remove_identifier(index)
self.find_by_terms(:identifier).slice(index.to_i).remove
end
def insert_classification(value=nil, edition=nil, authority=nil, display_label=nil)
classification_index = self.mods(0).classification.count
if value.present?
self.mods(0).classification(classification_index, value)
self.mods(0).classification(classification_index).edition = edition unless edition.blank?
self.mods(0).classification(classification_index).authority = authority unless authority.blank?
self.mods(0).classification(classification_index).displayLabel = display_label unless display_label.blank?
end
end
define_template :mcgreevy do |xml|
xml.recordInfo {
xml.recordContentSource {
xml.text "Boston Public Library"
}
xml.recordOrigin {
xml.text "human prepared"
}
xml.languageOfCataloging {
xml.languageTerm(:authority=>"iso639-2b", :authorityURI=>"http://id.loc.gov/vocabulary/iso639-2", :type=>'text', :valueURI=>"http://id.loc.gov/vocabulary/iso639-2/eng") {
xml.text "English"
}
}
}
end
def insert_mcgreevy
add_child_node(ng_xml.root, :mcgreevy)
end
def remove_mcgreevy(index)
self.find_by_terms(:mcgreevy).slice(index.to_i).remove
end
def insert_record_information(record_content_source, record_content_authority=nil)
self.mods(0).record_info(0).record_content_source = record_content_source unless record_content_source.blank?
self.mods(0).record_info(0).record_content_source(0).authority = record_content_authority unless record_content_authority.blank?
self.mods(0).record_info(0).record_origin = 'human prepared'
self.mods(0).record_info(0).language_of_cataloging(0).language_term = 'English'
end
def insert_new_node(term)
add_child_node(ng_xml.root, term)
end
def remove_node(term, index)
node = self.find_by_terms(term.to_sym => index.to_i).first
unless node.nil?
node.remove
self.dirty = true
end
end
end
end
|
module SurfaceMaster
module Orbit
# Low-level interface to Numark Orbit wireless MIDI control surface.
class Device < SurfaceMaster::Device
include MIDICodes
def initialize(opts = nil)
@name = "Numark ORBIT"
super(opts)
reset!
end
def reset!
# Hack to get around apparent portmidi message truncation.
return
# Skip Sysex begin, vendor header, command code, aaaaand sysex end --
# this will let us compare command vs. response payloads to determine
# if the state of the device is what we want. Of course, sometimes it
# lies, but we can't do much about that.
# expected_state = MAPPINGS[6..-2]
# sysex!(MAPPINGS)
# sleep 0.1
# sysex!(READ_STATE)
# current_state = nil
# started_at = Time.now.to_f
# attempts = 1
# loop do
# # TODO: It appears that accessing `buffer` is HIGHLY unsafe! We may
# # TODO: be OK if everyone's waiting on us to come back from this
# # TODO: method before they begin clamoring for input, but that's just
# # TODO: a guess right now.
# if @input.buffer.length == 0
# elapsed = Time.now.to_f - started_at
# if elapsed > 4.0
# logger.warn { "Timeout fetching state of Numark Orbit!" }
# break
# elsif elapsed > (1.0 * attempts)
# logger.warn { "Asking for current state of Numark Orbit again!" }
# attempts += 1
# @output.puts(READ_STATE)
# next
# end
# sleep 0.01
# next
# end
# raw = @input.gets
# current_state = raw.find { |ii| ii[:data][0] == 0xF0 }
# break unless current_state.nil?
# end
# return unless current_state
# current_state = current_state[:data][6..-2].dup
# logger.debug { "Got state info from Numark Orbit!" }
# if expected_state != current_state
# logger.error { "UH OH! Numark Orbit state didn't match what we sent!" }
# logger.error { "Expected: #{expected_state.inspect}" }
# logger.error { "Got: #{current_state.inspect}" }
# else
# logger.debug { "Your Numark Orbit should be in the right state now." }
# end
end
def read
super
.map { |input| decode_input(input) }
.compact
end
protected
MAPPINGS = [0x03, 0x01, 0x70,
0x00, 0x00, 0x00,
0x00, 0x04, 0x00,
0x00, 0x08, 0x00,
0x00, 0x0C, 0x00,
0x00, 0x01, 0x00,
0x00, 0x05, 0x00,
0x00, 0x09, 0x00,
0x00, 0x0D, 0x00,
0x00, 0x02, 0x00,
0x00, 0x06, 0x00,
0x00, 0x0A, 0x00,
0x00, 0x0E, 0x00,
0x00, 0x03, 0x00,
0x00, 0x07, 0x00,
0x00, 0x0B, 0x00,
0x00, 0x0F, 0x00,
0x01, 0x00, 0x00,
0x01, 0x04, 0x00,
0x01, 0x08, 0x00,
0x01, 0x0C, 0x00,
0x01, 0x01, 0x00,
0x01, 0x05, 0x00,
0x01, 0x09, 0x00,
0x01, 0x0D, 0x00,
0x01, 0x02, 0x00,
0x01, 0x06, 0x00,
0x01, 0x0A, 0x00,
0x01, 0x0E, 0x00,
0x01, 0x03, 0x00,
0x01, 0x07, 0x00,
0x01, 0x0B, 0x00,
0x01, 0x0F, 0x00,
0x02, 0x00, 0x00,
0x02, 0x04, 0x00,
0x02, 0x08, 0x00,
0x02, 0x0C, 0x00,
0x02, 0x01, 0x00,
0x02, 0x05, 0x00,
0x02, 0x09, 0x00,
0x02, 0x0D, 0x00,
0x02, 0x02, 0x00,
0x02, 0x06, 0x00,
0x02, 0x0A, 0x00,
0x02, 0x0E, 0x00,
0x02, 0x03, 0x00,
0x02, 0x07, 0x00,
0x02, 0x0B, 0x00,
0x02, 0x0F, 0x00,
0x03, 0x00, 0x00,
0x03, 0x04, 0x00,
0x03, 0x08, 0x00,
0x03, 0x0C, 0x00,
0x03, 0x01, 0x00,
0x03, 0x05, 0x00,
0x03, 0x09, 0x00,
0x03, 0x0D, 0x00,
0x03, 0x02, 0x00,
0x03, 0x06, 0x00,
0x03, 0x0A, 0x00,
0x03, 0x0E, 0x00,
0x03, 0x03, 0x00,
0x03, 0x07, 0x00,
0x03, 0x0B, 0x00,
0x03, 0x0F, 0x00,
0x00, 0x00, 0x01,
0x00, 0x02, 0x00,
0x03, 0x00, 0x00,
0x01, 0x01, 0x01,
0x02, 0x01, 0x03,
0x01, 0x00, 0x02,
0x01, 0x02, 0x02,
0x02, 0x03, 0x02,
0x00, 0x03, 0x01,
0x03, 0x02, 0x03,
0x03, 0x03, 0x0C,
0x00, 0x0D, 0x00,
0x0C, 0x00, 0x0D,
0x00, 0x0C, 0x00,
0x0D, 0x00, 0x0C,
0x00, 0x0D, 0x00]
READ_STATE = [0x01, 0x00, 0x00]
def sysex_prefix; @sysex_prefix ||= super + [0x00, 0x01, 0x3F, 0x2B]; end
def decode_shoulder(decoded, note, _velocity)
decoded[:control] = decoded[:control].merge(SurfaceMaster::Orbit::Device::SHOULDERS[note])
decoded
end
def decode_grid(decoded, note, _velocity)
decoded[:control] = decoded[:control].merge(x: note / 4, y: note % 4)
decoded
end
def decode_knob(decoded, note, velocity)
decoded[:control] = decoded[:control].merge(bank: note)
decoded[:value] = velocity
decoded
end
def decode_control(decoded, note, velocity)
decoded = decoded.merge(SurfaceMaster::Orbit::Device::SELECTORS[note])
decoded[:control] = { button: velocity }
decoded
end
def decode_accelerometer(decoded, _note, velocity)
decoded[:value] = velocity
decoded
end
def enrich_decoded_message(decoded, note, velocity, timestamp)
case decoded[:type]
when :shoulder then decoded = decode_shoulder(decoded, note, velocity)
when :grid then decoded = decode_grid(decoded, note, velocity)
when :vknob then decoded = decode_knob(decoded, note, velocity)
when :accelerometer then decoded = decode_accelerometer(decoded, note, velocity)
else decoded = decode_control(decoded, note, velocity)
end
decoded[:timestamp] = timestamp
decoded
end
def decode_input(input)
note = input[:note]
velocity = input[:velocity]
code_high = input[:code] & 0xF0
code_low = input[:code] & 0x0F
raw = SurfaceMaster::Orbit::Device::CONTROLS[code_high]
raw = raw[code_low] if raw
raw = enrich_decoded_message(raw.dup, note, velocity, input[:timestamp]) if raw
raw
end
end
end
end
Differentiate a reset from initialization for the Numark Orbit.
module SurfaceMaster
module Orbit
# Low-level interface to Numark Orbit wireless MIDI control surface.
class Device < SurfaceMaster::Device
include MIDICodes
def initialize(opts = nil)
@name = "Numark ORBIT"
super(opts)
init!
end
def reset!; end
def init!
# Hack to get around apparent portmidi message truncation.
return
# Skip Sysex begin, vendor header, command code, aaaaand sysex end --
# this will let us compare command vs. response payloads to determine
# if the state of the device is what we want. Of course, sometimes it
# lies, but we can't do much about that.
# expected_state = MAPPINGS[6..-2]
# sysex!(MAPPINGS)
# sleep 0.1
# sysex!(READ_STATE)
# current_state = nil
# started_at = Time.now.to_f
# attempts = 1
# loop do
# # TODO: It appears that accessing `buffer` is HIGHLY unsafe! We may
# # TODO: be OK if everyone's waiting on us to come back from this
# # TODO: method before they begin clamoring for input, but that's just
# # TODO: a guess right now.
# if @input.buffer.length == 0
# elapsed = Time.now.to_f - started_at
# if elapsed > 4.0
# logger.warn { "Timeout fetching state of Numark Orbit!" }
# break
# elsif elapsed > (1.0 * attempts)
# logger.warn { "Asking for current state of Numark Orbit again!" }
# attempts += 1
# @output.puts(READ_STATE)
# next
# end
# sleep 0.01
# next
# end
# raw = @input.gets
# current_state = raw.find { |ii| ii[:data][0] == 0xF0 }
# break unless current_state.nil?
# end
# return unless current_state
# current_state = current_state[:data][6..-2].dup
# logger.debug { "Got state info from Numark Orbit!" }
# if expected_state != current_state
# logger.error { "UH OH! Numark Orbit state didn't match what we sent!" }
# logger.error { "Expected: #{expected_state.inspect}" }
# logger.error { "Got: #{current_state.inspect}" }
# else
# logger.debug { "Your Numark Orbit should be in the right state now." }
# end
end
def read
super
.map { |input| decode_input(input) }
.compact
end
protected
MAPPINGS = [0x03, 0x01, 0x70,
0x00, 0x00, 0x00,
0x00, 0x04, 0x00,
0x00, 0x08, 0x00,
0x00, 0x0C, 0x00,
0x00, 0x01, 0x00,
0x00, 0x05, 0x00,
0x00, 0x09, 0x00,
0x00, 0x0D, 0x00,
0x00, 0x02, 0x00,
0x00, 0x06, 0x00,
0x00, 0x0A, 0x00,
0x00, 0x0E, 0x00,
0x00, 0x03, 0x00,
0x00, 0x07, 0x00,
0x00, 0x0B, 0x00,
0x00, 0x0F, 0x00,
0x01, 0x00, 0x00,
0x01, 0x04, 0x00,
0x01, 0x08, 0x00,
0x01, 0x0C, 0x00,
0x01, 0x01, 0x00,
0x01, 0x05, 0x00,
0x01, 0x09, 0x00,
0x01, 0x0D, 0x00,
0x01, 0x02, 0x00,
0x01, 0x06, 0x00,
0x01, 0x0A, 0x00,
0x01, 0x0E, 0x00,
0x01, 0x03, 0x00,
0x01, 0x07, 0x00,
0x01, 0x0B, 0x00,
0x01, 0x0F, 0x00,
0x02, 0x00, 0x00,
0x02, 0x04, 0x00,
0x02, 0x08, 0x00,
0x02, 0x0C, 0x00,
0x02, 0x01, 0x00,
0x02, 0x05, 0x00,
0x02, 0x09, 0x00,
0x02, 0x0D, 0x00,
0x02, 0x02, 0x00,
0x02, 0x06, 0x00,
0x02, 0x0A, 0x00,
0x02, 0x0E, 0x00,
0x02, 0x03, 0x00,
0x02, 0x07, 0x00,
0x02, 0x0B, 0x00,
0x02, 0x0F, 0x00,
0x03, 0x00, 0x00,
0x03, 0x04, 0x00,
0x03, 0x08, 0x00,
0x03, 0x0C, 0x00,
0x03, 0x01, 0x00,
0x03, 0x05, 0x00,
0x03, 0x09, 0x00,
0x03, 0x0D, 0x00,
0x03, 0x02, 0x00,
0x03, 0x06, 0x00,
0x03, 0x0A, 0x00,
0x03, 0x0E, 0x00,
0x03, 0x03, 0x00,
0x03, 0x07, 0x00,
0x03, 0x0B, 0x00,
0x03, 0x0F, 0x00,
0x00, 0x00, 0x01,
0x00, 0x02, 0x00,
0x03, 0x00, 0x00,
0x01, 0x01, 0x01,
0x02, 0x01, 0x03,
0x01, 0x00, 0x02,
0x01, 0x02, 0x02,
0x02, 0x03, 0x02,
0x00, 0x03, 0x01,
0x03, 0x02, 0x03,
0x03, 0x03, 0x0C,
0x00, 0x0D, 0x00,
0x0C, 0x00, 0x0D,
0x00, 0x0C, 0x00,
0x0D, 0x00, 0x0C,
0x00, 0x0D, 0x00]
READ_STATE = [0x01, 0x00, 0x00]
def sysex_prefix; @sysex_prefix ||= super + [0x00, 0x01, 0x3F, 0x2B]; end
def decode_shoulder(decoded, note, _velocity)
decoded[:control] = decoded[:control].merge(SurfaceMaster::Orbit::Device::SHOULDERS[note])
decoded
end
def decode_grid(decoded, note, _velocity)
decoded[:control] = decoded[:control].merge(x: note / 4, y: note % 4)
decoded
end
def decode_knob(decoded, note, velocity)
decoded[:control] = decoded[:control].merge(bank: note)
decoded[:value] = velocity
decoded
end
def decode_control(decoded, note, velocity)
decoded = decoded.merge(SurfaceMaster::Orbit::Device::SELECTORS[note])
decoded[:control] = { button: velocity }
decoded
end
def decode_accelerometer(decoded, _note, velocity)
decoded[:value] = velocity
decoded
end
def enrich_decoded_message(decoded, note, velocity, timestamp)
case decoded[:type]
when :shoulder then decoded = decode_shoulder(decoded, note, velocity)
when :grid then decoded = decode_grid(decoded, note, velocity)
when :vknob then decoded = decode_knob(decoded, note, velocity)
when :accelerometer then decoded = decode_accelerometer(decoded, note, velocity)
else decoded = decode_control(decoded, note, velocity)
end
decoded[:timestamp] = timestamp
decoded
end
def decode_input(input)
note = input[:note]
velocity = input[:velocity]
code_high = input[:code] & 0xF0
code_low = input[:code] & 0x0F
raw = SurfaceMaster::Orbit::Device::CONTROLS[code_high]
raw = raw[code_low] if raw
raw = enrich_decoded_message(raw.dup, note, velocity, input[:timestamp]) if raw
raw
end
end
end
end
|
adds rake task to create StudentsClassrooms row for each existing student
namespace :students_classrooms do
desc 'give every existing user a classroom based off of the classcode column'
task :create => :environment do
create_initial_assocations
end
def create_initial_assocations
students = User.where(role: 'student')
students.each do |s|
if s.classcode
classroom = Classroom.find_by_code s.classcode
StudentsClassrooms.find_or_create_by(student_id: s.id, classroom_id: classroom.id) if classroom
end
end
end
end
|
# desc "Explaining what the task does"
# task :swagger_rails do
# # Task goes here
# end
if defined?(RSpec)
require 'rspec/core/rake_task'
desc 'Generate Swagger JSON files from integration specs'
RSpec::Core::RakeTask.new('swaggerize') do |t|
t.pattern = 'spec/requests/**/*_spec.rb, spec/api/**/*_spec.rb, spec/integration/**/*_spec.rb'
t.rspec_opts = [ '--format SwaggerRails::RSpec::Formatter', '--dry-run' ]
end
end
Keep the execution order of the specs so that the resulting swagger.json will be consistent.
# desc "Explaining what the task does"
# task :swagger_rails do
# # Task goes here
# end
if defined?(RSpec)
require 'rspec/core/rake_task'
desc 'Generate Swagger JSON files from integration specs'
RSpec::Core::RakeTask.new('swaggerize') do |t|
t.pattern = 'spec/requests/**/*_spec.rb, spec/api/**/*_spec.rb, spec/integration/**/*_spec.rb'
t.rspec_opts = [ '--format SwaggerRails::RSpec::Formatter', '--dry-run', '--order defined' ]
end
end
|
require File.join(Rails.root,"app","data_migrations","terminate_plan_year.rb.rb")
# This rake tasks terminates plan years.
# format RAILS_ENV=production bundle exec rake migrations:terminate_plan_year start_date='01-01-2017' new_end_date='01-31-2017'
namespace :migrations do
desc "Terminate Plan Year"
TerminatePlanYear.define_task :terminate_plan_year => :environment
end
Refs #17590 update rake task example
require File.join(Rails.root,"app","data_migrations","terminate_plan_year.rb.rb")
# This rake tasks terminates plan years.
# format RAILS_ENV=production bundle exec rake migrations:terminate_plan_year fein='123456789' start_date='01-01-2017' new_end_date='01-31-2017'
namespace :migrations do
desc "Terminate Plan Year"
TerminatePlanYear.define_task :terminate_plan_year => :environment
end |
# frozen_string_literal: true
require "ripper"
module Textbringer
CONFIG[:ruby_indent_level] = 2
CONFIG[:ruby_indent_tabs_mode] = false
class RubyMode < ProgrammingMode
self.file_name_pattern =
/\A(?:.*\.(?:rb|ru|rake|thor|jbuilder|gemspec|podspec)|
(?:Gem|Rake|Cap|Thor|Vagrant|Guard|Pod)file)\z/ix
self.interpreter_name_pattern = /ruby/i
def initialize(buffer)
super(buffer)
@buffer[:indent_level] = CONFIG[:ruby_indent_level]
@buffer[:indent_tabs_mode] = CONFIG[:ruby_indent_tabs_mode]
end
def forward_definition(n = number_prefix_arg || 1)
tokens = Ripper.lex(@buffer.to_s)
@buffer.forward_line
n.times do |i|
tokens = tokens.drop_while { |(l, _), e, t|
l < @buffer.current_line ||
e != :on_kw || /\A(?:class|module|def)\z/ !~ t
}
(line,), = tokens.first
if line.nil?
@buffer.end_of_buffer
break
end
@buffer.goto_line(line)
tokens = tokens.drop(1)
end
while /\s/ =~ @buffer.char_after
@buffer.forward_char
end
end
def backward_definition(n = number_prefix_arg || 1)
tokens = Ripper.lex(@buffer.to_s).reverse
@buffer.beginning_of_line
n.times do |i|
tokens = tokens.drop_while { |(l, _), e, t|
l >= @buffer.current_line ||
e != :on_kw || /\A(?:class|module|def)\z/ !~ t
}
(line,), = tokens.first
if line.nil?
@buffer.beginning_of_buffer
break
end
@buffer.goto_line(line)
tokens = tokens.drop(1)
end
while /\s/ =~ @buffer.char_after
@buffer.forward_char
end
end
def compile(cmd = read_from_minibuffer("Compile: ",
default: default_compile_command))
shell_execute(cmd, "*Ruby compile result*")
backtrace_mode
end
def symbol_pattern
/[\p{Letter}\p{Number}_$@!?]/
end
def default_compile_command
@buffer[:ruby_compile_command] ||
if File.exist?("Rakefile")
prefix = File.exist?("Gemfile") ? "bundle exec " : ""
prefix + "rake"
elsif @buffer.file_name
"ruby " + @buffer.file_name
else
nil
end
end
def toggle_test
case @buffer.file_name
when %r'(.*)/test/(.*/)?test_(.*?)\.rb\z'
base = $1
namespace = $2
name = $3
if namespace
paths = Dir.glob("#{base}/{lib,app}/**/#{namespace}#{name}.rb")
if !paths.empty?
find_file(paths.first)
return
end
end
paths = Dir.glob("#{base}/{lib,app}/**/#{name}.rb")
if !paths.empty?
find_file(paths.first)
return
end
raise EditorError, "Test subject not found"
when %r'(.*)/(?:lib|app)/(.*/)?(.*?)\.rb\z'
base = $1
namespace = $2
name = $3
if namespace
paths = Dir.glob("#{base}/test/**/#{namespace}test_#{name}.rb")
if !paths.empty?
find_file(paths.first)
return
end
end
paths = Dir.glob("#{base}/test/**/test_#{name}.rb")
if !paths.empty?
find_file(paths.first)
return
end
raise EditorError, "Test not found"
else
raise EditorError, "Unknown file type"
end
end
private
def calculate_indentation
if @buffer.current_line == 1
return 0
end
@buffer.save_excursion do
@buffer.beginning_of_line
bol_pos = @buffer.point
tokens = Ripper.lex(@buffer.substring(@buffer.point_min,
@buffer.point))
_, event, = tokens.last
if event == :on_tstring_beg ||
event == :on_heredoc_beg ||
event == :on_tstring_content
return nil
end
line, column, event, = find_nearest_beginning_token(tokens)
if event == :on_lparen
return column + 1
end
if line
@buffer.goto_line(line)
while !@buffer.beginning_of_buffer?
if @buffer.save_excursion {
@buffer.backward_char
@buffer.skip_re_backward(/\s/)
@buffer.char_before == ?,
}
@buffer.backward_line
else
break
end
end
else
@buffer.backward_line
end
@buffer.looking_at?(/[ \t]*/)
base_indentation = @buffer.match_string(0).
gsub(/\t/, " " * @buffer[:tab_width]).size
@buffer.goto_char(bol_pos)
if line.nil? ||
@buffer.looking_at?(/[ \t]*([}\])]|(end|else|elsif|when|rescue|ensure)\b)/)
indentation = base_indentation
else
indentation = base_indentation + @buffer[:indent_level]
end
_, last_event, last_text = tokens.reverse_each.find { |_, e, _|
e != :on_sp && e != :on_nl && e != :on_ignored_nl
}
if (last_event == :on_op && last_text != "|") ||
last_event == :on_period
indentation += @buffer[:indent_level]
end
indentation
end
end
BLOCK_END = {
"{" => "}",
"(" => ")",
"[" => "]"
}
def find_nearest_beginning_token(tokens)
stack = []
(tokens.size - 1).downto(0) do |i|
(line, column), event, text = tokens[i]
case event
when :on_kw
case text
when "class", "module", "def", "if", "unless", "case",
"do", "for", "while", "until", "begin"
if /\A(if|unless|while|until)\z/ =~ text
ts = tokens[0...i].reverse_each.take_while { |(l,_),| l == line }
t = ts.find { |_, e| e != :on_sp }
next if t && !(t[1] == :on_op && t[2] == "=")
end
if stack.empty?
return line, column, event, text
end
if stack.last != "end"
raise EditorError, "#{@buffer.name}:#{line}: Unmatched #{text}"
end
stack.pop
when "end"
stack.push(text)
end
when :on_rbrace, :on_rparen, :on_rbracket
stack.push(text)
when :on_lbrace, :on_lparen, :on_lbracket, :on_tlambeg
if stack.empty?
return line, column, event, text
end
if stack.last != BLOCK_END[text]
raise EditorError, "#{@buffer.name}:#{line}: Unmatched #{text}"
end
stack.pop
end
end
return nil
end
end
end
Don't change indentation in regular expression literals.
# frozen_string_literal: true
require "ripper"
module Textbringer
CONFIG[:ruby_indent_level] = 2
CONFIG[:ruby_indent_tabs_mode] = false
class RubyMode < ProgrammingMode
self.file_name_pattern =
/\A(?:.*\.(?:rb|ru|rake|thor|jbuilder|gemspec|podspec)|
(?:Gem|Rake|Cap|Thor|Vagrant|Guard|Pod)file)\z/ix
self.interpreter_name_pattern = /ruby/i
def initialize(buffer)
super(buffer)
@buffer[:indent_level] = CONFIG[:ruby_indent_level]
@buffer[:indent_tabs_mode] = CONFIG[:ruby_indent_tabs_mode]
end
def forward_definition(n = number_prefix_arg || 1)
tokens = Ripper.lex(@buffer.to_s)
@buffer.forward_line
n.times do |i|
tokens = tokens.drop_while { |(l, _), e, t|
l < @buffer.current_line ||
e != :on_kw || /\A(?:class|module|def)\z/ !~ t
}
(line,), = tokens.first
if line.nil?
@buffer.end_of_buffer
break
end
@buffer.goto_line(line)
tokens = tokens.drop(1)
end
while /\s/ =~ @buffer.char_after
@buffer.forward_char
end
end
def backward_definition(n = number_prefix_arg || 1)
tokens = Ripper.lex(@buffer.to_s).reverse
@buffer.beginning_of_line
n.times do |i|
tokens = tokens.drop_while { |(l, _), e, t|
l >= @buffer.current_line ||
e != :on_kw || /\A(?:class|module|def)\z/ !~ t
}
(line,), = tokens.first
if line.nil?
@buffer.beginning_of_buffer
break
end
@buffer.goto_line(line)
tokens = tokens.drop(1)
end
while /\s/ =~ @buffer.char_after
@buffer.forward_char
end
end
def compile(cmd = read_from_minibuffer("Compile: ",
default: default_compile_command))
shell_execute(cmd, "*Ruby compile result*")
backtrace_mode
end
def symbol_pattern
/[\p{Letter}\p{Number}_$@!?]/
end
def default_compile_command
@buffer[:ruby_compile_command] ||
if File.exist?("Rakefile")
prefix = File.exist?("Gemfile") ? "bundle exec " : ""
prefix + "rake"
elsif @buffer.file_name
"ruby " + @buffer.file_name
else
nil
end
end
def toggle_test
case @buffer.file_name
when %r'(.*)/test/(.*/)?test_(.*?)\.rb\z'
base = $1
namespace = $2
name = $3
if namespace
paths = Dir.glob("#{base}/{lib,app}/**/#{namespace}#{name}.rb")
if !paths.empty?
find_file(paths.first)
return
end
end
paths = Dir.glob("#{base}/{lib,app}/**/#{name}.rb")
if !paths.empty?
find_file(paths.first)
return
end
raise EditorError, "Test subject not found"
when %r'(.*)/(?:lib|app)/(.*/)?(.*?)\.rb\z'
base = $1
namespace = $2
name = $3
if namespace
paths = Dir.glob("#{base}/test/**/#{namespace}test_#{name}.rb")
if !paths.empty?
find_file(paths.first)
return
end
end
paths = Dir.glob("#{base}/test/**/test_#{name}.rb")
if !paths.empty?
find_file(paths.first)
return
end
raise EditorError, "Test not found"
else
raise EditorError, "Unknown file type"
end
end
private
def calculate_indentation
if @buffer.current_line == 1
return 0
end
@buffer.save_excursion do
@buffer.beginning_of_line
bol_pos = @buffer.point
tokens = Ripper.lex(@buffer.substring(@buffer.point_min,
@buffer.point))
_, event, text = tokens.last
if event == :on_tstring_beg ||
event == :on_heredoc_beg ||
event == :on_regexp_beg ||
(event == :on_regexp_end && text.size > 1) ||
event == :on_tstring_content
return nil
end
line, column, event, = find_nearest_beginning_token(tokens)
if event == :on_lparen
return column + 1
end
if line
@buffer.goto_line(line)
while !@buffer.beginning_of_buffer?
if @buffer.save_excursion {
@buffer.backward_char
@buffer.skip_re_backward(/\s/)
@buffer.char_before == ?,
}
@buffer.backward_line
else
break
end
end
else
@buffer.backward_line
end
@buffer.looking_at?(/[ \t]*/)
base_indentation = @buffer.match_string(0).
gsub(/\t/, " " * @buffer[:tab_width]).size
@buffer.goto_char(bol_pos)
if line.nil? ||
@buffer.looking_at?(/[ \t]*([}\])]|(end|else|elsif|when|rescue|ensure)\b)/)
indentation = base_indentation
else
indentation = base_indentation + @buffer[:indent_level]
end
_, last_event, last_text = tokens.reverse_each.find { |_, e, _|
e != :on_sp && e != :on_nl && e != :on_ignored_nl
}
if (last_event == :on_op && last_text != "|") ||
last_event == :on_period
indentation += @buffer[:indent_level]
end
indentation
end
end
BLOCK_END = {
"{" => "}",
"(" => ")",
"[" => "]"
}
def find_nearest_beginning_token(tokens)
stack = []
(tokens.size - 1).downto(0) do |i|
(line, column), event, text = tokens[i]
case event
when :on_kw
case text
when "class", "module", "def", "if", "unless", "case",
"do", "for", "while", "until", "begin"
if /\A(if|unless|while|until)\z/ =~ text
ts = tokens[0...i].reverse_each.take_while { |(l,_),| l == line }
t = ts.find { |_, e| e != :on_sp }
next if t && !(t[1] == :on_op && t[2] == "=")
end
if stack.empty?
return line, column, event, text
end
if stack.last != "end"
raise EditorError, "#{@buffer.name}:#{line}: Unmatched #{text}"
end
stack.pop
when "end"
stack.push(text)
end
when :on_rbrace, :on_rparen, :on_rbracket
stack.push(text)
when :on_lbrace, :on_lparen, :on_lbracket, :on_tlambeg
if stack.empty?
return line, column, event, text
end
if stack.last != BLOCK_END[text]
raise EditorError, "#{@buffer.name}:#{line}: Unmatched #{text}"
end
stack.pop
end
end
return nil
end
end
end
|
require 'travis/api/app'
require 'securerandom'
class Travis::Api::App
class AccessToken
DEFAULT_SCOPES = [:public, :private]
attr_reader :token, :scopes, :user_id, :app_id
def self.create(options = {})
new(options).tap(&:save)
end
def self.find_by_token(token)
user_id, app_id, *scopes = redis.lrange(key(token), 0, -1)
new(token: token, scopes: scopes, user_id: user_id, app_id: app_id) if user_id
end
def initialize(options = {})
raise ArgumentError, 'must supply either user_id or user' unless options.key?(:user) ^ options.key?(:user_id)
raise ArgumentError, 'must supply app_id' unless options.key?(:app_id)
@app_id = Integer(options[:app_id])
@scopes = Array(options[:scopes] || options[:scope] || DEFAULT_SCOPES).map(&:to_sym)
@user = options[:user]
@user_id = Integer(options[:user_id] || @user.id)
@token = options[:token] || reuse_token || SecureRandom.urlsafe_base64(16)
end
def save
key = key(token)
redis.del(key)
redis.rpush(key, [user_id, '', *scopes].map(&:to_s))
redis.set(reuse_key, token)
end
def user
@user ||= User.find(user_id) if user_id
end
def user?
!!user
end
def to_s
token
end
module Helpers
private
def redis
Thread.current[:redis] ||= ::Redis.connect(url: Travis.config.redis.url)
end
def key(token)
"t:#{token}"
end
end
include Helpers
extend Helpers
private
def reuse_token
redis.get(reuse_key)
end
def reuse_key
@reuse_key ||= begin
keys = ["r", user_id, app_id]
keys.append(scopes.mpa(&:to_s).sort) if scopes != DEFAULT_SCOPES
keys.join(':')
end
end
end
end
set app_id
require 'travis/api/app'
require 'securerandom'
class Travis::Api::App
class AccessToken
DEFAULT_SCOPES = [:public, :private]
attr_reader :token, :scopes, :user_id, :app_id
def self.create(options = {})
new(options).tap(&:save)
end
def self.find_by_token(token)
user_id, app_id, *scopes = redis.lrange(key(token), 0, -1)
new(token: token, scopes: scopes, user_id: user_id, app_id: app_id) if user_id
end
def initialize(options = {})
raise ArgumentError, 'must supply either user_id or user' unless options.key?(:user) ^ options.key?(:user_id)
raise ArgumentError, 'must supply app_id' unless options.key?(:app_id)
@app_id = Integer(options[:app_id])
@scopes = Array(options[:scopes] || options[:scope] || DEFAULT_SCOPES).map(&:to_sym)
@user = options[:user]
@user_id = Integer(options[:user_id] || @user.id)
@token = options[:token] || reuse_token || SecureRandom.urlsafe_base64(16)
end
def save
key = key(token)
redis.del(key)
redis.rpush(key, [user_id, app_id, *scopes].map(&:to_s))
redis.set(reuse_key, token)
end
def user
@user ||= User.find(user_id) if user_id
end
def user?
!!user
end
def to_s
token
end
module Helpers
private
def redis
Thread.current[:redis] ||= ::Redis.connect(url: Travis.config.redis.url)
end
def key(token)
"t:#{token}"
end
end
include Helpers
extend Helpers
private
def reuse_token
redis.get(reuse_key)
end
def reuse_key
@reuse_key ||= begin
keys = ["r", user_id, app_id]
keys.append(scopes.mpa(&:to_s).sort) if scopes != DEFAULT_SCOPES
keys.join(':')
end
end
end
end
|
require 's3'
require 'travis/services/base'
require 'google/apis/storage_v1'
module Travis
module Services
class FindCaches < Base
register :find_caches
class S3Wrapper
attr_reader :repository, :s3_object
def initialize(repository, s3_object)
@repository = repository
@s3_object = s3_object
end
def last_modified
s3_object.last_modified
end
def size
Integer(s3_object.size)
end
def slug
File.basename(s3_object.key, '.tbz')
end
def branch
s3_object.key[%r{^\d+/(.*)/[^/]+$}, 1]
end
def destroy
s3_object.destroy
end
end
class GcsWrapper
attr_reader :storage, :bucket_name, :repository, :cache_object
def initialize(storage, bucket_name, repository, cache_object)
@storage = storage
@bucket_name = bucket_name
@repository = repository
@cache_object = cache_object
end
def last_modified
cache_object.updated
end
def size
Integer(cache_object.size)
end
def slug
File.basename(cache_object.name, '.tbz')
end
def branch
cache_object.name[%r{^\d+/(.*)/[^/]+$}, 1]
end
def destroy
storage.delete_object(bucket_name, cache_object.name)
end
end
def run
return [] unless permission?
c = caches(prefix: prefix).tap {|x| Travis.logger.info "caches_before=#{x}"}
c.select! { |o| o.slug.include?(params[:match]) } if params[:match]
c.tap {|x| Travis.logger.info "caches_after=#{x}"}
end
private
# def setup?
# return true if caches.any?
# logger.warn "[services:find-caches] S3 credentials missing"
# false
# end
def permission?
current_user.permission?(required_role, repository_id: repo.id)
end
def required_role
Travis.config.roles.find_cache || "push"
end
def repo
@repo ||= run_service(:find_repo, params)
end
def branch
params[:branch].presence
end
def prefix
prefix = "#{repo.github_id}/"
prefix << branch << '/' if branch
prefix
end
def caches(options = {})
Travis.logger.info("options=#{options}")
c = []
entries = Travis.config.to_h.fetch(:cache_options) { [] }
entries = [entries] unless entries.is_a? Array
entries.map do |entry|
if config = entry[:s3]
svc = ::S3::Service.new(config.to_h.slice(:secret_access_key, :access_key_id))
bucket = svc.buckets.find(config.fetch(:bucket_name))
Travis.logger.info("bucket=#{bucket}")
next unless bucket
c += bucket.objects(options).map { |object| S3Wrapper.new(repo, object) }
elsif config = entry[:gcs]
storage = ::Google::Apis::StorageV1::StorageService.new
json_key_io = StringIO.new(config.to_h[:json_key].tap {|k| Travis.logger.info("json_key=#{k}")})
storage.authorization = ::Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: json_key_io,
scope: [
'https://www.googleapis.com/auth/devstorage.read_write'
]
)
bucket_name = config[:bucket_name]
Travis.logger.info("storage=#{storage}")
storage.list_objects(bucket_name, prefix: prefix).items.map do |object|
Travis.logger.info("item=#{object}")
c << GcsWrapper.new(storage, bucket_name, repo, object)
end
end
end
c.compact
end
end
end
end
Memoize @caches
Clean up debugging output
require 's3'
require 'travis/services/base'
require 'google/apis/storage_v1'
module Travis
module Services
class FindCaches < Base
register :find_caches
class S3Wrapper
attr_reader :repository, :s3_object
def initialize(repository, s3_object)
@repository = repository
@s3_object = s3_object
end
def last_modified
s3_object.last_modified
end
def size
Integer(s3_object.size)
end
def slug
File.basename(s3_object.key, '.tbz')
end
def branch
s3_object.key[%r{^\d+/(.*)/[^/]+$}, 1]
end
def destroy
Travis.logger.info "action=delete backend=s3 s3_object=#{s3_object.key}"
s3_object.destroy
end
end
class GcsWrapper
attr_reader :storage, :bucket_name, :repository, :cache_object
def initialize(storage, bucket_name, repository, cache_object)
@storage = storage
@bucket_name = bucket_name
@repository = repository
@cache_object = cache_object
end
def last_modified
cache_object.updated
end
def size
Integer(cache_object.size)
end
def slug
File.basename(cache_object.name, '.tbz')
end
def branch
cache_object.name[%r{^\d+/(.*)/[^/]+$}, 1]
end
def destroy
Travis.logger.info "action=delete backend=gcs bucket_name=#{bucket_name} cache_name=#{cache_object.name}"
storage.delete_object(bucket_name, cache_object.name)
rescue Google::Apis::ClientError
end
end
def run
return [] unless permission?
c = caches(prefix: prefix)
c.select! { |o| o.slug.include?(params[:match]) } if params[:match]
c
end
private
# def setup?
# return true if caches.any?
# logger.warn "[services:find-caches] S3 credentials missing"
# false
# end
def permission?
current_user.permission?(required_role, repository_id: repo.id)
end
def required_role
Travis.config.roles.find_cache || "push"
end
def repo
@repo ||= run_service(:find_repo, params)
end
def branch
params[:branch].presence
end
def prefix
prefix = "#{repo.github_id}/"
prefix << branch << '/' if branch
prefix
end
def caches(options = {})
if @caches
return @caches
end
c = []
entries = Travis.config.to_h.fetch(:cache_options) { [] }
entries = [entries] unless entries.is_a? Array
entries.map do |entry|
if config = entry[:s3]
svc = ::S3::Service.new(config.to_h.slice(:secret_access_key, :access_key_id))
bucket = svc.buckets.find(config.fetch(:bucket_name))
next unless bucket
c += bucket.objects(options).map { |object| S3Wrapper.new(repo, object) }
elsif config = entry[:gcs]
storage = ::Google::Apis::StorageV1::StorageService.new
json_key_io = StringIO.new(config.to_h[:json_key])
storage.authorization = ::Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: json_key_io,
scope: [
'https://www.googleapis.com/auth/devstorage.read_write'
]
)
bucket_name = config[:bucket_name]
storage.list_objects(bucket_name, prefix: prefix).items.map do |object|
c << GcsWrapper.new(storage, bucket_name, repo, object)
end
end
end
@caches = c.compact
end
end
end
end
|
module Turnstile
module Collector
class Updater
class Session < ::Struct.new(:uid, :platform, :ip); end
attr_accessor :queue, :semaphore, :cache, :tracker, :buffer_interval, :flush_interval
def initialize(queue, buffer_interval = 5, flush_interval = 6)
@queue = queue
@semaphore = Mutex.new
@cache = Hash.new(0)
@tracker = Turnstile::Tracker.new
@buffer_interval = buffer_interval
@buffer_interval = 6 if @buffer_interval <= 0
@flush_interval = flush_interval
@flush_interval = 5 if @flush_interval <= 0
end
def run
Thread.new do
Thread.current[:name] = "updater:queue"
loop do
unless queue.empty?
Turnstile::Logger.logging "caching [#{queue.size}] keys locally" do
while !queue.empty?
semaphore.synchronize {
add(queue.pop)
}
end
end
else
Turnstile::Logger.log "nothing in the queue, sleeping #{buffer_interval}s..."
end
sleep buffer_interval
end
end
Thread.new do
Thread.current[:name] = "updater:flush"
loop do
semaphore.synchronize {
unless cache.empty?
Turnstile::Logger.logging "flushing cache with [#{cache.keys.size}] keys" do
cache.keys.each do |key|
session = parse(key)
if session.uid && !session.uid.empty?
tracker.track(session.uid, session.platform, session.ip)
end
end
reset_cache
end
else
Turnstile::Logger.log "nothing to flush, sleeping #{flush_interval}s.."
end
}
sleep flush_interval
end
end
end
def add(token)
cache[token] = 1
end
private
def parse(token)
a = token.split(':')
Session.new(a[2], a[0], a[1])
end
def reset_cache
@cache.clear
GC.start
end
end
end
end
Minor refactor
module Turnstile
module Collector
class Updater
class Session < ::Struct.new(:uid, :platform, :ip); end
attr_accessor :queue, :semaphore, :cache, :tracker, :buffer_interval, :flush_interval
def initialize(queue, buffer_interval = 5, flush_interval = 6)
@queue = queue
@semaphore = Mutex.new
@cache = Hash.new(0)
@tracker = Turnstile::Tracker.new
@buffer_interval = buffer_interval
@buffer_interval = 6 if @buffer_interval <= 0
@flush_interval = flush_interval
@flush_interval = 5 if @flush_interval <= 0
end
def run
run_queue_popper
run_flusher
end
private
def run_flusher
Thread.new do
Thread.current[:name] = "updater:flush"
loop do
semaphore.synchronize {
unless cache.empty?
Turnstile::Logger.logging "flushing cache with [#{cache.keys.size}] keys" do
cache.keys.each do |key|
session = parse(key)
if session.uid && !session.uid.empty?
tracker.track(session.uid, session.platform, session.ip)
end
end
reset_cache
end
else
Turnstile::Logger.log "nothing to flush, sleeping #{flush_interval}s.."
end
}
sleep flush_interval
end
end
end
def run_queue_popper
Thread.new do
Thread.current[:name] = "updater:queue"
loop do
unless queue.empty?
Turnstile::Logger.logging "caching [#{queue.size}] keys locally" do
while !queue.empty?
semaphore.synchronize {
add(queue.pop)
}
end
end
else
Turnstile::Logger.log "nothing in the queue, sleeping #{buffer_interval}s..."
end
sleep buffer_interval
end
end
end
def add(token)
cache[token] = 1
end
def parse(token)
a = token.split(':')
Session.new(a[2], a[0], a[1])
end
def reset_cache
@cache.clear
GC.start
end
end
end
end
|
#--
# Copyright (c) 2005-2006 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.
#++
require 'tzinfo/time_or_datetime'
require 'tzinfo/timezone_period'
module TZInfo
# Thrown to indicate that no TimezonePeriod matching a given time could be found.
class PeriodNotFound < StandardError
end
# A list of TimezonePeriod instances defining a Timezone.
class TimezonePeriodList
# Initializes a new TimezonePeriodList
def initialize
@list = nil
@last_year = nil
@last_month = nil
@start_year = nil
@start_month = nil
@unbounded_start = nil
end
# One unbounded start period can be defined. This must be set before any
# calls to add.
#
# ArgumentError will be thrown if add or add_unbounded_start has already
# been called.
def add_unbounded_start(&block)
raise ArgumentError, 'add_unbounded_start has already been called' if !@unbounded_start.nil?
raise ArgumentError, 'add has already been called' if !@list.nil?
@unbounded_start = block
end
# Adds a new TimezonePeriod to the list. utc_start_year and utc_start_month
# are the year and month in which the period starts in UTC. A block must
# be passed in that will return the TimezonePeriod when called with no
# arguments.
#
# If the start year and month are less than the previously encountered
# year and month ArgumentError will be thrown.
#
# Blocks must be added in order of increasing UTC start date.
def add(utc_start_year, utc_start_month, &block)
if @list.nil?
@list = [block]
@start_year = utc_start_year
@start_month = utc_start_month
else
if utc_start_year < @last_year || (utc_start_year == @last_year && utc_start_month < @last_month)
raise ArgumentError, 'Calls to add must be in increasing start date order'
end
index = index_for_utc(utc_start_year, utc_start_month)
if @list[index].nil?
@list[index] = block
elsif @list[index].is_a?(Array)
@list[index] << block
else
@list[index] = [@list[index], block]
end
end
@last_year = utc_start_year
@last_month = utc_start_month
end
# Returns the period for the given utc time.
# If no period is found for the given time, PeriodNotFound is thrown.
def period_for_utc(utc)
utc = TimeOrDateTime.wrap(utc)
if @list.nil?
result = nil
else
index = index_for_utc(utc.year, utc.mon)
index = 0 if index < 0
index = @list.length - 1 if index >= @list.length
result = nil
index.downto(0) {|i|
contents = get_contents(i)
if contents.is_a?(Array)
(contents.length - 1).downto(0) {|j|
if contents[j].valid_for_utc?(utc)
result = contents[j]
break
end
}
break unless result.nil?
elsif !contents.nil? && contents.valid_for_utc?(utc)
result = contents
break
end
}
end
if result.nil?
unbounded_start = get_unbounded_start
if !unbounded_start.nil? && unbounded_start.valid_for_utc?(utc)
unbounded_start
else
raise PeriodNotFound, "No period found for utc: #{utc}"
end
else
result
end
end
# Returns the set of periods for the given local time as an array.
# If no period is found for the given time, PeriodNotFound is thrown.
# Results returned are ordered by increasing UTC start date.
def periods_for_local(local)
local = TimeOrDateTime.wrap(local)
# found_first is used to avoid searching back to far
# the search will be limited at the next half year block after discovering
# the first match
found_first = nil
result = []
if !@list.nil?
# add one to the index because the periods are indexed by UTC start
# and the period we are looking for could therefore be in the next
# half of the year
index = index_for_utc(local.year, local.mon) + 1
index = 0 if index < 0
index = @list.length - 1 if index >= @list.length
index.downto(0) {|i|
contents = get_contents(i)
if contents.is_a?(Array)
(contents.length - 1).downto(0) {|j|
if contents[j].valid_for_local?(local)
result << contents[j]
found_first = i if found_first.nil?
end
}
if !found_first.nil? && i < found_first
# searched far enough
break
end
elsif !contents.nil? && contents.valid_for_local?(local)
result << contents
end
}
end
if result.empty? || found_first == 0
unbounded_start = get_unbounded_start
result << unbounded_start if !unbounded_start.nil? && unbounded_start.valid_for_local?(local)
end
if result.empty?
raise PeriodNotFound, "No period found for utc: #{local}"
else
result.reverse!
result
end
end
private
# Returns the index into the @list array for a given utc year and month.
def index_for_utc(year, month)
index = (year - @start_year) * 2
index += 1 if month > 6
index -= 1 if @start_month > 6
index
end
# Returns the contents of any 6 month period, exapanding any blocks to
# TimezonePeriods first.
def get_contents(index)
contents = @list[index]
if contents.nil?
nil
elsif contents.is_a?(TimezonePeriod)
contents
elsif contents.is_a?(Array)
if contents.first.is_a?(TimezonePeriod)
contents
else
contents = contents.collect {|proc|
proc.call
}
@list[index] = contents
contents
end
elsif contents.is_a?(Proc)
contents = contents.call
@list[index] = contents
contents
end
end
# Expands unbounded_start if it is defined.
def get_unbounded_start
contents = @unbounded_start
if contents.nil?
nil
elsif contents.is_a?(TimezonePeriod)
contents
else
contents = contents.call
@unbounded_start = contents
contents
end
end
end
end
Correct typo in documentation.
git-svn-id: f5927daa5f457e40ee4ba532b77e716d68680ae3@84 6a820049-d607-0410-8d0c-bb5410e29337
#--
# Copyright (c) 2005-2006 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.
#++
require 'tzinfo/time_or_datetime'
require 'tzinfo/timezone_period'
module TZInfo
# Thrown to indicate that no TimezonePeriod matching a given time could be found.
class PeriodNotFound < StandardError
end
# A list of TimezonePeriod instances defining a Timezone.
class TimezonePeriodList
# Initializes a new TimezonePeriodList
def initialize
@list = nil
@last_year = nil
@last_month = nil
@start_year = nil
@start_month = nil
@unbounded_start = nil
end
# One unbounded start period can be defined. This must be set before any
# calls to add.
#
# ArgumentError will be thrown if add or add_unbounded_start has already
# been called.
def add_unbounded_start(&block)
raise ArgumentError, 'add_unbounded_start has already been called' if !@unbounded_start.nil?
raise ArgumentError, 'add has already been called' if !@list.nil?
@unbounded_start = block
end
# Adds a new TimezonePeriod to the list. utc_start_year and utc_start_month
# are the year and month in which the period starts in UTC. A block must
# be passed in that will return the TimezonePeriod when called with no
# arguments.
#
# If the start year and month are less than the previously encountered
# year and month ArgumentError will be thrown.
#
# Blocks must be added in order of increasing UTC start date.
def add(utc_start_year, utc_start_month, &block)
if @list.nil?
@list = [block]
@start_year = utc_start_year
@start_month = utc_start_month
else
if utc_start_year < @last_year || (utc_start_year == @last_year && utc_start_month < @last_month)
raise ArgumentError, 'Calls to add must be in increasing start date order'
end
index = index_for_utc(utc_start_year, utc_start_month)
if @list[index].nil?
@list[index] = block
elsif @list[index].is_a?(Array)
@list[index] << block
else
@list[index] = [@list[index], block]
end
end
@last_year = utc_start_year
@last_month = utc_start_month
end
# Returns the period for the given utc time.
# If no period is found for the given time, PeriodNotFound is thrown.
def period_for_utc(utc)
utc = TimeOrDateTime.wrap(utc)
if @list.nil?
result = nil
else
index = index_for_utc(utc.year, utc.mon)
index = 0 if index < 0
index = @list.length - 1 if index >= @list.length
result = nil
index.downto(0) {|i|
contents = get_contents(i)
if contents.is_a?(Array)
(contents.length - 1).downto(0) {|j|
if contents[j].valid_for_utc?(utc)
result = contents[j]
break
end
}
break unless result.nil?
elsif !contents.nil? && contents.valid_for_utc?(utc)
result = contents
break
end
}
end
if result.nil?
unbounded_start = get_unbounded_start
if !unbounded_start.nil? && unbounded_start.valid_for_utc?(utc)
unbounded_start
else
raise PeriodNotFound, "No period found for utc: #{utc}"
end
else
result
end
end
# Returns the set of periods for the given local time as an array.
# If no period is found for the given time, PeriodNotFound is thrown.
# Results returned are ordered by increasing UTC start date.
def periods_for_local(local)
local = TimeOrDateTime.wrap(local)
# found_first is used to avoid searching back to far
# the search will be limited at the next half year block after discovering
# the first match
found_first = nil
result = []
if !@list.nil?
# add one to the index because the periods are indexed by UTC start
# and the period we are looking for could therefore be in the next
# half of the year
index = index_for_utc(local.year, local.mon) + 1
index = 0 if index < 0
index = @list.length - 1 if index >= @list.length
index.downto(0) {|i|
contents = get_contents(i)
if contents.is_a?(Array)
(contents.length - 1).downto(0) {|j|
if contents[j].valid_for_local?(local)
result << contents[j]
found_first = i if found_first.nil?
end
}
if !found_first.nil? && i < found_first
# searched far enough
break
end
elsif !contents.nil? && contents.valid_for_local?(local)
result << contents
end
}
end
if result.empty? || found_first == 0
unbounded_start = get_unbounded_start
result << unbounded_start if !unbounded_start.nil? && unbounded_start.valid_for_local?(local)
end
if result.empty?
raise PeriodNotFound, "No period found for utc: #{local}"
else
result.reverse!
result
end
end
private
# Returns the index into the @list array for a given utc year and month.
def index_for_utc(year, month)
index = (year - @start_year) * 2
index += 1 if month > 6
index -= 1 if @start_month > 6
index
end
# Returns the contents of any 6 month period, expanding any blocks to
# TimezonePeriods first.
def get_contents(index)
contents = @list[index]
if contents.nil?
nil
elsif contents.is_a?(TimezonePeriod)
contents
elsif contents.is_a?(Array)
if contents.first.is_a?(TimezonePeriod)
contents
else
contents = contents.collect {|proc|
proc.call
}
@list[index] = contents
contents
end
elsif contents.is_a?(Proc)
contents = contents.call
@list[index] = contents
contents
end
end
# Expands unbounded_start if it is defined.
def get_unbounded_start
contents = @unbounded_start
if contents.nil?
nil
elsif contents.is_a?(TimezonePeriod)
contents
else
contents = contents.call
@unbounded_start = contents
contents
end
end
end
end
|
# -*- encoding: utf-8 -*-
require "unicode_utils/east_asian_width"
require "unicode_utils/nfc"
module UnicodeUtils
# Fixed pitch fonts display certain east asian characters with
# double the width of other characters (e.g. latin characters or
# a space). This function calculates a display width for +str+ based
# on the EastAsianWidth property of its codepoints.
#
# Converts str into Normalization Form C and counts codepoints,
# where codepoints with an East Asian Width of Wide or Fullwidth
# count double, codepoints with a General Category of Mn or Me count
# zero and all other codepoints count one. This implementation can't
# account for all possibilities, especially when Control characters
# are involved, all bets are off.
#
# Examples:
#
# require "unicode_utils/display_width"
# "別れ".length => 2
# UnicodeUtils.display_width("別れ") => 4
# "12".length => 2
# UnicodeUtils.display_width("12") => 2
#
# See also: UnicodeUtils.east_asian_width
def display_width(str)
UnicodeUtils.nfc(str).each_codepoint.reduce(0) { |sum, cp|
sum +
case UnicodeUtils.east_asian_width(cp)
when :Wide, :Fullwidth then 2
else 1
end
}
end
module_function :display_width
end
display_width: take general category into account
# -*- encoding: utf-8 -*-
require "unicode_utils/east_asian_width"
require "unicode_utils/gc"
require "unicode_utils/graphic_char_q"
module UnicodeUtils
#--
GENERAL_CATEGORY_BASIC_WIDTH_MAP = Hash.new.tap do |h|
GENERAL_CATEGORY_IS_GRAPHIC_MAP.each_pair { |key, value|
if value && key != :Mn && key != :Me
h[key] = 1
else
h[key] = 0
end
}
end
#++
# Get the width of +str+ when displayed with a fixed pitch font.
#
# Counts codepoints, where codepoints with an east asian width of
# +Wide+ or +Fullwidth+ count for two, non-graphic codepoints (e.g.
# control characters, including newline!) and non-spacing marks
# count for zero and all others count for one.
#
# Examples:
#
# require "unicode_utils/display_width"
# "別れ".length => 2
# UnicodeUtils.display_width("別れ") => 4
# "12".length => 2
# UnicodeUtils.display_width("12") => 2
# "a\u{308}".length => 2
# UnicodeUtils.display_width("a\u{308}") => 1
#
# Unicode assigns some reserved codepoints an east asian width of
# +Wide+. Some systems correctly display a double width replacement
# character, others not.
#
# See also: UnicodeUtils.graphic_char?, UnicodeUtils.east_asian_width
def display_width(str)
str.each_codepoint.reduce(0) { |sum, cp|
sum +
case UnicodeUtils.east_asian_width(cp)
when :Wide, :Fullwidth then 2
else GENERAL_CATEGORY_BASIC_WIDTH_MAP[UnicodeUtils.gc(cp)]
end
}
end
module_function :display_width
end
|
module Unidom
module Common
module RSpec
VERSION = '0.5'
end
end
end
1, Migrate the version from v0.5 to v0.6.
module Unidom
module Common
module RSpec
VERSION = '0.6'
end
end
end
|
require 'Gosu'
#require 'win32/sound'
require_relative 'Sprite'
require_relative 'Background'
#require_relative 'Crate'
include Gosu
#include Win32
class Game < Gosu::Window
def initialize
# Game Window
super(1280, 600, false)
# Backgrounds / Cursor
@cursor = Gosu::Image.new(self, 'media/cursor.png')
@menu = Background.new(self, 'media/menu.png')
@title = Sprite.new(self, 'media/title.png')
@no_ammo = Sprite.new(self, 'media/no_ammo_screen.png')
@no_ammo.hide
@game_over = Sprite.new(self, 'media/game_over.png')
@game_over.hide
@title.move_to(270,0)
# Character
@stand_left = Sprite.new(self,'media/Character/stand_left.png')
@stand_right = Sprite.new(self,'media/Character/stand_right.png')
@walk_left = Sprite.new(self,'media/Character/walk_left.png')
@walk_right = Sprite.new(self,'media/Character/walk_right.png')
@shoot_left = Sprite.new(self,'media/Character/shooting_left.png')
@shoot_right = Sprite.new(self,'media/Character/shooting_right.png')
@stand_right.move_to(640, 445)
@char = @stand_right
@dir = :right
# Bullets / Zombie / Crates
@bullet = Array.new
@zombie = Array.new
@crates = Array.new
# Health
@health1 = Sprite.new(self, 'media/heart.png')
@health2 = Sprite.new(self, 'media/heart.png')
@health3 = Sprite.new(self, 'media/heart.png')
@health1.move_to(1175, 0)
@health2.move_to(1210, 0)
@health3.move_to(1245, 0)
# Game Detection
@score = 0
@ammo = 12
@counter = 0
@lives = 90
@cooldown = 0
@shooting = false
@falling = false
# Game Sounds
#@zombie_sound = Sample.new('media/Sounds/zombies.wav')
#@gunshot = Sample.new('media/Sounds/gunshot.wav')
#@click = Sample.new('media/Sounds/no_ammo.wav')
# Font
@text = Font.new(self, default_font_name, 20)
# Game Caption
self.caption = "Zombie Gate - Beta - 0.3.1"
end
def update
# Start Game
if button_down? KbReturn
#Sound.play('media/Sounds/zombies.wav', Sound::ASYNC | Sound::LOOP)
@game_start = true
@title.hide
end
# Updates Sprites
if @game_start
@stand_left.move_to(@char.x,@char.y)
@stand_right.move_to(@char.x,@char.y)
@walk_right.move_to(@char.x,@char.y)
@walk_left.move_to(@char.x,@char.y)
@shoot_left.move_to(@char.x, @char.y)
@shoot_right.move_to(@char.x, @char.y)
@counter = rand(1..300)
# Switches sprite based on side
if @dir == :left then
@char = @stand_left
elsif @dir == :right then
@char = @stand_right
end
# Movement
if button_down? KbSpace and @ammo > 0 and @shooting == false # Shooting
#@gunshot.play
@shooting = true
@ammo -= 1
bullet = Sprite.new(self, 'media/bullet.png')
bullet.move_to(@char.x + 50, @char.y + 30)
@bullet << bullet
if @dir == :left then
@char = @shoot_left
elsif @dir == :right then
@char = @shoot_right
end
elsif button_down? KbSpace and @ammo == 0
@no_ammo.show
elsif (button_down? KbD or button_down? KbRight) and @shooting == false
@char = @walk_right
@dir = :right
@char.adjust_xpos 7
elsif (button_down? KbA or button_down? KbLeft) and @shooting == false
@char = @walk_left
@dir = :left
@char.adjust_xpos(-7)
end
# Zombie Spawning
if @counter == 1
zombie = Zombie.new(self, "media/Zombie/stand_right.png", :left)
zombie.move_to(-50, 440)
@zombie << zombie
elsif @counter == 100
zombie = Zombie.new(self, "media/Zombie/stand_left.png", :right)
zombie.move_to(1280, 440)
@zombie << zombie
end
# Zombie Movement
@zombie.each do |zombie|
if zombie.touching?(@char)
zombie.adjust_xpos 0
@lives -= 1
elsif zombie.dir == :left
zombie.adjust_xpos((@score / 30) + 3)
elsif zombie.dir == :right
zombie.adjust_xpos((@score / -30) - 3)
end
end
# Crate
if @counter == 48 and not @falling and @lives < 90
crate = Crate.new(self, "media/heart.png", :lives)
crate.move_to(rand(30..1250), -10)
@crates << crate
@falling = true
elsif @counter.between?(4,10) and not @falling and @ammo <= 10
crate = Crate.new(self, "media/ammo.png", :ammo)
crate.move_to(rand(30..1250), -10)
@crates << crate
@falling = true
end
# Crate Movement
@crates.each do |crate|
if @char.touching? crate and crate.item == :lives
@lives += 30 if @lives < 90
if @lives > 90
@lives = 90
end
@crates.delete(crate)
@falling = false
@cooldown = 0
elsif @char.touching? crate and crate.item == :ammo
@no_ammo.hide
@ammo += 5 if @ammo < 50
if @ammo > 50 #makes ammo equal to 50 if it goes above it
@ammo = 50
end
@crates.delete(crate)
@falling = false
@cooldown = 0
elsif crate.y > 500
crate.adjust_ypos 0
@cooldown += 1
if crate.item == :lives and @cooldown > 500
@crates.delete(crate)
@cooldown = 0
@falling = false
elsif crate.item == :ammo and @cooldown > 200
@crates.delete(crate)
@cooldown = 0
@falling = false
end
elsif crate.y <= 500
crate.adjust_ypos 2
end
end
# Health
if @lives <= 30 and @lives > 0
@health2.hide
elsif @lives <= 60 and @lives > 30
@health1.hide
@health2.show
elsif @lives <= 90 and @lives > 60
@health1.show
@health2.show
@health3.show
elsif @lives <= 0
@health1.hide
@health2.hide
@health3.hide
end
end # End @game_start
# Shooting
if @shooting and @ammo >= 0 then
if @dir == :left
@bullet.each do |bullet|
bullet.adjust_xpos(-20)
end
elsif @dir == :right
@bullet.each do |bullet|
bullet.adjust_xpos 20
end
end
elsif @shooting and @ammo == 0
@no_ammo.show
end
# Bullet Detection
@bullet.each do |bullet|
@zombie.each do |zombie|
if bullet.touching? zombie
@score += 1
@zombie.delete(zombie)
@bullet.delete(bullet)
@shooting = false
end
end
end
# Wall
if @char.x >= 1192
@char.move_to(1191, @char.y)
elsif @char.x <= -10
@char.move_to(-9, @char.y)
end
# Game Over
if @lives < 0
@game_over.show
@game_start = false
end
# Close Window
close if button_down? KbEscape
end # End update
def draw
@menu.see(0,0,0,1.6,1.25)
@title.draw
# Bullet Draw
@bullet.each do |bullet|
bullet.draw
if bullet.x > 1280
@bullet.delete(bullet)
@shooting = false
elsif bullet.x < 10
@bullet.delete(bullet)
@shooting = false
end
end
# Zombie Draw
@zombie.each do |zombie|
zombie.draw
end
# Crate Draw
@crates.each do |crate|
crate.draw
end
@no_ammo.draw
@char.draw
# Health Draw
@health1.draw
@health2.draw
@health3.draw
# Text Draw
@text.draw("Ammo: #{@ammo}", 1, 0, 0)
#@text.draw("Lives: #{@lives}", 1180, 0, 0)
@text.draw("Score: #{@score}", 640, 0, 0)
@cursor.draw(self.mouse_x, self.mouse_y, 0)
@game_over.draw
end
end
class Crate < Sprite
attr_accessor :item
def initialize(window, image, item)
@item = item
super window, image
end
end
class Zombie < Sprite
attr_accessor :dir
def initialize(window, image, dir)
@dir = dir
super window, image
end
end
Game.new.show
Fine tuning
require 'Gosu'
#require 'win32/sound'
require_relative 'Sprite'
require_relative 'Background'
#require_relative 'Crate'
include Gosu
#include Win32
class Game < Gosu::Window
def initialize
# Game Window
super(1280, 600, false)
# Backgrounds / Cursor
@cursor = Gosu::Image.new(self, 'media/cursor.png')
@menu = Background.new(self, 'media/menu.png')
@title = Sprite.new(self, 'media/title.png')
@no_ammo = Sprite.new(self, 'media/no_ammo_screen.png')
@no_ammo.hide
@game_over = Sprite.new(self, 'media/game_over.png')
@game_over.hide
@title.move_to(270,0)
# Character
@stand_left = Sprite.new(self,'media/Character/stand_left.png')
@stand_right = Sprite.new(self,'media/Character/stand_right.png')
@walk_left = Sprite.new(self,'media/Character/walk_left.png')
@walk_right = Sprite.new(self,'media/Character/walk_right.png')
@shoot_left = Sprite.new(self,'media/Character/shooting_left.png')
@shoot_right = Sprite.new(self,'media/Character/shooting_right.png')
@stand_right.move_to(640, 445)
@char = @stand_right
@dir = :right
# Bullets / Zombie / Crates
@bullet = Array.new
@zombie = Array.new
@crates = Array.new
# Health
@health1 = Sprite.new(self, 'media/heart.png')
@health2 = Sprite.new(self, 'media/heart.png')
@health3 = Sprite.new(self, 'media/heart.png')
@health1.move_to(1175, 0)
@health2.move_to(1210, 0)
@health3.move_to(1245, 0)
# Game Detection
@score = 0
@ammo = 12
@counter = 0
@lives = 90
@cooldown = 0
@shooting = false
@falling = false
# Game Sounds
#@zombie_sound = Sample.new('media/Sounds/zombies.wav')
#@gunshot = Sample.new('media/Sounds/gunshot.wav')
#@click = Sample.new('media/Sounds/no_ammo.wav')
# Font
@text = Font.new(self, default_font_name, 20)
# Game Caption
self.caption = "Zombie Gate - Beta - 0.3.1"
end
def update
# Start Game
if button_down? KbReturn
#Sound.play('media/Sounds/zombies.wav', Sound::ASYNC | Sound::LOOP)
@game_start = true
@title.hide
end
# Updates Sprites
if @game_start
@stand_left.move_to(@char.x,@char.y)
@stand_right.move_to(@char.x,@char.y)
@walk_right.move_to(@char.x,@char.y)
@walk_left.move_to(@char.x,@char.y)
@shoot_left.move_to(@char.x, @char.y)
@shoot_right.move_to(@char.x, @char.y)
@counter = rand(1..300)
# Switches sprite based on side
if @dir == :left then
@char = @stand_left
elsif @dir == :right then
@char = @stand_right
end
# Movement
if button_down? KbSpace and @ammo > 0 and @shooting == false # Shooting
#@gunshot.play
@shooting = true
@ammo -= 1
bullet = Sprite.new(self, 'media/bullet.png')
bullet.move_to(@char.x + 50, @char.y + 30)
@bullet << bullet
if @dir == :left then
@char = @shoot_left
elsif @dir == :right then
@char = @shoot_right
end
elsif button_down? KbSpace and @ammo == 0
@no_ammo.show
elsif (button_down? KbD or button_down? KbRight) and @shooting == false
@char = @walk_right
@dir = :right
@char.adjust_xpos 7
elsif (button_down? KbA or button_down? KbLeft) and @shooting == false
@char = @walk_left
@dir = :left
@char.adjust_xpos(-7)
end
# Zombie Spawning
if @counter.between?(3,4)
zombie = Zombie.new(self, "media/Zombie/stand_right.png", :left)
zombie.move_to(-50, 440)
@zombie << zombie
elsif @counter == 100
zombie = Zombie.new(self, "media/Zombie/stand_left.png", :right)
zombie.move_to(1280, 440)
@zombie << zombie
end
# Zombie Movement
@zombie.each do |zombie|
if zombie.touching?(@char)
zombie.adjust_xpos 0
@lives -= 1
elsif zombie.dir == :left
zombie.adjust_xpos((@score / 30) + 3)
elsif zombie.dir == :right
zombie.adjust_xpos((@score / -30) - 3)
end
end
# Crate
if @counter == 48 and not @falling and @lives < 90
crate = Crate.new(self, "media/heart.png", :lives)
crate.move_to(rand(30..1250), -10)
@crates << crate
@falling = true
elsif @counter.between?(4,10) and not @falling and @ammo <= 10
crate = Crate.new(self, "media/ammo.png", :ammo)
crate.move_to(rand(30..1250), -10)
@crates << crate
@falling = true
end
# Crate Movement
@crates.each do |crate|
if @char.touching? crate and crate.item == :lives
@lives += 30 if @lives < 90
if @lives > 90
@lives = 90
end
@crates.delete(crate)
@falling = false
@cooldown = 0
elsif @char.touching? crate and crate.item == :ammo
@no_ammo.hide
@ammo += 5 if @ammo < 50
if @ammo > 50 #makes ammo equal to 50 if it goes above it
@ammo = 50
end
@crates.delete(crate)
@falling = false
@cooldown = 0
elsif crate.y > 500
crate.adjust_ypos 0
@cooldown += 1
if crate.item == :lives and @cooldown > 500
@crates.delete(crate)
@cooldown = 0
@falling = false
elsif crate.item == :ammo and @cooldown > 200
@crates.delete(crate)
@cooldown = 0
@falling = false
end
elsif crate.y <= 500
crate.adjust_ypos 2
end
end
# Health
if @lives <= 30 and @lives > 0
@health2.hide
elsif @lives <= 60 and @lives > 30
@health1.hide
@health2.show
elsif @lives <= 90 and @lives > 60
@health1.show
@health2.show
@health3.show
elsif @lives <= 0
@health1.hide
@health2.hide
@health3.hide
end
end # End @game_start
# Shooting
if @shooting and @ammo >= 0 then
if @dir == :left
@bullet.each do |bullet|
bullet.adjust_xpos(-20)
end
elsif @dir == :right
@bullet.each do |bullet|
bullet.adjust_xpos 20
end
end
elsif @shooting and @ammo == 0
@no_ammo.show
end
# Bullet Detection
@bullet.each do |bullet|
@zombie.each do |zombie|
if bullet.touching? zombie
@score += 1
@zombie.delete(zombie)
@bullet.delete(bullet)
@shooting = false
end
end
end
# Wall
if @char.x >= 1192
@char.move_to(1191, @char.y)
elsif @char.x <= -10
@char.move_to(-9, @char.y)
end
# Game Over
if @lives < 0
@game_over.show
@game_start = false
end
# Close Window
close if button_down? KbEscape
end # End update
def draw
@menu.see(0,0,0,1.6,1.25)
@title.draw
# Bullet Draw
@bullet.each do |bullet|
bullet.draw
if bullet.x > 1280
@bullet.delete(bullet)
@shooting = false
elsif bullet.x < 10
@bullet.delete(bullet)
@shooting = false
end
end
# Zombie Draw
@zombie.each do |zombie|
zombie.draw
end
# Crate Draw
@crates.each do |crate|
crate.draw
end
@no_ammo.draw
@char.draw
# Health Draw
@health1.draw
@health2.draw
@health3.draw
# Text Draw
@text.draw("Ammo: #{@ammo}", 1, 0, 0)
#@text.draw("Lives: #{@lives}", 1180, 0, 0)
@text.draw("Score: #{@score}", 640, 0, 0)
@cursor.draw(self.mouse_x, self.mouse_y, 0)
@game_over.draw
end
end
class Crate < Sprite
attr_accessor :item
def initialize(window, image, item)
@item = item
super window, image
end
end
class Zombie < Sprite
attr_accessor :dir
def initialize(window, image, dir)
@dir = dir
super window, image
end
end
Game.new.show
|
Add buttons for printing invoices in admin panel
Deface::Override.new(:virtual_path => %q{spree/admin/orders/index},
:insert_after => "[data-hook='admin_orders_index_header_actions']",
:name => "print_button_header",
:text => "<th>print</th>")
Deface::Override.new(:virtual_path => %q{spree/admin/orders/index},
:insert_after => "[data-hook='admin_orders_index_row_actions']",
:name => "print_button_link",
:text => %q{<td><%= link_to "Print", "##{order.id}" %></td>})
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# These needed to load the config.yml
require 'yaml'
require 'ostruct'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Kassi
class Application < Rails::Application
# Read the config from the config.yml # THIS SHOULD BE DONE IN load_config.yml, but for some reason APP_CONFIG is not usable here
APP_CONFIG = OpenStruct.new(YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env].symbolize_keys)
# 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.
# Add additional load paths for your own custom dirs
# config.load_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.
# config.time_zone = 'Central 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 = APP_CONFIG.default_locale.to_sym
# Configure generators values. Many other options are available, be sure to check the documentation.
# config.generators do |g|
# g.orm :active_record
# g.template_engine :erb
# g.test_framework :test_unit, :fixture => true
# end
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
config.time_zone = 'Helsinki'
#if APP_CONFIG.use_recaptcha
ENV['RECAPTCHA_PUBLIC_KEY'] = APP_CONFIG.recaptcha_public_key
ENV['RECAPTCHA_PRIVATE_KEY'] = APP_CONFIG.recaptcha_private_key
#end
end
end
recaptha to depended on the setting use_recaptha
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# These needed to load the config.yml
require 'yaml'
require 'ostruct'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Kassi
class Application < Rails::Application
# Read the config from the config.yml # THIS SHOULD BE DONE IN load_config.yml, but for some reason APP_CONFIG is not usable here
APP_CONFIG = OpenStruct.new(YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env].symbolize_keys)
# 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.
# Add additional load paths for your own custom dirs
# config.load_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.
# config.time_zone = 'Central 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 = APP_CONFIG.default_locale.to_sym
# Configure generators values. Many other options are available, be sure to check the documentation.
# config.generators do |g|
# g.orm :active_record
# g.template_engine :erb
# g.test_framework :test_unit, :fixture => true
# end
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
config.time_zone = 'Helsinki'
if APP_CONFIG.use_recaptcha
ENV['RECAPTCHA_PUBLIC_KEY'] = APP_CONFIG.recaptcha_public_key
ENV['RECAPTCHA_PRIVATE_KEY'] = APP_CONFIG.recaptcha_private_key
end
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Adapt
class Application < Rails::Application
# -- reads configuration parameters from various places
require File.join(File.dirname(__FILE__), 'read_configuration')
# 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(#{Rails.root}/lib)
# 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.
config.time_zone = 'Canberra'
# 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
# JavaScript files you want as :defaults (application.js is always included).
config.action_view.javascript_expansions[:defaults] = %w()
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password, :authenticity_token, :licence_text]
end
end
Added workaround for YAML merge issue.
require File.expand_path('../boot', __FILE__)
YAML::ENGINE.yamler = 'syck' # psych may handle merges incorrectly in Ruby 1.9.2
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Adapt
class Application < Rails::Application
# -- reads configuration parameters from various places
require File.join(File.dirname(__FILE__), 'read_configuration')
# 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(#{Rails.root}/lib)
# 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.
config.time_zone = 'Canberra'
# 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
# JavaScript files you want as :defaults (application.js is always included).
config.action_view.javascript_expansions[:defaults] = %w()
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password, :authenticity_token, :licence_text]
end
end
|
require 'socket'
require 'io/wait'
begin
#require 'kgio'
rescue LoadError
end
require_relative 'common'
module Tarantool16
module Connection
class Dumb
include Common
def initialize(host, opts = {})
_init_common(host, opts)
@reconnect_time = now_f - 1
@socket = nil
_connect
end
def send_request(code, body, cb)
_connect
syswrite format_request(code, next_sync, body)
written = true
response = _read_response
rescue ::Errno::EPIPE, Retry => e
@socket.close rescue nil
@socket = nil
if !written && @retry && @reconnect
@retry = false
retry
end
cb.call Option.error(nil, Disconnected, e.message)
rescue StandardError => e
cb.call Option.error(nil, e, nil)
else
cb.call response
end
def disconnect
if @socket
@socket.close rescue nil
@socket = nil
@s = 0
end
end
def close
@reconnect = false
if @socket
@socket.close rescue nil
@socket = false
@s = 0
end
end
def connected?
@socket
end
def could_be_connected?
@socket || (@socket.nil? && (@reconnect || @reconnect_time < now_f))
end
private
def _connect
return if @socket
unless could_be_connected?
raise Disconnected, "connection is closed"
end
if @host =~ /\Aunix:(.+)\z/
path = $1
@socket = Socket.unix(path)
else
@socket = Socket.new((_ipv6? ? Socket::AF_INET6 : Socket::AF_INET), Socket::SOCK_STREAM)
@socket.setsockopt(::Socket::IPPROTO_TCP, ::Socket::TCP_NODELAY, 1)
@socket.sync = true
sockaddr = Socket.pack_sockaddr_in(*host_port.reverse)
@retry = @reconnect
if @timeout
_connect_nonblock(sockaddr)
else
@socket.connect(sockaddr)
end
end
greeting = _read(IPROTO_GREETING_SIZE)
unless greeting && greeting.bytesize == IPROTO_GREETING_SIZE
raise Disconnected, "mailformed greeting #{greeting.inspect}"
end
@nbuf = "\x00\x00\x00\x00\x00".force_encoding('BINARY')
parse_greeting greeting
authenticate if @user
rescue ::Errno::ECONNREFUSED, ::Errno::EPIPE, Disconnected, Timeout => e
@socket.close rescue nil
@socket = nil
if !@reconnect
@socket = false
@s = 0
else
@reconnect_time = now_f + @reconnect_timeout
end
raise CouldNotConnect, e.message
end
def _connect_nonblock(sockaddr)
expire = now_f + @timeout
begin
@socket.connect_nonblock(sockaddr)
rescue IO::WaitWritable
t = [@socket]
IO.select(t, t, nil, expire - now_f)
begin
@socket.connect_nonblock(sockaddr)
rescue Errno::EISCONN
end
end
end
def syswrite(req)
unless @timeout
if @socket.syswrite(req) != req.bytesize
raise Retry, "Could not write message"
end
else
expire = now_f
begin
until req.empty?
n = @socket.write_nonblock(req)
req = req[n..-1]
end
rescue IO::WaitWritable
nf = now_f
if expire <= nf
raise Timeout, "response timeouted"
else
_wait_writable(expire - nf)
retry
end
rescue Errno::EINTR
retry
end
end
end
def authenticate
syswrite format_authenticate(@user, @passwd, @salt)
_read_response.raise_if_error!
end
def _read_response
str = _read(5, @nbuf)
unless str && str.bytesize == 5
# check if we sent request or not
begin
@socket.send("\x00", 0)
rescue ::Errno::EPIPE
# if OS knows that socket is closed, then request were not sent
raise Retry
else
# otherwise request were sent
raise Disconnected, "disconnected while read length"
end
end
n = parse_size(str)
raise n unless ::Integer === n
resp = _read(n)
raise Disconnected, "disconnected while read response" unless resp && resp.bytesize == n
r = parse_response(resp)
if r.ok? && r.sync != @s
raise UnexpectedResponse, "sync mismatch: #{@s} != #{r.sync}"
end
r
end
def _read(n, buf=nil)
unless @timeout
buf ? @socket.read(n, buf) : @socket.read(n)
else
expire = now_f + @timeout
rbuf = nil
while n > 0
case tbuf = _read_nonblock(n, buf)
when String
if rbuf
rbuf << tbuf
else
rbuf = tbuf
end
buf = nil
n -= tbuf.size
when :wait_readable
nf = now_f
if expire <= nf
raise Timeout, "response timeouted"
else
_wait_readable(expire - nf)
end
when nil
raise EOFError
end
end
return rbuf
end
end
if defined?(Kgio)
def _read_nonblock(n, buf)
return buf ? Kgio.tryread(@socket, n, buf) : Kgio.tryread(@socket, n)
end
else
def _read_nonblock(n, buf)
begin
if buf
@socket.read_nonblock(n, buf)
else
@socket.read_nonblock(n)
end
rescue IO::WaitReadable
return :wait_readable
rescue Errno::EINTR
retry
end
end
end
if RUBY_ENGINE == 'jruby'
def _wait_readable(timeout)
IO.select([@socket], nil, nil, timeout)
end
else
def _wait_readable(timeout)
@socket.wait(timeout)
end
end
if IO.instance_methods.include?(:wait_writable)
def _wait_writable(timeout)
@socket.wait_writable(timeout)
end
else
def _wait_writable(timeout)
t = [@socket]
IO.select(t, t, nil, expire - now_f)
end
end
end
end
end
for ruby >= 2.3 use non-exceptional read_nonblock
require 'socket'
require 'io/wait'
begin
#require 'kgio'
rescue LoadError
end
require_relative 'common'
module Tarantool16
module Connection
class Dumb
include Common
def initialize(host, opts = {})
_init_common(host, opts)
@reconnect_time = now_f - 1
@socket = nil
_connect
end
def send_request(code, body, cb)
_connect
syswrite format_request(code, next_sync, body)
written = true
response = _read_response
rescue ::Errno::EPIPE, Retry => e
@socket.close rescue nil
@socket = nil
if !written && @retry && @reconnect
@retry = false
retry
end
cb.call Option.error(nil, Disconnected, e.message)
rescue StandardError => e
cb.call Option.error(nil, e, nil)
else
cb.call response
end
def disconnect
if @socket
@socket.close rescue nil
@socket = nil
@s = 0
end
end
def close
@reconnect = false
if @socket
@socket.close rescue nil
@socket = false
@s = 0
end
end
def connected?
@socket
end
def could_be_connected?
@socket || (@socket.nil? && (@reconnect || @reconnect_time < now_f))
end
private
def _connect
return if @socket
unless could_be_connected?
raise Disconnected, "connection is closed"
end
if @host =~ /\Aunix:(.+)\z/
path = $1
@socket = Socket.unix(path)
else
@socket = Socket.new((_ipv6? ? Socket::AF_INET6 : Socket::AF_INET), Socket::SOCK_STREAM)
@socket.setsockopt(::Socket::IPPROTO_TCP, ::Socket::TCP_NODELAY, 1)
@socket.sync = true
sockaddr = Socket.pack_sockaddr_in(*host_port.reverse)
@retry = @reconnect
if @timeout
_connect_nonblock(sockaddr)
else
@socket.connect(sockaddr)
end
end
greeting = _read(IPROTO_GREETING_SIZE)
unless greeting && greeting.bytesize == IPROTO_GREETING_SIZE
raise Disconnected, "mailformed greeting #{greeting.inspect}"
end
@nbuf = "\x00\x00\x00\x00\x00".force_encoding('BINARY')
parse_greeting greeting
authenticate if @user
rescue ::Errno::ECONNREFUSED, ::Errno::EPIPE, Disconnected, Timeout => e
@socket.close rescue nil
@socket = nil
if !@reconnect
@socket = false
@s = 0
else
@reconnect_time = now_f + @reconnect_timeout
end
raise CouldNotConnect, e.message
end
def _connect_nonblock(sockaddr)
expire = now_f + @timeout
begin
@socket.connect_nonblock(sockaddr)
rescue IO::WaitWritable
t = [@socket]
IO.select(t, t, nil, expire - now_f)
begin
@socket.connect_nonblock(sockaddr)
rescue Errno::EISCONN
end
end
end
def syswrite(req)
unless @timeout
if @socket.syswrite(req) != req.bytesize
raise Retry, "Could not write message"
end
else
expire = now_f
begin
until req.empty?
n = @socket.write_nonblock(req)
req = req[n..-1]
end
rescue IO::WaitWritable
nf = now_f
if expire <= nf
raise Timeout, "response timeouted"
else
_wait_writable(expire - nf)
retry
end
rescue Errno::EINTR
retry
end
end
end
def authenticate
syswrite format_authenticate(@user, @passwd, @salt)
_read_response.raise_if_error!
end
def _read_response
str = _read(5, @nbuf)
unless str && str.bytesize == 5
# check if we sent request or not
begin
@socket.send("\x00", 0)
rescue ::Errno::EPIPE
# if OS knows that socket is closed, then request were not sent
raise Retry
else
# otherwise request were sent
raise Disconnected, "disconnected while read length"
end
end
n = parse_size(str)
raise n unless ::Integer === n
resp = _read(n)
raise Disconnected, "disconnected while read response" unless resp && resp.bytesize == n
r = parse_response(resp)
if r.ok? && r.sync != @s
raise UnexpectedResponse, "sync mismatch: #{@s} != #{r.sync}"
end
r
end
def _read(n, buf=nil)
unless @timeout
buf ? @socket.read(n, buf) : @socket.read(n)
else
expire = now_f + @timeout
rbuf = nil
while n > 0
case tbuf = _read_nonblock(n, buf)
when String
if rbuf
rbuf << tbuf
else
rbuf = tbuf
end
buf = nil
n -= tbuf.size
when :wait_readable
nf = now_f
if expire <= nf
raise Timeout, "response timeouted"
else
_wait_readable(expire - nf)
end
when nil
raise EOFError
end
end
return rbuf
end
end
if RUBY_VERSION.split('.').map(&:to_i) >= [2,3]
EXCEPTION_FALSE = {exception: false}.freeze
def _read_nonblock(n, buf)
if buf
@socket.read_nonblock(n, buf, EXCEPTION_FALSE)
else
@socket.read_nonblock(n, EXCEPTION_FALSE)
end
end
elsif defined?(Kgio)
def _read_nonblock(n, buf)
return buf ? Kgio.tryread(@socket, n, buf) : Kgio.tryread(@socket, n)
end
else
def _read_nonblock(n, buf)
begin
if buf
@socket.read_nonblock(n, buf)
else
@socket.read_nonblock(n)
end
rescue IO::WaitReadable
return :wait_readable
rescue Errno::EINTR
retry
end
end
end
if RUBY_ENGINE == 'jruby'
def _wait_readable(timeout)
IO.select([@socket], nil, nil, timeout)
end
else
def _wait_readable(timeout)
@socket.wait(timeout)
end
end
if IO.instance_methods.include?(:wait_writable)
def _wait_writable(timeout)
@socket.wait_writable(timeout)
end
else
def _wait_writable(timeout)
t = [@socket]
IO.select(t, t, nil, expire - now_f)
end
end
end
end
end
|
# frozen_string_literal: true
require_relative 'boot'
require 'rails'
# Pick the frameworks you want:
require 'active_model/railtie'
require 'active_job/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
require 'action_cable/engine'
require 'sprockets/railtie'
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Tgdf
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults(6.1)
config.i18n.default_locale = :'zh-TW'
config.i18n.available_locales = %i[
zh-TW
en
]
# Don't generate system test files.
config.generators do |g|
g.test_framework(:rspec)
g.stylesheets(false)
g.javascripts(false)
g.helper(false)
end
config.middleware.insert(0, Rack::UTF8Sanitizer)
end
end
Set template engine to erb
# frozen_string_literal: true
require_relative 'boot'
require 'rails'
# Pick the frameworks you want:
require 'active_model/railtie'
require 'active_job/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
require 'action_cable/engine'
require 'sprockets/railtie'
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Tgdf
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults(6.1)
config.i18n.default_locale = :'zh-TW'
config.i18n.available_locales = %i[
zh-TW
en
]
# Don't generate system test files.
config.generators do |g|
g.test_framework :rspec
g.stylesheets false
g.javascripts false
g.helper false
g.template_engine :erb
end
config.middleware.insert(0, Rack::UTF8Sanitizer)
end
end
|
module Vcloud
module Core
class OrgVdcNetwork
attr_reader :id
def initialize(id)
unless id =~ /^[-0-9a-f]+$/
raise "orgVdcNetwork id : #{id} is not in correct format"
end
@id = id
end
def self.get_by_name(name)
q = Query.new('orgVdcNetwork', :filter => "name==#{name}")
unless res = q.get_all_results
raise "Error finding orgVdcNetwork by name #{name}"
end
case res.size
when 0
raise "orgVdcNetwork #{name} not found"
when 1
return self.new(res.first[:href].split('/').last)
else
raise "found multiple orgVdcNetwork with name #{name}!"
end
end
def self.provision(config)
raise "Must specify a name" unless name = config[:name]
raise "Must specify a vdc_name" unless vdc_name = config[:vdc_name]
unless config[:fence_mode] == 'isolated' || config[:fence_mode] == 'natRouted'
raise "fence_mode #{config[:fence_mode]} not supported"
end
config[:is_shared] = false unless config[:is_shared]
if config[:fence_mode] == 'natRouted'
raise "Must specify an edge_gateway to connect to" unless config.key?(:edge_gateway)
edgegw = Vcloud::Core::EdgeGateway.get_by_name(config[:edge_gateway])
end
vdc = Vcloud::Core::Vdc.get_by_name(vdc_name)
options = construct_network_options(config)
options[:EdgeGateway] = { :href => edgegw.href } if edgegw
begin
Vcloud.logger.info("Provisioning new OrgVdcNetwork #{name} in vDC '#{vdc_name}'")
attrs = Vcloud::Fog::ServiceInterface.new.post_create_org_vdc_network(vdc.id, name, options)
rescue RuntimeError => e
Vcloud.logger.error("Could not provision orgVdcNetwork: #{e.message}")
end
raise "Did not successfully create orgVdcNetwork" unless attrs && attrs.key?(:href)
self.new(attrs[:href].split('/').last)
end
def vcloud_attributes
Vcloud::Fog::ServiceInterface.new.get_network(id)
end
def name
vcloud_attributes[:name]
end
def href
vcloud_attributes[:href]
end
def delete
Vcloud::Fog::ServiceInterface.new.delete_network(id)
end
private
def self.construct_network_options(config)
opts = {}
opts[:Description] = config[:description] if config.key?(:description)
opts[:IsShared] = config[:is_shared]
ip_scope = {}
ip_scope[:IsInherited] = config[:is_inherited] || false
ip_scope[:Gateway] = config[:gateway] if config.key?(:gateway)
ip_scope[:Netmask] = config[:netmask] if config.key?(:netmask)
ip_scope[:Dns1] = config[:dns1] if config.key?(:dns1)
ip_scope[:Dns2] = config[:dns2] if config.key?(:dns2)
ip_scope[:DnsSuffix] = config[:dns_suffix] if config.key?(:dns_suffix)
ip_scope[:IsEnabled] = config[:is_enabled] || true
if config.key?(:ip_ranges) && config[:ip_ranges].size > 0
ip_scope[:IpRanges] = []
config[:ip_ranges].each do |range|
ip_scope[:IpRanges] << {
:IpRange => {
:StartAddress => range[:start_address],
:EndAddress => range[:end_address]
}
}
end
end
opts[:Configuration] = {
:FenceMode => config[:fence_mode],
:IpScopes => {
:IpScope => ip_scope
},
}
opts
end
end
end
end
remove unused get_by_name code
pending discussion on how to implement widely
module Vcloud
module Core
class OrgVdcNetwork
attr_reader :id
def initialize(id)
unless id =~ /^[-0-9a-f]+$/
raise "orgVdcNetwork id : #{id} is not in correct format"
end
@id = id
end
def self.provision(config)
raise "Must specify a name" unless name = config[:name]
raise "Must specify a vdc_name" unless vdc_name = config[:vdc_name]
unless config[:fence_mode] == 'isolated' || config[:fence_mode] == 'natRouted'
raise "fence_mode #{config[:fence_mode]} not supported"
end
config[:is_shared] = false unless config[:is_shared]
if config[:fence_mode] == 'natRouted'
raise "Must specify an edge_gateway to connect to" unless config.key?(:edge_gateway)
edgegw = Vcloud::Core::EdgeGateway.get_by_name(config[:edge_gateway])
end
vdc = Vcloud::Core::Vdc.get_by_name(vdc_name)
options = construct_network_options(config)
options[:EdgeGateway] = { :href => edgegw.href } if edgegw
begin
Vcloud.logger.info("Provisioning new OrgVdcNetwork #{name} in vDC '#{vdc_name}'")
attrs = Vcloud::Fog::ServiceInterface.new.post_create_org_vdc_network(vdc.id, name, options)
rescue RuntimeError => e
Vcloud.logger.error("Could not provision orgVdcNetwork: #{e.message}")
end
raise "Did not successfully create orgVdcNetwork" unless attrs && attrs.key?(:href)
self.new(attrs[:href].split('/').last)
end
def vcloud_attributes
Vcloud::Fog::ServiceInterface.new.get_network(id)
end
def name
vcloud_attributes[:name]
end
def href
vcloud_attributes[:href]
end
def delete
Vcloud::Fog::ServiceInterface.new.delete_network(id)
end
private
def self.construct_network_options(config)
opts = {}
opts[:Description] = config[:description] if config.key?(:description)
opts[:IsShared] = config[:is_shared]
ip_scope = {}
ip_scope[:IsInherited] = config[:is_inherited] || false
ip_scope[:Gateway] = config[:gateway] if config.key?(:gateway)
ip_scope[:Netmask] = config[:netmask] if config.key?(:netmask)
ip_scope[:Dns1] = config[:dns1] if config.key?(:dns1)
ip_scope[:Dns2] = config[:dns2] if config.key?(:dns2)
ip_scope[:DnsSuffix] = config[:dns_suffix] if config.key?(:dns_suffix)
ip_scope[:IsEnabled] = config[:is_enabled] || true
if config.key?(:ip_ranges) && config[:ip_ranges].size > 0
ip_scope[:IpRanges] = []
config[:ip_ranges].each do |range|
ip_scope[:IpRanges] << {
:IpRange => {
:StartAddress => range[:start_address],
:EndAddress => range[:end_address]
}
}
end
end
opts[:Configuration] = {
:FenceMode => config[:fence_mode],
:IpScopes => {
:IpScope => ip_scope
},
}
opts
end
end
end
end
|
Rake::Task['db:migrate'].enhance do
unless ActiveRecordViews::Extension.create_enabled
Rails.application.eager_load!
ActiveRecordViews::Extension.process_create_queue!
ActiveRecordViews.drop_unregistered_views!
end
end
schema_rake_task = Gem::Version.new(Rails.version) >= Gem::Version.new("6.1") ? 'db:schema:dump' : 'db:structure:dump'
Rake::Task[schema_rake_task].enhance do
table_exists = if Rails::VERSION::MAJOR >= 5
ActiveRecord::Base.connection.data_source_exists?('active_record_views')
else
ActiveRecord::Base.connection.table_exists?('active_record_views')
end
if schema_rake_task == 'db:structure:dump'
ActiveRecord::Base.schema_format = :sql
end
if table_exists && ActiveRecord::Base.schema_format == :sql
tasks = ActiveRecord::Tasks::DatabaseTasks
filename = case
when tasks.respond_to?(:dump_filename)
tasks.dump_filename('primary')
else
tasks.schema_file
end
config = tasks.current_config
adapter = config.fetch('adapter')
pg_tasks = tasks.send(:class_for_adapter, adapter).new(config)
pg_tasks.send(:set_psql_env)
require 'shellwords'
system("pg_dump --data-only --table=active_record_views #{Shellwords.escape config['database']} >> #{Shellwords.escape filename}")
raise 'active_record_views metadata dump failed' unless $?.success?
File.open filename, 'a' do |io|
io.puts 'UPDATE public.active_record_views SET refreshed_at = NULL WHERE refreshed_at IS NOT NULL;'
end
end
end
Extract database name into a local variable
Rake::Task['db:migrate'].enhance do
unless ActiveRecordViews::Extension.create_enabled
Rails.application.eager_load!
ActiveRecordViews::Extension.process_create_queue!
ActiveRecordViews.drop_unregistered_views!
end
end
schema_rake_task = Gem::Version.new(Rails.version) >= Gem::Version.new("6.1") ? 'db:schema:dump' : 'db:structure:dump'
Rake::Task[schema_rake_task].enhance do
table_exists = if Rails::VERSION::MAJOR >= 5
ActiveRecord::Base.connection.data_source_exists?('active_record_views')
else
ActiveRecord::Base.connection.table_exists?('active_record_views')
end
if schema_rake_task == 'db:structure:dump'
ActiveRecord::Base.schema_format = :sql
end
if table_exists && ActiveRecord::Base.schema_format == :sql
tasks = ActiveRecord::Tasks::DatabaseTasks
filename = case
when tasks.respond_to?(:dump_filename)
tasks.dump_filename('primary')
else
tasks.schema_file
end
config = tasks.current_config
adapter = config.fetch('adapter')
database = config.fetch('database')
pg_tasks = tasks.send(:class_for_adapter, adapter).new(config)
pg_tasks.send(:set_psql_env)
require 'shellwords'
system("pg_dump --data-only --table=active_record_views #{Shellwords.escape database} >> #{Shellwords.escape filename}")
raise 'active_record_views metadata dump failed' unless $?.success?
File.open filename, 'a' do |io|
io.puts 'UPDATE public.active_record_views SET refreshed_at = NULL WHERE refreshed_at IS NOT NULL;'
end
end
end
|
# frozen_string_literal: true
source 'https://rubygems.org'
gem 'rails', '5.1.1'
# Database Adapter
gem 'pg', '0.20.0'
# Gems used by project
gem 'autoprefixer-rails'
gem 'bootstrap-sass', '~> 3.3.7'
gem 'carrierwave', '~> 1.1.0'
gem 'devise', '~> 4.3.0'
gem 'figaro', '~> 1.1.1'
gem 'haml', '~> 5.0.1'
gem 'kaminari', '~> 1.0.1'
# Rails Defaults
gem 'coffee-rails', '~> 4.2'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'jbuilder', '~> 2.5'
gem 'jquery-rails', '~> 4.3.1'
gem 'turbolinks', '~> 5'
# Testing
group :test do
gem 'minitest'
gem 'rails-controller-testing'
gem 'simplecov', '~> 0.14.1', require: false
end
group :development do
gem 'web-console', '~> 3.0'
end
Prefer double quotes
# frozen_string_literal: true
source "https://rubygems.org"
gem "rails", "5.1.1"
# Database Adapter
gem "pg", "0.20.0"
# Gems used by project
gem "autoprefixer-rails"
gem "bootstrap-sass", "~> 3.3.7"
gem "carrierwave", "~> 1.1.0"
gem "devise", "~> 4.3.0"
gem "figaro", "~> 1.1.1"
gem "haml", "~> 5.0.1"
gem "kaminari", "~> 1.0.1"
# Rails Defaults
gem "coffee-rails", "~> 4.2"
gem "sass-rails", "~> 5.0"
gem "uglifier", ">= 1.3.0"
gem "jbuilder", "~> 2.5"
gem "jquery-rails", "~> 4.3.1"
gem "turbolinks", "~> 5"
# Testing
group :test do
gem "minitest"
gem "rails-controller-testing"
gem "simplecov", "~> 0.14.1", require: false
end
group :development do
gem "web-console", "~> 3.0"
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'active_support/dependencies'
# FIXME this silences the warnings about Rails 2.3-style plugins under
# vendor/plugins, which are deprecated. Hiding those warnings makes it easier
# to work for now, but we should really look at putting those plugins away.
ActiveSupport::Deprecation.silenced = true
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
# Bundler.require(:default, :assets, Rails.env)
end
module Noosfero
class Application < Rails::Application
require 'noosfero/plugin'
# Adds custom attributes to the Set of allowed html attributes for the #sanitize helper
config.action_view.sanitized_allowed_attributes = 'align', 'border', 'alt', 'vspace', 'hspace', 'width', 'heigth', 'value', 'type', 'data', 'style', 'target', 'codebase', 'archive', 'classid', 'code', 'flashvars', 'scrolling', 'frameborder', 'controls', 'autoplay', 'colspan', 'rowspan'
# Adds custom tags to the Set of allowed html tags for the #sanitize helper
config.action_view.sanitized_allowed_tags = 'object', 'embed', 'param', 'table', 'tr', 'th', 'td', 'applet', 'comment', 'iframe', 'audio', 'video', 'source'
config.action_controller.include_all_helpers = false
# 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( #{Rails.root.join('app', 'sweepers')} )
config.autoload_paths += Dir["#{config.root}/lib/**/"]
config.autoload_paths += Dir["#{config.root}/app/controllers/**/"]
config.autoload_paths += %W( #{Rails.root.join('test', 'mocks', Rails.env)} )
# 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.
# Sweepers are observers
# don't load the sweepers while loading the database
ignore_rake_commands = %w[
db:schema:load
gems:install
clobber
noosfero:translations:compile
makemo
]
if $PROGRAM_NAME =~ /rake$/ && (ignore_rake_commands.include?(ARGV.first))
Noosfero::Plugin.should_load = false
else
config.active_record.observers = :article_sweeper, :role_assignment_sweeper, :friendship_sweeper, :category_sweeper, :block_sweeper
end
# 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 = 'Central 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 = nil
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
ActiveSupport::JSON::Encoding.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.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Straight support for assets from a rails 2 pattern
# See also config/initializers/assets.rb
config.assets.paths =
Dir.glob("{base,config/}plugins/*/{assets,public}/{,javascripts,stylesheets}") +
Dir.glob("public/{,javascripts,stylesheets}") +
# no precedence over core
Dir.glob("public/{designs/themes,user_themes}/*/{,javascripts,stylesheets}")
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.sass.preferred_syntax = :scss
config.sass.cache = true
config.sass.line_comments = false
def noosfero_session_secret
require 'fileutils'
target_dir = File.join(File.dirname(__FILE__), '../tmp')
FileUtils.mkdir_p(target_dir)
file = File.join(target_dir, 'session.secret')
if !File.exists?(file)
secret = (1..128).map { %w[0 1 2 3 4 5 6 7 8 9 a b c d e f][rand(16)] }.join('')
File.open(file, 'w') do |f|
f.puts secret
end
end
File.read(file).strip
end
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions 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.
config.secret_token = noosfero_session_secret
config.action_dispatch.session = {
:key => '_noosfero_session',
}
config.time_zone = File.read('/etc/timezone').split("\n").first
config.active_record.default_timezone = :local
config.paths['db/migrate'] += Dir.glob "#{Rails.root}/{baseplugins,config/plugins/*}/db/migrate"
config.i18n.load_path += Dir.glob "#{Rails.root}/{baseplugins,config/plugins/*}/locales/*.{rb,yml}"
Noosfero::Plugin.setup(config)
end
end
Fallback to en in i18n
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'active_support/dependencies'
# FIXME this silences the warnings about Rails 2.3-style plugins under
# vendor/plugins, which are deprecated. Hiding those warnings makes it easier
# to work for now, but we should really look at putting those plugins away.
ActiveSupport::Deprecation.silenced = true
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
# Bundler.require(:default, :assets, Rails.env)
end
module Noosfero
class Application < Rails::Application
require 'noosfero/plugin'
# Adds custom attributes to the Set of allowed html attributes for the #sanitize helper
config.action_view.sanitized_allowed_attributes = 'align', 'border', 'alt', 'vspace', 'hspace', 'width', 'heigth', 'value', 'type', 'data', 'style', 'target', 'codebase', 'archive', 'classid', 'code', 'flashvars', 'scrolling', 'frameborder', 'controls', 'autoplay', 'colspan', 'rowspan'
# Adds custom tags to the Set of allowed html tags for the #sanitize helper
config.action_view.sanitized_allowed_tags = 'object', 'embed', 'param', 'table', 'tr', 'th', 'td', 'applet', 'comment', 'iframe', 'audio', 'video', 'source'
config.action_controller.include_all_helpers = false
# 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( #{Rails.root.join('app', 'sweepers')} )
config.autoload_paths += Dir["#{config.root}/lib/**/"]
config.autoload_paths += Dir["#{config.root}/app/controllers/**/"]
config.autoload_paths += %W( #{Rails.root.join('test', 'mocks', Rails.env)} )
# 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.
# Sweepers are observers
# don't load the sweepers while loading the database
ignore_rake_commands = %w[
db:schema:load
gems:install
clobber
noosfero:translations:compile
makemo
]
if $PROGRAM_NAME =~ /rake$/ && (ignore_rake_commands.include?(ARGV.first))
Noosfero::Plugin.should_load = false
else
config.active_record.observers = :article_sweeper, :role_assignment_sweeper, :friendship_sweeper, :category_sweeper, :block_sweeper
end
# 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 = 'Central 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 = nil
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
ActiveSupport::JSON::Encoding.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.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Straight support for assets from a rails 2 pattern
# See also config/initializers/assets.rb
config.assets.paths =
Dir.glob("{base,config/}plugins/*/{assets,public}/{,javascripts,stylesheets}") +
Dir.glob("public/{,javascripts,stylesheets}") +
# no precedence over core
Dir.glob("public/{designs/themes,user_themes}/*/{,javascripts,stylesheets}")
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.sass.preferred_syntax = :scss
config.sass.cache = true
config.sass.line_comments = false
def noosfero_session_secret
require 'fileutils'
target_dir = File.join(File.dirname(__FILE__), '../tmp')
FileUtils.mkdir_p(target_dir)
file = File.join(target_dir, 'session.secret')
if !File.exists?(file)
secret = (1..128).map { %w[0 1 2 3 4 5 6 7 8 9 a b c d e f][rand(16)] }.join('')
File.open(file, 'w') do |f|
f.puts secret
end
end
File.read(file).strip
end
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions 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.
config.secret_token = noosfero_session_secret
config.action_dispatch.session = {
:key => '_noosfero_session',
}
config.time_zone = File.read('/etc/timezone').split("\n").first
config.active_record.default_timezone = :local
config.i18n.fallbacks = [:en_US, :en]
config.paths['db/migrate'] += Dir.glob "#{Rails.root}/{baseplugins,config/plugins/*}/db/migrate"
config.i18n.load_path += Dir.glob "#{Rails.root}/{baseplugins,config/plugins/*}/locales/*.{rb,yml}"
Noosfero::Plugin.setup(config)
end
end
|
Add new rake task to for architecture redesign
namespace :db do
desc 'Migrates assessments to the new schema in 20140527151234_assessment_redesign.rb'
task migrate_assessments: :environment do
Mission.all.each do |m|
puts m.to_yaml
end
end
end
|
# == Schema Information
#
# Table name: feed_versions
#
# id :integer not null, primary key
# feed_id :integer
# feed_type :string
# file :string
# earliest_calendar_date :date
# latest_calendar_date :date
# sha1 :string
# md5 :string
# tags :hstore
# fetched_at :datetime
# imported_at :datetime
# created_at :datetime
# updated_at :datetime
# import_level :integer default(0)
# url :string
# file_raw :string
# sha1_raw :string
# md5_raw :string
# file_feedvalidator :string
#
# Indexes
#
# index_feed_versions_on_earliest_calendar_date (earliest_calendar_date)
# index_feed_versions_on_feed_type_and_feed_id (feed_type,feed_id)
# index_feed_versions_on_latest_calendar_date (latest_calendar_date)
#
class FeedVersionSerializer < ApplicationSerializer
attributes :sha1,
:earliest_calendar_date,
:latest_calendar_date,
:md5,
:tags,
:fetched_at,
:imported_at,
:import_level,
:created_at,
:updated_at,
:feed_version_imports,
:feed_version_imports_url,
:import_level,
:is_active_feed_version,
:changesets_imported_from_this_feed_version,
:download_url,
:feedvalidator_url
def feed_version_imports
object.feed_version_imports.map(&:id)
end
def feed_version_imports_url
api_v1_feed_version_imports_url({
feed_onestop_id: object.feed.onestop_id,
feed_version_sha1: object.sha1
})
end
def is_active_feed_version
object.is_active_feed_version
end
def changesets_imported_from_this_feed_version
object.changesets_imported_from_this_feed_version.map(&:id)
end
end
FeedVersion serializer: url [ci skip]
# == Schema Information
#
# Table name: feed_versions
#
# id :integer not null, primary key
# feed_id :integer
# feed_type :string
# file :string
# earliest_calendar_date :date
# latest_calendar_date :date
# sha1 :string
# md5 :string
# tags :hstore
# fetched_at :datetime
# imported_at :datetime
# created_at :datetime
# updated_at :datetime
# import_level :integer default(0)
# url :string
# file_raw :string
# sha1_raw :string
# md5_raw :string
# file_feedvalidator :string
#
# Indexes
#
# index_feed_versions_on_earliest_calendar_date (earliest_calendar_date)
# index_feed_versions_on_feed_type_and_feed_id (feed_type,feed_id)
# index_feed_versions_on_latest_calendar_date (latest_calendar_date)
#
class FeedVersionSerializer < ApplicationSerializer
attributes :sha1,
:earliest_calendar_date,
:latest_calendar_date,
:md5,
:tags,
:fetched_at,
:imported_at,
:import_level,
:created_at,
:updated_at,
:feed_version_imports,
:feed_version_imports_url,
:import_level,
:is_active_feed_version,
:changesets_imported_from_this_feed_version,
:url,
:download_url,
:feedvalidator_url
def feed_version_imports
object.feed_version_imports.map(&:id)
end
def feed_version_imports_url
api_v1_feed_version_imports_url({
feed_onestop_id: object.feed.onestop_id,
feed_version_sha1: object.sha1
})
end
def is_active_feed_version
object.is_active_feed_version
end
def changesets_imported_from_this_feed_version
object.changesets_imported_from_this_feed_version.map(&:id)
end
end
|
require_relative './boot'
require 'active_model/railtie'
require 'active_job/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
require 'sprockets/railtie'
Bundler.require(*Rails.groups)
module RecordOfGuidance
class Application < Rails::Application
config.active_record.raise_in_transactional_callbacks = true
end
end
Configure ActiveJob to use Sidekiq
require_relative './boot'
require 'active_model/railtie'
require 'active_job/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
require 'sprockets/railtie'
Bundler.require(*Rails.groups)
module RecordOfGuidance
class Application < Rails::Application
config.active_job.queue_adapter = :sidekiq
config.active_record.raise_in_transactional_callbacks = true
end
end
|
Create a rake task to search for entries that will expire
namespace :email do
desc 'Send an email notifying the deadline of an expense'
task notifications: :environment do
User.find_each do |user|
user_accounts = user.accounts.where(reminder_active: true, owner: user.id)
user_accounts.each do |account|
days_before = account.reminder_days_before
date_to_compare = Date.today - days_before
user_entries = account.entries.where(paid: false, date: date_to_compare, entries_type: :expense)
user_entries.each do |entry|
Mailers::NotificationMessage.perform(user, account, entry)
end
end
end
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(:default, Rails.env)
module Autolab3
class Application < Rails::Application
config.to_prepare do
Devise::ConfirmationsController.skip_before_action :set_course
Devise::ConfirmationsController.skip_before_action :authorize_user_for_course
Devise::ConfirmationsController.skip_before_action :authenticate_for_action
Devise::ConfirmationsController.skip_before_action :update_persistent_announcements
Devise::SessionsController.skip_before_action :set_course
Devise::SessionsController.skip_before_action :authorize_user_for_course
Devise::SessionsController.skip_before_action :authenticate_for_action
Devise::SessionsController.skip_before_action :update_persistent_announcements
Devise::PasswordsController.skip_before_action :set_course
Devise::PasswordsController.skip_before_action :authorize_user_for_course
Devise::PasswordsController.skip_before_action :authenticate_for_action
Devise::PasswordsController.skip_before_action :update_persistent_announcements
Devise::RegistrationsController.skip_before_action :set_course
Devise::RegistrationsController.skip_before_action :authorize_user_for_course
Devise::RegistrationsController.skip_before_action :authenticate_for_action
Devise::RegistrationsController.skip_before_action :update_persistent_announcements
Devise::OmniauthCallbacksController.skip_before_action :set_course
Devise::OmniauthCallbacksController.skip_before_action :authorize_user_for_course
Devise::OmniauthCallbacksController.skip_before_action :authenticate_for_action
Devise::OmniauthCallbacksController.skip_before_action :update_persistent_announcements
Devise::SessionsController.layout "home"
Devise::RegistrationsController.layout proc{ |controller| user_signed_in? ? "application" : "home" }
Devise::ConfirmationsController.layout "home"
Devise::UnlocksController.layout "home"
Devise::PasswordsController.layout "home"
Doorkeeper::AuthorizationsController.layout "home"
Doorkeeper::AuthorizedApplicationsController.layout "home"
end
# TODO: this should be a macro
config.action_mailer.default_url_options = {protocol: 'https', host: 'YOUR_APP_URL' }
# 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 time:zones:all" for a list of tasks for finding time zone names. Default is UTC.
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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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
# Don't fall back to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = false
config.serve_static_files = false
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Customize form control error state: controls with erroneous input get wrapped with this
config.action_view.field_error_proc = Proc.new { |html_tag, instance|
"<div class=\"field_with_errors has-error\">#{html_tag}</div>".html_safe
}
# Allow embedding as iFrame on external sites
config.action_dispatch.default_headers.merge!({'X-Frame-Options' => 'ALLOWALL'})
# Allow MOSS to work with as many files as it wants
Rack::Utils.multipart_part_limit = 0
# School specific configuration (please edit config/school.yml)
config.school = config_for(:school)
# configure throttling middleware rack-attack
config.middleware.use Rack::Attack
# site version
config.site_version = "2.2.1"
end
end
changed version number to 2.3.0
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(:default, Rails.env)
module Autolab3
class Application < Rails::Application
config.to_prepare do
Devise::ConfirmationsController.skip_before_action :set_course
Devise::ConfirmationsController.skip_before_action :authorize_user_for_course
Devise::ConfirmationsController.skip_before_action :authenticate_for_action
Devise::ConfirmationsController.skip_before_action :update_persistent_announcements
Devise::SessionsController.skip_before_action :set_course
Devise::SessionsController.skip_before_action :authorize_user_for_course
Devise::SessionsController.skip_before_action :authenticate_for_action
Devise::SessionsController.skip_before_action :update_persistent_announcements
Devise::PasswordsController.skip_before_action :set_course
Devise::PasswordsController.skip_before_action :authorize_user_for_course
Devise::PasswordsController.skip_before_action :authenticate_for_action
Devise::PasswordsController.skip_before_action :update_persistent_announcements
Devise::RegistrationsController.skip_before_action :set_course
Devise::RegistrationsController.skip_before_action :authorize_user_for_course
Devise::RegistrationsController.skip_before_action :authenticate_for_action
Devise::RegistrationsController.skip_before_action :update_persistent_announcements
Devise::OmniauthCallbacksController.skip_before_action :set_course
Devise::OmniauthCallbacksController.skip_before_action :authorize_user_for_course
Devise::OmniauthCallbacksController.skip_before_action :authenticate_for_action
Devise::OmniauthCallbacksController.skip_before_action :update_persistent_announcements
Devise::SessionsController.layout "home"
Devise::RegistrationsController.layout proc{ |controller| user_signed_in? ? "application" : "home" }
Devise::ConfirmationsController.layout "home"
Devise::UnlocksController.layout "home"
Devise::PasswordsController.layout "home"
Doorkeeper::AuthorizationsController.layout "home"
Doorkeeper::AuthorizedApplicationsController.layout "home"
end
# TODO: this should be a macro
config.action_mailer.default_url_options = {protocol: 'https', host: 'YOUR_APP_URL' }
# 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 time:zones:all" for a list of tasks for finding time zone names. Default is UTC.
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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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
# Don't fall back to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = false
config.serve_static_files = false
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Customize form control error state: controls with erroneous input get wrapped with this
config.action_view.field_error_proc = Proc.new { |html_tag, instance|
"<div class=\"field_with_errors has-error\">#{html_tag}</div>".html_safe
}
# Allow embedding as iFrame on external sites
config.action_dispatch.default_headers.merge!({'X-Frame-Options' => 'ALLOWALL'})
# Allow MOSS to work with as many files as it wants
Rack::Utils.multipart_part_limit = 0
# School specific configuration (please edit config/school.yml)
config.school = config_for(:school)
# configure throttling middleware rack-attack
config.middleware.use Rack::Attack
# site version
config.site_version = "2.3.0"
end
end
|
# desc "Explaining what the task does"
# task :jasmine-rails do
# # Task goes here
# end
add headless mode for jasmine tests
module JasmineAssetPaths
extend ActiveSupport::Concern
included do
alias_method_chain :compute_public_path, :cached_asset
end
def compute_public_path_with_cached_asset(source, dir, options={})
spec_assets_dir = Rails.root.join('spec/tmp/assets/')
content = Rails.application.assets[source].to_s
source_path = spec_assets_dir.join(source)
FileUtils.mkdir_p File.dirname(source_path)
File.open(source_path, 'w') {|f| f << content }
source_path.to_s
end
end
namespace :jasmine do
desc "run test with phantomjs"
task :phantom => :environment do
tmp_asset_dir = Rails.root.join('spec/tmp/assets')
FileUtils.mkdir_p tmp_asset_dir
ActionView::AssetPaths.send :include, JasmineAssetPaths
app = ActionController::Integration::Session.new(Rails.application)
app.get '/jasmine'
html = app.response.body
File.open(Rails.root.join('spec/tmp/runner.html'), 'w') {|f| f << html}
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module LoveEquation
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.
# 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 = 'Central 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 = :ja
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.serve_static_assets = true
end
end
Rename config
config.serve_static_assets -> config.serve_static_files
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module LoveEquation
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.
# 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 = 'Central 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 = :ja
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.serve_static_files = true
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Exerking
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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.api_only = true
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
end
end
allow put and delete methods
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Exerking
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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.api_only = true
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options, :put, :delete]
end
end
end
end
|
class TopTenIslandsCliGem::Cli
def start
TopTenIslandsCliGem::Island.create_islands_from_hash
puts " "
puts "Welcome to the Worlds Top Islands to visit!!"
puts " "
list
discription
end
def list
TopTenIslandsCliGem::Island.all.each.with_index(1) {|island, index| puts "#{index}. #{island.name}"}
end
def discription
@input = 0
#binding.pry
until @input.to_i.between?(1,10) || @input == "list"
puts " "
puts "What number island would you like to read about? Or type list"
@input = gets.chomp
end
if @input.to_i.between?(1,10)
#binding.pry
@input = @input.to_i
puts ""
puts "--------#{TopTenIslandsCliGem::Island.all[@input-1].name}--------"
puts ""
puts TopTenIslandsCliGem::Island.all[@input-1].get_discription
puts ""
ending
elsif @input == "list"
list
discription
else
discription
end
end
def ending
input = ""
until input == "y" || input == "n"
puts "Would you like to read about another island? Y or N"
input = gets.chomp.downcase
end
case input
when "y"
discription
when "n"
puts "Hope to see you at #{TopTenIslandsCliGem::Island.all[@input-1].name} soon!!"
end
end
end
added list to end method
class TopTenIslandsCliGem::Cli
def start
TopTenIslandsCliGem::Island.create_islands_from_hash
puts " "
puts "Welcome to the Worlds Top Islands to visit!!"
puts " "
list
discription
end
def list
TopTenIslandsCliGem::Island.all.each.with_index(1) {|island, index| puts "#{index}. #{island.name}"}
end
def discription
@input = 0
#binding.pry
until @input.to_i.between?(1,10) || @input == "list"
puts " "
puts "What number island would you like to read about? Or type list"
@input = gets.chomp.downcase
end
if @input.to_i.between?(1,10)
#binding.pry
@input = @input.to_i
puts ""
puts "--------#{TopTenIslandsCliGem::Island.all[@input-1].name}--------"
puts ""
puts TopTenIslandsCliGem::Island.all[@input-1].get_discription
puts ""
ending
elsif @input.downcase == "list"
list
discription
end
end
def ending
input = ""
until input == "y" || input == "n" || input == "list"
puts "Would you like to read about another island? Y,N or list"
input = gets.chomp.downcase
end
case input
when "y"
discription
when "n"
puts "Hope to see you at #{TopTenIslandsCliGem::Island.all[@input-1].name} soon!!"
when "list"
list
discription
end
end
end
|
# -*- encoding : utf-8 -*-
require File.expand_path('../boot', __FILE__)
require 'rails/all'
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
# Bundler.require(:default, :assets, Rails.env)
end
require 'tire/rails/logger'
require 'zip/zip'
require 'yajl/json_gem'
module Otwartezabytki
class Application < Rails::Application
config.autoload_paths += %W(#{config.root}/lib #{config.root}/app/strategies)
ActiveSupport::Dependencies.explicitly_unloadable_constants << 'Polygon'
config.time_zone = 'Warsaw'
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
config.i18n.default_locale = config.i18n.locale = I18n.locale = :pl
config.i18n.available_locales = Settings.oz.locale.available
config.i18n.fallbacks = true
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# 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.
config.active_record.whitelist_attributes = false
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.3'
# generators
config.generators do |g|
g.template_engine :haml
g.test_framework :rspec, :fixture => true, :view_specs => false
g.fixture_replacement :factory_girl, :dir => "spec/factories"
g.stylesheets false
g.javascripts false
end
config.assets.paths << "#{Rails.root}/app/assets/fonts"
config.assets.precompile << /\.(?:svg|eot|woff|ttf)$/
unless ['test', 'development'].include?(Rails.env)
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w( active_admin.js ie8.css iframe.css print.css widgets/* )
config.cache_store = :dalli_store, { :namespace => "otwartezabytki-#{Rails.env}-#{Digest::MD5.hexdigest(Rails.root.to_s[0..31])}", :expires_in => 1.day, :compress => true }
end
config.action_mailer.default_url_options = { :host => Settings.oz.host }
config.action_view.sanitized_allowed_tags = ['table', 'tr', 'td', 'strong', 'em', 'li', 'ul', 'ol', 'a', 'p', 'div', 'del', 'ins']
end
end
dodano jsts do prekompilacji
# -*- encoding : utf-8 -*-
require File.expand_path('../boot', __FILE__)
require 'rails/all'
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
# Bundler.require(:default, :assets, Rails.env)
end
require 'tire/rails/logger'
require 'zip/zip'
require 'yajl/json_gem'
module Otwartezabytki
class Application < Rails::Application
config.autoload_paths += %W(#{config.root}/lib #{config.root}/app/strategies)
ActiveSupport::Dependencies.explicitly_unloadable_constants << 'Polygon'
config.time_zone = 'Warsaw'
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
config.i18n.default_locale = config.i18n.locale = I18n.locale = :pl
config.i18n.available_locales = Settings.oz.locale.available
config.i18n.fallbacks = true
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# 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.
config.active_record.whitelist_attributes = false
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.3'
# generators
config.generators do |g|
g.template_engine :haml
g.test_framework :rspec, :fixture => true, :view_specs => false
g.fixture_replacement :factory_girl, :dir => "spec/factories"
g.stylesheets false
g.javascripts false
end
config.assets.paths << "#{Rails.root}/app/assets/fonts"
config.assets.precompile << /\.(?:svg|eot|woff|ttf)$/
unless ['test', 'development'].include?(Rails.env)
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w( active_admin.js js/jsts.js ie8.css iframe.css print.css widgets/* )
config.cache_store = :dalli_store, { :namespace => "otwartezabytki-#{Rails.env}-#{Digest::MD5.hexdigest(Rails.root.to_s[0..31])}", :expires_in => 1.day, :compress => true }
end
config.action_mailer.default_url_options = { :host => Settings.oz.host }
config.action_view.sanitized_allowed_tags = ['table', 'tr', 'td', 'strong', 'em', 'li', 'ul', 'ol', 'a', 'p', 'div', 'del', 'ins']
end
end
|
module TotallyTabular
class HtmlHelper
def tag(tag, content="", attributes={})
case tag.to_s
when "br"
"<br>"
when "input"
"<input>"
when "img"
"<img>"
when /^\w+$/
if attributes.any?
attr_string =
attr_string = ' %s' % attributes.map { |attr| '%s="%s"' % attr }.join(" ")
end
"<%s%s>%s</%s>" % [tag, attr_string, content, tag]
else
""
end
end
end
end
Refactor html helper
module TotallyTabular
class HtmlHelper
EMPTY_TAG = /br|input|img/
def tag(tag, content="", attributes={})
case tag.to_s
when EMPTY_TAG
"<%s>" % tag
when /^\w+$/
if attributes.any?
attr_string =
attr_string = ' %s' % attributes.map { |attr| '%s="%s"' % attr }.join(" ")
end
"<%s%s>%s</%s>" % [tag, attr_string, content, tag]
else
""
end
end
end
end
|
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SeattlerbOrg
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)
Remove load_defaults
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SeattlerbOrg
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)
|
module Tuning
module ActionView
module Template
extend ActiveSupport::Concern
included do
alias_method_chain :render, :seo
end
def render_with_seo(view, locals, buffer=nil, &block)
output = render_without_seo(view, locals, buffer, &block)
if Rails::VERSION::MAJOR > 3
format = type.symbol
else
format = mime_type.symbol
end
if format == :html and virtual_path and virtual_path.split('/').last.first != '_'
if virtual_path.split('/').first == 'layouts'
%w(title description keywords seo_options).each do |tag|
if view.instance_variable_defined? :"@#{tag}"
view.remove_instance_variable :"@#{tag}"
end
end
else
%w(title description keywords).each do |tag|
unless view.instance_variable_defined? :"@#{tag}"
options = (view.instance_variable_get(:@seo_options) || {}).merge(default: '')
content = I18n.t("#{virtual_path.gsub('/', '.')}.#{tag}", options)
view.instance_variable_set :"@#{tag}", content
end
end
end
end
output
end
end
end
end
Ensure ruby 1.9 compatibility
module Tuning
module ActionView
module Template
extend ActiveSupport::Concern
included do
alias_method_chain :render, :seo
end
def render_with_seo(view, locals, buffer=nil, &block)
output = render_without_seo(view, locals, buffer, &block)
if Rails::VERSION::MAJOR > 3
format = type.symbol
else
format = mime_type.symbol
end
if format == :html and virtual_path and virtual_path.split('/').last.first != '_'
if virtual_path.split('/').first == 'layouts'
%w(title description keywords seo_options).each do |tag|
if view.instance_variable_defined? :"@#{tag}"
view.send :remove_instance_variable, :"@#{tag}"
end
end
else
%w(title description keywords).each do |tag|
unless view.instance_variable_defined? :"@#{tag}"
options = (view.instance_variable_get(:@seo_options) || {}).merge(default: '')
content = I18n.t("#{virtual_path.gsub('/', '.')}.#{tag}", options)
view.instance_variable_set :"@#{tag}", content
end
end
end
end
output
end
end
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Expertiza
class Application < Rails::Application
#This is a logger to capture internal server errors that do not show up when testing javascript. Look in log/diagnostic.txt when there is a 500 error.
if Rails.env == 'test'
require File.expand_path("../diagnostic.rb", __FILE__)
config.middleware.use(MyApp::DiagnosticMiddleware)
end
# Do not access db or load models while precompiling
config.assets.initialize_on_precompile = false
config.time_zone = 'UTC'
#setting the default ssl setting to false
config.use_ssl = false
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
#When you are ready, you can opt into the new behavior and remove the deprecation warning by adding following configuration to your config/application.rb
config.active_record.raise_in_transactional_callbacks = true
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password, :password_confirmation, :password, :password_confirmation]
config.active_record.whitelist_attributes = true
config.autoload_paths += Dir[Rails.root.join('lib', '{**}')]
config.react.addons = true
config.assets.paths << Rails.root.join('vendor', 'assets', 'components')
config.cache_store = :redis_store, "redis://#{ENV.fetch('REDIS_HOST', 'localhost')}:6379/0/cache", { raise_errors: false }
# Bower asset paths
root.join('vendor', 'assets', 'components').to_s.tap do |bower_path|
config.sass.load_paths << bower_path
config.assets.paths << bower_path
end
# Precompile Bootstrap fonts
config.assets.precompile << %r(bootstrap-sass/assets/fonts/bootstrap/[\w-]+\.(?:eot|svg|ttf|woff2?)$)
# Minimum Sass number precision required by bootstrap-sass
::Sass::Script::Value::Number.precision = [8, ::Sass::Script::Value::Number.precision].max
end
module Recaptcha
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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
end
set white list false
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Expertiza
class Application < Rails::Application
#This is a logger to capture internal server errors that do not show up when testing javascript. Look in log/diagnostic.txt when there is a 500 error.
if Rails.env == 'test'
require File.expand_path("../diagnostic.rb", __FILE__)
config.middleware.use(MyApp::DiagnosticMiddleware)
end
# Do not access db or load models while precompiling
config.assets.initialize_on_precompile = false
config.time_zone = 'UTC'
#setting the default ssl setting to false
config.use_ssl = false
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
#When you are ready, you can opt into the new behavior and remove the deprecation warning by adding following configuration to your config/application.rb
config.active_record.raise_in_transactional_callbacks = true
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password, :password_confirmation, :password, :password_confirmation]
config.active_record.whitelist_attributes = false
config.autoload_paths += Dir[Rails.root.join('lib', '{**}')]
config.react.addons = true
config.assets.paths << Rails.root.join('vendor', 'assets', 'components')
config.cache_store = :redis_store, "redis://#{ENV.fetch('REDIS_HOST', 'localhost')}:6379/0/cache", { raise_errors: false }
# Bower asset paths
root.join('vendor', 'assets', 'components').to_s.tap do |bower_path|
config.sass.load_paths << bower_path
config.assets.paths << bower_path
end
# Precompile Bootstrap fonts
config.assets.precompile << %r(bootstrap-sass/assets/fonts/bootstrap/[\w-]+\.(?:eot|svg|ttf|woff2?)$)
# Minimum Sass number precision required by bootstrap-sass
::Sass::Script::Value::Number.precision = [8, ::Sass::Script::Value::Number.precision].max
end
module Recaptcha
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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
end |
require_relative 'boot'
require "rails"
%w(
active_record/railtie
action_controller/railtie
action_view/railtie
rails/test_unit/railtie
sprockets/railtie
).each do |railtie|
begin
require railtie
rescue LoadError
end
end
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Octobox
class Application < Rails::Application
require Rails.root.join('lib/octobox')
config.autoload_paths << Rails.root.join("lib")
end
end
Fix production loading (#405)
In Rails 5, autoload paths are no longer used in the production
environment
require_relative 'boot'
require "rails"
%w(
active_record/railtie
action_controller/railtie
action_view/railtie
rails/test_unit/railtie
sprockets/railtie
).each do |railtie|
begin
require railtie
rescue LoadError
end
end
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Octobox
class Application < Rails::Application
require Rails.root.join('lib/octobox')
config.eager_load_paths << Rails.root.join("lib")
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups(:default, Rails.env))
module Reservations
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}/lib/extras #{config.root}/lib/)
config.watchable_dirs['lib'] = [:rb]
# 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.
config.time_zone = 'Eastern Time (US & Canada)'
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
# 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
# JavaScript files you want as :defaults (application.js is always
# included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = 'utf-8'
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# config.rubycas.cas_base_url = 'https://secure.its.yale.edu/cas/'
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Change the path that assets are served from
# config.assets.prefix = "/assets"
# Add app/assets/fonts to the asset pipeline known paths
config.assets.paths << Rails.root.join('app', 'assets', 'fonts')
# Ensures that each controller doesn't load every helper in the application
config.action_controller.include_all_helpers = false
PermanentRecords.dependent_record_window = 10.seconds
# set up routing options for Reports (at a minimum)
config.after_initialize do
Rails.application.routes.default_url_options =
config.action_mailer.default_url_options
end
end
end
Update application.rb (#1)
* Update application.rb
* Update application.rb
* Update application.rb
* Update application.rb
* Update application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups(:default, Rails.env))
module Reservations
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}/lib/extras #{config.root}/lib/)
config.watchable_dirs['lib'] = [:rb]
# 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.
config.time_zone = 'London'
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
# 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
# JavaScript files you want as :defaults (application.js is always
# included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = 'utf-8'
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# config.rubycas.cas_base_url = 'https://secure.its.yale.edu/cas/'
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Change the path that assets are served from
# config.assets.prefix = "/assets"
# Add app/assets/fonts to the asset pipeline known paths
config.assets.paths << Rails.root.join('app', 'assets', 'fonts')
# Ensures that each controller doesn't load every helper in the application
config.action_controller.include_all_helpers = false
PermanentRecords.dependent_record_window = 10.seconds
# set up routing options for Reports (at a minimum)
config.after_initialize do
Rails.application.routes.default_url_options =
config.action_mailer.default_url_options
end
end
end
|
require "vagrant"
module VagrantPlugins
module DigitalOcean
module Errors
class DigitalOceanError < Vagrant::Errors::VagrantError
error_namespace("vagrant_digital_ocean.errors")
end
class APIStatusError < DigitalOceanError
error_key(:api_status)
end
class JSONError < DigitalOceanError
error_key(:json)
end
class ResultMatchError < DigitalOceanError
error_key(:result_match)
end
class CertificateError < DigitalOceanError
error_key(:certificate)
end
class LocalIPError < DigitalOceanError
error_key(:local_ip)
end
class RsyncError < DigitalOceanError
error_key(:rsync)
class PublicKeyError < DigitalOceanError
error_key(:public_key)
end
end
end
end
Fixed syntax error due to merge.
require "vagrant"
module VagrantPlugins
module DigitalOcean
module Errors
class DigitalOceanError < Vagrant::Errors::VagrantError
error_namespace("vagrant_digital_ocean.errors")
end
class APIStatusError < DigitalOceanError
error_key(:api_status)
end
class JSONError < DigitalOceanError
error_key(:json)
end
class ResultMatchError < DigitalOceanError
error_key(:result_match)
end
class CertificateError < DigitalOceanError
error_key(:certificate)
end
class LocalIPError < DigitalOceanError
error_key(:local_ip)
end
class RsyncError < DigitalOceanError
error_key(:rsync)
end
class PublicKeyError < DigitalOceanError
error_key(:public_key)
end
end
end
end
|
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.dirname(__FILE__), '..', 'lib')
%w(models validators api services).each do |load_path|
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'app', load_path))
end
require 'boot'
Bundler.require :default, ENV['RACK_ENV']
if %w(development test).include?(ENV['RACK_ENV'])
Dotenv.load '.env.local', ".env.#{ENV['RACK_ENV']}", '.env'
end
# Main application module
module LearningRegistry
VERSION = '0.4'.freeze
def self.env
ENV['RACK_ENV']
end
def self.connect
config = StandaloneMigrations::Configurator.new.config_for(env)
ActiveRecord::Base.establish_connection(config)
end
def self.logger
@logger ||= Logger.new(STDOUT)
end
def self.dumps_path
'tmp/dumps'
end
end
LR = LearningRegistry # Alias for application module
ActiveRecord::Base.raise_in_transactional_callbacks = true
LearningRegistry.connect
require 'paper_trail/frameworks/active_record'
require 'base'
Bump version to v0.5
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.dirname(__FILE__), '..', 'lib')
%w(models validators api services).each do |load_path|
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'app', load_path))
end
require 'boot'
Bundler.require :default, ENV['RACK_ENV']
if %w(development test).include?(ENV['RACK_ENV'])
Dotenv.load '.env.local', ".env.#{ENV['RACK_ENV']}", '.env'
end
# Main application module
module LearningRegistry
VERSION = '0.5'.freeze
def self.env
ENV['RACK_ENV']
end
def self.connect
config = StandaloneMigrations::Configurator.new.config_for(env)
ActiveRecord::Base.establish_connection(config)
end
def self.logger
@logger ||= Logger.new(STDOUT)
end
def self.dumps_path
'tmp/dumps'
end
end
LR = LearningRegistry # Alias for application module
ActiveRecord::Base.raise_in_transactional_callbacks = true
LearningRegistry.connect
require 'paper_trail/frameworks/active_record'
require 'base'
|
module VagrantPlugins
module Dotvm
module Injector
class Root < AbstractInjector
def self.inject(config: nil, vc: nil)
config.options.to_h[:ssh].to_a.each do |option|
vc.ssh.send("#{option.name}=", option.value)
end
config.options.to_h[:winrm].to_a.each do |option|
vc.winrm.send("#{option.name}=", option.value)
end
config.options.to_h[:vagrant].to_a.each do |option|
vc.vagrant.send("#{option.name}=", option.value)
end
config.machines.each do |machine_cfg|
Machine.inject machine_cfg: machine_cfg, vc: vc
end
end
end # Root
end # Injector
end # Dotvm
end # VagrantPlugins
make it simpler
module VagrantPlugins
module Dotvm
module Injector
class Root < AbstractInjector
def self.inject(config: nil, vc: nil)
config.options.to_h.each do |category, options|
options.to_a.each do |option|
vc.call(category).call("#{option.name}=", option.value)
end
end
config.machines.each do |machine_cfg|
Machine.inject machine_cfg: machine_cfg, vc: vc
end
end
end # Root
end # Injector
end # Dotvm
end # VagrantPlugins
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module TeamNotes
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.
# 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 = 'Central 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 = :"zh-CN"
config.assets.paths << Rails.root.join("app", "assets", "fonts")
config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif *.svg *.eot *.woff *.ttf)
config.autoload_paths += %W(#{config.root}/app/modules)
end
end
Update application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module TeamNotes
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.
# 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 = 'Central 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.enforce_available_locales = false
config.i18n.available_locales = ["zh-CN"]
config.i18n.default_locale = :'zh-CN'
config.assets.paths << Rails.root.join("app", "assets", "fonts")
config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif *.svg *.eot *.woff *.ttf)
config.autoload_paths += %W(#{config.root}/app/modules)
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
MultiJson.use :yajl
module Docm
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.
config.autoload_paths += %W(#{config.root}/lib)
config.assets.initialize_on_precompile = false
config.data_dump_version = 11
config.data_dump_path = File.join(Rails.root, 'db', 'data.sql')
# 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 = 'Central 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
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:from => 'docm-submissions@genome.wustl.edu',
:address => 'gscsmtp.wustl.edu',
:port => 25,
:domain => 'genome.wustl.edu',
:enable_starttls_auto => false
}
end
end
fix deprecation notice
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
MultiJson.use :yajl
module Docm
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.
config.autoload_paths += %W(#{config.root}/lib)
config.assets.initialize_on_precompile = false
config.data_dump_version = 11
config.data_dump_path = File.join(Rails.root, 'db', 'data.sql')
# 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 = 'Central Time (US & Canada)'
config.active_record.raise_in_transactional_callbacks = true
# 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
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:from => 'docm-submissions@genome.wustl.edu',
:address => 'gscsmtp.wustl.edu',
:port => 25,
:domain => 'genome.wustl.edu',
:enable_starttls_auto => false
}
end
end
|
Resource
Sku resource and sku action were added
module Vtex
class SkuResource < ResourceKit::Resource
resources do
action :sku, 'GET /api/catalog_system/pvt/sku/stockkeepingunitbyid/:sku_id' do
handler(200) { |response| SkuMapping.extract_single(response.body, :read) }
end
end
end
end
|
require_relative 'boot'
require 'rails'
# Pick the frameworks you want:
require 'active_model/railtie'
require 'active_job/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
require 'action_cable/engine'
require 'sprockets/railtie'
# require 'rails/test_unit/railtie'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Prometheus20
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.
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :factory_girl
g.helper false
end
# http://batsov.com/articles/2012/09/12/setting-up-fallback-locale-s-in-rails-3/
# Fallback for empty translations
config.i18n.fallbacks = true
end
end
Configure locales
require_relative 'boot'
require 'rails'
# Pick the frameworks you want:
require 'active_model/railtie'
require 'active_job/railtie'
require 'active_record/railtie'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'action_view/railtie'
require 'action_cable/engine'
require 'sprockets/railtie'
# require 'rails/test_unit/railtie'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Prometheus20
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.
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :factory_girl
g.helper false
end
config.i18n.available_locales = [:en, :uk, :ru, :'pt-BR', :br]
# http://batsov.com/articles/2012/09/12/setting-up-fallback-locale-s-in-rails-3/
config.i18n.fallbacks = { br: [:'pt-BR'] }
end
end
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
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
# Bundler.require(:default, :assets, Rails.env)
end
module Transition
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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Route exceptions to our custom error pages.
config.exceptions_app = self.routes
# 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.
config.active_record.whitelist_attributes = true
# Use db/structure.sql over db/schema.rb because schema.rb is
# DB-agnostic and we're relying on myISAM for speed of hits import
config.active_record.schema_format = :sql
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.assets.precompile += %w(html5.js)
config.assets.precompile += %w(respond.min.js)
end
end
Add lib to autoload
This fixes an undefined constant Transition::OffSiteRedirectChecker in
MappingsController when bulk adding in development.
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
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
# Bundler.require(:default, :assets, Rails.env)
end
module Transition
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}/lib)
# 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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Route exceptions to our custom error pages.
config.exceptions_app = self.routes
# 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.
config.active_record.whitelist_attributes = true
# Use db/structure.sql over db/schema.rb because schema.rb is
# DB-agnostic and we're relying on myISAM for speed of hits import
config.active_record.schema_format = :sql
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.assets.precompile += %w(html5.js)
config.assets.precompile += %w(respond.min.js)
end
end
|
class Wechat::ShakeAround::License
extend Wechat::Core::Common
extend ::Wechat::ShakeAround::Common
extend ::Wechat::ShakeAround::Material
# 上传图片素材
# http://mp.weixin.qq.com/wiki/5/e997428269ff189d8f9a4b9e177be2d9.html
#
# Return hash format if success:
# {
# data: { pic_url: <LICENSE_LINK> },
# errcode: 0,
# errmsg: 'success.'
# }
#
# media 图片完整路径。
def self.create(access_token, media)
assert_present! :access_token, access_token
upload access_token, media, 'license'
end
end
1, Improve the License wrapper class for the argument
validation.
class Wechat::ShakeAround::License
extend Wechat::Core::Common
extend ::Wechat::ShakeAround::Common
extend ::Wechat::ShakeAround::Material
# 上传图片素材
# http://mp.weixin.qq.com/wiki/5/e997428269ff189d8f9a4b9e177be2d9.html
#
# Return hash format if success:
# {
# data: { pic_url: <LICENSE_LINK> },
# errcode: 0,
# errmsg: 'success.'
# }
#
# media 图片完整路径。
def self.create(access_token, media)
assert_present! :access_token, access_token
assert_present! :media, media
upload access_token, media, 'license'
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
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
# Bundler.require(:default, :assets, Rails.env)
end
module Prelaunchr
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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
config.assets.debug = false
# 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.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
config.middleware.use '::Rack::Auth::Basic' do |u, p|
[u, p] == ["ngrefuser", "ngrefpass"]
end
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.ended = false
end
end
heroku precompile fix
require File.expand_path('../boot', __FILE__)
require 'rails/all'
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
# Bundler.require(:default, :assets, Rails.env)
end
module Prelaunchr
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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
config.assets.debug = false
# 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.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
config.assets.initialize_on_precompile = false
config.middleware.use '::Rack::Auth::Basic' do |u, p|
[u, p] == ["ngrefuser", "ngrefpass"]
end
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.ended = false
end
end
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
#require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
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
# Bundler.require(:default, :assets, Rails.env)
end
$stdout.sync = true
module Rubyfriends
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)
config.autoload_paths += %W(#{config.root}/lib)
# 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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.generators do |g|
g.stylesheets false
g.javascripts false
g.helper false
g.test_framework nil
end
# Fix for Heroku asset compilation
config.assets.initialize_on_precompile = false
end
end
remove commented railtie requires
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"
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
# Bundler.require(:default, :assets, Rails.env)
end
$stdout.sync = true
module Rubyfriends
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)
config.autoload_paths += %W(#{config.root}/lib)
# 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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.generators do |g|
g.stylesheets false
g.javascripts false
g.helper false
g.test_framework nil
end
# Fix for Heroku asset compilation
config.assets.initialize_on_precompile = false
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Helpful
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.
config.autoload_paths << File.join(config.root, 'lib')
# Use MiniTest::Spec and FactoryGirl
config.generators do |g|
g.assets false
g.helper false
g.test_framework :mini_test, spec: true, fixture: false
end
# 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 = 'Central 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
config.i18n.enforce_available_locales = true
# Stop assets from accessing models. Useful for Heroku and Devise.
config.assets.initialize_on_precompile = false
# TODO Remove once the Embeddable form is in a seperate repo
config.assets.precompile << 'embed.css'
config.assets.precompile << 'embed.js'
end
end
Change devise layout #192
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Helpful
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.
config.autoload_paths << File.join(config.root, 'lib')
# Use MiniTest::Spec and FactoryGirl
config.generators do |g|
g.assets false
g.helper false
g.test_framework :mini_test, spec: true, fixture: false
end
# 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 = 'Central 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
config.i18n.enforce_available_locales = true
# Stop assets from accessing models. Useful for Heroku and Devise.
config.assets.initialize_on_precompile = false
# TODO Remove once the Embeddable form is in a seperate repo
config.assets.precompile << 'embed.css'
config.assets.precompile << 'embed.js'
config.to_prepare do
Devise::Mailer.layout "email"
end
end
end
|
require 'will_paginate/per_page'
require 'will_paginate/page_number'
require 'will_paginate/collection'
require 'active_record'
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'
#
module ActiveRecord
# makes a Relation look like WillPaginate::Collection
module RelationMethods
include WillPaginate::CollectionMethods
attr_accessor :current_page
attr_writer :total_entries, :wp_count_options
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
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
def offset(value = nil)
if value.nil? then offset_value
else super(value)
end
end
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
def count
if limit_value
excluded = [:order, :limit, :offset]
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
def size
if !loaded? and limit_value and group_values.empty?
[super, limit_value].min
else
super
end
end
# overloaded to be pagination-aware
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
def clone
copy_will_paginate_data super
end
# workaround for Active Record 3.0
def scoped(options = nil)
copy_will_paginate_data super
end
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
private
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
module Pagination
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
def page(num)
rel = scoped.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
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.
#
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
# add limit, offset
query << " LIMIT #{pager.per_page} OFFSET #{pager.offset}"
# 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})"
unless self.connection.adapter_name =~ /^(oracle|oci$)/i
count_query << ' AS count_table'
end
# perform the count query
pager.total_entries = count_by_sql(count_query)
end
end
end
end
# mix everything into Active Record
::ActiveRecord::Base.extend PerPage
::ActiveRecord::Base.extend Pagination
::ActiveRecord::Base.extend BaseMethods
klasses = [::ActiveRecord::Relation]
if defined? ::ActiveRecord::Associations::CollectionProxy
klasses << ::ActiveRecord::Associations::CollectionProxy
else
klasses << ::ActiveRecord::Associations::AssociationCollection
end
# support pagination on associations and scopes
klasses.each { |klass| klass.send(:include, Pagination) }
end
end
Active Record: fix paginate_by_sql for Oracle
require 'will_paginate/per_page'
require 'will_paginate/page_number'
require 'will_paginate/collection'
require 'active_record'
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'
#
module ActiveRecord
# makes a Relation look like WillPaginate::Collection
module RelationMethods
include WillPaginate::CollectionMethods
attr_accessor :current_page
attr_writer :total_entries, :wp_count_options
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
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
def offset(value = nil)
if value.nil? then offset_value
else super(value)
end
end
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
def count
if limit_value
excluded = [:order, :limit, :offset]
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
def size
if !loaded? and limit_value and group_values.empty?
[super, limit_value].min
else
super
end
end
# overloaded to be pagination-aware
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
def clone
copy_will_paginate_data super
end
# workaround for Active Record 3.0
def scoped(options = nil)
copy_will_paginate_data super
end
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
private
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
module Pagination
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
def page(num)
rel = scoped.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
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.
#
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
::ActiveRecord::Base.extend PerPage
::ActiveRecord::Base.extend Pagination
::ActiveRecord::Base.extend BaseMethods
klasses = [::ActiveRecord::Relation]
if defined? ::ActiveRecord::Associations::CollectionProxy
klasses << ::ActiveRecord::Associations::CollectionProxy
else
klasses << ::ActiveRecord::Associations::AssociationCollection
end
# support pagination on associations and scopes
klasses.each { |klass| klass.send(:include, Pagination) }
end
end
|
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 the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Apollog2
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.
# 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 = 'Central 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
end
end
fixed the deprec message about I18n
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 the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Apollog2
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.
# 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 = 'Central 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
I18n.config.enforce_available_locales = false
end
end
|
added script to generate the various types
#!/usr/bin/env ruby
# This script automagically[TM] generates the various "Waifu" types
# (c) 2015 nilsding
$: << File.expand_path('../../../', __FILE__)
require 'yourwaifu/defaults'
require 'erb'
script_name = File.basename __FILE__
types = Dir[YourWaifu::LIST_PATH + '/*.yml'].map{ |x| File.basename(x).sub(/\.yml/, '') }
erb = ERB.new(DATA.read)
types.each do |thing|
puts "require 'yourwaifu/types/#{thing}'"
File.open "#{thing}.rb", 'w' do |f|
f.puts erb.result(binding)
end
end
__END__
# This file was generated by <%= File.basename script_name %>
# <%= Time.now.strftime '%F %T' %>
module YourWaifu
class <%= thing.capitalize %> < YourWaifu::Base
def config_name
'<%= thing %>'
end
end
end
|
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module App
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.
config.autoload_paths += %W["#{config.root}/app/validators/"]
end
end
Add 'fonts' folder to config.assets.paths
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module App
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.
config.autoload_paths += %W["#{config.root}/app/validators/"]
config.assets.paths << Rails.root.join("app", "assets", "fonts")
end
end
|
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Ozfortress
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.
# 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 = 'Central 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
# Autoload lib/
config.autoload_paths += Dir["#{config.root}/lib/**/"]
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
# Make view helpers, view specific
config.action_controller.include_all_helpers = false
end
end
Removed deprecated config
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Ozfortress
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.
# 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 = 'Central 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
# Autoload lib/
config.autoload_paths += Dir["#{config.root}/lib/**/"]
# Make view helpers, view specific
config.action_controller.include_all_helpers = false
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Duckrails
class Application < Rails::Application
VERSION = '0.0.1 beta'
# 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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.autoload_paths += Dir["#{config.root}/lib/**/"]
end
end
Bump version to 1.0.0
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Duckrails
class Application < Rails::Application
VERSION = '1.0.0'
# 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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.autoload_paths += Dir["#{config.root}/lib/**/"]
end
end
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"
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
# Bundler.require(:default, :assets, Rails.env)
end
module ContentStore
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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
# config.active_record.whitelist_attributes = true
end
end
Disable Rack::Cache
As documented here:
https://github.com/alphagov/wiki/wiki/Setting-up-a-new-app#disabling-caching
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"
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
# Bundler.require(:default, :assets, Rails.env)
end
module ContentStore
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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
# config.active_record.whitelist_attributes = true
# Disable Rack::Cache
config.action_dispatch.rack_cache = nil
end
end
|
require File.expand_path("../boot", __FILE__)
require "rails/all"
require "coffee_script"
Bundler.require(*Rails.groups)
module ELMO
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.
# add concerns folders to autoload paths
config.autoload_paths += [
"#{config.root}/app/controllers/concerns",
"#{config.root}/app/controllers/concerns/application_controller",
"#{config.root}/app/models/concerns",
"#{config.root}/lib"
]
# 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.
# default to eastern -- this will be overwritten if there is a timezone setting in the DB
config.time_zone = "Eastern Time (US & Canada)"
# be picky about available locales
config.i18n.enforce_available_locales = false
# 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]
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password, :password_confirmation,
:twilio_account_sid, :twilio_auth_token, :frontlinecloud_api_key,
:session, :warden, :secret, :salt, :cookie, :csrf, :user_credentials, :session_id, :data]
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = "1.0"
# Use Delayed::Job as the ActiveJob queue adapter
config.active_job.queue_adapter = :delayed_job
config.generators do |g|
g.test_framework :rspec
g.integration_framework :rspec
g.orm :active_record, primary_key_type: :uuid
end
####################################
# CUSTOM SETTINGS
####################################
# NOTE: Don't add anymore configatron settings. Use settings.yml instead.
# read system version from file
configatron.system_version = File.read("#{Rails.root}/VERSION").strip
# regular expressions
configatron.lat_lng_regexp = /^(-?\d+(\.\d+)?)\s*[,;:\s]\s*(-?\d+(\.\d+)?)/
# locales with full translations (I18n.available_locales returns a whole bunch more defined by i18n-js)
configatron.full_locales = %i[en fr es ar ko]
# Of the locales in full_locales, the ones displayed RTL.
configatron.rtl_locales = %i[ar]
# For security.
config.action_dispatch.default_headers = { "X-Frame-Options" => "DENY" }
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
# requests-per-minute limit for ODK Collect endpoints
configatron.direct_auth_request_limit = 30
# logins-per-minute threshold for showing a captcha
configatron.login_captcha_threshold = 30
# default timeout for sensitive areas requiring a password reprompt
configatron.recent_login_max_age = 60.minutes
# We use \r\n for CSV row separator because Excel seems to prefer it.
configatron.csv_row_separator = "\r\n"
# Restrict available locales to defined system locales
# This should replace `configatron.full_locales` eventually
# assuming this caused no further issues
I18n.available_locales = configatron.full_locales
# This is the default. It can be overridden in local_config.rb, which comes later.
configatron.offline_mode = false
end
end
Fixed i18n load path
# frozen_string_literal: true
require File.expand_path("../boot", __FILE__)
require "rails/all"
require "coffee_script"
Bundler.require(*Rails.groups)
module ELMO
# Application-wide settings and setup.
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.
# add concerns folders to autoload paths
config.autoload_paths += [
"#{config.root}/app/controllers/concerns",
"#{config.root}/app/controllers/concerns/application_controller",
"#{config.root}/app/models/concerns",
"#{config.root}/lib"
]
# 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.
# default to eastern -- this will be overwritten if there is a timezone setting in the DB
config.time_zone = "Eastern Time (US & Canada)"
# be picky about available locales
config.i18n.enforce_available_locales = false
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join("config", "locales", "**", "*.{rb,yml}")]
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += %i[password password_confirmation
twilio_account_sid twilio_auth_token frontlinecloud_api_key
session warden secret salt cookie csrf user_credentials session_id data]
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = "1.0"
# Use Delayed::Job as the ActiveJob queue adapter
config.active_job.queue_adapter = :delayed_job
config.generators do |g|
g.test_framework :rspec
g.integration_framework :rspec
g.orm :active_record, primary_key_type: :uuid
end
####################################
# CUSTOM SETTINGS
####################################
# NOTE: Don't add anymore configatron settings. Use settings.yml instead.
# read system version from file
configatron.system_version = File.read(Rails.root.join("VERSION")).strip
# regular expressions
configatron.lat_lng_regexp = /^(-?\d+(\.\d+)?)\s*[,;:\s]\s*(-?\d+(\.\d+)?)/
# locales with full translations (I18n.available_locales returns a whole bunch more defined by i18n-js)
configatron.full_locales = %i[en fr es ar ko]
# Of the locales in full_locales, the ones displayed RTL.
configatron.rtl_locales = %i[ar]
# For security.
config.action_dispatch.default_headers = {"X-Frame-Options" => "DENY"}
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
# requests-per-minute limit for ODK Collect endpoints
configatron.direct_auth_request_limit = 30
# logins-per-minute threshold for showing a captcha
configatron.login_captcha_threshold = 30
# default timeout for sensitive areas requiring a password reprompt
configatron.recent_login_max_age = 60.minutes
# We use \r\n for CSV row separator because Excel seems to prefer it.
configatron.csv_row_separator = "\r\n"
# Restrict available locales to defined system locales
# This should replace `configatron.full_locales` eventually
# assuming this caused no further issues
I18n.available_locales = configatron.full_locales
# This is the default. It can be overridden in local_config.rb, which comes later.
configatron.offline_mode = false
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'devise'
Bundler.require(:default, Rails.env)
module Gitlab
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}/lib #{config.root}/app/models/concerns #{config.root}/app/models/project_services)
# 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 = :activity_observer,
:project_activity_cache_observer,
:issue_observer,
:key_observer,
:merge_request_observer,
:note_observer,
:project_observer,
:system_hook_observer,
:user_observer,
:users_group_observer,
:users_project_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.
# config.time_zone = 'Central 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
config.i18n.enforce_available_locales = false
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Uncomment and customize the last line to run in a non-root path
# WARNING: We recommend creating a FQDN to host GitLab in a root path instead of this.
# Note that four settings need to be changed for this to work.
# 1) In your application.rb file: config.relative_url_root = "/gitlab"
# 2) In your gitlab.yml file: relative_url_root: /gitlab
# 3) In your unicorn.rb: ENV['RAILS_RELATIVE_URL_ROOT'] = "/gitlab"
# 4) In ../gitlab-shell/config.yml: gitlab_url: "http://127.0.0.1/gitlab"
# To update the path, run: sudo -u git -H bundle exec rake assets:precompile RAILS_ENV=production
#
# config.relative_url_root = "/gitlab"
config.middleware.use Rack::Attack
# Allow access to GitLab API from other domains
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '/api/*', headers: :any, methods: [:get, :post, :options, :put, :delete]
end
end
end
end
Add emoji images to asset load path.
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'devise'
Bundler.require(:default, Rails.env)
module Gitlab
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}/lib #{config.root}/app/models/concerns #{config.root}/app/models/project_services)
# 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 = :activity_observer,
:project_activity_cache_observer,
:issue_observer,
:key_observer,
:merge_request_observer,
:note_observer,
:project_observer,
:system_hook_observer,
:user_observer,
:users_group_observer,
:users_project_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.
# config.time_zone = 'Central 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
config.i18n.enforce_available_locales = false
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
config.assets.paths << Emoji.images_path
config.assets.precompile << "emoji/*.png"
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Uncomment and customize the last line to run in a non-root path
# WARNING: We recommend creating a FQDN to host GitLab in a root path instead of this.
# Note that four settings need to be changed for this to work.
# 1) In your application.rb file: config.relative_url_root = "/gitlab"
# 2) In your gitlab.yml file: relative_url_root: /gitlab
# 3) In your unicorn.rb: ENV['RAILS_RELATIVE_URL_ROOT'] = "/gitlab"
# 4) In ../gitlab-shell/config.yml: gitlab_url: "http://127.0.0.1/gitlab"
# To update the path, run: sudo -u git -H bundle exec rake assets:precompile RAILS_ENV=production
#
# config.relative_url_root = "/gitlab"
config.middleware.use Rack::Attack
# Allow access to GitLab API from other domains
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '/api/*', headers: :any, methods: [:get, :post, :options, :put, :delete]
end
end
end
end
|
# coding: utf-8
require File.expand_path('../boot', __FILE__)
require "action_controller/railtie"
require "sequel-rails/railtie"
require "action_mailer/railtie"
require_relative '../lib/carto/configuration'
if defined?(Bundler)
Bundler.require(:default, :assets, Rails.env)
end
module CartoDB
class Application < Rails::Application
include Carto::Configuration
# 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.
# config.time_zone = 'Central 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Filter out connector connection credentials. We'd rather filter just 'connector.connection',
# but version 3.x of Rails doesn't support nested parameter filtering.
config.filter_parameters += [:connection]
::Sequel.extension(:pagination)
::Sequel.extension(:connection_validator)
# Enable the asset pipeline
config.assets.enabled = false
FileUtils.mkdir_p(log_dir_path) unless File.directory?(log_dir_path)
config.paths['public'] = [public_uploads_path]
config.assets.paths << Rails.root.join('bower_components')
# Default setting is [/\w+\.(?!js|css).+/, /application.(css|js)$/]
config.assets.precompile = %w(
config.js
app.js
cdb.js
embed.js
dashboard_deps.js
dashboard.js
dashboard_templates.js
public_dashboard_deps.js
public_dashboard.js
data_library_deps.js
data_library.js
public_map.js
public_map_deps.js
editor.js
vendor_editor3.js
common_editor3.js
editor3.js
dataset.js
public_editor3.js
account_templates.js
account_deps.js
account.js
keys_templates.js
keys_deps.js
keys.js
models.js
organization_templates.js
organization_deps.js
organization.js
table.js
public_dashboard.js
public_like.js
tangram.min.js
common.js
old_common.js
old_common_without_core.js
templates.js
templates_mustache.js
specs.js
sessions.js
signup.js
confirmation_templates.js
confirmation.js
new_public_table.js
mobile_apps.js
mobile_apps_templates.js
mobile_apps_deps.js
explore_deps.js
explore.js
user_feed_deps.js
user_feed.js
tipsy.js
modernizr.js
statsc.js
deep_insights.css
cdb.css
cdb/themes/css/cartodb.css
cdb/themes/css/cartodb.ie.css
common.css
old_common.css
dashboard.css
cartodb.css
front.css
editor.css
editor3.css
public_editor3.css
table.css
leaflet.css
map.css
map/leaflet.ie.css
keys.css
organization.css
password_protected.css
public_dashboard.css
public_map.css
data_library.css
public_table.css
sessions.css
user_feed.css
explore.css
mobile_apps.css
api_keys.css
plugins/tipsy.css
*.jpg
*.ico
*.gif
*.png
*.eot
*.otf
*.svg
*.woff
*.ttf
*.swf
)
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
frontend_assets_version = JSON::parse(File.read(Rails.root.join('package.json')))['version']
config.action_controller.relative_url_root = "/assets/#{frontend_assets_version}"
custom_app_views_paths.reverse.each do |custom_views_path|
config.paths['app/views'].unshift(custom_views_path)
end
end
end
require 'csv'
require 'state_machine'
require 'cartodb/controller_flows/public/content'
require 'cartodb/controller_flows/public/datasets'
require 'cartodb/controller_flows/public/maps'
require 'cartodb/errors'
require 'cartodb/logger'
require 'cartodb/connection_pool'
require 'cartodb/pagination'
require 'cartodb/mini_sequel'
require 'cartodb/central'
# require 'importer/lib/cartodb-importer'
require 'importer/lib/cartodb-migrator'
require 'varnish/lib/cartodb-varnish'
$pool = CartoDB::ConnectionPool.new
Carto::CartoGearsSupport.new.gears.reject(&:installable).each do |gear|
$LOAD_PATH << File::join(gear.full_path, 'lib')
require gear.name
end
Fix require for gears support
# coding: utf-8
require File.expand_path('../boot', __FILE__)
require "action_controller/railtie"
require "sequel-rails/railtie"
require "action_mailer/railtie"
require_relative '../lib/carto/configuration'
require_relative '../lib/carto/carto_gears_support'
if defined?(Bundler)
Bundler.require(:default, :assets, Rails.env)
end
module CartoDB
class Application < Rails::Application
include Carto::Configuration
# 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.
# config.time_zone = 'Central 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Filter out connector connection credentials. We'd rather filter just 'connector.connection',
# but version 3.x of Rails doesn't support nested parameter filtering.
config.filter_parameters += [:connection]
::Sequel.extension(:pagination)
::Sequel.extension(:connection_validator)
# Enable the asset pipeline
config.assets.enabled = false
FileUtils.mkdir_p(log_dir_path) unless File.directory?(log_dir_path)
config.paths['public'] = [public_uploads_path]
config.assets.paths << Rails.root.join('bower_components')
# Default setting is [/\w+\.(?!js|css).+/, /application.(css|js)$/]
config.assets.precompile = %w(
config.js
app.js
cdb.js
embed.js
dashboard_deps.js
dashboard.js
dashboard_templates.js
public_dashboard_deps.js
public_dashboard.js
data_library_deps.js
data_library.js
public_map.js
public_map_deps.js
editor.js
vendor_editor3.js
common_editor3.js
editor3.js
dataset.js
public_editor3.js
account_templates.js
account_deps.js
account.js
keys_templates.js
keys_deps.js
keys.js
models.js
organization_templates.js
organization_deps.js
organization.js
table.js
public_dashboard.js
public_like.js
tangram.min.js
common.js
old_common.js
old_common_without_core.js
templates.js
templates_mustache.js
specs.js
sessions.js
signup.js
confirmation_templates.js
confirmation.js
new_public_table.js
mobile_apps.js
mobile_apps_templates.js
mobile_apps_deps.js
explore_deps.js
explore.js
user_feed_deps.js
user_feed.js
tipsy.js
modernizr.js
statsc.js
deep_insights.css
cdb.css
cdb/themes/css/cartodb.css
cdb/themes/css/cartodb.ie.css
common.css
old_common.css
dashboard.css
cartodb.css
front.css
editor.css
editor3.css
public_editor3.css
table.css
leaflet.css
map.css
map/leaflet.ie.css
keys.css
organization.css
password_protected.css
public_dashboard.css
public_map.css
data_library.css
public_table.css
sessions.css
user_feed.css
explore.css
mobile_apps.css
api_keys.css
plugins/tipsy.css
*.jpg
*.ico
*.gif
*.png
*.eot
*.otf
*.svg
*.woff
*.ttf
*.swf
)
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
frontend_assets_version = JSON::parse(File.read(Rails.root.join('package.json')))['version']
config.action_controller.relative_url_root = "/assets/#{frontend_assets_version}"
custom_app_views_paths.reverse.each do |custom_views_path|
config.paths['app/views'].unshift(custom_views_path)
end
end
end
require 'csv'
require 'state_machine'
require 'cartodb/controller_flows/public/content'
require 'cartodb/controller_flows/public/datasets'
require 'cartodb/controller_flows/public/maps'
require 'cartodb/errors'
require 'cartodb/logger'
require 'cartodb/connection_pool'
require 'cartodb/pagination'
require 'cartodb/mini_sequel'
require 'cartodb/central'
# require 'importer/lib/cartodb-importer'
require 'importer/lib/cartodb-migrator'
require 'varnish/lib/cartodb-varnish'
$pool = CartoDB::ConnectionPool.new
Carto::CartoGearsSupport.new.gears.reject(&:installable).each do |gear|
$LOAD_PATH << File::join(gear.full_path, 'lib')
require gear.name
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module RailsRecurlyJsSampleApplication
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.
# 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 = 'Central 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
end
end
Configure trial duration
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module RailsRecurlyJsSampleApplication
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.
# 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 = 'Central 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
config.trial_duration = 14
end
end
|
require File.expand_path('../boot', __FILE__)
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
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
# Bundler.require(:default, :assets, Rails.env)
end
# Monkey-patch Rails to handle the lack of database.yml
class Rails::Application::Configuration
def database_configuration
# There is no config file, so manufacture one
config = {
'test' => 'sqlite3://localhost/:memory:',
'development' => ENV['DATABASE_URL'],
'production' => ENV['DATABASE_URL']
}
config.each_key do |key|
# Based on how Heroku do it: https://gist.github.com/1059446
begin
uri = URI.parse(config[key])
# Values
adapter = uri.scheme
adapter = "postgresql" if adapter == "postgres"
database = (uri.path || "").split("/")[1]
username = uri.user
password = uri.password
host = uri.host
port = uri.port
config[key] = {
'adapter' => adapter,
'database' => database,
'username' => username,
'password' => password,
'host' => host,
'port' => port
}
rescue URI::InvalidURIError
config.delete(key)
end
end
config
end
end
module Miletus
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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Add observers
config.active_record.observers = :rifcs_record_observer,
:oaipmh_output_observer, :sru_rifcs_lookup_observer
end
end
Simplifying DB url monkey patch.
require File.expand_path('../boot', __FILE__)
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
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
# Bundler.require(:default, :assets, Rails.env)
end
# Monkey-patch Rails to handle the lack of database.yml
class Rails::Application::Configuration
def database_configuration
# There is no config file, so manufacture one
config = {
'test' => 'sqlite3://localhost/:memory:',
'development' => ENV['DATABASE_URL'],
'production' => ENV['DATABASE_URL']
}
config.each do |key, value|
env_config = get_database_environment_from_database_url(value)
if env_config.nil?
config.delete(key)
else
config[key] = env_config
end
end
config
end
def get_database_environment_from_database_url(db_url)
# Based on how Heroku do it: https://gist.github.com/1059446
begin
uri = URI.parse(db_url)
return {
'adapter' => adapter == "postgres" ? "postgresql" : uri.scheme,
'database' => (uri.path || "").split("/")[1],
'username' => uri.user,
'password' => uri.password,
'host' => uri.host,
'port' => uri.port
}
rescue URI::InvalidURIError
nil
end
end
end
module Miletus
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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Add observers
config.active_record.observers = :rifcs_record_observer,
:oaipmh_output_observer, :sru_rifcs_lookup_observer
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Hassler
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.
# 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 = 'Central 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
# asset pipeline compatibility
config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)
end
end
manually precompile assets
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Hassler
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.
# 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 = 'Central 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
# asset pipeline compatibility
config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)
config.assets.precompile += ['connectfour.css', 'game.js']
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
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
Bundler.require(:default, :assets, Rails.env)
end
module LivroDaClasse
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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
Rolling bak config/application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
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
# Bundler.require(:default, :assets, Rails.env)
end
module LivroDaClasse
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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'devise'
Bundler.require(:default, Rails.env)
module Gitlab
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}/lib #{config.root}/app/models/concerns #{config.root}/app/models/project_services)
# 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 = :activity_observer,
:project_activity_cache_observer,
:issue_observer,
:key_observer,
:merge_request_observer,
:note_observer,
:project_observer,
:system_hook_observer,
:user_observer,
:users_group_observer,
:users_project_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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Uncomment and customize the last line to run in a non-root path
# WARNING: We recommend creating a FQDN to host GitLab in a root path instead of this.
# Note that four settings need to be changed for this to work.
# 1) In your application.rb file: config.relative_url_root = "/gitlab"
# 2) In your gitlab.yml file: relative_url_root: /gitlab
# 3) In your unicorn.rb: ENV['RAILS_RELATIVE_URL_ROOT'] = "/gitlab"
# 4) In ../gitlab-shell/config.yml: gitlab_url: "http://127.0.0.1/gitlab"
# To update the path, run: sudo -u git -H bundle exec rake assets:precompile RAILS_ENV=production
#
# config.relative_url_root = "/gitlab"
config.middleware.use Rack::Attack
# Allow access to GitLab API from other domains
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '/api/*', headers: :any, methods: [:get, :post, :options, :put, :delete]
end
end
end
end
Fixed the I18n deprecation warning
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'devise'
Bundler.require(:default, Rails.env)
module Gitlab
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}/lib #{config.root}/app/models/concerns #{config.root}/app/models/project_services)
# 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 = :activity_observer,
:project_activity_cache_observer,
:issue_observer,
:key_observer,
:merge_request_observer,
:note_observer,
:project_observer,
:system_hook_observer,
:user_observer,
:users_group_observer,
:users_project_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.
# config.time_zone = 'Central 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
config.i18n.enforce_available_locales = false
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Uncomment and customize the last line to run in a non-root path
# WARNING: We recommend creating a FQDN to host GitLab in a root path instead of this.
# Note that four settings need to be changed for this to work.
# 1) In your application.rb file: config.relative_url_root = "/gitlab"
# 2) In your gitlab.yml file: relative_url_root: /gitlab
# 3) In your unicorn.rb: ENV['RAILS_RELATIVE_URL_ROOT'] = "/gitlab"
# 4) In ../gitlab-shell/config.yml: gitlab_url: "http://127.0.0.1/gitlab"
# To update the path, run: sudo -u git -H bundle exec rake assets:precompile RAILS_ENV=production
#
# config.relative_url_root = "/gitlab"
config.middleware.use Rack::Attack
# Allow access to GitLab API from other domains
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '/api/*', headers: :any, methods: [:get, :post, :options, :put, :delete]
end
end
end
end
|
require 'jsonclient'
class Wechat::ShakeAround::Shaking
extend Wechat::Core::Common
extend Wechat::ShakeAround::Common
# 获取摇周边的设备及用户信息
# http://mp.weixin.qq.com/wiki/3/34904a5db3d0ec7bb5306335b8da1faf.html
#
# Return hash format if success:
# {
# data:
# {
# page_id: <PAGE_ID>,
# openid: <OPEN_ID>,
# poi_id: <POI_ID>,
# beacon_info:
# {
# distance: <DISTANCE>,
# uuid: <UUID>,
# major: <MAJOR>,
# minor: <MINOR>
# }
# },
# errcode: 0,
# errmsg: 'success.'
# }
def self.load(access_token, ticket)
assert_present! :access_token, access_token
assert_present! :ticket, ticket
message = ::JSONClient.new.post "https://api.weixin.qq.com/shakearound/user/getshakeinfo?access_token=#{access_token}",
{
ticket: ticket,
need_poi: 1
}
message.body
end
end
1, Improve the Shaking wrapper class for the HTTP request.
require 'jsonclient'
class Wechat::ShakeAround::Shaking
extend Wechat::Core::Common
extend Wechat::ShakeAround::Common
# 获取摇周边的设备及用户信息
# http://mp.weixin.qq.com/wiki/3/34904a5db3d0ec7bb5306335b8da1faf.html
#
# Return hash format if success:
# {
# data:
# {
# page_id: <PAGE_ID>,
# openid: <OPEN_ID>,
# poi_id: <POI_ID>,
# beacon_info:
# {
# distance: <DISTANCE>,
# uuid: <UUID>,
# major: <MAJOR>,
# minor: <MINOR>
# }
# },
# errcode: 0,
# errmsg: 'success.'
# }
def self.load(access_token, ticket)
assert_present! :access_token, access_token
assert_present! :ticket, ticket
message = post_json "https://api.weixin.qq.com/shakearound/user/getshakeinfo?access_token=#{access_token}", body:
{
ticket: ticket,
need_poi: 1
}
message.body
end
end
|
# frozen_string_literal: true
module Wings
class MultiChecksum < ::Valkyrie::Resource
attribute :sha256, ::Valkyrie::Types::SingleValuedString
attribute :md5, ::Valkyrie::Types::SingleValuedString
attribute :sha1, ::Valkyrie::Types::SingleValuedString
def self.for(file_object)
digests = file_object.checksum(digests: [::Digest::MD5.new, ::Digest::SHA256.new, ::Digest::SHA1.new])
MultiChecksum.new(
md5: digests.shift,
sha256: digests.shift,
sha1: digests.shift
)
end
end
end
wings: remove unused MultiChecksum resource model class
this class isn't used. delete it.
|
require 'fileutils'
require 'yaml'
module ZencoderCLI::Command
class Setup < Base
provides "setup", { "setup" => "Caches authentication credentials",
"setup:delete" => "Removes cached credentials and plugins" }
class << self
def run(args, global_options, command_options)
display("Enter Your Zencoder API Key: ", false)
save_api_key(global_options[:environment], ask)
display("Your API key has been saved to #{home_directory}/.zencoder/api-key.")
end
def delete(args, global_options, command_options)
delete_setup
display("#{home_directory}/.zencoder has been removed.")
end
protected
def save_api_key(environment, api_key)
environment = "production" if !environment || environment.blank?
begin
FileUtils.mkdir_p("#{home_directory}/.zencoder")
if File.exist?("#{home_directory}/.zencoder/api-key")
key_envs = YAML.load_file("#{home_directory}/.zencoder/api-key")
else
key_envs = {}
end
key_envs[environment] = api_key
File.open("#{home_directory}/.zencoder/api-key", 'w') do |out|
YAML.dump(key_envs, out)
end
FileUtils.chmod 0700, "#{home_directory}/.zencoder"
FileUtils.chmod 0600, "#{home_directory}/.zencoder/api-key"
rescue Exception => e
raise e
end
end
def delete_setup
FileUtils.rm_rf("#{home_directory}/.zencoder") if File.exist?("#{home_directory}/.zencoder")
end
end
end
end
Added confirm to setup:delete.
require 'fileutils'
require 'yaml'
module ZencoderCLI::Command
class Setup < Base
provides "setup", { "setup" => "Caches authentication credentials",
"setup:delete" => "Removes cached credentials and plugins" }
class << self
def run(args, global_options, command_options)
display("Enter Your Zencoder API Key: ", false)
save_api_key(global_options[:environment], ask)
display "Your API key has been saved to #{home_directory}/.zencoder/api-key."
end
def delete(args, global_options, command_options)
if confirm
delete_setup
display "#{home_directory}/.zencoder has been removed."
else
display "Ok, nothing changed."
end
end
protected
def save_api_key(environment, api_key)
environment = "production" if !environment || environment.blank?
begin
FileUtils.mkdir_p("#{home_directory}/.zencoder")
if File.exist?("#{home_directory}/.zencoder/api-key")
key_envs = YAML.load_file("#{home_directory}/.zencoder/api-key")
else
key_envs = {}
end
key_envs[environment] = api_key
File.open("#{home_directory}/.zencoder/api-key", 'w') do |out|
YAML.dump(key_envs, out)
end
FileUtils.chmod 0700, "#{home_directory}/.zencoder"
FileUtils.chmod 0600, "#{home_directory}/.zencoder/api-key"
rescue Exception => e
raise e
end
end
def delete_setup
FileUtils.rm_rf("#{home_directory}/.zencoder") if File.exist?("#{home_directory}/.zencoder")
end
end
end
end
|
require 'zendesk_apps_tools/common'
module ZendeskAppsTools
class Settings
def get_settings_from(user_input, parameters)
return {} if parameters.nil?
parameters.inject({}) do |settings, param|
if param[:default]
input = user_input.get_value_from_stdin("Enter a value for parameter '#{param[:name]}' or press 'Return' to use the default value '#{param[:default]}':\n", :allow_empty => true)
input = param[:default] if input.empty?
elsif param[:required]
input = user_input.get_value_from_stdin("Enter a value for required parameter '#{param[:name]}':\n")
else
input = user_input.get_value_from_stdin("Enter a value for optional parameter '#{param[:name]}' or press 'Return' to skip:\n", :allow_empty => true)
end
if param[:type] == 'checkbox' && ![TrueClass, FalseClass].include?(input.class)
input = (input =~ /^(true|t|yes|y|1)$/i) ? true : false
end
settings[param[:name]] = input if input != ''
settings
end
end
end
end
extract a private method to convert the input to boolean
require 'zendesk_apps_tools/common'
module ZendeskAppsTools
class Settings
def get_settings_from(user_input, parameters)
return {} if parameters.nil?
parameters.inject({}) do |settings, param|
if param[:default]
input = user_input.get_value_from_stdin("Enter a value for parameter '#{param[:name]}' or press 'Return' to use the default value '#{param[:default]}':\n", :allow_empty => true)
input = param[:default] if input.empty?
elsif param[:required]
input = user_input.get_value_from_stdin("Enter a value for required parameter '#{param[:name]}':\n")
else
input = user_input.get_value_from_stdin("Enter a value for optional parameter '#{param[:name]}' or press 'Return' to skip:\n", :allow_empty => true)
end
if param[:type] == 'checkbox'
input = convert_to_boolean_for_checkbox(input)
end
settings[param[:name]] = input if input != ''
settings
end
end
private
def convert_to_boolean_for_checkbox(input)
if ![TrueClass, FalseClass].include?(input.class)
return (input =~ /^(true|t|yes|y|1)$/i) ? true : false
end
input
end
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Cartocs
VERSION = '0.1.0'
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.
# config.time_zone = 'Central 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
config.i18n.default_locale = :fr
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Generators replacement
config.generators do |g|
g.test_framework :test_unit, :fixture => false
g.test_framework :shoulda, :fixture => false
g.fallbacks[:shoulda] = :test_unit
g.fixture_replacement :factory_girl, :dir => 'test/factories'
end
end
end
Bump to version 0.2.0
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Cartocs
VERSION = '0.2.0'
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.
# config.time_zone = 'Central 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
config.i18n.default_locale = :fr
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Generators replacement
config.generators do |g|
g.test_framework :test_unit, :fixture => false
g.test_framework :shoulda, :fixture => false
g.fallbacks[:shoulda] = :test_unit
g.fixture_replacement :factory_girl, :dir => 'test/factories'
end
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Hcking
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)
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += %W(#{config.root}/app/presenters)
# 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 ]
# 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 = 'Central Time (US & Canada)'
config.time_zone = "Berlin"
# 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password, :password_confirm]
# Enable the asset pipeline
config.assets.enabled = true
# We do not need rails when precompiling
config.assets.initialize_on_precompile = false
config.assets.precompile += ['active_admin.css', 'active_admin.js', 'active_admin/print.css']
config.assets.version = '1.0'
# Disable Feature "allow external guestes!
config.allow_external_guests = false
# Enforce Available locales (new rails default behavior)
I18n.config.enforce_available_locales = false
# Our weeks in analytics should start on Monday
Groupdate.week_start = :mon
end
end
Explicitely load only certain locales
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Hcking
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)
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += %W(#{config.root}/app/presenters)
# 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 ]
# 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 = 'Central Time (US & Canada)'
config.time_zone = "Berlin"
# The default locale is :de
config.i18n.default_locale = :de
# Only load some locales (especially from the rails-i18n gem)
config.i18n.available_locales = [:de, :en]
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password, :password_confirm]
# Enable the asset pipeline
config.assets.enabled = true
# We do not need rails when precompiling
config.assets.initialize_on_precompile = false
config.assets.precompile += ['active_admin.css', 'active_admin.js', 'active_admin/print.css']
config.assets.version = '1.0'
# Disable Feature "allow external guestes!
config.allow_external_guests = false
# Enforce Available locales (new rails default behavior)
I18n.config.enforce_available_locales = false
# Our weeks in analytics should start on Monday
Groupdate.week_start = :mon
end
end
|
# coding: utf-8
require File.expand_path('../boot', __FILE__)
require "action_controller/railtie"
require "sequel-rails/railtie"
require "action_mailer/railtie"
if defined?(Bundler)
Bundler.require(:default, :assets, Rails.env)
end
# Require optional rails engines
# TODO reactivate in order to enable CartoDB plugins
# Dir["engines" + "/*/*.gemspec"].each do |gemspec_file|
# gem_name = File.basename(gemspec_file, File.extname(gemspec_file))
# puts "** Loading engine #{gem_name}"
# require gem_name
# end
module CartoDB
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.
# config.time_zone = 'Central 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
::Sequel.extension(:pagination)
::Sequel.extension(:connection_validator)
# Enable the asset pipeline
config.assets.enabled = false
config.assets.paths << Rails.root.join('bower_components')
# Default setting is [/\w+\.(?!js|css).+/, /application.(css|js)$/]
config.assets.precompile = %w(
config.js
app.js
cdb.js
embed.js
dashboard_deps.js
dashboard.js
dashboard_templates.js
public_dashboard_deps.js
public_dashboard.js
public_data_dashboard.js
public_map.js
public_map_deps.js
editor.js
account_templates.js
account_deps.js
account.js
keys_templates.js
keys_deps.js
keys.js
models.js
organization_templates.js
organization_deps.js
organization.js
table.js
public_dashboard.js
public_like.js
common.js
old_common.js
old_common_without_core.js
templates.js
templates_mustache.js
specs.js
sessions.js
signup.js
confirmation_templates.js
confirmation.js
new_public_table.js
tipsy.js
modernizr.js
statsc.js
cdb.css
cdb/themes/css/cartodb.css
cdb/themes/css/cartodb.ie.css
common.css
old_common.css
dashboard.css
cartodb.css
fonts_ie.css
fonts.css
front.css
editor.css
table.css
leaflet.css
map.css
map/leaflet.ie.css
keys.css
organization.css
password_protected.css
public_dashboard.css
public_map.css
public_data_dashboard.css
public_table.css
sessions.css
plugins/tipsy.css
*.jpg
*.ico
*.gif
*.png
*.eot
*.otf
*.svg
*.woff
*.ttf
*.swf
)
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
frontend_assets_version = JSON::parse(File.read(Rails.root.join('package.json')))['version']
config.action_controller.relative_url_root = "/assets/#{frontend_assets_version}"
end
end
require 'csv'
require 'state_machine'
require 'cartodb/controller_flows/public/content'
require 'cartodb/controller_flows/public/datasets'
require 'cartodb/controller_flows/public/maps'
require 'cartodb/errors'
require 'cartodb/logger'
require 'cartodb/sql_parser'
require 'cartodb/connection_pool'
require 'cartodb/pagination'
require 'cartodb/mini_sequel'
require 'cartodb/central'
#require 'importer/lib/cartodb-importer'
require 'importer/lib/cartodb-migrator'
require 'varnish/lib/cartodb-varnish'
$pool = CartoDB::ConnectionPool.new
Adds user_feed.js to the list of precompiled files
# coding: utf-8
require File.expand_path('../boot', __FILE__)
require "action_controller/railtie"
require "sequel-rails/railtie"
require "action_mailer/railtie"
if defined?(Bundler)
Bundler.require(:default, :assets, Rails.env)
end
# Require optional rails engines
# TODO reactivate in order to enable CartoDB plugins
# Dir["engines" + "/*/*.gemspec"].each do |gemspec_file|
# gem_name = File.basename(gemspec_file, File.extname(gemspec_file))
# puts "** Loading engine #{gem_name}"
# require gem_name
# end
module CartoDB
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.
# config.time_zone = 'Central 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
::Sequel.extension(:pagination)
::Sequel.extension(:connection_validator)
# Enable the asset pipeline
config.assets.enabled = false
config.assets.paths << Rails.root.join('bower_components')
# Default setting is [/\w+\.(?!js|css).+/, /application.(css|js)$/]
config.assets.precompile = %w(
config.js
app.js
cdb.js
embed.js
dashboard_deps.js
dashboard.js
dashboard_templates.js
public_dashboard_deps.js
public_dashboard.js
public_data_dashboard.js
public_map.js
public_map_deps.js
editor.js
account_templates.js
account_deps.js
account.js
keys_templates.js
keys_deps.js
keys.js
models.js
organization_templates.js
organization_deps.js
organization.js
table.js
public_dashboard.js
public_like.js
common.js
old_common.js
old_common_without_core.js
templates.js
templates_mustache.js
specs.js
sessions.js
signup.js
confirmation_templates.js
confirmation.js
new_public_table.js
user_feed.js
tipsy.js
modernizr.js
statsc.js
cdb.css
cdb/themes/css/cartodb.css
cdb/themes/css/cartodb.ie.css
common.css
old_common.css
dashboard.css
cartodb.css
fonts_ie.css
fonts.css
front.css
editor.css
table.css
leaflet.css
map.css
map/leaflet.ie.css
keys.css
organization.css
password_protected.css
public_dashboard.css
public_map.css
public_data_dashboard.css
public_table.css
sessions.css
plugins/tipsy.css
*.jpg
*.ico
*.gif
*.png
*.eot
*.otf
*.svg
*.woff
*.ttf
*.swf
)
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
frontend_assets_version = JSON::parse(File.read(Rails.root.join('package.json')))['version']
config.action_controller.relative_url_root = "/assets/#{frontend_assets_version}"
end
end
require 'csv'
require 'state_machine'
require 'cartodb/controller_flows/public/content'
require 'cartodb/controller_flows/public/datasets'
require 'cartodb/controller_flows/public/maps'
require 'cartodb/errors'
require 'cartodb/logger'
require 'cartodb/sql_parser'
require 'cartodb/connection_pool'
require 'cartodb/pagination'
require 'cartodb/mini_sequel'
require 'cartodb/central'
#require 'importer/lib/cartodb-importer'
require 'importer/lib/cartodb-migrator'
require 'varnish/lib/cartodb-varnish'
$pool = CartoDB::ConnectionPool.new
|
require_relative 'boot'
require 'rails/all'
require 'active_resource'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Imelavi
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.
# 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 = 'Central 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('config', 'locales','**', '*.{rb,yml}').to_s]
config.i18n.default_locale = :fr
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.autoload_paths << Rails.root.join('lib')
config.generators do |g|
g.test_framework :rspec,
:fixtures => true,
:view_specs => false,
:helper_specs => false,
:routing_specs => false,
:controller_specs => true,
:request_specs => true
g.fixture_replacement :factory_bot, :dir => "spec/factories"
end
end
end
ActiveSupport::Deprecation.behavior = [:stderr, :log]
require File.expand_path('config/extra_config.rb',Rails.root)
RABBITMQ_CONFIG=ExtraConfig.new(File.expand_path("config/rabbitmq.yml",Rails.root),"RABBITMQ")
Remove obsolete active_record.raise_in_transactional_callbacks config
require_relative 'boot'
require 'rails/all'
require 'active_resource'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Imelavi
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.
# 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 = 'Central 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('config', 'locales','**', '*.{rb,yml}').to_s]
config.i18n.default_locale = :fr
# Do not swallow errors in after_commit/after_rollback callbacks.
config.autoload_paths << Rails.root.join('lib')
config.generators do |g|
g.test_framework :rspec,
:fixtures => true,
:view_specs => false,
:helper_specs => false,
:routing_specs => false,
:controller_specs => true,
:request_specs => true
g.fixture_replacement :factory_bot, :dir => "spec/factories"
end
end
end
ActiveSupport::Deprecation.behavior = [:stderr, :log]
require File.expand_path('config/extra_config.rb',Rails.root)
RABBITMQ_CONFIG=ExtraConfig.new(File.expand_path("config/rabbitmq.yml",Rails.root),"RABBITMQ")
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SeattleAttractions
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.
# 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 = 'Central 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
end
end
attempt to fix invalid authenticity token error on ajax form, now getting missing template error
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SeattleAttractions
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.
# 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 = 'Central 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
config.action_view.embed_authenticity_token_in_remote_forms = true
end
end
|
require File.expand_path('../boot', __FILE__)
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Stackoverflow
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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
require pg_search (was causing probs in console)
require File.expand_path('../boot', __FILE__)
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
require 'pg_search'
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Stackoverflow
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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Prxcast
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.
# 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 = 'Central 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
config.active_job.queue_adapter = :shoryuken
config.active_job.queue_name_prefix = Rails.env
config.active_job.queue_name_delimiter = '_'
config.active_record.raise_in_transactional_callbacks = true
end
end
rename to feeder, add version for generator value
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Feeder
VERSION = '1.0.0'
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.
# 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 = 'Central 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
config.active_job.queue_adapter = :shoryuken
config.active_job.queue_name_prefix = Rails.env
config.active_job.queue_name_delimiter = '_'
config.active_record.raise_in_transactional_callbacks = true
end
end
|
require File.expand_path('../boot', __FILE__)
require "active_model/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
Bundler.require(*Rails.groups)
module Gov
class Application < Rails::Application
# 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 = 'Central Time (US & Canada)'
config.i18n.default_locale = :bg
end
end
Set the time zone to Sofia
require File.expand_path('../boot', __FILE__)
require "active_model/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
Bundler.require(*Rails.groups)
module Gov
class Application < Rails::Application
config.time_zone = 'Sofia'
config.i18n.default_locale = :bg
end
end
|
require File.expand_path('../boot', __FILE__)
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
require 'open-uri'
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Pretender
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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.serve_static_assets = true
end
end
most recent asset pipeline issue fixed, image and overlay working
require File.expand_path('../boot', __FILE__)
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
require 'open-uri'
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Pretender
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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.serve_static_files = true
end
end
|
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Formaggio
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.
#Emoji
config.assets.paths << Gemojione.images_path
config.assets.precompile << "emoji/*.png"
config.assets.precompile << "emoji/*.svg"
config.assets.paths << Gemojione.sprites_path
config.assets.precompile << "emojione.sprites.css"
config.assets.precompile << "emojione.sprites.png"
config.middleware.insert 0, Rack::UTF8Sanitizer
config.encoding = "utf-8"
Encoding.default_internal = Encoding::UTF_8
Encoding.default_external = Encoding::UTF_8
end
end
#16 - heroku - NoMethodError: undefined method images_path for Gemojione:Module
Signed-off-by: Wellington Torrejais da Silva <3eb82f72b586c115fda9ecc045094c10d61255a4@gmail.com>
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Formaggio
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.
#Emoji
#config.assets.paths << Gemojione.images_path
config.assets.precompile << "emoji/*.png"
config.assets.precompile << "emoji/*.svg"
config.assets.paths << Gemojione.sprites_path
config.assets.precompile << "emojione.sprites.css"
config.assets.precompile << "emojione.sprites.png"
config.middleware.insert 0, Rack::UTF8Sanitizer
config.encoding = "utf-8"
Encoding.default_internal = Encoding::UTF_8
Encoding.default_external = Encoding::UTF_8
end
end
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource"
require "sprockets/railtie"
require "rails/test_unit/railtie"
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
# Bundler.require(:default, :assets, Rails.env)
end
module Foodcloud
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)
config.autoload_paths += %W(#{config.root}/lib)
# 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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
# config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.assets.precompile += ['menu_editor.js']
end
end
prolly shouldnt be pushing like this. oh well
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource"
require "sprockets/railtie"
require "rails/test_unit/railtie"
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
# Bundler.require(:default, :assets, Rails.env)
end
module Foodcloud
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)
config.autoload_paths += %W(#{config.root}/lib)
# 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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
# config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.assets.precompile += ['menu_editor.js','interactive_menu.js']
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
module Abilitysheet
class Application < Rails::Application
config.time_zone = 'Tokyo'
config.active_record.default_timezone = :local
config.i18n.default_locale = :ja
config.generators.template_engine = :slim
config.generators.helper = false
config.generators.assets = false
# copyright
config.copyright = 'IIDX☆12参考表 by839 2014-2015'
# Current git revision
config.git_revision = `git log --abbrev-commit --pretty=oneline | head -1 | cut -d' ' -f1`
# Current IIDX version
config.iidx_version = 22
# Current IIDX grade
config.iidx_grade = 0
# lib auto load
config.autoload_paths += %W(#{config.root}/lib)
# api auto load
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api')]
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]
# test_framework
config.generators.test_framework = 'rspec'
config.assets.paths << Rails.root.join('vendor', 'assets', 'bower_components')
SLACK_URI = URI.parse(ENV['NOTIFY_SLACK_URL'])
end
end
refs #279 slackのURLが指定されていない場合の処理を追加
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
module Abilitysheet
class Application < Rails::Application
config.time_zone = 'Tokyo'
config.active_record.default_timezone = :local
config.i18n.default_locale = :ja
config.generators.template_engine = :slim
config.generators.helper = false
config.generators.assets = false
# copyright
config.copyright = 'IIDX☆12参考表 by839 2014-2015'
# Current git revision
config.git_revision = `git log --abbrev-commit --pretty=oneline | head -1 | cut -d' ' -f1`
# Current IIDX version
config.iidx_version = 22
# Current IIDX grade
config.iidx_grade = 0
# lib auto load
config.autoload_paths += %W(#{config.root}/lib)
# api auto load
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api')]
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]
# test_framework
config.generators.test_framework = 'rspec'
config.assets.paths << Rails.root.join('vendor', 'assets', 'bower_components')
SLACK_URI = URI.parse(ENV['NOTIFY_SLACK_URL']) if ENV['NOTIFY_SLACK_URL']
end
end
|
require_relative 'boot'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "action_cable/engine"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module TruckTrack
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# 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.
# Only loads a smaller set of middleware suitable for API only apps.
# Middleware like session, flash, cookies can be added back manually.
# Skip views, helpers and assets when generating a new resource.
config.api_only = true
end
end
added /lib to the autoloaded paths
require_relative 'boot'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "action_cable/engine"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module TruckTrack
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# 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.
# add lib/ to the autoloaded paths
config.autoload_paths << Rails.root.join('lib')
# Only loads a smaller set of middleware suitable for API only apps.
# Middleware like session, flash, cookies can be added back manually.
# Skip views, helpers and assets when generating a new resource.
config.api_only = true
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
Bundler.require(:default, Rails.env)
end
module DchousingApps
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}/lib)
# 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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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
# Enable the asset pipeline
config.assets.enabled = true
config.assets.initialize_on_precompile = false
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# TODO Remove this in Rails 4.1
config.secret_key_base = YAML.load(File.open("#{Rails.root}/config/secrets.yml"))[Rails.env]['secret_key_base']
config.i18n.enforce_available_locales = true
end
end
Don't require attr_accessible for model attibutes set by params
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
Bundler.require(:default, Rails.env)
end
module DchousingApps
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}/lib)
# 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.
# config.time_zone = 'Central 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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
# Enable the asset pipeline
config.assets.enabled = true
config.assets.initialize_on_precompile = false
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# TODO Remove this in Rails 4.1
config.secret_key_base = YAML.load(File.open("#{Rails.root}/config/secrets.yml"))[Rails.env]['secret_key_base']
config.i18n.enforce_available_locales = true
# Don't require attr_accessible for model attibutes set by params
config.active_record.whitelist_attributes = false
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Classroom
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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
# Add bower assets to the path
root.join('vendor', 'assets', 'bower_components').to_s.tap do |bower_path|
config.sass.load_paths << bower_path
config.assets.paths << bower_path
end
# Append directories to autoload paths
config.autoload_paths += Dir["#{Rails.root}/lib"]
# Precompile Fonts
# Compile all font types except octicons-local
config.assets.precompile << %r(octicons/octicons/octicons+\.(?:svg|eot|woff|ttf)$)
# Configure the generators
config.generators do |g|
g.test_framework :rspec, fixture: false
end
# GC Profiler for analytics
GC::Profiler.enable
# Use SideKiq for background jobs
config.active_job.queue_adapter = :sidekiq
# Health checks endpoint for monitoring
if ENV['PINGLISH_ENABLED'] == 'true'
config.middleware.use Pinglish do |ping|
ping.check :db do
ActiveRecord::Base.connection.tables.size
'ok'
end
ping.check :memcached do
ActiveSupport::Cache.lookup_store(:dalli_store).stats.values.include? nil
'ok'
end
ping.check :redis do
Sidekiq.redis { |redis| redis.ping }
'ok'
end
end
end
end
end
use `Dalli#client.alive!` to check memcached connection
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Classroom
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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
# Add bower assets to the path
root.join('vendor', 'assets', 'bower_components').to_s.tap do |bower_path|
config.sass.load_paths << bower_path
config.assets.paths << bower_path
end
# Append directories to autoload paths
config.autoload_paths += Dir["#{Rails.root}/lib"]
# Precompile Fonts
# Compile all font types except octicons-local
config.assets.precompile << %r(octicons/octicons/octicons+\.(?:svg|eot|woff|ttf)$)
# Configure the generators
config.generators do |g|
g.test_framework :rspec, fixture: false
end
# GC Profiler for analytics
GC::Profiler.enable
# Use SideKiq for background jobs
config.active_job.queue_adapter = :sidekiq
# Health checks endpoint for monitoring
if ENV['PINGLISH_ENABLED'] == 'true'
config.middleware.use Pinglish do |ping|
ping.check :db do
ActiveRecord::Base.connection.tables.size
'ok'
end
ping.check :memcached do
Rails.cache.dalli.with_connection do |connection|
connection.alive!
end
'ok'
end
ping.check :redis do
Sidekiq.redis { |redis| redis.ping }
'ok'
end
end
end
end
end
|
class Glpk < Formula
desc "Library for Linear (LP) and Mixed-Integer Programming (MIP)"
homepage "https://www.gnu.org/software/glpk/"
url "https://ftpmirror.gnu.org/glpk/glpk-4.61.tar.gz"
mirror "https://ftp.gnu.org/gnu/glpk/glpk-4.61.tar.gz"
sha256 "9866de41777782d4ce21da11b88573b66bb7858574f89c28be6967ac22dfaba9"
bottle do
cellar :any
sha256 "6e8074de7e8208178e2f60948e5d938d9d5f8f256323ef7846294d5888ec269c" => :sierra
sha256 "33d07d0c1f0fb2350e2d1efbbd31115cc590c7367ae3d2cf3390928261015a60" => :el_capitan
sha256 "c9e2ac11b4bfc18f0ec86572c4b368239366242086bc485e79333bebebfaef36" => :yosemite
sha256 "5a3a441f6b0b07e17cc933b40cf24f231f332021f03258e95aba9d8653784dc2" => :mavericks
sha256 "4048de9e46db1bcc7e10a96cce052c7b7bb7d13b38ca25d741cdec1f265ded7b" => :x86_64_linux
end
depends_on "gmp" => :recommended
def install
args = %W[--disable-dependency-tracking --prefix=#{prefix}]
args << "--with-gmp" if build.with? "gmp"
system "./configure", *args
system "make"
system "make", "check"
system "make", "install"
end
test do
(testpath/"test.c").write <<-EOF.undent
#include "stdio.h"
#include "glpk.h"
int main(int argc, const char *argv[])
{
printf("%s", glp_version());
return 0;
}
EOF
system ENV.cc, "test.c", "-L#{lib}", "-I#{include}", "-lglpk", "-o", "test"
assert_match version.to_s, shell_output("./test")
end
end
glpk: update 4.61 bottle.
class Glpk < Formula
desc "Library for Linear (LP) and Mixed-Integer Programming (MIP)"
homepage "https://www.gnu.org/software/glpk/"
url "https://ftpmirror.gnu.org/glpk/glpk-4.61.tar.gz"
mirror "https://ftp.gnu.org/gnu/glpk/glpk-4.61.tar.gz"
sha256 "9866de41777782d4ce21da11b88573b66bb7858574f89c28be6967ac22dfaba9"
bottle do
cellar :any
sha256 "4f03fce647763acf07b4d7b158fc1c10d324ccc3e3536cd8f3cf3fcfbe312d13" => :sierra
sha256 "13e284d8a723a54617ffa3f61114070833d7d6b21848fecdfe6a1175893bbebc" => :el_capitan
sha256 "4a9997de364745c6a6c063773078a9e34865a81aea65c45d8443f01794fd5798" => :yosemite
end
depends_on "gmp" => :recommended
def install
args = %W[--disable-dependency-tracking --prefix=#{prefix}]
args << "--with-gmp" if build.with? "gmp"
system "./configure", *args
system "make"
system "make", "check"
system "make", "install"
end
test do
(testpath/"test.c").write <<-EOF.undent
#include "stdio.h"
#include "glpk.h"
int main(int argc, const char *argv[])
{
printf("%s", glp_version());
return 0;
}
EOF
system ENV.cc, "test.c", "-L#{lib}", "-I#{include}", "-lglpk", "-o", "test"
assert_match version.to_s, shell_output("./test")
end
end
|
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 the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module HeisenBugDev
class Application < Rails::Application
# don't generate RSpec tests for views and helpers
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :factory_girl, dir: 'spec/factories'
g.view_specs false
g.helper_specs false
end
config.assets.initialize_on_precompile = false
config.i18n.enforce_available_locales = true
# 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.
# 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 = 'Central 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
end
end
we shoukdn't need taht
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 the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module HeisenBugDev
class Application < Rails::Application
# don't generate RSpec tests for views and helpers
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :factory_girl, dir: 'spec/factories'
g.view_specs false
g.helper_specs false
end
config.i18n.enforce_available_locales = true
# 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.
# 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 = 'Central 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
end
end
|
require_relative "boot"
require "rails/all"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module LoveEquation
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
# Default locale Japanese
config.i18n.default_locale = :ja
Rails.application.config.action_controller.urlsafe_csrf_tokens = false
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
end
end
Fix DEPRECATION WARNING
- Using legacy connection handling is deprecated. Please set `legacy_connection_handling` to `false` in your application.
require_relative "boot"
require "rails/all"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module LoveEquation
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
# Default locale Japanese
config.i18n.default_locale = :ja
Rails.application.config.action_controller.urlsafe_csrf_tokens = false
config.active_record.legacy_connection_handling = false
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
require 'activerecord-import' # doesn't auto-require properly
# patch for https://github.com/mikel/mail/pull/782 / https://github.com/rubinius/rubinius/issues/3050
module Mail
class PartsList
def sort_by args = nil
p "custom sort_by - args: #{args.inspect}, self: #{self.inspect}"
(self.empty? or args.blank?) ? self : super(args)
end
end
end
module MakeyourlawsOrg
class Application < Rails::Application
config.logger = Rubinius::RailsLogger.new 'mylfrontend'
# 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)
config.autoload_paths += [Rails.root.join('lib'), Rails.root.join('lib', '{**}')]
# Don't do this. See http://stackoverflow.com/questions/12467847/rails-namespaced-model-conflicting-with-non-namespaced-model
# config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]
config.middleware.insert_after ActionDispatch::RemoteIp, Rack::TorTag,
host_ips: ['173.255.252.140']
config.middleware.use Rack::Attack
Rack::Attack.cache.store = Redis::Store.new(db: 5)
# 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.
# config.time_zone = 'Central 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.enforce_available_locales = true
config.i18n.default_locale = :en
# Rails 4.2.0+. Current coinbase & bitpay not yet compatible.
# Do not swallow errors in after_commit/after_rollback callbacks.
# config.active_record.raise_in_transactional_callbacks = true
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = 'utf-8'
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
# config.active_record.whitelist_attributes = true
config.action_mailer.default_options = {
from: 'MYL Robot <no-reply@makeyourlaws.org>'
}
config.cache_store = :redis_store, { db: 1 }
# Enable the asset pipeline
# config.assets.enabled = true
# Disabling to allow mod_pagespeed to take over
config.assets.enabled = false
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
# TODO: Expand once we start doing more than just US states
JURISDICTIONS = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado',
'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois',
'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland',
'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana',
'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York',
'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania',
'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah',
'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming',
'District of Columbia', 'Puerto Rico', 'Guam', 'American Samoa',
'U.S. Virgin Islands', 'Northern Mariana Islands']
guard rbx logger for rbx env only
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
require 'activerecord-import' # doesn't auto-require properly
# patch for https://github.com/mikel/mail/pull/782 / https://github.com/rubinius/rubinius/issues/3050
module Mail
class PartsList
def sort_by args = nil
p "custom sort_by - args: #{args.inspect}, self: #{self.inspect}"
(self.empty? or args.blank?) ? self : super(args)
end
end
end
module MakeyourlawsOrg
class Application < Rails::Application
if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx'
config.logger = Rubinius::RailsLogger.new 'mylfrontend'
end
# 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)
config.autoload_paths += [Rails.root.join('lib'), Rails.root.join('lib', '{**}')]
# Don't do this. See http://stackoverflow.com/questions/12467847/rails-namespaced-model-conflicting-with-non-namespaced-model
# config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]
config.middleware.insert_after ActionDispatch::RemoteIp, Rack::TorTag,
host_ips: ['173.255.252.140']
config.middleware.use Rack::Attack
Rack::Attack.cache.store = Redis::Store.new(db: 5)
# 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.
# config.time_zone = 'Central 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.enforce_available_locales = true
config.i18n.default_locale = :en
# Rails 4.2.0+. Current coinbase & bitpay not yet compatible.
# Do not swallow errors in after_commit/after_rollback callbacks.
# config.active_record.raise_in_transactional_callbacks = true
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = 'utf-8'
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
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.
# config.active_record.whitelist_attributes = true
config.action_mailer.default_options = {
from: 'MYL Robot <no-reply@makeyourlaws.org>'
}
config.cache_store = :redis_store, { db: 1 }
# Enable the asset pipeline
# config.assets.enabled = true
# Disabling to allow mod_pagespeed to take over
config.assets.enabled = false
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
end
end
# TODO: Expand once we start doing more than just US states
JURISDICTIONS = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado',
'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois',
'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland',
'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana',
'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York',
'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania',
'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah',
'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming',
'District of Columbia', 'Puerto Rico', 'Guam', 'American Samoa',
'U.S. Virgin Islands', 'Northern Mariana Islands']
|
require File.expand_path('../boot', __FILE__)
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
# require "active_job/railtie"
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
# require "action_view/railtie"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module RouterApi
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.
# 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 = 'Central 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
#config.i18n.enforce_available_locales = true
end
end
Configurable log path
This makes it relatively easy to have a differently name draft log file for
when two instances of this app are running in docker containers.
require File.expand_path('../boot', __FILE__)
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
# require "active_job/railtie"
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
# require "action_view/railtie"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module RouterApi
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.
# 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 = 'Central 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
#config.i18n.enforce_available_locales = true
config.paths["log"] = ENV["LOG_PATH"] if ENV["LOG_PATH"]
end
end
|
require File.expand_path('../boot', __FILE__)
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
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
# Bundler.require(:default, :assets, Rails.env)
end
module Halloped
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}/lib)
# 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.
# config.time_zone = 'Central 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 = :fi
# Fallbacks are configured to work only for dynamic values stored in database
# Fallbacks are not supported for static strings that come from locales/:locale.yml files
# See also initializers/i18n.rb
# Note: Defining "config.i18n.fallbacks = false" and defining fallback maps in i18n.rb
# seems to be only way to make this work correctly.
config.i18n.fallbacks = false
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# 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.
# config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.generators do |g|
g.test_framework :rspec, :fixture => true, :views => false, :fixture_replacement => :factory_girl, :view_specs => false
g.fixture_replacement :factory_girl, :dir=>"spec/factories"
end
end
def self.languages
[:fi, :sv, :en].concat(I18n.available_locales).uniq
end
end
Remove the automatic addition of available locales as supported languages.
require File.expand_path('../boot', __FILE__)
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
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
# Bundler.require(:default, :assets, Rails.env)
end
module Halloped
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}/lib)
# 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.
# config.time_zone = 'Central 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 = :fi
# Fallbacks are configured to work only for dynamic values stored in database
# Fallbacks are not supported for static strings that come from locales/:locale.yml files
# See also initializers/i18n.rb
# Note: Defining "config.i18n.fallbacks = false" and defining fallback maps in i18n.rb
# seems to be only way to make this work correctly.
config.i18n.fallbacks = false
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# 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.
# config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.generators do |g|
g.test_framework :rspec, :fixture => true, :views => false, :fixture_replacement => :factory_girl, :view_specs => false
g.fixture_replacement :factory_girl, :dir=>"spec/factories"
end
end
def self.languages
[:fi, :sv, :en]
end
end
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module PRX
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.
# 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 = 'Central 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
I18n.config.enforce_available_locales = true
config.i18n.enforce_available_locales = true
config.i18n.default_locale = :en
config.autoload_paths += %W( #{config.root}/app/representers/concerns )
# Disable the asset pipeline.
config.assets.enabled = false
config.generators do |g|
g.test_framework :mini_test, spec: true, fixture: false
end
config.middleware.insert_after Rails::Rack::Logger, Rack::Cors do
allow do
origins /.*\.prx\.(?:org|dev|tech|docker)$/
resource '/api/*', methods: [:get, :put, :post, :options], headers: :any
end
allow do
origins '*'
resource '/api/*', methods: [:get]
end
end
config.active_job.queue_adapter = :shoryuken
config.active_job.queue_name_prefix = Rails.env
config.active_job.queue_name_delimiter = '_'
config.active_record.raise_in_transactional_callbacks = true
prx_url_options = { host: ENV['PRX_HOST'], protocol: 'https' }
config.action_mailer.default_url_options = prx_url_options
cms_url_options = { host: ENV['CMS_HOST'], protocol: 'https' }
Rails.application.routes.default_url_options = cms_url_options
end
end
Allow cross origin deletes
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module PRX
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.
# 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 = 'Central 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
I18n.config.enforce_available_locales = true
config.i18n.enforce_available_locales = true
config.i18n.default_locale = :en
config.autoload_paths += %W( #{config.root}/app/representers/concerns )
# Disable the asset pipeline.
config.assets.enabled = false
config.generators do |g|
g.test_framework :mini_test, spec: true, fixture: false
end
config.middleware.insert_after Rails::Rack::Logger, Rack::Cors do
allow do
origins /.*\.prx\.(?:org|dev|tech|docker)$/
resource '/api/*', methods: [:get, :put, :post, :delete, :options], headers: :any
end
allow do
origins '*'
resource '/api/*', methods: [:get]
end
end
config.active_job.queue_adapter = :shoryuken
config.active_job.queue_name_prefix = Rails.env
config.active_job.queue_name_delimiter = '_'
config.active_record.raise_in_transactional_callbacks = true
prx_url_options = { host: ENV['PRX_HOST'], protocol: 'https' }
config.action_mailer.default_url_options = prx_url_options
cms_url_options = { host: ENV['CMS_HOST'], protocol: 'https' }
Rails.application.routes.default_url_options = cms_url_options
end
end
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Publisher
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}/lib #{config.root}/app/presenters)
config.generators do |g|
g.orm :mongoid
g.template_engine :erb # this could be :haml or whatever
g.test_framework :test_unit, :fixture => false # this could be :rpsec or whatever
end
# 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.
# config.time_zone = 'Central 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
end
end
require 'open-uri'
require 'builder'
# This configuration is suitable for development, it should be managed by puppet
# in production.
# TODO: Check if this is thread/forked process safe under passenger. Possible risk
# that client connections get copied when passenger forks a process but the mutexes
# protecting those connections do not.
require 'messenger'
if File.basename($0) != "rake" && !Rails.env.test?
Messenger.transport = Stomp::Client.new "stomp://localhost:61613"
end
Object.send :include, Pethau::InitializeWith
remove the stomp connection for the moment
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Publisher
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}/lib #{config.root}/app/presenters)
config.generators do |g|
g.orm :mongoid
g.template_engine :erb # this could be :haml or whatever
g.test_framework :test_unit, :fixture => false # this could be :rpsec or whatever
end
# 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.
# config.time_zone = 'Central 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
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
end
end
require 'open-uri'
require 'builder'
# This configuration is suitable for development, it should be managed by puppet
# in production.
# TODO: Check if this is thread/forked process safe under passenger. Possible risk
# that client connections get copied when passenger forks a process but the mutexes
# protecting those connections do not.
require 'messenger'
Object.send :include, Pethau::InitializeWith
|
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SaferstallsRails
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.0
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
config.middleware.insert_before 0, Rack::Cors do
allow do
origins "*"
resource "/api/*", headers: :any, methods: [:get, :post, :options]
end
end
# I18n stuff
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
config.i18n.available_locales = [:en, :es, :fil, :fr, :hi, :it, :pl, :"pt-BR"]
config.i18n.default_locale = :en
end
end
config/application.rb: Add Tagalog (:tl) locale
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module SaferstallsRails
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.0
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
config.middleware.insert_before 0, Rack::Cors do
allow do
origins "*"
resource "/api/*", headers: :any, methods: [:get, :post, :options]
end
end
# I18n stuff
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
config.i18n.available_locales = [:en, :es, :fil, :fr, :hi, :it, :pl, :"pt-BR", :tl]
config.i18n.default_locale = :en
end
end
|
require 'dotenv'
if %w[development test].include?(ENV['RACK_ENV'])
Dotenv.load(
".env.#{ENV['RACK_ENV']}.local",
'.env.local',
".env.#{ENV['RACK_ENV']}",
'.env'
)
end
Load Dotenv in dev & test envs only
if %w[development test].include?(ENV['RACK_ENV'])
require 'dotenv'
Dotenv.load(
".env.#{ENV['RACK_ENV']}.local",
'.env.local',
".env.#{ENV['RACK_ENV']}",
'.env'
)
end
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_model/railtie"
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Pf
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.
# 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 = 'Central 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
config.generators.stylesheets = false
config.generators.javascripts = false
config.generators.helper = false
config.generators.jbuilder = false
config.sass.preferred_syntax = :sass
config.time_zone = "Pacific Time (US & Canada)"
CarrierWave.configure do |c|
c.storage = :grid_fs
c.root = Rails.root.join('tmp')
c.cache_dir = "uploads"
c.grid_fs_access_url = "/upload/grid"
end
end
end
carrierwave: change cache_dir to something more explicit
This more human-friendly, as 'uploads' is too close to just 'upload'.
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_model/railtie"
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Pf
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.
# 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 = 'Central 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
config.generators.stylesheets = false
config.generators.javascripts = false
config.generators.helper = false
config.generators.jbuilder = false
config.sass.preferred_syntax = :sass
config.time_zone = "Pacific Time (US & Canada)"
CarrierWave.configure do |c|
c.storage = :grid_fs
c.root = Rails.root.join('tmp')
c.cache_dir = "upload-cache"
c.grid_fs_access_url = "/upload/grid"
end
end
end
|
require_relative "boot"
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
# require "active_record/railtie"
# require "active_storage/engine"
require "action_controller/railtie"
require "action_mailer/railtie"
# require "action_mailbox/engine"
# require "action_text/engine"
require "action_view/railtie"
# require "action_cable/engine"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
if !Rails.env.production? || ENV["HEROKU_APP_NAME"].present?
require "govuk_publishing_components"
end
module FinderFrontend
class Application < Rails::Application
# 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 = 'Central Time (US & Canada)'
# config.i18n.default_locale = :de
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
config.i18n.load_path += Dir[Rails.root.join("config/locales/**/*yml")]
config.action_view.raise_on_missing_translations = true
# Override Rails 4 default which restricts framing to SAMEORIGIN.
config.action_dispatch.default_headers = {
"X-Frame-Options" => "ALLOWALL",
}
# Path within public/ where assets are compiled to
config.assets.prefix = "/assets/finder-frontend"
# allow overriding the asset host with an enironment variable, useful for
# when router is proxying to this app but asset proxying isn't set up.
config.asset_host = ENV["ASSET_HOST"]
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
# Using a sass css compressor causes a scss file to be processed twice
# (once to build, once to compress) which breaks the usage of "unquote"
# to use CSS that has same function names as SCSS such as max.
# https://github.com/alphagov/govuk-frontend/issues/1350
config.assets.css_compressor = nil
end
end
Add accounts feature flag to rails config
We want to be able to toggle this feature on/off in the environment so we can launch this seemlessly with finder-frontend's continuious deployment and roll back if required.
require_relative "boot"
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
# require "active_record/railtie"
# require "active_storage/engine"
require "action_controller/railtie"
require "action_mailer/railtie"
# require "action_mailbox/engine"
# require "action_text/engine"
require "action_view/railtie"
# require "action_cable/engine"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
if !Rails.env.production? || ENV["HEROKU_APP_NAME"].present?
require "govuk_publishing_components"
end
module FinderFrontend
class Application < Rails::Application
# 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 = 'Central Time (US & Canada)'
# config.i18n.default_locale = :de
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
config.i18n.load_path += Dir[Rails.root.join("config/locales/**/*yml")]
config.action_view.raise_on_missing_translations = true
# Override Rails 4 default which restricts framing to SAMEORIGIN.
config.action_dispatch.default_headers = {
"X-Frame-Options" => "ALLOWALL",
}
# Path within public/ where assets are compiled to
config.assets.prefix = "/assets/finder-frontend"
# allow overriding the asset host with an enironment variable, useful for
# when router is proxying to this app but asset proxying isn't set up.
config.asset_host = ENV["ASSET_HOST"]
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
# Using a sass css compressor causes a scss file to be processed twice
# (once to build, once to compress) which breaks the usage of "unquote"
# to use CSS that has same function names as SCSS such as max.
# https://github.com/alphagov/govuk-frontend/issues/1350
config.assets.css_compressor = nil
# As part of the 2020 user discovery into GOV.UK accounts we want to deploy
# a live prototype allowing Brexit/Transition checker users to persisit their
# results page. We want to be able to toggle this feature on/off in the environment
# so we can launch this seemlessly with finder-frontend's continuious deployment
# and roll back if required.
config.feature_flag_govuk_accounts = ENV["FEATURE_FLAG_ACCOUNTS"] == "enabled"
end
end
|
require File.expand_path('../boot', __FILE__)
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
require 'mongoid'
require 'mongo'
Mongoid.load!(File.expand_path('mongoid.yml', './config'))
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module LastStop
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.
# 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 = 'Central 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
end
end
Test add for variables in config
require File.expand_path('../boot', __FILE__)
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
# require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
require 'mongoid'
Mongoid.load!('mongoid.yml', :production)
# Mongoid.load!(File.expand_path('mongoid.yml', './config'))
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module LastStop
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.
# 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 = 'Central 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
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
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
# Bundler.require(:default, :assets, Rails.env)
end
module Zammad
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 += Dir["#{config.root}/lib/*", "#{config.root}/lib/**/"]
config.autoload_paths += %W(#{config.root}/lib)
# 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
config.active_record.observers =
'observer::_session',
'observer::_ticket::_first_response',
'observer::_ticket::_last_contact',
'observer::_ticket::_close_time',
'observer::_ticket::_user_ticket_counter',
'observer::_ticket::_article_counter',
'observer::_ticket::_article_sender_type',
'observer::_ticket::_article::_fillup_from_general',
'observer::_ticket::_article::_fillup_from_email',
'observer::_ticket::_article::_communicate_email',
'observer::_ticket::_article::_communicate_facebook',
'observer::_ticket::_article::_communicate_twitter',
'observer::_ticket::_notification',
'observer::_ticket::_reset_new_state',
'observer::_ticket::_escalation_calculation',
'observer::_tag::_ticket_history',
'observer::_user::_geo'
# 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# 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
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Use a different cache store in production
config.cache_store = :file_store, 'tmp/cache/file_store'
# REST api path
config.api_path = '/api/v1'
end
end
Removed not needed line.
require File.expand_path('../boot', __FILE__)
require 'rails/all'
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
# Bundler.require(:default, :assets, Rails.env)
end
module Zammad
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}/lib)
# 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
config.active_record.observers =
'observer::_session',
'observer::_ticket::_first_response',
'observer::_ticket::_last_contact',
'observer::_ticket::_close_time',
'observer::_ticket::_user_ticket_counter',
'observer::_ticket::_article_counter',
'observer::_ticket::_article_sender_type',
'observer::_ticket::_article::_fillup_from_general',
'observer::_ticket::_article::_fillup_from_email',
'observer::_ticket::_article::_communicate_email',
'observer::_ticket::_article::_communicate_facebook',
'observer::_ticket::_article::_communicate_twitter',
'observer::_ticket::_notification',
'observer::_ticket::_reset_new_state',
'observer::_ticket::_escalation_calculation',
'observer::_tag::_ticket_history',
'observer::_user::_geo'
# 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.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# 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
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# Use a different cache store in production
config.cache_store = :file_store, 'tmp/cache/file_store'
# REST api path
config.api_path = '/api/v1'
end
end
|
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module MasterChef
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.
# 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 = 'Central 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
config.autoload_paths += Dir["#{config.root}/lib/services/"]
end
end
avoid deprecation warning
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module MasterChef
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.
# 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 = 'Central Time (US & Canada)'
I18n.config.enforce_available_locales = true
# 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
config.autoload_paths += Dir["#{config.root}/lib/services/"]
end
end
|
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module StableNyc
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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
#try to fix heroku push failure with this:
config.assets.initialize_on_precompile = false
end
end
change heroku setting
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module StableNyc
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.
# 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 = 'Central 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
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
#try to fix heroku push failure with this:
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.