CombinedText stringlengths 4 3.42M |
|---|
require 'test/unit'
require 'active_support/test_case'
require 'active_support/inflector'
require 'jbuilder'
Comment = Struct.new(:content, :id)
class JbuilderProxy
# Faking Object#instance_eval for 1.8
def instance_eval(code)
eval code
end
end if ::RUBY_VERSION < '1.9'
class NonEnumerable
def initialize(collection)
@collection = collection
end
def map(&block)
@collection.map(&block)
end
end
class JbuilderTest < ActiveSupport::TestCase
test 'single key' do
json = Jbuilder.encode do |json|
json.content 'hello'
end
assert_equal 'hello', MultiJson.load(json)['content']
end
test 'single key with false value' do
json = Jbuilder.encode do |json|
json.content false
end
assert_equal false, MultiJson.load(json)['content']
end
test 'single key with nil value' do
json = Jbuilder.encode do |json|
json.content nil
end
assert MultiJson.load(json).has_key?('content')
assert_equal nil, MultiJson.load(json)['content']
end
test 'multiple keys' do
json = Jbuilder.encode do |json|
json.title 'hello'
json.content 'world'
end
parsed = MultiJson.load(json)
assert_equal 'hello', parsed['title']
assert_equal 'world', parsed['content']
end
test 'extracting from object' do
person = Struct.new(:name, :age).new('David', 32)
json = Jbuilder.encode do |json|
json.extract! person, :name, :age
end
parsed = MultiJson.load(json)
assert_equal 'David', parsed['name']
assert_equal 32, parsed['age']
end
test 'extracting from object using call style for 1.9' do
person = Struct.new(:name, :age).new('David', 32)
json = Jbuilder.encode do |json|
if ::RUBY_VERSION > '1.9'
instance_eval 'json.(person, :name, :age)'
else
instance_eval 'json.call(person, :name, :age)'
end
end
parsed = MultiJson.load(json)
assert_equal 'David', parsed['name']
assert_equal 32, parsed['age']
end
test 'extracting from hash' do
person = {:name => 'Jim', :age => 34}
json = Jbuilder.encode do |json|
json.extract! person, :name, :age
end
parsed = MultiJson.load(json)
assert_equal 'Jim', parsed['name']
assert_equal 34, parsed['age']
end
test 'nesting single child with block' do
json = Jbuilder.encode do |json|
json.author do
json.name 'David'
json.age 32
end
end
parsed = MultiJson.load(json)
assert_equal 'David', parsed['author']['name']
assert_equal 32, parsed['author']['age']
end
test 'nesting multiple children with block' do
json = Jbuilder.encode do |json|
json.comments do
json.child! { json.content 'hello' }
json.child! { json.content 'world' }
end
end
parsed = MultiJson.load(json)
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'nesting single child with inline extract' do
person = Class.new do
attr_reader :name, :age
def initialize(name, age)
@name, @age = name, age
end
end.new('David', 32)
json = Jbuilder.encode do |json|
json.author person, :name, :age
end
parsed = MultiJson.load(json)
assert_equal 'David', parsed['author']['name']
assert_equal 32, parsed['author']['age']
end
test 'nesting multiple children from array' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.comments comments, :content
end
parsed = MultiJson.load(json)
assert_equal ['content'], parsed['comments'].first.keys
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'nesting multiple children from array when child array is empty' do
comments = []
json = Jbuilder.encode do |json|
json.name 'Parent'
json.comments comments, :content
end
parsed = MultiJson.load(json)
assert_equal 'Parent', parsed['name']
assert_equal [], parsed['comments']
end
test 'nesting multiple children from array with inline loop' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.comments comments do |comment|
json.content comment.content
end
end
parsed = MultiJson.load(json)
assert_equal ['content'], parsed['comments'].first.keys
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'handles nil-collections as empty arrays' do
json = Jbuilder.encode do |json|
json.comments nil do |comment|
json.content comment.content
end
end
assert_equal [], MultiJson.load(json)['comments']
end
test 'nesting multiple children from a non-Enumerable that responds to #map' do
comments = NonEnumerable.new([ Comment.new('hello', 1), Comment.new('world', 2) ])
json = Jbuilder.encode do |json|
json.comments comments, :content
end
parsed = MultiJson.load(json)
assert_equal ['content'], parsed['comments'].first.keys
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'nesting multiple chilren from a non-Enumerable that responds to #map with inline loop' do
comments = NonEnumerable.new([ Comment.new('hello', 1), Comment.new('world', 2) ])
json = Jbuilder.encode do |json|
json.comments comments do |comment|
json.content comment.content
end
end
parsed = MultiJson.load(json)
assert_equal ['content'], parsed['comments'].first.keys
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'nesting multiple children from array with inline loop with old api' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.comments comments do |json, comment|
json.content comment.content
end
end
parsed = MultiJson.load(json)
assert_equal ['content'], parsed['comments'].first.keys
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'nesting multiple children from array with inline loop on root' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.call(comments) do |comment|
json.content comment.content
end
end
parsed = MultiJson.load(json)
assert_equal 'hello', parsed.first['content']
assert_equal 'world', parsed.second['content']
end
test 'nesting multiple children from array with inline loop on root with old api' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.call(comments) do |json, comment|
json.content comment.content
end
end
parsed = MultiJson.load(json)
assert_equal 'hello', parsed.first['content']
assert_equal 'world', parsed.second['content']
end
test 'array nested inside nested hash' do
json = Jbuilder.encode do |json|
json.author do
json.name 'David'
json.age 32
json.comments do
json.child! { json.content 'hello' }
json.child! { json.content 'world' }
end
end
end
parsed = MultiJson.load(json)
assert_equal 'hello', parsed['author']['comments'].first['content']
assert_equal 'world', parsed['author']['comments'].second['content']
end
test 'array nested inside array' do
json = Jbuilder.encode do |json|
json.comments do
json.child! do
json.authors do
json.child! do
json.name 'david'
end
end
end
end
end
assert_equal 'david', MultiJson.load(json)['comments'].first['authors'].first['name']
end
test 'directly set an array nested in another array' do
data = [ { :department => 'QA', :not_in_json => 'hello', :names => ['John', 'David'] } ]
json = Jbuilder.encode do |json|
json.array! data do |object|
json.department object[:department]
json.names do
json.array! object[:names]
end
end
end
assert_equal 'David', MultiJson.load(json)[0]['names'].last
assert_not_equal 'hello', MultiJson.load(json)[0]['not_in_json']
end
test 'directly set an array nested in another array with old api' do
data = [ { :department => 'QA', :not_in_json => 'hello', :names => ['John', 'David'] } ]
json = Jbuilder.encode do |json|
json.array! data do |json, object|
json.department object[:department]
json.names do
json.array! object[:names]
end
end
end
assert_equal 'David', MultiJson.load(json)[0]['names'].last
assert_not_equal 'hello', MultiJson.load(json)[0]['not_in_json']
end
test 'nested jbuilder objects' do
to_nest = Jbuilder.new
to_nest.nested_value 'Nested Test'
json = Jbuilder.encode do |json|
json.value 'Test'
json.nested to_nest
end
result = {'value' => 'Test', 'nested' => {'nested_value' => 'Nested Test'}}
assert_equal result, MultiJson.load(json)
end
test 'nested jbuilder object via set!' do
to_nest = Jbuilder.new
to_nest.nested_value 'Nested Test'
json = Jbuilder.encode do |json|
json.value 'Test'
json.set! :nested, to_nest
end
result = {'value' => 'Test', 'nested' => {'nested_value' => 'Nested Test'}}
assert_equal result, MultiJson.load(json)
end
test 'top-level array' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.array!(comments) do |comment|
json.content comment.content
end
end
parsed = MultiJson.load(json)
assert_equal 'hello', parsed.first['content']
assert_equal 'world', parsed.second['content']
end
test 'empty top-level array' do
comments = []
json = Jbuilder.encode do |json|
json.array!(comments) do |comment|
json.content comment.content
end
end
assert_equal [], MultiJson.load(json)
end
test 'dynamically set a key/value' do
json = Jbuilder.encode do |json|
json.set! :each, 'stuff'
end
assert_equal 'stuff', MultiJson.load(json)['each']
end
test 'dynamically set a key/nested child with block' do
json = Jbuilder.encode do |json|
json.set!(:author) do
json.name 'David'
json.age 32
end
end
parsed = MultiJson.load(json)
assert_equal 'David', parsed['author']['name']
assert_equal 32, parsed['author']['age']
end
test 'dynamically sets a collection' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.set! :comments, comments, :content
end
parsed = MultiJson.load(json)
assert_equal ['content'], parsed['comments'].first.keys
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'query like object' do
class Person
attr_reader :name, :age
def initialize(name, age)
@name, @age = name, age
end
end
class RelationMock
include Enumerable
def each(&block)
[Person.new('Bob', 30), Person.new('Frank', 50)].each(&block)
end
def empty?
false
end
end
result = Jbuilder.encode do |json|
json.relations RelationMock.new, :name, :age
end
parsed = MultiJson.load(result)
assert_equal 2, parsed['relations'].length
assert_equal 'Bob', parsed['relations'][0]['name']
assert_equal 50, parsed['relations'][1]['age']
end
test 'initialize with positioned arguments (deprecated)' do
::ActiveSupport::Deprecation.silence do
jbuilder = Jbuilder.new(1, 2)
assert_equal 1, jbuilder.instance_eval('@key_formatter')
assert_equal 2, jbuilder.instance_eval('@ignore_nil')
end
end
test 'initialize via options hash' do
jbuilder = Jbuilder.new(:key_formatter => 1, :ignore_nil => 2)
assert_equal 1, jbuilder.instance_eval('@key_formatter')
assert_equal 2, jbuilder.instance_eval('@ignore_nil')
end
test 'key_format! with parameter' do
json = Jbuilder.new
json.key_format! :camelize => [:lower]
json.camel_style 'for JS'
assert_equal ['camelStyle'], json.attributes!.keys
end
test 'key_format! with parameter not as an array' do
json = Jbuilder.new
json.key_format! :camelize => :lower
json.camel_style 'for JS'
assert_equal ['camelStyle'], json.attributes!.keys
end
test 'key_format! propagates to child elements' do
json = Jbuilder.new
json.key_format! :upcase
json.level1 'one'
json.level2 do
json.value 'two'
end
result = json.attributes!
assert_equal 'one', result['LEVEL1']
assert_equal 'two', result['LEVEL2']['VALUE']
end
test 'key_format! resets after child element' do
json = Jbuilder.new
json.level2 do
json.key_format! :upcase
json.value 'two'
end
json.level1 'one'
result = json.attributes!
assert_equal 'two', result['level2']['VALUE']
assert_equal 'one', result['level1']
end
test 'key_format! with no parameter' do
json = Jbuilder.new
json.key_format! :upcase
json.lower 'Value'
assert_equal ['LOWER'], json.attributes!.keys
end
test 'key_format! with multiple steps' do
json = Jbuilder.new
json.key_format! :upcase, :pluralize
json.pill ''
assert_equal ['PILLs'], json.attributes!.keys
end
test 'key_format! with lambda/proc' do
json = Jbuilder.new
json.key_format! lambda { |key| key + ' and friends' }
json.oats ''
assert_equal ['oats and friends'], json.attributes!.keys
end
test 'default key_format!' do
Jbuilder.key_format :camelize => :lower
json = Jbuilder.new
json.camel_style 'for JS'
assert_equal ['camelStyle'], json.attributes!.keys
Jbuilder.send(:class_variable_set, '@@key_formatter', Jbuilder::KeyFormatter.new)
end
test 'do not use default key formatter directly' do
json = Jbuilder.new
json.key 'value'
assert_equal [], Jbuilder.send(:class_variable_get, '@@key_formatter').instance_variable_get('@cache').keys
end
test 'ignore_nil! without a parameter' do
json = Jbuilder.new
json.ignore_nil!
json.test nil
assert_equal [], json.attributes!.keys
end
test 'ignore_nil! with parameter' do
json = Jbuilder.new
json.ignore_nil! true
json.name 'Bob'
json.dne nil
assert_equal ['name'], json.attributes!.keys
json = Jbuilder.new
json.ignore_nil! false
json.name 'Bob'
json.dne nil
assert_equal ['name', 'dne'], json.attributes!.keys
end
test 'default ignore_nil!' do
Jbuilder.ignore_nil
json = Jbuilder.new
json.name 'Bob'
json.dne nil
assert_equal ['name'], json.attributes!.keys
Jbuilder.send(:class_variable_set, '@@ignore_nil', false)
end
test "nil!" do
json = Jbuilder.new
json.nil!
assert_equal nil, json.attributes!
end
end
Added some tests for nil!/null!
require 'test/unit'
require 'active_support/test_case'
require 'active_support/inflector'
require 'jbuilder'
Comment = Struct.new(:content, :id)
class JbuilderProxy
# Faking Object#instance_eval for 1.8
def instance_eval(code)
eval code
end
end if ::RUBY_VERSION < '1.9'
class NonEnumerable
def initialize(collection)
@collection = collection
end
def map(&block)
@collection.map(&block)
end
end
class JbuilderTest < ActiveSupport::TestCase
test 'single key' do
json = Jbuilder.encode do |json|
json.content 'hello'
end
assert_equal 'hello', MultiJson.load(json)['content']
end
test 'single key with false value' do
json = Jbuilder.encode do |json|
json.content false
end
assert_equal false, MultiJson.load(json)['content']
end
test 'single key with nil value' do
json = Jbuilder.encode do |json|
json.content nil
end
assert MultiJson.load(json).has_key?('content')
assert_equal nil, MultiJson.load(json)['content']
end
test 'multiple keys' do
json = Jbuilder.encode do |json|
json.title 'hello'
json.content 'world'
end
parsed = MultiJson.load(json)
assert_equal 'hello', parsed['title']
assert_equal 'world', parsed['content']
end
test 'extracting from object' do
person = Struct.new(:name, :age).new('David', 32)
json = Jbuilder.encode do |json|
json.extract! person, :name, :age
end
parsed = MultiJson.load(json)
assert_equal 'David', parsed['name']
assert_equal 32, parsed['age']
end
test 'extracting from object using call style for 1.9' do
person = Struct.new(:name, :age).new('David', 32)
json = Jbuilder.encode do |json|
if ::RUBY_VERSION > '1.9'
instance_eval 'json.(person, :name, :age)'
else
instance_eval 'json.call(person, :name, :age)'
end
end
parsed = MultiJson.load(json)
assert_equal 'David', parsed['name']
assert_equal 32, parsed['age']
end
test 'extracting from hash' do
person = {:name => 'Jim', :age => 34}
json = Jbuilder.encode do |json|
json.extract! person, :name, :age
end
parsed = MultiJson.load(json)
assert_equal 'Jim', parsed['name']
assert_equal 34, parsed['age']
end
test 'nesting single child with block' do
json = Jbuilder.encode do |json|
json.author do
json.name 'David'
json.age 32
end
end
parsed = MultiJson.load(json)
assert_equal 'David', parsed['author']['name']
assert_equal 32, parsed['author']['age']
end
test 'nesting multiple children with block' do
json = Jbuilder.encode do |json|
json.comments do
json.child! { json.content 'hello' }
json.child! { json.content 'world' }
end
end
parsed = MultiJson.load(json)
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'nesting single child with inline extract' do
person = Class.new do
attr_reader :name, :age
def initialize(name, age)
@name, @age = name, age
end
end.new('David', 32)
json = Jbuilder.encode do |json|
json.author person, :name, :age
end
parsed = MultiJson.load(json)
assert_equal 'David', parsed['author']['name']
assert_equal 32, parsed['author']['age']
end
test 'nesting multiple children from array' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.comments comments, :content
end
parsed = MultiJson.load(json)
assert_equal ['content'], parsed['comments'].first.keys
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'nesting multiple children from array when child array is empty' do
comments = []
json = Jbuilder.encode do |json|
json.name 'Parent'
json.comments comments, :content
end
parsed = MultiJson.load(json)
assert_equal 'Parent', parsed['name']
assert_equal [], parsed['comments']
end
test 'nesting multiple children from array with inline loop' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.comments comments do |comment|
json.content comment.content
end
end
parsed = MultiJson.load(json)
assert_equal ['content'], parsed['comments'].first.keys
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'handles nil-collections as empty arrays' do
json = Jbuilder.encode do |json|
json.comments nil do |comment|
json.content comment.content
end
end
assert_equal [], MultiJson.load(json)['comments']
end
test 'nesting multiple children from a non-Enumerable that responds to #map' do
comments = NonEnumerable.new([ Comment.new('hello', 1), Comment.new('world', 2) ])
json = Jbuilder.encode do |json|
json.comments comments, :content
end
parsed = MultiJson.load(json)
assert_equal ['content'], parsed['comments'].first.keys
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'nesting multiple chilren from a non-Enumerable that responds to #map with inline loop' do
comments = NonEnumerable.new([ Comment.new('hello', 1), Comment.new('world', 2) ])
json = Jbuilder.encode do |json|
json.comments comments do |comment|
json.content comment.content
end
end
parsed = MultiJson.load(json)
assert_equal ['content'], parsed['comments'].first.keys
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'nesting multiple children from array with inline loop with old api' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.comments comments do |json, comment|
json.content comment.content
end
end
parsed = MultiJson.load(json)
assert_equal ['content'], parsed['comments'].first.keys
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'nesting multiple children from array with inline loop on root' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.call(comments) do |comment|
json.content comment.content
end
end
parsed = MultiJson.load(json)
assert_equal 'hello', parsed.first['content']
assert_equal 'world', parsed.second['content']
end
test 'nesting multiple children from array with inline loop on root with old api' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.call(comments) do |json, comment|
json.content comment.content
end
end
parsed = MultiJson.load(json)
assert_equal 'hello', parsed.first['content']
assert_equal 'world', parsed.second['content']
end
test 'array nested inside nested hash' do
json = Jbuilder.encode do |json|
json.author do
json.name 'David'
json.age 32
json.comments do
json.child! { json.content 'hello' }
json.child! { json.content 'world' }
end
end
end
parsed = MultiJson.load(json)
assert_equal 'hello', parsed['author']['comments'].first['content']
assert_equal 'world', parsed['author']['comments'].second['content']
end
test 'array nested inside array' do
json = Jbuilder.encode do |json|
json.comments do
json.child! do
json.authors do
json.child! do
json.name 'david'
end
end
end
end
end
assert_equal 'david', MultiJson.load(json)['comments'].first['authors'].first['name']
end
test 'directly set an array nested in another array' do
data = [ { :department => 'QA', :not_in_json => 'hello', :names => ['John', 'David'] } ]
json = Jbuilder.encode do |json|
json.array! data do |object|
json.department object[:department]
json.names do
json.array! object[:names]
end
end
end
assert_equal 'David', MultiJson.load(json)[0]['names'].last
assert_not_equal 'hello', MultiJson.load(json)[0]['not_in_json']
end
test 'directly set an array nested in another array with old api' do
data = [ { :department => 'QA', :not_in_json => 'hello', :names => ['John', 'David'] } ]
json = Jbuilder.encode do |json|
json.array! data do |json, object|
json.department object[:department]
json.names do
json.array! object[:names]
end
end
end
assert_equal 'David', MultiJson.load(json)[0]['names'].last
assert_not_equal 'hello', MultiJson.load(json)[0]['not_in_json']
end
test 'nested jbuilder objects' do
to_nest = Jbuilder.new
to_nest.nested_value 'Nested Test'
json = Jbuilder.encode do |json|
json.value 'Test'
json.nested to_nest
end
result = {'value' => 'Test', 'nested' => {'nested_value' => 'Nested Test'}}
assert_equal result, MultiJson.load(json)
end
test 'nested jbuilder object via set!' do
to_nest = Jbuilder.new
to_nest.nested_value 'Nested Test'
json = Jbuilder.encode do |json|
json.value 'Test'
json.set! :nested, to_nest
end
result = {'value' => 'Test', 'nested' => {'nested_value' => 'Nested Test'}}
assert_equal result, MultiJson.load(json)
end
test 'top-level array' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.array!(comments) do |comment|
json.content comment.content
end
end
parsed = MultiJson.load(json)
assert_equal 'hello', parsed.first['content']
assert_equal 'world', parsed.second['content']
end
test 'empty top-level array' do
comments = []
json = Jbuilder.encode do |json|
json.array!(comments) do |comment|
json.content comment.content
end
end
assert_equal [], MultiJson.load(json)
end
test 'dynamically set a key/value' do
json = Jbuilder.encode do |json|
json.set! :each, 'stuff'
end
assert_equal 'stuff', MultiJson.load(json)['each']
end
test 'dynamically set a key/nested child with block' do
json = Jbuilder.encode do |json|
json.set!(:author) do
json.name 'David'
json.age 32
end
end
parsed = MultiJson.load(json)
assert_equal 'David', parsed['author']['name']
assert_equal 32, parsed['author']['age']
end
test 'dynamically sets a collection' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]
json = Jbuilder.encode do |json|
json.set! :comments, comments, :content
end
parsed = MultiJson.load(json)
assert_equal ['content'], parsed['comments'].first.keys
assert_equal 'hello', parsed['comments'].first['content']
assert_equal 'world', parsed['comments'].second['content']
end
test 'query like object' do
class Person
attr_reader :name, :age
def initialize(name, age)
@name, @age = name, age
end
end
class RelationMock
include Enumerable
def each(&block)
[Person.new('Bob', 30), Person.new('Frank', 50)].each(&block)
end
def empty?
false
end
end
result = Jbuilder.encode do |json|
json.relations RelationMock.new, :name, :age
end
parsed = MultiJson.load(result)
assert_equal 2, parsed['relations'].length
assert_equal 'Bob', parsed['relations'][0]['name']
assert_equal 50, parsed['relations'][1]['age']
end
test 'initialize with positioned arguments (deprecated)' do
::ActiveSupport::Deprecation.silence do
jbuilder = Jbuilder.new(1, 2)
assert_equal 1, jbuilder.instance_eval('@key_formatter')
assert_equal 2, jbuilder.instance_eval('@ignore_nil')
end
end
test 'initialize via options hash' do
jbuilder = Jbuilder.new(:key_formatter => 1, :ignore_nil => 2)
assert_equal 1, jbuilder.instance_eval('@key_formatter')
assert_equal 2, jbuilder.instance_eval('@ignore_nil')
end
test 'key_format! with parameter' do
json = Jbuilder.new
json.key_format! :camelize => [:lower]
json.camel_style 'for JS'
assert_equal ['camelStyle'], json.attributes!.keys
end
test 'key_format! with parameter not as an array' do
json = Jbuilder.new
json.key_format! :camelize => :lower
json.camel_style 'for JS'
assert_equal ['camelStyle'], json.attributes!.keys
end
test 'key_format! propagates to child elements' do
json = Jbuilder.new
json.key_format! :upcase
json.level1 'one'
json.level2 do
json.value 'two'
end
result = json.attributes!
assert_equal 'one', result['LEVEL1']
assert_equal 'two', result['LEVEL2']['VALUE']
end
test 'key_format! resets after child element' do
json = Jbuilder.new
json.level2 do
json.key_format! :upcase
json.value 'two'
end
json.level1 'one'
result = json.attributes!
assert_equal 'two', result['level2']['VALUE']
assert_equal 'one', result['level1']
end
test 'key_format! with no parameter' do
json = Jbuilder.new
json.key_format! :upcase
json.lower 'Value'
assert_equal ['LOWER'], json.attributes!.keys
end
test 'key_format! with multiple steps' do
json = Jbuilder.new
json.key_format! :upcase, :pluralize
json.pill ''
assert_equal ['PILLs'], json.attributes!.keys
end
test 'key_format! with lambda/proc' do
json = Jbuilder.new
json.key_format! lambda { |key| key + ' and friends' }
json.oats ''
assert_equal ['oats and friends'], json.attributes!.keys
end
test 'default key_format!' do
Jbuilder.key_format :camelize => :lower
json = Jbuilder.new
json.camel_style 'for JS'
assert_equal ['camelStyle'], json.attributes!.keys
Jbuilder.send(:class_variable_set, '@@key_formatter', Jbuilder::KeyFormatter.new)
end
test 'do not use default key formatter directly' do
json = Jbuilder.new
json.key 'value'
assert_equal [], Jbuilder.send(:class_variable_get, '@@key_formatter').instance_variable_get('@cache').keys
end
test 'ignore_nil! without a parameter' do
json = Jbuilder.new
json.ignore_nil!
json.test nil
assert_equal [], json.attributes!.keys
end
test 'ignore_nil! with parameter' do
json = Jbuilder.new
json.ignore_nil! true
json.name 'Bob'
json.dne nil
assert_equal ['name'], json.attributes!.keys
json = Jbuilder.new
json.ignore_nil! false
json.name 'Bob'
json.dne nil
assert_equal ['name', 'dne'], json.attributes!.keys
end
test 'default ignore_nil!' do
Jbuilder.ignore_nil
json = Jbuilder.new
json.name 'Bob'
json.dne nil
assert_equal ['name'], json.attributes!.keys
Jbuilder.send(:class_variable_set, '@@ignore_nil', false)
end
test 'nil!' do
json = Jbuilder.new
json.key 'value'
json.nil!
assert_nil json.attributes!
end
test 'null!' do
json = Jbuilder.new
json.key 'value'
json.null!
assert_nil json.attributes!
end
end
|
require 'spec_helper'
describe Net::SSH::Session do
describe '#initialize' do
context 'with :timeout option' do
it 'raises error if timeout value is not numeric' do
expect {
Net::SSH::Session.new('host', 'user', 'password', :timeout => 'data')
}.to raise_error ArgumentError, "Timeout value should be numeric"
end
end
end
describe '#method_missing' do
let(:session) { Net::SSH::Session.new('host', 'user', 'password') }
it 'runs a command based on missing method name' do
session.stub(:run).with("uname").and_return(fake_run("uname", "Linux"))
session.uname.output.should eq("Linux")
end
end
end
Raise error if :timeout option is not numeric
require 'spec_helper'
describe Net::SSH::Session do
describe '#initialize' do
context 'with :timeout option' do
it 'raises error if timeout value is not numeric' do
expect {
Net::SSH::Session.new('host', 'user', 'password', :timeout => 'data')
}.to raise_error ArgumentError, "Timeout value should be numeric"
end
it 'sets global session timeout value' do
session = Net::SSH::Session.new('host', 'user', 'password', :timeout => 1)
expect(session.timeout).to eq 1
end
end
end
describe '#method_missing' do
let(:session) { Net::SSH::Session.new('host', 'user', 'password') }
it 'runs a command based on missing method name' do
session.stub(:run).with("uname").and_return(fake_run("uname", "Linux"))
session.uname.output.should eq("Linux")
end
end
end |
# encoding: UTF-8
require 'spec_helper'
module FakeRedis
describe "StringsMethods" do
before(:each) do
@client = Redis.new
end
it "should append a value to key" do
@client.set("key1", "Hello")
@client.append("key1", " World")
expect(@client.get("key1")).to eq("Hello World")
end
it "should decrement the integer value of a key by one" do
@client.set("counter", "1")
@client.decr("counter")
expect(@client.get("counter")).to eq("0")
end
it "should decrement the integer value of a key by the given number" do
@client.set("counter", "10")
@client.decrby("counter", "5")
expect(@client.get("counter")).to eq("5")
end
it "should get the value of a key" do
expect(@client.get("key2")).to eq(nil)
end
it "should returns the bit value at offset in the string value stored at key" do
@client.set("key1", "a")
expect(@client.getbit("key1", 1)).to eq(1)
expect(@client.getbit("key1", 2)).to eq(1)
expect(@client.getbit("key1", 3)).to eq(0)
expect(@client.getbit("key1", 4)).to eq(0)
expect(@client.getbit("key1", 5)).to eq(0)
expect(@client.getbit("key1", 6)).to eq(0)
expect(@client.getbit("key1", 7)).to eq(1)
end
it "should allow direct bit manipulation even if the string isn't set" do
@client.setbit("key1", 10, 1)
expect(@client.getbit("key1", 10)).to eq(1)
end
context 'when a bit is previously set to 0' do
before { @client.setbit("key1", 10, 0) }
it 'setting it to 1 returns 0' do
expect(@client.setbit("key1", 10, 1)).to eql 0
end
it 'setting it to 0 returns 0' do
expect(@client.setbit("key1", 10, 0)).to eql 0
end
end
context 'when a bit is previously set to 1' do
before { @client.setbit("key1", 10, 1) }
it 'setting it to 0 returns 1' do
expect(@client.setbit("key1", 10, 0)).to eql 1
end
it 'setting it to 1 returns 1' do
expect(@client.setbit("key1", 10, 1)).to eql 1
end
end
it "should get a substring of the string stored at a key" do
@client.set("key1", "This a message")
expect(@client.getrange("key1", 0, 3)).to eq("This")
expect(@client.substr("key1", 0, 3)).to eq("This")
end
it "should set the string value of a key and return its old value" do
@client.set("key1","value1")
expect(@client.getset("key1", "value2")).to eq("value1")
expect(@client.get("key1")).to eq("value2")
end
it "should return nil for #getset if the key does not exist when setting" do
expect(@client.getset("key1", "value1")).to eq(nil)
expect(@client.get("key1")).to eq("value1")
end
it "should increment the integer value of a key by one" do
@client.set("counter", "1")
expect(@client.incr("counter")).to eq(2)
expect(@client.get("counter")).to eq("2")
end
it "should not change the expire value of the key during incr" do
@client.set("counter", "1")
expect(@client.expire("counter", 600)).to be true
expect(@client.ttl("counter")).to eq(600)
expect(@client.incr("counter")).to eq(2)
expect(@client.ttl("counter")).to eq(600)
end
it "should decrement the integer value of a key by one" do
@client.set("counter", "1")
expect(@client.decr("counter")).to eq(0)
expect(@client.get("counter")).to eq("0")
end
it "should not change the expire value of the key during decr" do
@client.set("counter", "2")
expect(@client.expire("counter", 600)).to be true
expect(@client.ttl("counter")).to eq(600)
expect(@client.decr("counter")).to eq(1)
expect(@client.ttl("counter")).to eq(600)
end
it "should increment the integer value of a key by the given number" do
@client.set("counter", "10")
expect(@client.incrby("counter", "5")).to eq(15)
expect(@client.incrby("counter", 2)).to eq(17)
expect(@client.get("counter")).to eq("17")
end
it "should increment the float value of a key by the given number" do
@client.set("counter", 10.0)
expect(@client.incrbyfloat("counter", 2.1)).to eq(12.1)
expect(@client.get("counter")).to eq("12.1")
end
it "should not change the expire value of the key during incrby" do
@client.set("counter", "1")
expect(@client.expire("counter", 600)).to be true
expect(@client.ttl("counter")).to eq(600)
expect(@client.incrby("counter", "5")).to eq(6)
expect(@client.ttl("counter")).to eq(600)
end
it "should decrement the integer value of a key by the given number" do
@client.set("counter", "10")
expect(@client.decrby("counter", "5")).to eq(5)
expect(@client.decrby("counter", 2)).to eq(3)
expect(@client.get("counter")).to eq("3")
end
it "should not change the expire value of the key during decrby" do
@client.set("counter", "8")
expect(@client.expire("counter", 600)).to be true
expect(@client.ttl("counter")).to eq(600)
expect(@client.decrby("counter", "3")).to eq(5)
expect(@client.ttl("counter")).to eq(600)
end
it "should get the values of all the given keys" do
@client.set("key1", "value1")
@client.set("key2", "value2")
@client.set("key3", "value3")
expect(@client.mget("key1", "key2", "key3")).to eq(["value1", "value2", "value3"])
expect(@client.mget(["key1", "key2", "key3"])).to eq(["value1", "value2", "value3"])
end
it "returns nil for non existent keys" do
@client.set("key1", "value1")
@client.set("key3", "value3")
expect(@client.mget("key1", "key2", "key3", "key4")).to eq(["value1", nil, "value3", nil])
expect(@client.mget(["key1", "key2", "key3", "key4"])).to eq(["value1", nil, "value3", nil])
end
it 'raises an argument error when not passed any fields' do
@client.set("key3", "value3")
expect { @client.mget }.to raise_error(Redis::CommandError)
end
it "should set multiple keys to multiple values" do
@client.mset(:key1, "value1", :key2, "value2")
expect(@client.get("key1")).to eq("value1")
expect(@client.get("key2")).to eq("value2")
end
it "should raise error if command arguments count is wrong" do
expect { @client.mset }.to raise_error(Redis::CommandError, "ERR wrong number of arguments for 'mset' command")
expect { @client.mset(:key1) }.to raise_error(Redis::CommandError, "ERR wrong number of arguments for 'mset' command")
expect { @client.mset(:key1, "value", :key2) }.to raise_error(Redis::CommandError, "ERR wrong number of arguments for MSET")
expect(@client.get("key1")).to be_nil
expect(@client.get("key2")).to be_nil
end
it "should set multiple keys to multiple values, only if none of the keys exist" do
expect(@client.msetnx(:key1, "value1", :key2, "value2")).to eq(true)
expect(@client.msetnx(:key1, "value3", :key2, "value4")).to eq(false)
expect(@client.get("key1")).to eq("value1")
expect(@client.get("key2")).to eq("value2")
end
it "should set multiple keys to multiple values with a hash" do
@client.mapped_mset(:key1 => "value1", :key2 => "value2")
expect(@client.get("key1")).to eq("value1")
expect(@client.get("key2")).to eq("value2")
end
it "should set multiple keys to multiple values with a hash, only if none of the keys exist" do
expect(@client.mapped_msetnx(:key1 => "value1", :key2 => "value2")).to eq(true)
expect(@client.mapped_msetnx(:key1 => "value3", :key2 => "value4")).to eq(false)
expect(@client.get("key1")).to eq("value1")
expect(@client.get("key2")).to eq("value2")
end
it "should set the string value of a key" do
@client.set("key1", "1")
expect(@client.get("key1")).to eq("1")
end
it "should sets or clears the bit at offset in the string value stored at key" do
@client.set("key1", "abc")
@client.setbit("key1", 11, 1)
expect(@client.get("key1")).to eq("arc")
end
it "should set the value and expiration of a key" do
@client.setex("key1", 30, "value1")
expect(@client.get("key1")).to eq("value1")
expect(@client.ttl("key1")).to eq(30)
end
it "should set the value of a key, only if the key does not exist" do
@client.set("key1", "test value")
@client.setnx("key1", "new value")
@client.setnx("key2", "another value")
expect(@client.get("key1")).to eq("test value")
expect(@client.get("key2")).to eq("another value")
end
it "should overwrite part of a string at key starting at the specified offset" do
@client.set("key1", "Hello World")
@client.setrange("key1", 6, "Redis")
expect(@client.get("key1")).to eq("Hello Redis")
end
it "should get the length of the value stored in a key" do
@client.set("key1", "abc")
expect(@client.strlen("key1")).to eq(3)
end
it "should return 0 bits when there's no key" do
expect(@client.bitcount("key1")).to eq(0)
end
it "should count the number of bits of a string" do
@client.set("key1", "foobar")
expect(@client.bitcount("key1")).to eq(26)
end
it "should count correctly with UTF-8 strings" do
@client.set("key1", '判')
expect(@client.bitcount("key1")).to eq(10)
end
it "should count the number of bits of a string given a range" do
@client.set("key1", "foobar")
expect(@client.bitcount("key1", 0, 0)).to eq(4)
expect(@client.bitcount("key1", 1, 1)).to eq(6)
expect(@client.bitcount("key1", 0, 1)).to eq(10)
end
describe "#bitpos" do
it "should return -1 when there's no key" do
expect(@client.bitpos("key", 0)).to eq(-1)
end
it "should return -1 for empty key" do
@client.set("key", "")
expect(@client.bitpos("key", 0)).to eq(-1)
end
it "should return position of the bit in a string" do
@client.set("key", "foobar") # 01100110 01101111 01101111
expect(@client.bitpos("key", 1)).to eq(1)
end
it "should return position of the bit correctly with UTF-8 strings" do
@client.set("key", "判") # 11100101 10001000 10100100
expect(@client.bitpos("key", 0)).to eq(3)
end
it "should return position of the bit in a string given a range" do
@client.set("key", "foobar")
expect(@client.bitpos("key", 1, 0)).to eq(1)
expect(@client.bitpos("key", 1, 1, 2)).to eq(9)
expect(@client.bitpos("key", 0, 1, -1)).to eq(8)
end
end
end
end
Mirror msetnx text to check return value
# encoding: UTF-8
require 'spec_helper'
module FakeRedis
describe "StringsMethods" do
before(:each) do
@client = Redis.new
end
it "should append a value to key" do
@client.set("key1", "Hello")
@client.append("key1", " World")
expect(@client.get("key1")).to eq("Hello World")
end
it "should decrement the integer value of a key by one" do
@client.set("counter", "1")
@client.decr("counter")
expect(@client.get("counter")).to eq("0")
end
it "should decrement the integer value of a key by the given number" do
@client.set("counter", "10")
@client.decrby("counter", "5")
expect(@client.get("counter")).to eq("5")
end
it "should get the value of a key" do
expect(@client.get("key2")).to eq(nil)
end
it "should returns the bit value at offset in the string value stored at key" do
@client.set("key1", "a")
expect(@client.getbit("key1", 1)).to eq(1)
expect(@client.getbit("key1", 2)).to eq(1)
expect(@client.getbit("key1", 3)).to eq(0)
expect(@client.getbit("key1", 4)).to eq(0)
expect(@client.getbit("key1", 5)).to eq(0)
expect(@client.getbit("key1", 6)).to eq(0)
expect(@client.getbit("key1", 7)).to eq(1)
end
it "should allow direct bit manipulation even if the string isn't set" do
@client.setbit("key1", 10, 1)
expect(@client.getbit("key1", 10)).to eq(1)
end
context 'when a bit is previously set to 0' do
before { @client.setbit("key1", 10, 0) }
it 'setting it to 1 returns 0' do
expect(@client.setbit("key1", 10, 1)).to eql 0
end
it 'setting it to 0 returns 0' do
expect(@client.setbit("key1", 10, 0)).to eql 0
end
end
context 'when a bit is previously set to 1' do
before { @client.setbit("key1", 10, 1) }
it 'setting it to 0 returns 1' do
expect(@client.setbit("key1", 10, 0)).to eql 1
end
it 'setting it to 1 returns 1' do
expect(@client.setbit("key1", 10, 1)).to eql 1
end
end
it "should get a substring of the string stored at a key" do
@client.set("key1", "This a message")
expect(@client.getrange("key1", 0, 3)).to eq("This")
expect(@client.substr("key1", 0, 3)).to eq("This")
end
it "should set the string value of a key and return its old value" do
@client.set("key1","value1")
expect(@client.getset("key1", "value2")).to eq("value1")
expect(@client.get("key1")).to eq("value2")
end
it "should return nil for #getset if the key does not exist when setting" do
expect(@client.getset("key1", "value1")).to eq(nil)
expect(@client.get("key1")).to eq("value1")
end
it "should increment the integer value of a key by one" do
@client.set("counter", "1")
expect(@client.incr("counter")).to eq(2)
expect(@client.get("counter")).to eq("2")
end
it "should not change the expire value of the key during incr" do
@client.set("counter", "1")
expect(@client.expire("counter", 600)).to be true
expect(@client.ttl("counter")).to eq(600)
expect(@client.incr("counter")).to eq(2)
expect(@client.ttl("counter")).to eq(600)
end
it "should decrement the integer value of a key by one" do
@client.set("counter", "1")
expect(@client.decr("counter")).to eq(0)
expect(@client.get("counter")).to eq("0")
end
it "should not change the expire value of the key during decr" do
@client.set("counter", "2")
expect(@client.expire("counter", 600)).to be true
expect(@client.ttl("counter")).to eq(600)
expect(@client.decr("counter")).to eq(1)
expect(@client.ttl("counter")).to eq(600)
end
it "should increment the integer value of a key by the given number" do
@client.set("counter", "10")
expect(@client.incrby("counter", "5")).to eq(15)
expect(@client.incrby("counter", 2)).to eq(17)
expect(@client.get("counter")).to eq("17")
end
it "should increment the float value of a key by the given number" do
@client.set("counter", 10.0)
expect(@client.incrbyfloat("counter", 2.1)).to eq(12.1)
expect(@client.get("counter")).to eq("12.1")
end
it "should not change the expire value of the key during incrby" do
@client.set("counter", "1")
expect(@client.expire("counter", 600)).to be true
expect(@client.ttl("counter")).to eq(600)
expect(@client.incrby("counter", "5")).to eq(6)
expect(@client.ttl("counter")).to eq(600)
end
it "should decrement the integer value of a key by the given number" do
@client.set("counter", "10")
expect(@client.decrby("counter", "5")).to eq(5)
expect(@client.decrby("counter", 2)).to eq(3)
expect(@client.get("counter")).to eq("3")
end
it "should not change the expire value of the key during decrby" do
@client.set("counter", "8")
expect(@client.expire("counter", 600)).to be true
expect(@client.ttl("counter")).to eq(600)
expect(@client.decrby("counter", "3")).to eq(5)
expect(@client.ttl("counter")).to eq(600)
end
it "should get the values of all the given keys" do
@client.set("key1", "value1")
@client.set("key2", "value2")
@client.set("key3", "value3")
expect(@client.mget("key1", "key2", "key3")).to eq(["value1", "value2", "value3"])
expect(@client.mget(["key1", "key2", "key3"])).to eq(["value1", "value2", "value3"])
end
it "returns nil for non existent keys" do
@client.set("key1", "value1")
@client.set("key3", "value3")
expect(@client.mget("key1", "key2", "key3", "key4")).to eq(["value1", nil, "value3", nil])
expect(@client.mget(["key1", "key2", "key3", "key4"])).to eq(["value1", nil, "value3", nil])
end
it 'raises an argument error when not passed any fields' do
@client.set("key3", "value3")
expect { @client.mget }.to raise_error(Redis::CommandError)
end
it "should set multiple keys to multiple values" do
@client.mset(:key1, "value1", :key2, "value2")
expect(@client.get("key1")).to eq("value1")
expect(@client.get("key2")).to eq("value2")
end
it "should raise error if command arguments count is wrong" do
expect { @client.mset }.to raise_error(Redis::CommandError, "ERR wrong number of arguments for 'mset' command")
expect { @client.mset(:key1) }.to raise_error(Redis::CommandError, "ERR wrong number of arguments for 'mset' command")
expect { @client.mset(:key1, "value", :key2) }.to raise_error(Redis::CommandError, "ERR wrong number of arguments for MSET")
expect(@client.get("key1")).to be_nil
expect(@client.get("key2")).to be_nil
end
it "should set multiple keys to multiple values, only if none of the keys exist" do
expect(@client.msetnx(:key1, "value1", :key2, "value2")).to eq(true)
expect(@client.msetnx(:key1, "value3", :key2, "value4")).to eq(false)
expect(@client.get("key1")).to eq("value1")
expect(@client.get("key2")).to eq("value2")
end
it "should set multiple keys to multiple values with a hash" do
@client.mapped_mset(:key1 => "value1", :key2 => "value2")
expect(@client.get("key1")).to eq("value1")
expect(@client.get("key2")).to eq("value2")
end
it "should set multiple keys to multiple values with a hash, only if none of the keys exist" do
expect(@client.mapped_msetnx(:key1 => "value1", :key2 => "value2")).to eq(true)
expect(@client.mapped_msetnx(:key1 => "value3", :key2 => "value4")).to eq(false)
expect(@client.get("key1")).to eq("value1")
expect(@client.get("key2")).to eq("value2")
end
it "should set the string value of a key" do
@client.set("key1", "1")
expect(@client.get("key1")).to eq("1")
end
it "should sets or clears the bit at offset in the string value stored at key" do
@client.set("key1", "abc")
@client.setbit("key1", 11, 1)
expect(@client.get("key1")).to eq("arc")
end
it "should set the value and expiration of a key" do
@client.setex("key1", 30, "value1")
expect(@client.get("key1")).to eq("value1")
expect(@client.ttl("key1")).to eq(30)
end
it "should set the value of a key, only if the key does not exist" do
expect(@client.setnx("key1", "test value")).to eq(true)
expect(@client.setnx("key1", "new value")).to eq(false)
@client.setnx("key2", "another value")
expect(@client.get("key1")).to eq("test value")
expect(@client.get("key2")).to eq("another value")
end
it "should overwrite part of a string at key starting at the specified offset" do
@client.set("key1", "Hello World")
@client.setrange("key1", 6, "Redis")
expect(@client.get("key1")).to eq("Hello Redis")
end
it "should get the length of the value stored in a key" do
@client.set("key1", "abc")
expect(@client.strlen("key1")).to eq(3)
end
it "should return 0 bits when there's no key" do
expect(@client.bitcount("key1")).to eq(0)
end
it "should count the number of bits of a string" do
@client.set("key1", "foobar")
expect(@client.bitcount("key1")).to eq(26)
end
it "should count correctly with UTF-8 strings" do
@client.set("key1", '判')
expect(@client.bitcount("key1")).to eq(10)
end
it "should count the number of bits of a string given a range" do
@client.set("key1", "foobar")
expect(@client.bitcount("key1", 0, 0)).to eq(4)
expect(@client.bitcount("key1", 1, 1)).to eq(6)
expect(@client.bitcount("key1", 0, 1)).to eq(10)
end
describe "#bitpos" do
it "should return -1 when there's no key" do
expect(@client.bitpos("key", 0)).to eq(-1)
end
it "should return -1 for empty key" do
@client.set("key", "")
expect(@client.bitpos("key", 0)).to eq(-1)
end
it "should return position of the bit in a string" do
@client.set("key", "foobar") # 01100110 01101111 01101111
expect(@client.bitpos("key", 1)).to eq(1)
end
it "should return position of the bit correctly with UTF-8 strings" do
@client.set("key", "判") # 11100101 10001000 10100100
expect(@client.bitpos("key", 0)).to eq(3)
end
it "should return position of the bit in a string given a range" do
@client.set("key", "foobar")
expect(@client.bitpos("key", 1, 0)).to eq(1)
expect(@client.bitpos("key", 1, 1, 2)).to eq(9)
expect(@client.bitpos("key", 0, 1, -1)).to eq(8)
end
end
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "Ticketmaster::Provider::Kanbanpad::Ticket" do
before(:all) do
headers = {'Authorization' => 'Basic YWJjQGcuY29tOmllODIzZDYzanM='}
wheaders = headers.merge('Accept' => 'application/json')
ActiveResource::HttpMock.respond_to do |mock|
mock.get '/api/v1/projects/be74b643b64e3dc79aa0.json', wheaders, fixture_for('projects/be74b643b64e3dc79aa0'), 200
mock.get '/api/v1/projects/be74b643b64e3dc79aa0/tasks.json', wheaders, fixture_for('tasks'), 200
mock.get '/api/v1/projects/be74b643b64e3dc79aa0/tasks.json?backlog=yes&finished=yes', wheaders, fixture_for('tasks'), 200
mock.get '/api/v1/projects/be74b643b64e3dc79aa0/tasks/4cd428c496f0734eef000007.json', wheaders, fixture_for('tasks/4cd428c496f0734eef000007'), 200
end
@project_id = 'be74b643b64e3dc79aa0'
@ticket_id = '4cd428c496f0734eef000007'
end
before(:each) do
@ticketmaster = TicketMaster.new(:kanbanpad, :username => 'abc@g.com', :password => 'ie823d63js')
@project = @ticketmaster.project(@project_id)
@klass = TicketMaster::Provider::Kanbanpad::Ticket
@comment_klass = TicketMaster::Provider::Kanbanpad::Comment
end
it "should be able to load all tickets" do
@project.tickets.should be_an_instance_of(Array)
@project.tickets.first.should be_an_instance_of(@klass)
end
it "should be able to load all tickets based on an array of ids" do
@tickets = @project.tickets(['4d62b952faf6426596000061'])
@tickets.should be_an_instance_of(Array)
@tickets.first.should be_an_instance_of(@klass)
@tickets.first.id.should == '4cd428c496f0734eef000007'
end
it "should be able to load all tickets based on attributes" do
@tickets = @project.tickets(:id => '4d62b952faf6426596000061')
@tickets.should be_an_instance_of(Array)
@tickets.first.should be_an_instance_of(@klass)
@tickets.first.id.should == '4cd428c496f0734eef000007'
end
it "should return the ticket class" do
@project.ticket.should == @klass
end
it "should be able to load a single ticket" do
@ticket = @project.ticket(@ticket_id)
@ticket.should be_an_instance_of(@klass)
@ticket.id.should == @ticket_id
end
it "should be able to load a single ticket based on attributes" do
@ticket = @project.ticket(:id => @ticket_id)
@ticket.should be_an_instance_of(@klass)
@ticket.id.should == @ticket_id
end
end
fix tickets_spec to use mocked id
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "Ticketmaster::Provider::Kanbanpad::Ticket" do
before(:all) do
headers = {'Authorization' => 'Basic YWJjQGcuY29tOmllODIzZDYzanM='}
wheaders = headers.merge('Accept' => 'application/json')
ActiveResource::HttpMock.respond_to do |mock|
mock.get '/api/v1/projects/be74b643b64e3dc79aa0.json', wheaders, fixture_for('projects/be74b643b64e3dc79aa0'), 200
mock.get '/api/v1/projects/be74b643b64e3dc79aa0/tasks.json', wheaders, fixture_for('tasks'), 200
mock.get '/api/v1/projects/be74b643b64e3dc79aa0/tasks.json?backlog=yes&finished=yes', wheaders, fixture_for('tasks'), 200
mock.get '/api/v1/projects/be74b643b64e3dc79aa0/tasks/4cd428c496f0734eef000007.json', wheaders, fixture_for('tasks/4cd428c496f0734eef000007'), 200
end
@project_id = 'be74b643b64e3dc79aa0'
@ticket_id = '4cd428c496f0734eef000007'
end
before(:each) do
@ticketmaster = TicketMaster.new(:kanbanpad, :username => 'abc@g.com', :password => 'ie823d63js')
@project = @ticketmaster.project(@project_id)
@klass = TicketMaster::Provider::Kanbanpad::Ticket
@comment_klass = TicketMaster::Provider::Kanbanpad::Comment
end
it "should be able to load all tickets" do
@project.tickets.should be_an_instance_of(Array)
@project.tickets.first.should be_an_instance_of(@klass)
end
it "should be able to load all tickets based on an array of ids" do
@tickets = @project.tickets([@ticket_id])
@tickets.should be_an_instance_of(Array)
@tickets.first.should be_an_instance_of(@klass)
@tickets.first.id.should == '4cd428c496f0734eef000007'
end
it "should be able to load all tickets based on attributes" do
@tickets = @project.tickets(:id => @ticket_id)
@tickets.should be_an_instance_of(Array)
@tickets.first.should be_an_instance_of(@klass)
@tickets.first.id.should == '4cd428c496f0734eef000007'
end
it "should return the ticket class" do
@project.ticket.should == @klass
end
it "should be able to load a single ticket" do
@ticket = @project.ticket(@ticket_id)
@ticket.should be_an_instance_of(@klass)
@ticket.id.should == @ticket_id
end
it "should be able to load a single ticket based on attributes" do
@ticket = @project.ticket(:id => @ticket_id)
@ticket.should be_an_instance_of(@klass)
@ticket.id.should == @ticket_id
end
end
|
# -*- coding: utf-8 -*-
require File.dirname(__FILE__) + "/spec_helper"
context "Japanese text" do
specify "String should output string" do
"あ".to_yaml.should be_eql <<-EXPECTED
--- "あ"
EXPECTED
end
specify "Array-ed string should output string" do
['あ','い'].to_yaml.should be_eql <<-EXPECTED
---
- "あ"
- "い"
EXPECTED
end
specify "Hash-ed string should output string" do
{'日本語' => ['出力']}.to_yaml.should be_eql <<-EXPECTED
---
"日本語":
- "出力"
EXPECTED
end
specify "mixed Array should output string" do
actual = [["あ", "い"], {"う" => ["え"]}, Struct.new(:name).new("お")]
actual.to_yaml.should be_eql <<-EXPECTED
---
- - "あ"
- "い"
- "う":
- "え"
- !ruby/struct:
name: "お"
EXPECTED
end
end
add spec for YAML.dump with StringIO
# -*- coding: utf-8 -*-
require File.dirname(__FILE__) + "/spec_helper"
context "Japanese text" do
specify "String should output string" do
"あ".to_yaml.should be_eql <<-EXPECTED
--- "あ"
EXPECTED
end
specify "Array-ed string should output string" do
['あ','い'].to_yaml.should be_eql <<-EXPECTED
---
- "あ"
- "い"
EXPECTED
end
specify "Hash-ed string should output string" do
{'日本語' => ['出力']}.to_yaml.should be_eql <<-EXPECTED
---
"日本語":
- "出力"
EXPECTED
end
specify "mixed Array should output string" do
actual = [["あ", "い"], {"う" => ["え"]}, Struct.new(:name).new("お")]
actual.to_yaml.should be_eql <<-EXPECTED
---
- - "あ"
- "い"
- "う":
- "え"
- !ruby/struct:
name: "お"
EXPECTED
end
specify "YAML.dump should be StringIO-friendly" do
actual = [["あ", "い"], {"う" => ["え"]}, Struct.new(:name).new("お")]
io = StringIO.new
YAML.dump(actual, io)
io.string.should be_eql <<-EXPECTED
---
- - "あ"
- "い"
- "う":
- "え"
- !ruby/struct:
name: "お"
EXPECTED
end
end
|
require File.expand_path(File.dirname(__FILE__)+"/spec_helper.rb")
<<<<<<< HEAD
describe Distribution::Uniform do
shared_examples_for "uniform engine" do
it ".rng should generate sequences with the right mean & variance" do
samples = 100
sum = 0
ss = 0
lower = 0
upper = rand(20)
# Expectations
exp_mean = (upper + lower) / 2
exp_variance = (upper - lower) ** 2 / 12
rng = @engine.rng(exp_lower, exp_upper)
# Calculate the chi-squared test statistic
samples.times do
v = rng.call
sum += v
ss += (v - exp_mean) ** 2
end
mean = sum.to_f / samples
variance = ss.to_f / samples
mean.should be_within(1e-5).of(exp_mean)
variance.should be_within(1e-5).of(exp_variance)
end
it ".rng with a specified seed should be reproducible" do
seed = Random.new_seed
gena = @engine.rng(0, 1, seed)
genb = @engine.rng(0, 1, seed)
(gena.call).should eq(genb.call)
end
it ".pdf should return correct pdf for values within the defined range" do
if @engine.respond_to? :pdf
10.times do
low, width = rand, rand
x = low + rand * width
epdf = 1.0 / width
@engine.pdf(x, low, low + width).should be_within(1e-10).of(epdf)
end
else
pending("No #{@engine}.pdf")
end
end
it ".pdf should return 0 for values outside the defined range" do
if @engine.respond_to? :pdf
10.times do
low, width = rand, rand
# x lies just outside of where the pdf exists as a non-zero value
# A small amount (1e-10) is removed from bad_x to ensure no overlap
x = good_x - 2 * width - 1e-10
@engine.pdf(x, low, low + width).should be_within(1e-10).of(0.0)
end
=======
describe Distribution::Uniform do
shared_examples_for "uniform engine" do
it "should return correct pdf" do
if @engine.respond_to? :pdf
>>>>>>> 98c7ad8e4ab1dc53c1e664799c2a4545af56b11d
else
pending("No #{@engine}.pdf")
end
end
<<<<<<< HEAD
it ".cdf should return 0 for values smaller than the lower bound" do
if @engine.respond_to? :cdf
low, width = rand, rand
x = low - rand * width
@engine.cdf(x, low, low + width).should be_within(1e-10).of(0.0)
else
pending("No #{@engine}.cdf")
end
end
it ".cdf should return correct cdf for x within defined range" do
if @engine.respond_to? :cdf
low, width = rand, rand
x = low + rand * width
ecdf = (x - low) / width
@engine.cdf(x, low, low + width).should be_within(1e-10).of(ecdf)
else
pending("No #{@engine}.cdf")
end
end
it ".cdf should return 1 for values greater than the upper bound" do
if @engine.respond_to? :cdf
low, width = rand, rand
x = low + rand * (2 * width)
@engine.cdf(x, low, low + width).should be_within(1e-10).of(1.0)
=======
it "should return correct cdf" do
if @engine.respond_to? :cdf
>>>>>>> 98c7ad8e4ab1dc53c1e664799c2a4545af56b11d
else
pending("No #{@engine}.cdf")
end
end
<<<<<<< HEAD
it ".quantile should return correct inverse cdf" do
if @engine.respond_to? :quantile
low, width = rand, rand
scale = rand
x = low + scale * width
qn = (x - low) / width
@engine.quantile(qn, low, low + width).should be_within(1e-10).of(scale)
else
pending("No #{@engine}.quantile")
end
end
it ".p_value should return same result as .quantile" do
if @engine.respond_to? :p_value and @engine.respond_to? :quantile
low, width = rand, rand
scale = rand
x = low + scale * width
qn = (x - low) / width
@engine.quantile(qn, low, low + width).
should eq(@engine.p_value(qn, low, low + width))
else
pending("No #{@engine}.p_value")
end
end
end
=======
it "should return correct p_value" do
if @engine.respond_to? :p_value
else
pending("No #{@engine}.cdf")
end
end
end
>>>>>>> 98c7ad8e4ab1dc53c1e664799c2a4545af56b11d
describe "singleton" do
before do
@engine=Distribution::Uniform
end
it_should_behave_like "uniform engine"
end
<<<<<<< HEAD
=======
>>>>>>> 98c7ad8e4ab1dc53c1e664799c2a4545af56b11d
describe Distribution::Uniform::Ruby_ do
before do
@engine=Distribution::Uniform::Ruby_
end
it_should_behave_like "uniform engine"
<<<<<<< HEAD
end
=======
end
>>>>>>> 98c7ad8e4ab1dc53c1e664799c2a4545af56b11d
if Distribution.has_gsl?
describe Distribution::Uniform::GSL_ do
before do
@engine=Distribution::Uniform::GSL_
end
it_should_behave_like "uniform engine"
end
end
<<<<<<< HEAD
=======
>>>>>>> 98c7ad8e4ab1dc53c1e664799c2a4545af56b11d
end
Distribution::Uniform Specs completed. Still failing.
require File.expand_path(File.dirname(__FILE__)+"/spec_helper.rb")
describe Distribution::Uniform do
shared_examples_for "uniform engine" do
it ".rng should generate sequences with the right mean & variance" do
samples = 100
sum = 0
ss = 0
lower = 0
upper = rand(20)
# Expectations
exp_mean = (upper + lower) / 2
exp_variance = (upper - lower) ** 2 / 12
rng = @engine.rng(exp_lower, exp_upper)
# Calculate the chi-squared test statistic
samples.times do
v = rng.call
sum += v
ss += (v - exp_mean) ** 2
end
mean = sum.to_f / samples
variance = ss.to_f / samples
mean.should be_within(1e-5).of(exp_mean)
variance.should be_within(1e-5).of(exp_variance)
end
it ".rng with a specified seed should be reproducible" do
seed = Random.new_seed
gena = @engine.rng(0, 1, seed)
genb = @engine.rng(0, 1, seed)
(gena.call).should eq(genb.call)
end
it ".pdf should return correct pdf for values within the defined range" do
if @engine.respond_to? :pdf
10.times do
low, width = rand, rand
x = low + rand * width
epdf = 1.0 / width
@engine.pdf(x, low, low + width).should be_within(1e-10).of(epdf)
end
else
pending("No #{@engine}.pdf")
end
end
it ".pdf should return 0 for values outside the defined range" do
if @engine.respond_to? :pdf
10.times do
low, width = rand, rand
# x lies just outside of where the pdf exists as a non-zero value
# A small amount (1e-10) is removed from bad_x to ensure no overlap
x = good_x - 2 * width - 1e-10
@engine.pdf(x, low, low + width).should be_within(1e-10).of(0.0)
end
else
pending("No #{@engine}.pdf")
end
end
it ".cdf should return 0 for values smaller than the lower bound" do
if @engine.respond_to? :cdf
low, width = rand, rand
x = low - rand * width
@engine.cdf(x, low, low + width).should be_within(1e-10).of(0.0)
else
pending("No #{@engine}.cdf")
end
end
it ".cdf should return correct cdf for x within defined range" do
if @engine.respond_to? :cdf
low, width = rand, rand
x = low + rand * width
ecdf = (x - low) / width
@engine.cdf(x, low, low + width).should be_within(1e-10).of(ecdf)
else
pending("No #{@engine}.cdf")
end
end
it ".cdf should return 1 for values greater than the upper bound" do
if @engine.respond_to? :cdf
low, width = rand, rand
x = low + rand * (2 * width)
@engine.cdf(x, low, low + width).should be_within(1e-10).of(1.0)
else
pending("No #{@engine}.cdf")
end
end
it ".quantile should return correct inverse cdf" do
if @engine.respond_to? :quantile
low, width = rand, rand
scale = rand
x = low + scale * width
qn = (x - low) / width
@engine.quantile(qn, low, low + width).should be_within(1e-10).of(scale)
else
pending("No #{@engine}.quantile")
end
end
it ".p_value should return same result as .quantile" do
if @engine.respond_to? :p_value and @engine.respond_to? :quantile
low, width = rand, rand
scale = rand
x = low + scale * width
qn = (x - low) / width
@engine.quantile(qn, low, low + width).
should eq(@engine.p_value(qn, low, low + width))
else
pending("No #{@engine}.p_value")
end
end
end
describe "singleton" do
before do
@engine=Distribution::Uniform
end
it_should_behave_like "uniform engine"
end
describe Distribution::Uniform::Ruby_ do
before do
@engine=Distribution::Uniform::Ruby_
end
it_should_behave_like "uniform engine"
end
if Distribution.has_gsl?
describe Distribution::Uniform::GSL_ do
before do
@engine=Distribution::Uniform::GSL_
end
it_should_behave_like "uniform engine"
end
end
end
|
require './spec/support/vcr_setup'
TEST_SITES = %w(05 12)
FAIL_SITES = %w(0 16)
TEST_INFO = %w(name table)
FIXTURES = './spec/fixtures/vieshow_'
MONTHS = Date::ABBR_MONTHNAMES.compact
DAYS = Date::ABBR_DAYNAMES
PARTIAL_NAME = 4..10
HOUR_MIN = 11..15
AN_HOUR = 1 / 24.to_f
MIDNIGHT = %w(00 01 02 03)
TAIWAN_TIME = '+8'.to_f
describe 'Get film information' do
TEST_SITES.each do |site|
TEST_INFO.each do |t|
it "must return same list of movies for #{site}" do
VCR.use_cassette("vieshow_#{t}_#{site}") do
cinema = HsinChuMovie::Vieshow.new(site.to_i)
site_info = yml_load("#{FIXTURES}#{t}_#{site}.yml")
compare = t == TEST_INFO[0] ? cinema.movie_names : cinema.movie_table
site_info.must_equal compare
end; end; end
end
end
describe 'Get show times for a film' do
TEST_SITES.each do |site|
it 'should get viewing times for this film' do
VCR.use_cassette("vieshow_table_#{site}") do
cinema = HsinChuMovie::Vieshow.new(site.to_i)
one_movie = yml_load("#{FIXTURES}name_#{site}.yml").sample[PARTIAL_NAME]
# Films are saved as UPPERCASE but search should pass any case
cinema.film_times(one_movie.downcase).each do |film, date_times|
film.must_include one_movie
date_times.keys.each do |date|
words_in_date = date.split
MONTHS.must_include words_in_date.first
DAYS.must_include words_in_date.last
end; end; end
end
end
TEST_SITES.each do |site|
it 'should return empty array for random string' do
VCR.use_cassette("vieshow_table_#{site}") do
cinema = HsinChuMovie::Vieshow.new(site.to_i)
one_movie = (PARTIAL_NAME).map { ('A'..'Z').to_a[rand(26)] }.join
cinema.film_times(one_movie).must_be_empty
end; end
end
end
describe 'Get films after a given time on given day' do
it 'should return films after a time' do
TEST_SITES.each do |site|
VCR.use_cassette("vieshow_table_#{site}") do
cinema = HsinChuMovie::Vieshow.new(site.to_i)
time = DateTime.now TAIWAN_TIME
time_s = time.to_s[HOUR_MIN]
after_films = cinema.films_after_time(time_s)
exit if after_films.empty?
comparison_time = (time - AN_HOUR).to_s[HOUR_MIN]
after_films.each do |_film, date_times|
# We're taking user input and getting results starting an hour back
date_times.values.each do |show_times|
show_times.each do |show_time|
if (show_time < comparison_time) &&
(MIDNIGHT.include? show_time[0..1])
# Movies airing from midnight onwards are group with past day
show_time[0..1] = "#{show_time[0..1].to_i + 24}"
end
show_time.must_be :>=, comparison_time
end; end; end; end; end
end
it 'should not miss any films' do
# TODO: Check to make sure no late films are missed
end
end
describe 'Outside of 1 and 14 must fail' do
FAIL_SITES.each do |site|
it "must fail for #{site}" do
proc { HsinChuMovie::Vieshow.new(site.to_i) }.must_raise RuntimeError
end
end
end
Show times testing complete
- Now we can be certain list of returned films and times is accurate and exhaustive.
require './spec/support/vcr_setup'
TEST_SITES = %w(05 12)
FAIL_SITES = %w(0 16)
TEST_INFO = %w(name table)
FIXTURES = './spec/fixtures/vieshow_'
MONTHS = Date::ABBR_MONTHNAMES.compact
DAYS = Date::ABBR_DAYNAMES
PARTIAL_NAME = 4..10
HOUR_MIN = 11..15
AN_HOUR = 1 / 24.to_f
MIDNIGHT = %w(00 01 02 03)
TAIWAN_TIME = '+8'.to_f
GIVEN_DAY = (0..2).to_a
describe 'Get film information' do
TEST_SITES.each do |site|
TEST_INFO.each do |t|
it "must return same list of movies for #{site}" do
VCR.use_cassette("vieshow_#{t}_#{site}") do
cinema = HsinChuMovie::Vieshow.new(site.to_i)
site_info = yml_load("#{FIXTURES}#{t}_#{site}.yml")
compare = t == TEST_INFO[0] ? cinema.movie_names : cinema.movie_table
site_info.must_equal compare
end; end; end
end
end
describe 'Get show times for a film' do
TEST_SITES.each do |site|
it 'should get viewing times for this film' do
VCR.use_cassette("vieshow_table_#{site}") do
cinema = HsinChuMovie::Vieshow.new(site.to_i)
one_movie = yml_load("#{FIXTURES}name_#{site}.yml").sample[PARTIAL_NAME]
# Films are saved as UPPERCASE but search should pass any case
cinema.film_times(one_movie.downcase).each do |film, date_times|
film.must_include one_movie
date_times.keys.each do |date|
words_in_date = date.split
MONTHS.must_include words_in_date.first
DAYS.must_include words_in_date.last
end; end; end
end
end
TEST_SITES.each do |site|
it 'should return empty array for random string' do
VCR.use_cassette("vieshow_table_#{site}") do
cinema = HsinChuMovie::Vieshow.new(site.to_i)
one_movie = (PARTIAL_NAME).map { ('A'..'Z').to_a[rand(26)] }.join
cinema.film_times(one_movie).must_be_empty
end; end
end
end
describe 'Get films after a given time on given day' do
TEST_SITES.each do |site|
it "should only return films after a time for #{site}" do
VCR.use_cassette("vieshow_table_#{site}") do
cinema = HsinChuMovie::Vieshow.new(site.to_i)
time = DateTime.now TAIWAN_TIME
time += GIVEN_DAY.sample
time_s = time.to_s
day_films = cinema.films_on_day(time_s)
after_films = cinema.films_after_time(time_s)
# comparison_time is an hour earlier than specified time
comparison_time = (time - AN_HOUR).to_s[HOUR_MIN]
day_films.each do |film, date_times|
date_times.each do |date, show_times|
if after_films[film].nil?
# If empty, all show times must be less than comparison time
show_times.each do |show_time|
show_time.must_be :<, comparison_time
end
else
after_show_times = after_films[film][date]
after_show_times.each do |ast|
# On day show times must include after request show times
show_times.must_include ast
# After show times must be greater than comparison time
if (ast < comparison_time) &&
(MIDNIGHT.include? ast[0..1])
# Movies airing from midnight onwards are group with past day
ast[0..1] = "#{ast[0..1].to_i + 24}"
end
ast.must_be :>=, comparison_time
end
show_times -= after_films[film][date]
# Any show time not returned must be less than comparison time
show_times.each do |show_time|
show_time.must_be :<, comparison_time
end
end; end; end; end; end
end
end
describe 'Outside of 1 and 14 must fail' do
FAIL_SITES.each do |site|
it "must fail for #{site}" do
proc { HsinChuMovie::Vieshow.new(site.to_i) }.must_raise RuntimeError
end
end
end
|
require_relative '../spec_helper'
describe "A method send" do
evaluate <<-ruby do
def m(a) a end
ruby
a = b = m 1
a.should == 1
b.should == 1
end
context "with a single splatted Object argument" do
before :all do
def m(a) a end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
m(*x).should equal(x)
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([1])
m(*x).should == 1
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
m(*x).should == x
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { m(*x) }.should raise_error(TypeError)
end
end
context "with a leading splatted Object argument" do
before :all do
def m(a, b, *c, d, e) [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
m(*x, 1, 2, 3).should == [x, 1, [], 2, 3]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([1])
m(*x, 2, 3, 4).should == [1, 2, [], 3, 4]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
m(*x, 2, 3, 4).should == [x, 2, [], 3, 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { m(*x, 2, 3) }.should raise_error(TypeError)
end
end
context "with a middle splatted Object argument" do
before :all do
def m(a, b, *c, d, e) [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
m(1, 2, *x, 3, 4).should == [1, 2, [x], 3, 4]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([5, 6, 7])
m(1, 2, *x, 3).should == [1, 2, [5, 6], 7, 3]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
m(1, 2, *x, 4).should == [1, 2, [], x, 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { m(1, *x, 2, 3) }.should raise_error(TypeError)
end
it "copies the splatted array" do
args = [3, 4]
m(1, 2, *args, 4, 5).should == [1, 2, [3, 4], 4, 5]
m(1, 2, *args, 4, 5)[2].should_not equal(args)
end
it "allows an array being splatted to be modified by another argument" do
args = [3, 4]
m(1, args.shift, *args, 4, 5).should == [1, 3, [4], 4, 5]
end
end
context "with a trailing splatted Object argument" do
before :all do
def m(a, *b, c) [a, b, c] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
m(1, 2, *x).should == [1, [2], x]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([5, 6, 7])
m(1, 2, *x).should == [1, [2, 5, 6], 7]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
m(1, 2, *x, 4).should == [1, [2, x], 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { m(1, 2, *x) }.should raise_error(TypeError)
end
end
end
describe "An element assignment method send" do
before :each do
ScratchPad.clear
end
context "with a single splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.[]=(a, b) ScratchPad.record [a, b] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o[*x] = 1).should == 1
ScratchPad.recorded.should == [x, 1]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([1])
(@o[*x] = 2).should == 2
ScratchPad.recorded.should == [1, 2]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o[*x] = 1).should == 1
ScratchPad.recorded.should == [x, 1]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o[*x] = 1 }.should raise_error(TypeError)
end
end
context "with a leading splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.[]=(a, b, *c, d, e) ScratchPad.record [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o[*x, 2, 3, 4] = 1).should == 1
ScratchPad.recorded.should == [x, 2, [3], 4, 1]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([1, 2, 3])
(@o[*x, 4, 5] = 6).should == 6
ScratchPad.recorded.should == [1, 2, [3, 4], 5, 6]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o[*x, 2, 3, 4] = 5).should == 5
ScratchPad.recorded.should == [x, 2, [3], 4, 5]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o[*x, 2, 3] = 4 }.should raise_error(TypeError)
end
end
context "with a middle splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.[]=(a, b, *c, d, e) ScratchPad.record [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o[1, *x, 2, 3] = 4).should == 4
ScratchPad.recorded.should == [1, x, [2], 3, 4]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([2, 3])
(@o[1, *x, 4] = 5).should == 5
ScratchPad.recorded.should == [1, 2, [3], 4, 5]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o[1, 2, *x, 3] = 4).should == 4
ScratchPad.recorded.should == [1, 2, [x], 3, 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o[1, 2, *x, 3] = 4 }.should raise_error(TypeError)
end
end
context "with a trailing splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.[]=(a, b, *c, d, e) ScratchPad.record [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o[1, 2, 3, 4, *x] = 5).should == 5
ScratchPad.recorded.should == [1, 2, [3, 4], x, 5]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([4, 5])
(@o[1, 2, 3, *x] = 6).should == 6
ScratchPad.recorded.should == [1, 2, [3, 4], 5, 6]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o[1, 2, 3, *x] = 4).should == 4
ScratchPad.recorded.should == [1, 2, [3], x, 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o[1, 2, 3, *x] = 4 }.should raise_error(TypeError)
end
end
end
describe "An attribute assignment method send" do
context "with a single splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.m=(a, b) [a, b] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o.send :m=, *x, 1).should == [x, 1]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([1])
(@o.send :m=, *x, 2).should == [1, 2]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o.send :m=, *x, 1).should == [x, 1]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o.send :m=, *x, 1 }.should raise_error(TypeError)
end
end
context "with a leading splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.m=(a, b, *c, d, e) [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o.send :m=, *x, 2, 3, 4, 1).should == [x, 2, [3], 4, 1]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([1, 2, 3])
(@o.send :m=, *x, 4, 5, 6).should == [1, 2, [3, 4], 5, 6]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o.send :m=, *x, 2, 3, 4, 5).should == [x, 2, [3], 4, 5]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o.send :m=, *x, 2, 3, 4 }.should raise_error(TypeError)
end
end
context "with a middle splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.m=(a, b, *c, d, e) [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o.send :m=, 1, *x, 2, 3, 4).should == [1, x, [2], 3, 4]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([2, 3])
(@o.send :m=, 1, *x, 4, 5).should == [1, 2, [3], 4, 5]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o.send :m=, 1, 2, *x, 3, 4).should == [1, 2, [x], 3, 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o.send :m=, 1, 2, *x, 3, 4 }.should raise_error(TypeError)
end
end
context "with a trailing splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.m=(a, b, *c, d, e) [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o.send :m=, 1, 2, 3, 4, *x, 5).should == [1, 2, [3, 4], x, 5]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([4, 5])
(@o.send :m=, 1, 2, 3, *x, 6).should == [1, 2, [3, 4], 5, 6]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o.send :m=, 1, 2, 3, *x, 4).should == [1, 2, [3], x, 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o.send :m=, 1, 2, 3, *x, 4 }.should raise_error(TypeError)
end
end
end
describe "A method" do
SpecEvaluate.desc = "for definition"
context "assigns no local variables" do
evaluate <<-ruby do
def m
end
ruby
m.should be_nil
end
evaluate <<-ruby do
def m()
end
ruby
m.should be_nil
end
end
context "assigns local variables from method parameters" do
evaluate <<-ruby do
def m(a) a end
ruby
m((args = 1, 2, 3)).should equal(args)
end
evaluate <<-ruby do
def m((a)) a end
ruby
m(1).should == 1
m([1, 2, 3]).should == 1
end
evaluate <<-ruby do
def m((*a, b)) [a, b] end
ruby
m(1).should == [[], 1]
m([1, 2, 3]).should == [[1, 2], 3]
end
evaluate <<-ruby do
def m(a=1) a end
ruby
m().should == 1
m(2).should == 2
end
evaluate <<-ruby do
def m() end
ruby
m().should be_nil
m(*[]).should be_nil
m(**{}).should be_nil
end
evaluate <<-ruby do
def m(*) end
ruby
m().should be_nil
m(1).should be_nil
m(1, 2, 3).should be_nil
end
evaluate <<-ruby do
def m(*a) a end
ruby
m().should == []
m(1).should == [1]
m(1, 2, 3).should == [1, 2, 3]
m(*[]).should == []
m(**{}).should == []
end
evaluate <<-ruby do
def m(a:) a end
ruby
lambda { m() }.should raise_error(ArgumentError)
m(a: 1).should == 1
lambda { m("a" => 1, a: 1) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(a: 1) a end
ruby
m().should == 1
m(a: 2).should == 2
end
evaluate <<-ruby do
def m(**) end
ruby
m().should be_nil
m(a: 1, b: 2).should be_nil
lambda { m(1) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(**k) k end
ruby
m().should == {}
m(a: 1, b: 2).should == { a: 1, b: 2 }
m(*[]).should == {}
m(**{}).should == {}
lambda { m(2) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(&b) b end
ruby
m { }.should be_an_instance_of(Proc)
end
evaluate <<-ruby do
def m(a, b) [a, b] end
ruby
m(1, 2).should == [1, 2]
end
evaluate <<-ruby do
def m(a, (b, c)) [a, b, c] end
ruby
m(1, 2).should == [1, 2, nil]
m(1, [2, 3, 4]).should == [1, 2, 3]
end
evaluate <<-ruby do
def m((a), (b)) [a, b] end
ruby
m(1, 2).should == [1, 2]
m([1, 2], [3, 4]).should == [1, 3]
end
evaluate <<-ruby do
def m((*), (*)) end
ruby
m(2, 3).should be_nil
m([2, 3, 4], [5, 6]).should be_nil
lambda { m a: 1 }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m((*a), (*b)) [a, b] end
ruby
m(1, 2).should == [[1], [2]]
m([1, 2], [3, 4]).should == [[1, 2], [3, 4]]
end
evaluate <<-ruby do
def m((a, b), (c, d))
[a, b, c, d]
end
ruby
m(1, 2).should == [1, nil, 2, nil]
m([1, 2, 3], [4, 5, 6]).should == [1, 2, 4, 5]
end
evaluate <<-ruby do
def m((a, *b), (*c, d))
[a, b, c, d]
end
ruby
m(1, 2).should == [1, [], [], 2]
m([1, 2, 3], [4, 5, 6]).should == [1, [2, 3], [4, 5], 6]
end
evaluate <<-ruby do
def m((a, b, *c, d), (*e, f, g), (*h))
[a, b, c, d, e, f, g, h]
end
ruby
m(1, 2, 3).should == [1, nil, [], nil, [], 2, nil, [3]]
result = m([1, 2, 3], [4, 5, 6, 7, 8], [9, 10])
result.should == [1, 2, [], 3, [4, 5, 6], 7, 8, [9, 10]]
end
evaluate <<-ruby do
def m(a, (b, (c, *d), *e))
[a, b, c, d, e]
end
ruby
m(1, 2).should == [1, 2, nil, [], []]
m(1, [2, [3, 4, 5], 6, 7, 8]).should == [1, 2, 3, [4, 5], [6, 7, 8]]
end
evaluate <<-ruby do
def m(a, (b, (c, *d, (e, (*f)), g), (h, (i, j))))
[a, b, c, d, e, f, g, h, i, j]
end
ruby
m(1, 2).should == [1, 2, nil, [], nil, [nil], nil, nil, nil, nil]
result = m(1, [2, [3, 4, 5, [6, [7, 8]], 9], [10, [11, 12]]])
result.should == [1, 2, 3, [4, 5], 6, [7, 8], 9, 10, 11, 12]
end
evaluate <<-ruby do
def m(a, b=1) [a, b] end
ruby
m(2).should == [2, 1]
m(1, 2).should == [1, 2]
end
evaluate <<-ruby do
def m(a, *) a end
ruby
m(1).should == 1
m(1, 2, 3).should == 1
end
evaluate <<-ruby do
def m(a, *b) [a, b] end
ruby
m(1).should == [1, []]
m(1, 2, 3).should == [1, [2, 3]]
end
evaluate <<-ruby do
def m(a, b:) [a, b] end
ruby
m(1, b: 2).should == [1, 2]
lambda { m("a" => 1, b: 2) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(a, b: 1) [a, b] end
ruby
m(2).should == [2, 1]
m(1, b: 2).should == [1, 2]
m("a" => 1, b: 2).should == [{"a" => 1, b: 2}, 1]
end
evaluate <<-ruby do
def m(a, **) a end
ruby
m(1).should == 1
m(1, a: 2, b: 3).should == 1
m("a" => 1, b: 2).should == {"a" => 1, b: 2}
end
evaluate <<-ruby do
def m(a, **k) [a, k] end
ruby
m(1).should == [1, {}]
m(1, a: 2, b: 3).should == [1, {a: 2, b: 3}]
m("a" => 1, b: 2).should == [{"a" => 1, b: 2}, {}]
end
evaluate <<-ruby do
def m(a, &b) [a, b] end
ruby
m(1).should == [1, nil]
m(1, &(l = -> {})).should == [1, l]
end
evaluate <<-ruby do
def m(a=1, b) [a, b] end
ruby
m(2).should == [1, 2]
m(2, 3).should == [2, 3]
end
evaluate <<-ruby do
def m(a=1, *) a end
ruby
m().should == 1
m(2, 3, 4).should == 2
end
evaluate <<-ruby do
def m(a=1, *b) [a, b] end
ruby
m().should == [1, []]
m(2, 3, 4).should == [2, [3, 4]]
end
evaluate <<-ruby do
def m(a=1, (b, c)) [a, b, c] end
ruby
m(2).should == [1, 2, nil]
m(2, 3).should == [2, 3, nil]
m(2, [3, 4, 5]).should == [2, 3, 4]
end
evaluate <<-ruby do
def m(a=1, (b, (c, *d))) [a, b, c, d] end
ruby
m(2).should == [1, 2, nil, []]
m(2, 3).should == [2, 3, nil, []]
m(2, [3, [4, 5, 6], 7]).should == [2, 3, 4, [5, 6]]
end
evaluate <<-ruby do
def m(a=1, (b, (c, *d), *e)) [a, b, c, d, e] end
ruby
m(2).should == [1, 2, nil, [], []]
m(2, [3, 4, 5, 6]).should == [2, 3, 4, [], [5, 6]]
m(2, [3, [4, 5, 6], 7]).should == [2, 3, 4, [5, 6], [7]]
end
evaluate <<-ruby do
def m(a=1, (b), (c)) [a, b, c] end
ruby
m(2, 3).should == [1, 2, 3]
m(2, 3, 4).should == [2, 3, 4]
m(2, [3, 4], [5, 6, 7]).should == [2, 3, 5]
end
evaluate <<-ruby do
def m(a=1, (*b), (*c)) [a, b, c] end
ruby
lambda { m() }.should raise_error(ArgumentError)
lambda { m(2) }.should raise_error(ArgumentError)
m(2, 3).should == [1, [2], [3]]
m(2, [3, 4], [5, 6]).should == [2, [3, 4], [5, 6]]
end
evaluate <<-ruby do
def m(a=1, (b, c), (d, e)) [a, b, c, d, e] end
ruby
m(2, 3).should == [1, 2, nil, 3, nil]
m(2, [3, 4, 5], [6, 7, 8]).should == [2, 3, 4, 6, 7]
end
evaluate <<-ruby do
def m(a=1, (b, *c), (*d, e))
[a, b, c, d, e]
end
ruby
m(1, 2).should == [1, 1, [], [], 2]
m(1, [2, 3], [4, 5, 6]).should == [1, 2, [3], [4, 5], 6]
end
evaluate <<-ruby do
def m(a=1, (b, *c), (d, (*e, f)))
[a, b, c, d, e, f]
end
ruby
m(1, 2).should == [1, 1, [], 2, [], nil]
m(nil, nil).should == [1, nil, [], nil, [], nil]
result = m([1, 2, 3], [4, 5, 6], [7, 8, 9])
result.should == [[1, 2, 3], 4, [5, 6], 7, [], 8]
end
evaluate <<-ruby do
def m(a=1, b:) [a, b] end
ruby
m(b: 2).should == [1, 2]
m(2, b: 1).should == [2, 1]
ruby_version_is ""..."2.6" do
m("a" => 1, b: 2).should == [{"a" => 1}, 2]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, b: 2)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(a=1, b: 2) [a, b] end
ruby
m().should == [1, 2]
m(2).should == [2, 2]
m(b: 3).should == [1, 3]
ruby_version_is ""..."2.6" do
m("a" => 1, b: 2).should == [{"a" => 1}, 2]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, b: 2)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(a=1, **) a end
ruby
m().should == 1
m(2, a: 1, b: 0).should == 2
ruby_version_is ""..."2.6" do
m("a" => 1, a: 2).should == {"a" => 1}
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 2)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(a=1, **k) [a, k] end
ruby
m().should == [1, {}]
m(2, a: 1, b: 2).should == [2, {a: 1, b: 2}]
end
evaluate <<-ruby do
def m(a=1, &b) [a, b] end
ruby
m().should == [1, nil]
m(&(l = -> {})).should == [1, l]
p = -> {}
l = mock("to_proc")
l.should_receive(:to_proc).and_return(p)
m(&l).should == [1, p]
end
evaluate <<-ruby do
def m(*, a) a end
ruby
m(1).should == 1
m(1, 2, 3).should == 3
end
evaluate <<-ruby do
def m(*a, b) [a, b] end
ruby
m(1).should == [[], 1]
m(1, 2, 3).should == [[1, 2], 3]
end
evaluate <<-ruby do
def m(*, a:) a end
ruby
m(a: 1).should == 1
m(1, 2, a: 3).should == 3
ruby_version_is ""..."2.6" do
m("a" => 1, a: 2).should == 2
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 2)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(*a, b:) [a, b] end
ruby
m(b: 1).should == [[], 1]
m(1, 2, b: 3).should == [[1, 2], 3]
ruby_version_is ""..."2.6" do
m("a" => 1, b: 2).should == [[{"a" => 1}], 2]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, b: 2)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(*, a: 1) a end
ruby
m().should == 1
m(1, 2).should == 1
m(a: 2).should == 2
m(1, a: 2).should == 2
ruby_version_is ""..."2.6" do
m("a" => 1, a: 2).should == 2
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 2)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(*a, b: 1) [a, b] end
ruby
m().should == [[], 1]
m(1, 2, 3, b: 4).should == [[1, 2, 3], 4]
ruby_version_is ""..."2.6" do
m("a" => 1, b: 2).should == [[{"a" => 1}], 2]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, b: 2)}.should raise_error(ArgumentError)
end
a = mock("splat")
a.should_not_receive(:to_ary)
m(*a).should == [[a], 1]
end
evaluate <<-ruby do
def m(*, **) end
ruby
m().should be_nil
m(a: 1, b: 2).should be_nil
m(1, 2, 3, a: 4, b: 5).should be_nil
h = mock("keyword splat")
h.should_receive(:to_hash).and_return({a: 1})
m(h).should be_nil
h = mock("keyword splat")
error = RuntimeError.new("error while converting to a hash")
h.should_receive(:to_hash).and_raise(error)
lambda { m(h) }.should raise_error(error)
end
evaluate <<-ruby do
def m(*a, **) a end
ruby
m().should == []
m(1, 2, 3, a: 4, b: 5).should == [1, 2, 3]
ruby_version_is ""..."2.6" do
m("a" => 1, a: 1).should == [{"a" => 1}]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 1)}.should raise_error(ArgumentError)
end
m(1, **{a: 2}).should == [1]
h = mock("keyword splat")
h.should_receive(:to_hash)
lambda { m(**h) }.should raise_error(TypeError)
end
evaluate <<-ruby do
def m(*, **k) k end
ruby
m().should == {}
m(1, 2, 3, a: 4, b: 5).should == {a: 4, b: 5}
ruby_version_is ""..."2.6" do
m("a" => 1, a: 1).should == {a: 1}
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 1)}.should raise_error(ArgumentError)
end
h = mock("keyword splat")
h.should_receive(:to_hash).and_return({a: 1})
m(h).should == {a: 1}
end
evaluate <<-ruby do
def m(a = nil, **k) [a, k] end
ruby
m().should == [nil, {}]
m("a" => 1).should == [{"a" => 1}, {}]
m(a: 1).should == [nil, {a: 1}]
ruby_version_is ""..."2.6" do
m("a" => 1, a: 1).should == [{"a" => 1}, {a: 1}]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 1)}.should raise_error(ArgumentError)
end
m({ "a" => 1 }, a: 1).should == [{"a" => 1}, {a: 1}]
m({a: 1}, {}).should == [{a: 1}, {}]
h = {"a" => 1, b: 2}
ruby_version_is ""..."2.6" do
m(h).should == [{"a" => 1}, {b: 2}]
end
ruby_version_is "2.6" do
lambda {m(h)}.should raise_error(ArgumentError)
end
h.should == {"a" => 1, b: 2}
h = {"a" => 1}
m(h).first.should == h
h = {}
r = m(h)
r.first.should be_nil
r.last.should == {}
hh = {}
h = mock("keyword splat empty hash")
h.should_receive(:to_hash).and_return(hh)
r = m(h)
r.first.should be_nil
r.last.should == {}
h = mock("keyword splat")
h.should_receive(:to_hash).and_return({"a" => 1, a: 2})
ruby_version_is ""..."2.6" do
m(h).should == [{"a" => 1}, {a: 2}]
end
ruby_version_is "2.6" do
lambda {m(h)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(*a, **k) [a, k] end
ruby
m().should == [[], {}]
m(1).should == [[1], {}]
m(a: 1, b: 2).should == [[], {a: 1, b: 2}]
m(1, 2, 3, a: 2).should == [[1, 2, 3], {a: 2}]
m("a" => 1).should == [[{"a" => 1}], {}]
m(a: 1).should == [[], {a: 1}]
ruby_version_is ""..."2.6" do
m("a" => 1, a: 1).should == [[{"a" => 1}], {a: 1}]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 1)}.should raise_error(ArgumentError)
end
m({ "a" => 1 }, a: 1).should == [[{"a" => 1}], {a: 1}]
m({a: 1}, {}).should == [[{a: 1}], {}]
m({a: 1}, {"a" => 1}).should == [[{a: 1}, {"a" => 1}], {}]
bo = BasicObject.new
def bo.to_a; [1, 2, 3]; end
def bo.to_hash; {:b => 2, :c => 3}; end
m(*bo, **bo).should == [[1, 2, 3], {:b => 2, :c => 3}]
end
evaluate <<-ruby do
def m(*, &b) b end
ruby
m().should be_nil
m(1, 2, 3, 4).should be_nil
m(&(l = ->{})).should equal(l)
end
evaluate <<-ruby do
def m(*a, &b) [a, b] end
ruby
m().should == [[], nil]
m(1).should == [[1], nil]
m(1, 2, 3, &(l = -> {})).should == [[1, 2, 3], l]
end
evaluate <<-ruby do
def m(a:, b:) [a, b] end
ruby
m(a: 1, b: 2).should == [1, 2]
lambda { m("a" => 1, a: 1, b: 2) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(a:, b: 1) [a, b] end
ruby
m(a: 1).should == [1, 1]
m(a: 1, b: 2).should == [1, 2]
lambda { m("a" => 1, a: 1, b: 2) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(a:, **) a end
ruby
m(a: 1).should == 1
m(a: 1, b: 2).should == 1
lambda { m("a" => 1, a: 1, b: 2) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(a:, **k) [a, k] end
ruby
m(a: 1).should == [1, {}]
m(a: 1, b: 2, c: 3).should == [1, {b: 2, c: 3}]
lambda { m("a" => 1, a: 1, b: 2) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(a:, &b) [a, b] end
ruby
m(a: 1).should == [1, nil]
m(a: 1, &(l = ->{})).should == [1, l]
end
evaluate <<-ruby do
def m(a: 1, b:) [a, b] end
ruby
m(b: 0).should == [1, 0]
m(b: 2, a: 3).should == [3, 2]
end
evaluate <<-ruby do
def m(a: def m(a: 1) a end, b:)
[a, b]
end
ruby
m(a: 2, b: 3).should == [2, 3]
m(b: 1).should == [:m, 1]
# Note the default value of a: in the original method.
m().should == 1
end
evaluate <<-ruby do
def m(a: 1, b: 2) [a, b] end
ruby
m().should == [1, 2]
m(b: 3, a: 4).should == [4, 3]
end
evaluate <<-ruby do
def m(a: 1, **) a end
ruby
m().should == 1
m(a: 2, b: 1).should == 2
end
evaluate <<-ruby do
def m(a: 1, **k) [a, k] end
ruby
m(b: 2, c: 3).should == [1, {b: 2, c: 3}]
end
evaluate <<-ruby do
def m(a: 1, &b) [a, b] end
ruby
m(&(l = ->{})).should == [1, l]
m().should == [1, nil]
end
evaluate <<-ruby do
def m(**, &b) b end
ruby
m(a: 1, b: 2, &(l = ->{})).should == l
end
evaluate <<-ruby do
def m(**k, &b) [k, b] end
ruby
m(a: 1, b: 2).should == [{ a: 1, b: 2}, nil]
end
evaluate <<-ruby do
def m(a, b=1, *c, (*d, (e)), f: 2, g:, h:, **k, &l)
[a, b, c, d, e, f, g, h, k, l]
end
ruby
result = m(9, 8, 7, 6, f: 5, g: 4, h: 3, &(l = ->{}))
result.should == [9, 8, [7], [], 6, 5, 4, 3, {}, l]
end
evaluate <<-ruby do
def m(a, b=1, *c, d, e:, f: 2, g:, **k, &l)
[a, b, c, d, e, f, g, k, l]
end
ruby
result = m(1, 2, e: 3, g: 4, h: 5, i: 6, &(l = ->{}))
result.should == [1, 1, [], 2, 3, 2, 4, { h: 5, i: 6 }, l]
end
evaluate <<-ruby do
def m(a, b = nil, c = nil, d, e: nil, **f)
[a, b, c, d, e, f]
end
ruby
result = m(1, 2)
result.should == [1, nil, nil, 2, nil, {}]
result = m(1, 2, {foo: :bar})
result.should == [1, nil, nil, 2, nil, {foo: :bar}]
result = m(1, {foo: :bar})
result.should == [1, nil, nil, {foo: :bar}, nil, {}]
end
end
end
describe "A method call with a space between method name and parentheses" do
before(:each) do
def m(*args)
args
end
def n(value, &block)
[value, block.call]
end
end
context "when no arguments provided" do
it "assigns nil" do
args = m ()
args.should == [nil]
end
end
context "when a single argument provided" do
it "assigns it" do
args = m (1 == 1 ? true : false)
args.should == [true]
end
end
context "when 2+ arguments provided" do
it "raises a syntax error" do
lambda {
eval("m (1, 2)")
}.should raise_error(SyntaxError)
lambda {
eval("m (1, 2, 3)")
}.should raise_error(SyntaxError)
end
end
it "allows to pass a block with curly braces" do
args = n () { :block_value }
args.should == [nil, :block_value]
args = n (1) { :block_value }
args.should == [1, :block_value]
end
it "allows to pass a block with do/end" do
args = n () do
:block_value
end
args.should == [nil, :block_value]
args = n (1) do
:block_value
end
args.should == [1, :block_value]
end
end
describe "An array-dereference method ([])" do
SpecEvaluate.desc = "for definition"
context "received the passed-in block" do
evaluate <<-ruby do
def [](*, &b)
b.call
end
ruby
pr = proc {:ok}
self[&pr].should == :ok
self['foo', &pr].should == :ok
self.[](&pr).should == :ok
self.[]('foo', &pr).should == :ok
end
evaluate <<-ruby do
def [](*)
yield
end
ruby
pr = proc {:ok}
self[&pr].should == :ok
self['foo', &pr].should == :ok
self.[](&pr).should == :ok
self.[]('foo', &pr).should == :ok
end
end
end
Add spec to ensure incoming Hash is not mutated by keyword args.
See jruby/jruby#5267.
require_relative '../spec_helper'
describe "A method send" do
evaluate <<-ruby do
def m(a) a end
ruby
a = b = m 1
a.should == 1
b.should == 1
end
context "with a single splatted Object argument" do
before :all do
def m(a) a end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
m(*x).should equal(x)
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([1])
m(*x).should == 1
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
m(*x).should == x
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { m(*x) }.should raise_error(TypeError)
end
end
context "with a leading splatted Object argument" do
before :all do
def m(a, b, *c, d, e) [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
m(*x, 1, 2, 3).should == [x, 1, [], 2, 3]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([1])
m(*x, 2, 3, 4).should == [1, 2, [], 3, 4]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
m(*x, 2, 3, 4).should == [x, 2, [], 3, 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { m(*x, 2, 3) }.should raise_error(TypeError)
end
end
context "with a middle splatted Object argument" do
before :all do
def m(a, b, *c, d, e) [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
m(1, 2, *x, 3, 4).should == [1, 2, [x], 3, 4]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([5, 6, 7])
m(1, 2, *x, 3).should == [1, 2, [5, 6], 7, 3]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
m(1, 2, *x, 4).should == [1, 2, [], x, 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { m(1, *x, 2, 3) }.should raise_error(TypeError)
end
it "copies the splatted array" do
args = [3, 4]
m(1, 2, *args, 4, 5).should == [1, 2, [3, 4], 4, 5]
m(1, 2, *args, 4, 5)[2].should_not equal(args)
end
it "allows an array being splatted to be modified by another argument" do
args = [3, 4]
m(1, args.shift, *args, 4, 5).should == [1, 3, [4], 4, 5]
end
end
context "with a trailing splatted Object argument" do
before :all do
def m(a, *b, c) [a, b, c] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
m(1, 2, *x).should == [1, [2], x]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([5, 6, 7])
m(1, 2, *x).should == [1, [2, 5, 6], 7]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
m(1, 2, *x, 4).should == [1, [2, x], 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { m(1, 2, *x) }.should raise_error(TypeError)
end
end
end
describe "An element assignment method send" do
before :each do
ScratchPad.clear
end
context "with a single splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.[]=(a, b) ScratchPad.record [a, b] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o[*x] = 1).should == 1
ScratchPad.recorded.should == [x, 1]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([1])
(@o[*x] = 2).should == 2
ScratchPad.recorded.should == [1, 2]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o[*x] = 1).should == 1
ScratchPad.recorded.should == [x, 1]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o[*x] = 1 }.should raise_error(TypeError)
end
end
context "with a leading splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.[]=(a, b, *c, d, e) ScratchPad.record [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o[*x, 2, 3, 4] = 1).should == 1
ScratchPad.recorded.should == [x, 2, [3], 4, 1]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([1, 2, 3])
(@o[*x, 4, 5] = 6).should == 6
ScratchPad.recorded.should == [1, 2, [3, 4], 5, 6]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o[*x, 2, 3, 4] = 5).should == 5
ScratchPad.recorded.should == [x, 2, [3], 4, 5]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o[*x, 2, 3] = 4 }.should raise_error(TypeError)
end
end
context "with a middle splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.[]=(a, b, *c, d, e) ScratchPad.record [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o[1, *x, 2, 3] = 4).should == 4
ScratchPad.recorded.should == [1, x, [2], 3, 4]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([2, 3])
(@o[1, *x, 4] = 5).should == 5
ScratchPad.recorded.should == [1, 2, [3], 4, 5]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o[1, 2, *x, 3] = 4).should == 4
ScratchPad.recorded.should == [1, 2, [x], 3, 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o[1, 2, *x, 3] = 4 }.should raise_error(TypeError)
end
end
context "with a trailing splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.[]=(a, b, *c, d, e) ScratchPad.record [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o[1, 2, 3, 4, *x] = 5).should == 5
ScratchPad.recorded.should == [1, 2, [3, 4], x, 5]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([4, 5])
(@o[1, 2, 3, *x] = 6).should == 6
ScratchPad.recorded.should == [1, 2, [3, 4], 5, 6]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o[1, 2, 3, *x] = 4).should == 4
ScratchPad.recorded.should == [1, 2, [3], x, 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o[1, 2, 3, *x] = 4 }.should raise_error(TypeError)
end
end
end
describe "An attribute assignment method send" do
context "with a single splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.m=(a, b) [a, b] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o.send :m=, *x, 1).should == [x, 1]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([1])
(@o.send :m=, *x, 2).should == [1, 2]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o.send :m=, *x, 1).should == [x, 1]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o.send :m=, *x, 1 }.should raise_error(TypeError)
end
end
context "with a leading splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.m=(a, b, *c, d, e) [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o.send :m=, *x, 2, 3, 4, 1).should == [x, 2, [3], 4, 1]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([1, 2, 3])
(@o.send :m=, *x, 4, 5, 6).should == [1, 2, [3, 4], 5, 6]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o.send :m=, *x, 2, 3, 4, 5).should == [x, 2, [3], 4, 5]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o.send :m=, *x, 2, 3, 4 }.should raise_error(TypeError)
end
end
context "with a middle splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.m=(a, b, *c, d, e) [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o.send :m=, 1, *x, 2, 3, 4).should == [1, x, [2], 3, 4]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([2, 3])
(@o.send :m=, 1, *x, 4, 5).should == [1, 2, [3], 4, 5]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o.send :m=, 1, 2, *x, 3, 4).should == [1, 2, [x], 3, 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o.send :m=, 1, 2, *x, 3, 4 }.should raise_error(TypeError)
end
end
context "with a trailing splatted Object argument" do
before :all do
@o = mock("element set receiver")
def @o.m=(a, b, *c, d, e) [a, b, c, d, e] end
end
it "does not call #to_ary" do
x = mock("splat argument")
x.should_not_receive(:to_ary)
(@o.send :m=, 1, 2, 3, 4, *x, 5).should == [1, 2, [3, 4], x, 5]
end
it "calls #to_a" do
x = mock("splat argument")
x.should_receive(:to_a).and_return([4, 5])
(@o.send :m=, 1, 2, 3, *x, 6).should == [1, 2, [3, 4], 5, 6]
end
it "wraps the argument in an Array if #to_a returns nil" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(nil)
(@o.send :m=, 1, 2, 3, *x, 4).should == [1, 2, [3], x, 4]
end
it "raises a TypeError if #to_a does not return an Array" do
x = mock("splat argument")
x.should_receive(:to_a).and_return(1)
lambda { @o.send :m=, 1, 2, 3, *x, 4 }.should raise_error(TypeError)
end
end
end
describe "A method" do
SpecEvaluate.desc = "for definition"
context "assigns no local variables" do
evaluate <<-ruby do
def m
end
ruby
m.should be_nil
end
evaluate <<-ruby do
def m()
end
ruby
m.should be_nil
end
end
context "assigns local variables from method parameters" do
evaluate <<-ruby do
def m(a) a end
ruby
m((args = 1, 2, 3)).should equal(args)
end
evaluate <<-ruby do
def m((a)) a end
ruby
m(1).should == 1
m([1, 2, 3]).should == 1
end
evaluate <<-ruby do
def m((*a, b)) [a, b] end
ruby
m(1).should == [[], 1]
m([1, 2, 3]).should == [[1, 2], 3]
end
evaluate <<-ruby do
def m(a=1) a end
ruby
m().should == 1
m(2).should == 2
end
evaluate <<-ruby do
def m() end
ruby
m().should be_nil
m(*[]).should be_nil
m(**{}).should be_nil
end
evaluate <<-ruby do
def m(*) end
ruby
m().should be_nil
m(1).should be_nil
m(1, 2, 3).should be_nil
end
evaluate <<-ruby do
def m(*a) a end
ruby
m().should == []
m(1).should == [1]
m(1, 2, 3).should == [1, 2, 3]
m(*[]).should == []
m(**{}).should == []
end
evaluate <<-ruby do
def m(a:) a end
ruby
lambda { m() }.should raise_error(ArgumentError)
m(a: 1).should == 1
lambda { m("a" => 1, a: 1) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(a: 1) a end
ruby
m().should == 1
m(a: 2).should == 2
end
evaluate <<-ruby do
def m(**) end
ruby
m().should be_nil
m(a: 1, b: 2).should be_nil
lambda { m(1) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(**k) k end
ruby
m().should == {}
m(a: 1, b: 2).should == { a: 1, b: 2 }
m(*[]).should == {}
m(**{}).should == {}
lambda { m(2) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(&b) b end
ruby
m { }.should be_an_instance_of(Proc)
end
evaluate <<-ruby do
def m(a, b) [a, b] end
ruby
m(1, 2).should == [1, 2]
end
evaluate <<-ruby do
def m(a, (b, c)) [a, b, c] end
ruby
m(1, 2).should == [1, 2, nil]
m(1, [2, 3, 4]).should == [1, 2, 3]
end
evaluate <<-ruby do
def m((a), (b)) [a, b] end
ruby
m(1, 2).should == [1, 2]
m([1, 2], [3, 4]).should == [1, 3]
end
evaluate <<-ruby do
def m((*), (*)) end
ruby
m(2, 3).should be_nil
m([2, 3, 4], [5, 6]).should be_nil
lambda { m a: 1 }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m((*a), (*b)) [a, b] end
ruby
m(1, 2).should == [[1], [2]]
m([1, 2], [3, 4]).should == [[1, 2], [3, 4]]
end
evaluate <<-ruby do
def m((a, b), (c, d))
[a, b, c, d]
end
ruby
m(1, 2).should == [1, nil, 2, nil]
m([1, 2, 3], [4, 5, 6]).should == [1, 2, 4, 5]
end
evaluate <<-ruby do
def m((a, *b), (*c, d))
[a, b, c, d]
end
ruby
m(1, 2).should == [1, [], [], 2]
m([1, 2, 3], [4, 5, 6]).should == [1, [2, 3], [4, 5], 6]
end
evaluate <<-ruby do
def m((a, b, *c, d), (*e, f, g), (*h))
[a, b, c, d, e, f, g, h]
end
ruby
m(1, 2, 3).should == [1, nil, [], nil, [], 2, nil, [3]]
result = m([1, 2, 3], [4, 5, 6, 7, 8], [9, 10])
result.should == [1, 2, [], 3, [4, 5, 6], 7, 8, [9, 10]]
end
evaluate <<-ruby do
def m(a, (b, (c, *d), *e))
[a, b, c, d, e]
end
ruby
m(1, 2).should == [1, 2, nil, [], []]
m(1, [2, [3, 4, 5], 6, 7, 8]).should == [1, 2, 3, [4, 5], [6, 7, 8]]
end
evaluate <<-ruby do
def m(a, (b, (c, *d, (e, (*f)), g), (h, (i, j))))
[a, b, c, d, e, f, g, h, i, j]
end
ruby
m(1, 2).should == [1, 2, nil, [], nil, [nil], nil, nil, nil, nil]
result = m(1, [2, [3, 4, 5, [6, [7, 8]], 9], [10, [11, 12]]])
result.should == [1, 2, 3, [4, 5], 6, [7, 8], 9, 10, 11, 12]
end
evaluate <<-ruby do
def m(a, b=1) [a, b] end
ruby
m(2).should == [2, 1]
m(1, 2).should == [1, 2]
end
evaluate <<-ruby do
def m(a, *) a end
ruby
m(1).should == 1
m(1, 2, 3).should == 1
end
evaluate <<-ruby do
def m(a, *b) [a, b] end
ruby
m(1).should == [1, []]
m(1, 2, 3).should == [1, [2, 3]]
end
evaluate <<-ruby do
def m(a, b:) [a, b] end
ruby
m(1, b: 2).should == [1, 2]
lambda { m("a" => 1, b: 2) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(a, b: 1) [a, b] end
ruby
m(2).should == [2, 1]
m(1, b: 2).should == [1, 2]
m("a" => 1, b: 2).should == [{"a" => 1, b: 2}, 1]
end
evaluate <<-ruby do
def m(a, **) a end
ruby
m(1).should == 1
m(1, a: 2, b: 3).should == 1
m("a" => 1, b: 2).should == {"a" => 1, b: 2}
end
evaluate <<-ruby do
def m(a, **k) [a, k] end
ruby
m(1).should == [1, {}]
m(1, a: 2, b: 3).should == [1, {a: 2, b: 3}]
m("a" => 1, b: 2).should == [{"a" => 1, b: 2}, {}]
end
evaluate <<-ruby do
def m(a, &b) [a, b] end
ruby
m(1).should == [1, nil]
m(1, &(l = -> {})).should == [1, l]
end
evaluate <<-ruby do
def m(a=1, b) [a, b] end
ruby
m(2).should == [1, 2]
m(2, 3).should == [2, 3]
end
evaluate <<-ruby do
def m(a=1, *) a end
ruby
m().should == 1
m(2, 3, 4).should == 2
end
evaluate <<-ruby do
def m(a=1, *b) [a, b] end
ruby
m().should == [1, []]
m(2, 3, 4).should == [2, [3, 4]]
end
evaluate <<-ruby do
def m(a=1, (b, c)) [a, b, c] end
ruby
m(2).should == [1, 2, nil]
m(2, 3).should == [2, 3, nil]
m(2, [3, 4, 5]).should == [2, 3, 4]
end
evaluate <<-ruby do
def m(a=1, (b, (c, *d))) [a, b, c, d] end
ruby
m(2).should == [1, 2, nil, []]
m(2, 3).should == [2, 3, nil, []]
m(2, [3, [4, 5, 6], 7]).should == [2, 3, 4, [5, 6]]
end
evaluate <<-ruby do
def m(a=1, (b, (c, *d), *e)) [a, b, c, d, e] end
ruby
m(2).should == [1, 2, nil, [], []]
m(2, [3, 4, 5, 6]).should == [2, 3, 4, [], [5, 6]]
m(2, [3, [4, 5, 6], 7]).should == [2, 3, 4, [5, 6], [7]]
end
evaluate <<-ruby do
def m(a=1, (b), (c)) [a, b, c] end
ruby
m(2, 3).should == [1, 2, 3]
m(2, 3, 4).should == [2, 3, 4]
m(2, [3, 4], [5, 6, 7]).should == [2, 3, 5]
end
evaluate <<-ruby do
def m(a=1, (*b), (*c)) [a, b, c] end
ruby
lambda { m() }.should raise_error(ArgumentError)
lambda { m(2) }.should raise_error(ArgumentError)
m(2, 3).should == [1, [2], [3]]
m(2, [3, 4], [5, 6]).should == [2, [3, 4], [5, 6]]
end
evaluate <<-ruby do
def m(a=1, (b, c), (d, e)) [a, b, c, d, e] end
ruby
m(2, 3).should == [1, 2, nil, 3, nil]
m(2, [3, 4, 5], [6, 7, 8]).should == [2, 3, 4, 6, 7]
end
evaluate <<-ruby do
def m(a=1, (b, *c), (*d, e))
[a, b, c, d, e]
end
ruby
m(1, 2).should == [1, 1, [], [], 2]
m(1, [2, 3], [4, 5, 6]).should == [1, 2, [3], [4, 5], 6]
end
evaluate <<-ruby do
def m(a=1, (b, *c), (d, (*e, f)))
[a, b, c, d, e, f]
end
ruby
m(1, 2).should == [1, 1, [], 2, [], nil]
m(nil, nil).should == [1, nil, [], nil, [], nil]
result = m([1, 2, 3], [4, 5, 6], [7, 8, 9])
result.should == [[1, 2, 3], 4, [5, 6], 7, [], 8]
end
evaluate <<-ruby do
def m(a=1, b:) [a, b] end
ruby
m(b: 2).should == [1, 2]
m(2, b: 1).should == [2, 1]
ruby_version_is ""..."2.6" do
m("a" => 1, b: 2).should == [{"a" => 1}, 2]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, b: 2)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(a=1, b: 2) [a, b] end
ruby
m().should == [1, 2]
m(2).should == [2, 2]
m(b: 3).should == [1, 3]
ruby_version_is ""..."2.6" do
m("a" => 1, b: 2).should == [{"a" => 1}, 2]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, b: 2)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(a=1, **) a end
ruby
m().should == 1
m(2, a: 1, b: 0).should == 2
ruby_version_is ""..."2.6" do
m("a" => 1, a: 2).should == {"a" => 1}
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 2)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(a=1, **k) [a, k] end
ruby
m().should == [1, {}]
m(2, a: 1, b: 2).should == [2, {a: 1, b: 2}]
end
evaluate <<-ruby do
def m(a=1, &b) [a, b] end
ruby
m().should == [1, nil]
m(&(l = -> {})).should == [1, l]
p = -> {}
l = mock("to_proc")
l.should_receive(:to_proc).and_return(p)
m(&l).should == [1, p]
end
evaluate <<-ruby do
def m(*, a) a end
ruby
m(1).should == 1
m(1, 2, 3).should == 3
end
evaluate <<-ruby do
def m(*a, b) [a, b] end
ruby
m(1).should == [[], 1]
m(1, 2, 3).should == [[1, 2], 3]
end
evaluate <<-ruby do
def m(*, a:) a end
ruby
m(a: 1).should == 1
m(1, 2, a: 3).should == 3
ruby_version_is ""..."2.6" do
m("a" => 1, a: 2).should == 2
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 2)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(*a, b:) [a, b] end
ruby
m(b: 1).should == [[], 1]
m(1, 2, b: 3).should == [[1, 2], 3]
ruby_version_is ""..."2.6" do
m("a" => 1, b: 2).should == [[{"a" => 1}], 2]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, b: 2)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(*, a: 1) a end
ruby
m().should == 1
m(1, 2).should == 1
m(a: 2).should == 2
m(1, a: 2).should == 2
ruby_version_is ""..."2.6" do
m("a" => 1, a: 2).should == 2
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 2)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(*a, b: 1) [a, b] end
ruby
m().should == [[], 1]
m(1, 2, 3, b: 4).should == [[1, 2, 3], 4]
ruby_version_is ""..."2.6" do
m("a" => 1, b: 2).should == [[{"a" => 1}], 2]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, b: 2)}.should raise_error(ArgumentError)
end
a = mock("splat")
a.should_not_receive(:to_ary)
m(*a).should == [[a], 1]
end
evaluate <<-ruby do
def m(*, **) end
ruby
m().should be_nil
m(a: 1, b: 2).should be_nil
m(1, 2, 3, a: 4, b: 5).should be_nil
h = mock("keyword splat")
h.should_receive(:to_hash).and_return({a: 1})
m(h).should be_nil
h = mock("keyword splat")
error = RuntimeError.new("error while converting to a hash")
h.should_receive(:to_hash).and_raise(error)
lambda { m(h) }.should raise_error(error)
end
evaluate <<-ruby do
def m(*a, **) a end
ruby
m().should == []
m(1, 2, 3, a: 4, b: 5).should == [1, 2, 3]
ruby_version_is ""..."2.6" do
m("a" => 1, a: 1).should == [{"a" => 1}]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 1)}.should raise_error(ArgumentError)
end
m(1, **{a: 2}).should == [1]
h = mock("keyword splat")
h.should_receive(:to_hash)
lambda { m(**h) }.should raise_error(TypeError)
end
evaluate <<-ruby do
def m(*, **k) k end
ruby
m().should == {}
m(1, 2, 3, a: 4, b: 5).should == {a: 4, b: 5}
ruby_version_is ""..."2.6" do
m("a" => 1, a: 1).should == {a: 1}
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 1)}.should raise_error(ArgumentError)
end
h = mock("keyword splat")
h.should_receive(:to_hash).and_return({a: 1})
m(h).should == {a: 1}
end
evaluate <<-ruby do
def m(a = nil, **k) [a, k] end
ruby
m().should == [nil, {}]
m("a" => 1).should == [{"a" => 1}, {}]
m(a: 1).should == [nil, {a: 1}]
ruby_version_is ""..."2.6" do
m("a" => 1, a: 1).should == [{"a" => 1}, {a: 1}]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 1)}.should raise_error(ArgumentError)
end
m({ "a" => 1 }, a: 1).should == [{"a" => 1}, {a: 1}]
m({a: 1}, {}).should == [{a: 1}, {}]
h = {"a" => 1, b: 2}
ruby_version_is ""..."2.6" do
m(h).should == [{"a" => 1}, {b: 2}]
end
ruby_version_is "2.6" do
lambda {m(h)}.should raise_error(ArgumentError)
end
h.should == {"a" => 1, b: 2}
h = {"a" => 1}
m(h).first.should == h
h = {}
r = m(h)
r.first.should be_nil
r.last.should == {}
hh = {}
h = mock("keyword splat empty hash")
h.should_receive(:to_hash).and_return(hh)
r = m(h)
r.first.should be_nil
r.last.should == {}
h = mock("keyword splat")
h.should_receive(:to_hash).and_return({"a" => 1, a: 2})
ruby_version_is ""..."2.6" do
m(h).should == [{"a" => 1}, {a: 2}]
end
ruby_version_is "2.6" do
lambda {m(h)}.should raise_error(ArgumentError)
end
end
evaluate <<-ruby do
def m(*a, **k) [a, k] end
ruby
m().should == [[], {}]
m(1).should == [[1], {}]
m(a: 1, b: 2).should == [[], {a: 1, b: 2}]
m(1, 2, 3, a: 2).should == [[1, 2, 3], {a: 2}]
m("a" => 1).should == [[{"a" => 1}], {}]
m(a: 1).should == [[], {a: 1}]
ruby_version_is ""..."2.6" do
m("a" => 1, a: 1).should == [[{"a" => 1}], {a: 1}]
end
ruby_version_is "2.6" do
lambda {m("a" => 1, a: 1)}.should raise_error(ArgumentError)
end
m({ "a" => 1 }, a: 1).should == [[{"a" => 1}], {a: 1}]
m({a: 1}, {}).should == [[{a: 1}], {}]
m({a: 1}, {"a" => 1}).should == [[{a: 1}, {"a" => 1}], {}]
bo = BasicObject.new
def bo.to_a; [1, 2, 3]; end
def bo.to_hash; {:b => 2, :c => 3}; end
m(*bo, **bo).should == [[1, 2, 3], {:b => 2, :c => 3}]
end
evaluate <<-ruby do
def m(*, &b) b end
ruby
m().should be_nil
m(1, 2, 3, 4).should be_nil
m(&(l = ->{})).should equal(l)
end
evaluate <<-ruby do
def m(*a, &b) [a, b] end
ruby
m().should == [[], nil]
m(1).should == [[1], nil]
m(1, 2, 3, &(l = -> {})).should == [[1, 2, 3], l]
end
evaluate <<-ruby do
def m(a:, b:) [a, b] end
ruby
m(a: 1, b: 2).should == [1, 2]
lambda { m("a" => 1, a: 1, b: 2) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(a:, b: 1) [a, b] end
ruby
m(a: 1).should == [1, 1]
m(a: 1, b: 2).should == [1, 2]
lambda { m("a" => 1, a: 1, b: 2) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(a:, **) a end
ruby
m(a: 1).should == 1
m(a: 1, b: 2).should == 1
lambda { m("a" => 1, a: 1, b: 2) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(a:, **k) [a, k] end
ruby
m(a: 1).should == [1, {}]
m(a: 1, b: 2, c: 3).should == [1, {b: 2, c: 3}]
lambda { m("a" => 1, a: 1, b: 2) }.should raise_error(ArgumentError)
end
evaluate <<-ruby do
def m(a:, &b) [a, b] end
ruby
m(a: 1).should == [1, nil]
m(a: 1, &(l = ->{})).should == [1, l]
end
evaluate <<-ruby do
def m(a: 1, b:) [a, b] end
ruby
m(b: 0).should == [1, 0]
m(b: 2, a: 3).should == [3, 2]
end
evaluate <<-ruby do
def m(a: def m(a: 1) a end, b:)
[a, b]
end
ruby
m(a: 2, b: 3).should == [2, 3]
m(b: 1).should == [:m, 1]
# Note the default value of a: in the original method.
m().should == 1
end
evaluate <<-ruby do
def m(a: 1, b: 2) [a, b] end
ruby
m().should == [1, 2]
m(b: 3, a: 4).should == [4, 3]
end
evaluate <<-ruby do
def m(a: 1, **) a end
ruby
m().should == 1
m(a: 2, b: 1).should == 2
end
evaluate <<-ruby do
def m(a: 1, **k) [a, k] end
ruby
m(b: 2, c: 3).should == [1, {b: 2, c: 3}]
end
evaluate <<-ruby do
def m(a: 1, &b) [a, b] end
ruby
m(&(l = ->{})).should == [1, l]
m().should == [1, nil]
end
evaluate <<-ruby do
def m(**, &b) b end
ruby
m(a: 1, b: 2, &(l = ->{})).should == l
end
evaluate <<-ruby do
def m(**k, &b) [k, b] end
ruby
m(a: 1, b: 2).should == [{ a: 1, b: 2}, nil]
end
evaluate <<-ruby do
def m(a, b=1, *c, (*d, (e)), f: 2, g:, h:, **k, &l)
[a, b, c, d, e, f, g, h, k, l]
end
ruby
result = m(9, 8, 7, 6, f: 5, g: 4, h: 3, &(l = ->{}))
result.should == [9, 8, [7], [], 6, 5, 4, 3, {}, l]
end
evaluate <<-ruby do
def m(a, b=1, *c, d, e:, f: 2, g:, **k, &l)
[a, b, c, d, e, f, g, k, l]
end
ruby
result = m(1, 2, e: 3, g: 4, h: 5, i: 6, &(l = ->{}))
result.should == [1, 1, [], 2, 3, 2, 4, { h: 5, i: 6 }, l]
end
evaluate <<-ruby do
def m(a, b = nil, c = nil, d, e: nil, **f)
[a, b, c, d, e, f]
end
ruby
result = m(1, 2)
result.should == [1, nil, nil, 2, nil, {}]
result = m(1, 2, {foo: :bar})
result.should == [1, nil, nil, 2, nil, {foo: :bar}]
result = m(1, {foo: :bar})
result.should == [1, nil, nil, {foo: :bar}, nil, {}]
end
end
context "assigns keyword arguments from a passed Hash without modifying it" do
evaluate <<-ruby do
def m(a: nil); a; end
ruby
options = {a: 1}.freeze
lambda do
m(options).should == 1
end.should_not raise_error
options.should == {a: 1}
end
end
end
describe "A method call with a space between method name and parentheses" do
before(:each) do
def m(*args)
args
end
def n(value, &block)
[value, block.call]
end
end
context "when no arguments provided" do
it "assigns nil" do
args = m ()
args.should == [nil]
end
end
context "when a single argument provided" do
it "assigns it" do
args = m (1 == 1 ? true : false)
args.should == [true]
end
end
context "when 2+ arguments provided" do
it "raises a syntax error" do
lambda {
eval("m (1, 2)")
}.should raise_error(SyntaxError)
lambda {
eval("m (1, 2, 3)")
}.should raise_error(SyntaxError)
end
end
it "allows to pass a block with curly braces" do
args = n () { :block_value }
args.should == [nil, :block_value]
args = n (1) { :block_value }
args.should == [1, :block_value]
end
it "allows to pass a block with do/end" do
args = n () do
:block_value
end
args.should == [nil, :block_value]
args = n (1) do
:block_value
end
args.should == [1, :block_value]
end
end
describe "An array-dereference method ([])" do
SpecEvaluate.desc = "for definition"
context "received the passed-in block" do
evaluate <<-ruby do
def [](*, &b)
b.call
end
ruby
pr = proc {:ok}
self[&pr].should == :ok
self['foo', &pr].should == :ok
self.[](&pr).should == :ok
self.[]('foo', &pr).should == :ok
end
evaluate <<-ruby do
def [](*)
yield
end
ruby
pr = proc {:ok}
self[&pr].should == :ok
self['foo', &pr].should == :ok
self.[](&pr).should == :ok
self.[]('foo', &pr).should == :ok
end
end
end
|
require "formula"
class SpotlightActions < Formula
homepage "https://github.com/xwmx/spotlight-actions"
url "https://github.com/xwmx/spotlight-actions.git",
:using => :git,
:branch => "master"
head "https://github.com/xwmx/spotlight-actions.git"
def install
bin.install "spotlight-actions"
end
test do
system "#{bin}/spotlight-actions"
end
end
Only specify `head` in spotlight-actions.
require "formula"
class SpotlightActions < Formula
homepage "https://github.com/xwmx/spotlight-actions"
# url "https://github.com/xwmx/spotlight-actions.git",
# :using => :git
head "https://github.com/xwmx/spotlight-actions.git"
def install
bin.install "spotlight-actions"
end
test do
system "#{bin}/spotlight-actions"
end
end
|
# encoding: UTF-8
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_ipay88'
s.version = '2.1.3.4'
s.summary = 'Ipay88 For Spree'
s.description = 'Ipay88 For Spree'
s.required_ruby_version = '>= 1.9.3'
s.author = 'Calvin Tee'
s.email = 'calvin@collectskin.com'
s.homepage = 'http://collectskin.com'
#s.files = `git ls-files`.split("\n")
#s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'spree_core', '~> 2.1.1'
s.add_development_dependency 'capybara', '~> 2.1'
s.add_development_dependency 'coffee-rails'
s.add_development_dependency 'database_cleaner'
s.add_development_dependency 'factory_girl', '~> 4.2'
s.add_development_dependency 'ffaker'
s.add_development_dependency 'rspec-rails', '~> 2.13'
s.add_development_dependency 'sass-rails'
s.add_development_dependency 'selenium-webdriver'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'sqlite3'
end
Change requirements for ipay88 for spree 2.3.0
# encoding: UTF-8
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_ipay88'
s.version = '2.1.3.4'
s.summary = 'Ipay88 For Spree'
s.description = 'Ipay88 For Spree'
s.required_ruby_version = '>= 1.9.3'
s.author = 'Calvin Tee'
s.email = 'calvin@collectskin.com'
s.homepage = 'http://collectskin.com'
#s.files = `git ls-files`.split("\n")
#s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'spree_core', '~> 2.3.0'
s.add_development_dependency 'capybara', '~> 2.1'
s.add_development_dependency 'coffee-rails'
s.add_development_dependency 'database_cleaner'
s.add_development_dependency 'factory_girl', '~> 4.2'
s.add_development_dependency 'ffaker'
s.add_development_dependency 'rspec-rails', '~> 2.13'
s.add_development_dependency 'sass-rails'
s.add_development_dependency 'selenium-webdriver'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'sqlite3'
end
|
lib = File.expand_path('../lib/', __FILE__)
$LOAD_PATH.unshift lib unless $LOAD_PATH.include?(lib)
require 'spree_social/version'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_social'
s.version = SpreeSocial.version
s.summary = 'Adds social network login services (OAuth) to Spree'
s.description = s.summary
s.required_ruby_version = '>= 2.1.0'
s.author = 'John Dyer'
s.email = 'jdyer@spreecommerce.com'
s.homepage = 'http://www.spreecommerce.com'
s.license = 'BSD-3'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- spec/*`.split("\n")
s.require_path = 'lib'
s.requirements << 'none'
s.add_runtime_dependency 'spree_core', '>= 3.1.0', '< 4.0'
s.add_runtime_dependency 'spree_auth_devise', '>= 3.1.0', '< 4.0'
s.add_runtime_dependency 'spree_extension'
s.add_runtime_dependency 'omniauth'
s.add_runtime_dependency 'oa-core'
s.add_runtime_dependency 'omniauth-twitter'
s.add_runtime_dependency 'omniauth-facebook'
s.add_runtime_dependency 'omniauth-github'
s.add_runtime_dependency 'omniauth-google-oauth2'
s.add_runtime_dependency 'omniauth-amazon'
s.add_development_dependency 'capybara'
s.add_development_dependency 'capybara-screenshot'
s.add_development_dependency 'database_cleaner'
s.add_development_dependency 'ffaker'
s.add_development_dependency 'rspec-rails'
s.add_development_dependency 'factory_bot'
s.add_development_dependency 'pry-rails'
s.add_development_dependency 'selenium-webdriver'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'sqlite3'
s.add_development_dependency 'coffee-rails'
s.add_development_dependency 'sass-rails'
s.add_development_dependency 'guard-rspec'
s.add_development_dependency 'rubocop'
s.add_development_dependency 'appraisal'
s.add_development_dependency 'pg', '~> 0.18'
s.add_development_dependency 'mysql2', '~> 0.5.1'
s.add_development_dependency 'puma'
end
Lock factory-bot at 4.x
lib = File.expand_path('../lib/', __FILE__)
$LOAD_PATH.unshift lib unless $LOAD_PATH.include?(lib)
require 'spree_social/version'
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_social'
s.version = SpreeSocial.version
s.summary = 'Adds social network login services (OAuth) to Spree'
s.description = s.summary
s.required_ruby_version = '>= 2.1.0'
s.author = 'John Dyer'
s.email = 'jdyer@spreecommerce.com'
s.homepage = 'http://www.spreecommerce.com'
s.license = 'BSD-3'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- spec/*`.split("\n")
s.require_path = 'lib'
s.requirements << 'none'
s.add_runtime_dependency 'spree_core', '>= 3.1.0', '< 4.0'
s.add_runtime_dependency 'spree_auth_devise', '>= 3.1.0', '< 4.0'
s.add_runtime_dependency 'spree_extension'
s.add_runtime_dependency 'omniauth'
s.add_runtime_dependency 'oa-core'
s.add_runtime_dependency 'omniauth-twitter'
s.add_runtime_dependency 'omniauth-facebook'
s.add_runtime_dependency 'omniauth-github'
s.add_runtime_dependency 'omniauth-google-oauth2'
s.add_runtime_dependency 'omniauth-amazon'
s.add_development_dependency 'capybara'
s.add_development_dependency 'capybara-screenshot'
s.add_development_dependency 'database_cleaner'
s.add_development_dependency 'ffaker'
s.add_development_dependency 'rspec-rails'
s.add_development_dependency 'factory_bot', '~> 4.7'
s.add_development_dependency 'pry-rails'
s.add_development_dependency 'selenium-webdriver'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'sqlite3'
s.add_development_dependency 'coffee-rails'
s.add_development_dependency 'sass-rails'
s.add_development_dependency 'guard-rspec'
s.add_development_dependency 'rubocop'
s.add_development_dependency 'appraisal'
s.add_development_dependency 'pg', '~> 0.18'
s.add_development_dependency 'mysql2', '~> 0.5.1'
s.add_development_dependency 'puma'
end
|
require 'active_support/all'
module ControllerHacks
def api_get(action, params={}, session=nil, flash=nil)
api_process(action, params, session, flash, "GET")
end
def api_post(action, params={}, session=nil, flash=nil)
api_process(action, params, session, flash, "POST")
end
def api_put(action, params={}, session=nil, flash=nil)
api_process(action, params, session, flash, "PUT")
end
def api_delete(action, params={}, session=nil, flash=nil)
api_process(action, params, session, flash, "DELETE")
end
def api_process(action, params={}, session=nil, flash=nil, method="get")
scoping = respond_to?(:resource_scoping) ? resource_scoping : {}
process(action, params.merge(scoping).reverse_merge!(:use_route => :spree, :format => :json), session, { :foo => "bar" }, method)
end
end
RSpec.configure do |config|
config.include ControllerHacks, :type => :controller
end
Correct api_process method
require 'active_support/all'
module ControllerHacks
def api_get(action, params={}, session=nil, flash=nil)
api_process(action, params, session, flash, "GET")
end
def api_post(action, params={}, session=nil, flash=nil)
api_process(action, params, session, flash, "POST")
end
def api_put(action, params={}, session=nil, flash=nil)
api_process(action, params, session, flash, "PUT")
end
def api_delete(action, params={}, session=nil, flash=nil)
api_process(action, params, session, flash, "DELETE")
end
def api_process(action, params={}, session=nil, flash=nil, method="get")
scoping = respond_to?(:resource_scoping) ? resource_scoping : {}
process(action, params.merge(scoping).reverse_merge!(:use_route => :spree, :format => :json), session, flash, method)
end
end
RSpec.configure do |config|
config.include ControllerHacks, :type => :controller
end
|
require 'typhoeus'
require_relative '../presenters/snapshot_presenter'
module Evercam
def self.get_jpg(camera)
response = nil
unless camera.external_url.nil?
begin
conn = Faraday.new(:url => camera.external_url) do |faraday|
faraday.request :basic_auth, camera.cam_username, camera.cam_password
faraday.request :digest, camera.cam_username, camera.cam_password
faraday.adapter :typhoeus
faraday.options.timeout = Evercam::Config[:api][:timeout] # open/read timeout in seconds
faraday.options.open_timeout = Evercam::Config[:api][:timeout] # connection open timeout in seconds
end
response = conn.get do |req|
req.url camera.res_url('jpg')
end
rescue URI::InvalidURIError => error
raise BadRequestError, "Invalid URL. Cause: #{error}"
rescue Faraday::TimeoutError
raise CameraOfflineError, 'We can't connect to your camera at the moment - please check your settings'
end
if response.success?
response
elsif response.status == 401
raise AuthorizationError, 'Please check camera username and password'
else
raise CameraOfflineError, 'We can't connect to your camera at the moment - please check your settings'
end
end
end
class V1SnapshotJpgRoutes < Grape::API
format :json
namespace :cameras do
#-------------------------------------------------------------------
# GET /snapshot.jpg
#-------------------------------------------------------------------
params do
requires :id, type: String, desc: "Camera Id."
end
route_param :id do
desc 'Returns jpg from the camera'
get 'snapshot.jpg' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::SNAPSHOT)
unless camera.external_url.nil?
require 'openssl'
require 'base64'
cam_username = camera.config.fetch('auth', {}).fetch('basic', {}).fetch('username', '')
cam_password = camera.config.fetch('auth', {}).fetch('basic', {}).fetch('password', '')
cam_auth = "#{cam_username}:#{cam_password}"
api_id = params.fetch('api_id', '')
api_key = params.fetch('api_key', '')
credentials = "#{api_id}:#{api_key}"
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.encrypt
cipher.key = "#{Evercam::Config[:snapshots][:key]}"
cipher.iv = "#{Evercam::Config[:snapshots][:iv]}"
cipher.padding = 0
message = camera.external_url
message << camera.res_url('jpg') unless camera.res_url('jpg').blank?
message << "|#{cam_auth}|#{credentials}|#{Time.now.to_s}|"
message << ' ' until message.length % 16 == 0
token = cipher.update(message)
token << cipher.final
CameraActivity.create(
camera: camera,
access_token: access_token,
action: 'viewed',
done_at: Time.now,
ip: request.ip
)
redirect "#{Evercam::Config[:snapshots][:url]}v1/cameras/#{camera.exid}/live/snapshot.jpg?t=#{Base64.urlsafe_encode64(token)}"
end
end
end
end
namespace :public do
#-------------------------------------------------------------------
# GET /nearest.jpg
#-------------------------------------------------------------------
desc "Returns jpg from nearest publicly discoverable camera from within the Evercam system."\
"If location isn't provided requester's IP address is used.", {
}
params do
optional :near_to, type: String, desc: "Specify an address or latitude longitude points."
end
get 'nearest.jpg' do
begin
if params[:near_to]
location = {
latitude: Geocoding.as_point(params[:near_to]).y,
longitude: Geocoding.as_point(params[:near_to]).x
}
else
location = {
latitude: request.location.latitude,
longitude: request.location.longitude
}
end
rescue Exception => ex
raise_error(400, 400, ex.message)
end
if params[:near_to] or request.location
camera = Camera.nearest(location).limit(1).first
else
raise_error(400, 400, "Location is missing")
end
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::SNAPSHOT)
unless camera.external_url.nil?
require 'openssl'
require 'base64'
auth = camera.config.fetch('auth', {}).fetch('basic', '')
if auth != ''
auth = "#{camera.config['auth']['basic']['username']}:#{camera.config['auth']['basic']['password']}"
end
c = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
c.encrypt
c.key = "#{Evercam::Config[:snapshots][:key]}"
c.iv = "#{Evercam::Config[:snapshots][:iv]}"
# Padding was incompatible with node padding
c.padding = 0
msg = camera.external_url
msg << camera.res_url('jpg') unless camera.res_url('jpg').blank?
msg << "|#{auth}|#{Time.now.to_s}|"
until msg.length % 16 == 0 do
msg << ' '
end
t = c.update(msg)
t << c.final
CameraActivity.create(
camera: camera,
access_token: access_token,
action: 'viewed',
done_at: Time.now,
ip: request.ip
)
redirect "#{Evercam::Config[:snapshots][:url]}#{camera.exid}.jpg?t=#{Base64.strict_encode64(t)}"
end
end
end
end
class V1SnapshotRoutes < Grape::API
include WebErrors
before do
authorize!
end
DEFAULT_LIMIT_WITH_DATA = 10
DEFAULT_LIMIT_NO_DATA = 100
namespace :cameras do
params do
requires :id, type: String, desc: "Camera Id."
end
route_param :id do
#-------------------------------------------------------------------
# GET /cameras/:id/live
#-------------------------------------------------------------------
desc 'Returns base64 encoded jpg from the online camera'
get 'live' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::SNAPSHOT)
if camera.is_online
res = Evercam::get_jpg(camera)
data = Base64.encode64(res.body).gsub("\n", '')
{
camera: camera.exid,
created_at: Time.now.to_i,
timezone: camera.timezone.zone,
data: "data:image/jpeg;base64,#{data}"
}
else
{message: 'camera is offline'}
end
end
#-------------------------------------------------------------------
# GET /cameras/:id/snapshots
#-------------------------------------------------------------------
desc 'Returns the list of all snapshots currently stored for this camera'
get 'snapshots' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::LIST)
snap_q = Snapshot.where(:camera_id => camera.id).select(:created_at, :notes).all
present(snap_q, with: Presenters::Snapshot).merge!({
timezone: camera.timezone.zone
})
end
#-------------------------------------------------------------------
# GET /cameras/:id/snapshots/latest
#-------------------------------------------------------------------
desc 'Returns latest snapshot stored for this camera', {
entity: Evercam::Presenters::Snapshot
}
params do
optional :with_data, type: 'Boolean', desc: "Should it send image data?"
end
get 'snapshots/latest' do
camera = get_cam(params[:id])
snapshot = camera.snapshots.order(:created_at).last
if snapshot
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::LIST)
present(Array(snapshot), with: Presenters::Snapshot, with_data: params[:with_data]).merge!({
timezone: camera.timezone.zone
})
else
present([], with: Presenters::Snapshot, with_data: params[:with_data]).merge!({
timezone: camera.timezone.zone
})
end
end
#-------------------------------------------------------------------
# GET /cameras/:id/snapshots/range
#-------------------------------------------------------------------
desc 'Returns list of snapshots between two timestamps'
params do
requires :from, type: Integer, desc: "From Unix timestamp."
requires :to, type: Integer, desc: "To Unix timestamp."
optional :with_data, type: 'Boolean', desc: "Should it send image data?"
optional :limit, type: Integer, desc: "Limit number of results, default 100 with no data, 10 with data"
optional :page, type: Integer, desc: "Page number"
end
get 'snapshots/range' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::LIST)
from = Time.at(params[:from].to_i).to_s
to = Time.at(params[:to].to_i).to_s
limit = params[:limit]
if params[:with_data]
limit ||= DEFAULT_LIMIT_WITH_DATA
else
limit ||= DEFAULT_LIMIT_NO_DATA
end
offset = 0
if params[:page]
offset = (params[:page] - 1) * limit
end
snap = camera.snapshots.select_group(:notes, :created_at, :data).order(:created_at).filter(:created_at => (from..to)).limit(limit).offset(offset)
if params[:with_data]
snap = snap.select_group(:notes, :created_at, :data)
else
snap = snap.select_group(:notes, :created_at)
end
present Array(snap), with: Presenters::Snapshot, with_data: params[:with_data]
end
#-------------------------------------------------------------------
# GET /cameras/:id/snapshots/:year/:month/day
#-------------------------------------------------------------------
desc 'Returns list of specific days in a given month which contains any snapshots'
params do
requires :year, type: Integer, desc: "Year, for example 2013"
requires :month, type: Integer, desc: "Month, for example 11"
end
get 'snapshots/:year/:month/days' do
unless (1..12).include?(params[:month])
raise BadRequestError, 'Invalid month value'
end
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::LIST)
days = []
(1..Date.new(params[:year], params[:month], -1).day).each do |day|
from = camera.timezone.time(Time.utc(params[:year], params[:month], day)).to_s
to = camera.timezone.time(Time.utc(params[:year], params[:month], day, 23, 59, 59)).to_s
if camera.snapshots.filter(:created_at => (from..to)).count > 0
days << day
end
end
{ :days => days}
end
#-------------------------------------------------------------------
# GET /cameras/:id/snapshots/:year/:month/:day/hours
#-------------------------------------------------------------------
desc 'Returns list of specific hours in a given day which contains any snapshots'
params do
requires :year, type: Integer, desc: "Year, for example 2013"
requires :month, type: Integer, desc: "Month, for example 11"
requires :day, type: Integer, desc: "Day, for example 17"
end
get 'snapshots/:year/:month/:day/hours' do
unless (1..12).include?(params[:month])
raise BadRequestError, 'Invalid month value'
end
unless (1..31).include?(params[:day])
raise BadRequestError, 'Invalid day value'
end
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::LIST)
hours = []
(0..23).each do |hour|
from = camera.timezone.time(Time.utc(params[:year], params[:month], params[:day], hour)).to_s
to = camera.timezone.time(Time.utc(params[:year], params[:month], params[:day], hour, 59, 59)).to_s
if camera.snapshots.filter(:created_at => (from..to)).count > 0
hours << hour
end
end
{ :hours => hours}
end
#-------------------------------------------------------------------
# GET /cameras/:id/snapshots/:timestamp
#-------------------------------------------------------------------
desc 'Returns the snapshot stored for this camera closest to the given timestamp', {
entity: Evercam::Presenters::Snapshot
}
params do
requires :timestamp, type: Integer, desc: "Snapshot Unix timestamp."
optional :with_data, type: 'Boolean', desc: "Should it send image data?"
optional :range, type: Integer, desc: "Time range in seconds around specified timestamp. Default range is one second (so it matches only exact timestamp)."
end
get 'snapshots/:timestamp' do
camera = get_cam(params[:id])
snapshot = camera.snapshot_by_ts!(Time.at(params[:timestamp].to_i), params[:range].to_i)
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::LIST)
present Array(snapshot), with: Presenters::Snapshot, with_data: params[:with_data]
end
#-------------------------------------------------------------------
# POST /cameras/:id/snapshots
#-------------------------------------------------------------------
desc 'Fetches a snapshot from the camera and stores it using the current timestamp'
params do
optional :notes, type: String, desc: "Optional text note for this snapshot"
end
post 'snapshots' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new if !rights.allow?(AccessRight::SNAPSHOT)
outcome = Actors::SnapshotFetch.run(params)
unless outcome.success?
raise OutcomeError, outcome.to_json
end
CameraActivity.create(
camera: camera,
access_token: access_token,
action: 'captured',
done_at: Time.now,
ip: request.ip
)
present Array(outcome.result), with: Presenters::Snapshot
end
#-------------------------------------------------------------------
# POST /cameras/:id/snapshots/:timestamp
#-------------------------------------------------------------------
desc 'Stores the supplied snapshot image data for the given timestamp'
params do
requires :timestamp, type: Integer, desc: "Snapshot Unix timestamp."
requires :data, type: File, desc: "Image file."
optional :notes, type: String, desc: "Optional text note for this snapshot"
end
post 'snapshots/:timestamp' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new if !rights.allow?(AccessRight::SNAPSHOT)
outcome = Actors::SnapshotCreate.run(params)
unless outcome.success?
raise OutcomeError, outcome.to_json
end
CameraActivity.create(
camera: camera,
access_token: access_token,
action: 'captured',
done_at: Time.now,
ip: request.ip
)
present Array(outcome.result), with: Presenters::Snapshot
end
#-------------------------------------------------------------------
# DELETE /cameras/:id/snapshots/:timestamp
#-------------------------------------------------------------------
desc 'Deletes any snapshot for this camera which exactly matches the timestamp'
params do
requires :timestamp, type: Integer, desc: "Snapshot Unix timestamp."
end
delete 'snapshots/:timestamp' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera.owner, AccessRight::SNAPSHOTS)
raise AuthorizationError.new if !rights.allow?(AccessRight::DELETE)
CameraActivity.create(
camera: camera,
access_token: access_token,
action: 'deleted snapshot',
done_at: Time.now,
ip: request.ip
)
camera.snapshot_by_ts!(Time.at(params[:timestamp].to_i)).destroy
{}
end
end
end
end
end
Renamed snapshot token
require 'typhoeus'
require_relative '../presenters/snapshot_presenter'
module Evercam
def self.get_jpg(camera)
response = nil
unless camera.external_url.nil?
begin
conn = Faraday.new(:url => camera.external_url) do |faraday|
faraday.request :basic_auth, camera.cam_username, camera.cam_password
faraday.request :digest, camera.cam_username, camera.cam_password
faraday.adapter :typhoeus
faraday.options.timeout = Evercam::Config[:api][:timeout] # open/read timeout in seconds
faraday.options.open_timeout = Evercam::Config[:api][:timeout] # connection open timeout in seconds
end
response = conn.get do |req|
req.url camera.res_url('jpg')
end
rescue URI::InvalidURIError => error
raise BadRequestError, "Invalid URL. Cause: #{error}"
rescue Faraday::TimeoutError
raise CameraOfflineError, 'We can't connect to your camera at the moment - please check your settings'
end
if response.success?
response
elsif response.status == 401
raise AuthorizationError, 'Please check camera username and password'
else
raise CameraOfflineError, 'We can't connect to your camera at the moment - please check your settings'
end
end
end
class V1SnapshotJpgRoutes < Grape::API
format :json
namespace :cameras do
#-------------------------------------------------------------------
# GET /snapshot.jpg
#-------------------------------------------------------------------
params do
requires :id, type: String, desc: "Camera Id."
end
route_param :id do
desc 'Returns jpg from the camera'
get 'snapshot.jpg' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::SNAPSHOT)
unless camera.external_url.nil?
require 'openssl'
require 'base64'
cam_username = camera.config.fetch('auth', {}).fetch('basic', {}).fetch('username', '')
cam_password = camera.config.fetch('auth', {}).fetch('basic', {}).fetch('password', '')
cam_auth = "#{cam_username}:#{cam_password}"
api_id = params.fetch('api_id', '')
api_key = params.fetch('api_key', '')
credentials = "#{api_id}:#{api_key}"
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.encrypt
cipher.key = "#{Evercam::Config[:snapshots][:key]}"
cipher.iv = "#{Evercam::Config[:snapshots][:iv]}"
cipher.padding = 0
message = camera.external_url
message << camera.res_url('jpg') unless camera.res_url('jpg').blank?
message << "|#{cam_auth}|#{credentials}|#{Time.now.to_s}|"
message << ' ' until message.length % 16 == 0
token = cipher.update(message)
token << cipher.final
CameraActivity.create(
camera: camera,
access_token: access_token,
action: 'viewed',
done_at: Time.now,
ip: request.ip
)
redirect "#{Evercam::Config[:snapshots][:url]}v1/cameras/#{camera.exid}/live/snapshot.jpg?token=#{Base64.urlsafe_encode64(token)}"
end
end
end
end
namespace :public do
#-------------------------------------------------------------------
# GET /nearest.jpg
#-------------------------------------------------------------------
desc "Returns jpg from nearest publicly discoverable camera from within the Evercam system."\
"If location isn't provided requester's IP address is used.", {
}
params do
optional :near_to, type: String, desc: "Specify an address or latitude longitude points."
end
get 'nearest.jpg' do
begin
if params[:near_to]
location = {
latitude: Geocoding.as_point(params[:near_to]).y,
longitude: Geocoding.as_point(params[:near_to]).x
}
else
location = {
latitude: request.location.latitude,
longitude: request.location.longitude
}
end
rescue Exception => ex
raise_error(400, 400, ex.message)
end
if params[:near_to] or request.location
camera = Camera.nearest(location).limit(1).first
else
raise_error(400, 400, "Location is missing")
end
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::SNAPSHOT)
unless camera.external_url.nil?
require 'openssl'
require 'base64'
auth = camera.config.fetch('auth', {}).fetch('basic', '')
if auth != ''
auth = "#{camera.config['auth']['basic']['username']}:#{camera.config['auth']['basic']['password']}"
end
c = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
c.encrypt
c.key = "#{Evercam::Config[:snapshots][:key]}"
c.iv = "#{Evercam::Config[:snapshots][:iv]}"
# Padding was incompatible with node padding
c.padding = 0
msg = camera.external_url
msg << camera.res_url('jpg') unless camera.res_url('jpg').blank?
msg << "|#{auth}|#{Time.now.to_s}|"
until msg.length % 16 == 0 do
msg << ' '
end
t = c.update(msg)
t << c.final
CameraActivity.create(
camera: camera,
access_token: access_token,
action: 'viewed',
done_at: Time.now,
ip: request.ip
)
redirect "#{Evercam::Config[:snapshots][:url]}#{camera.exid}.jpg?t=#{Base64.strict_encode64(t)}"
end
end
end
end
class V1SnapshotRoutes < Grape::API
include WebErrors
before do
authorize!
end
DEFAULT_LIMIT_WITH_DATA = 10
DEFAULT_LIMIT_NO_DATA = 100
namespace :cameras do
params do
requires :id, type: String, desc: "Camera Id."
end
route_param :id do
#-------------------------------------------------------------------
# GET /cameras/:id/live
#-------------------------------------------------------------------
desc 'Returns base64 encoded jpg from the online camera'
get 'live' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::SNAPSHOT)
if camera.is_online
res = Evercam::get_jpg(camera)
data = Base64.encode64(res.body).gsub("\n", '')
{
camera: camera.exid,
created_at: Time.now.to_i,
timezone: camera.timezone.zone,
data: "data:image/jpeg;base64,#{data}"
}
else
{message: 'camera is offline'}
end
end
#-------------------------------------------------------------------
# GET /cameras/:id/snapshots
#-------------------------------------------------------------------
desc 'Returns the list of all snapshots currently stored for this camera'
get 'snapshots' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::LIST)
snap_q = Snapshot.where(:camera_id => camera.id).select(:created_at, :notes).all
present(snap_q, with: Presenters::Snapshot).merge!({
timezone: camera.timezone.zone
})
end
#-------------------------------------------------------------------
# GET /cameras/:id/snapshots/latest
#-------------------------------------------------------------------
desc 'Returns latest snapshot stored for this camera', {
entity: Evercam::Presenters::Snapshot
}
params do
optional :with_data, type: 'Boolean', desc: "Should it send image data?"
end
get 'snapshots/latest' do
camera = get_cam(params[:id])
snapshot = camera.snapshots.order(:created_at).last
if snapshot
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::LIST)
present(Array(snapshot), with: Presenters::Snapshot, with_data: params[:with_data]).merge!({
timezone: camera.timezone.zone
})
else
present([], with: Presenters::Snapshot, with_data: params[:with_data]).merge!({
timezone: camera.timezone.zone
})
end
end
#-------------------------------------------------------------------
# GET /cameras/:id/snapshots/range
#-------------------------------------------------------------------
desc 'Returns list of snapshots between two timestamps'
params do
requires :from, type: Integer, desc: "From Unix timestamp."
requires :to, type: Integer, desc: "To Unix timestamp."
optional :with_data, type: 'Boolean', desc: "Should it send image data?"
optional :limit, type: Integer, desc: "Limit number of results, default 100 with no data, 10 with data"
optional :page, type: Integer, desc: "Page number"
end
get 'snapshots/range' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::LIST)
from = Time.at(params[:from].to_i).to_s
to = Time.at(params[:to].to_i).to_s
limit = params[:limit]
if params[:with_data]
limit ||= DEFAULT_LIMIT_WITH_DATA
else
limit ||= DEFAULT_LIMIT_NO_DATA
end
offset = 0
if params[:page]
offset = (params[:page] - 1) * limit
end
snap = camera.snapshots.select_group(:notes, :created_at, :data).order(:created_at).filter(:created_at => (from..to)).limit(limit).offset(offset)
if params[:with_data]
snap = snap.select_group(:notes, :created_at, :data)
else
snap = snap.select_group(:notes, :created_at)
end
present Array(snap), with: Presenters::Snapshot, with_data: params[:with_data]
end
#-------------------------------------------------------------------
# GET /cameras/:id/snapshots/:year/:month/day
#-------------------------------------------------------------------
desc 'Returns list of specific days in a given month which contains any snapshots'
params do
requires :year, type: Integer, desc: "Year, for example 2013"
requires :month, type: Integer, desc: "Month, for example 11"
end
get 'snapshots/:year/:month/days' do
unless (1..12).include?(params[:month])
raise BadRequestError, 'Invalid month value'
end
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::LIST)
days = []
(1..Date.new(params[:year], params[:month], -1).day).each do |day|
from = camera.timezone.time(Time.utc(params[:year], params[:month], day)).to_s
to = camera.timezone.time(Time.utc(params[:year], params[:month], day, 23, 59, 59)).to_s
if camera.snapshots.filter(:created_at => (from..to)).count > 0
days << day
end
end
{ :days => days}
end
#-------------------------------------------------------------------
# GET /cameras/:id/snapshots/:year/:month/:day/hours
#-------------------------------------------------------------------
desc 'Returns list of specific hours in a given day which contains any snapshots'
params do
requires :year, type: Integer, desc: "Year, for example 2013"
requires :month, type: Integer, desc: "Month, for example 11"
requires :day, type: Integer, desc: "Day, for example 17"
end
get 'snapshots/:year/:month/:day/hours' do
unless (1..12).include?(params[:month])
raise BadRequestError, 'Invalid month value'
end
unless (1..31).include?(params[:day])
raise BadRequestError, 'Invalid day value'
end
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::LIST)
hours = []
(0..23).each do |hour|
from = camera.timezone.time(Time.utc(params[:year], params[:month], params[:day], hour)).to_s
to = camera.timezone.time(Time.utc(params[:year], params[:month], params[:day], hour, 59, 59)).to_s
if camera.snapshots.filter(:created_at => (from..to)).count > 0
hours << hour
end
end
{ :hours => hours}
end
#-------------------------------------------------------------------
# GET /cameras/:id/snapshots/:timestamp
#-------------------------------------------------------------------
desc 'Returns the snapshot stored for this camera closest to the given timestamp', {
entity: Evercam::Presenters::Snapshot
}
params do
requires :timestamp, type: Integer, desc: "Snapshot Unix timestamp."
optional :with_data, type: 'Boolean', desc: "Should it send image data?"
optional :range, type: Integer, desc: "Time range in seconds around specified timestamp. Default range is one second (so it matches only exact timestamp)."
end
get 'snapshots/:timestamp' do
camera = get_cam(params[:id])
snapshot = camera.snapshot_by_ts!(Time.at(params[:timestamp].to_i), params[:range].to_i)
rights = requester_rights_for(camera)
raise AuthorizationError.new unless rights.allow?(AccessRight::LIST)
present Array(snapshot), with: Presenters::Snapshot, with_data: params[:with_data]
end
#-------------------------------------------------------------------
# POST /cameras/:id/snapshots
#-------------------------------------------------------------------
desc 'Fetches a snapshot from the camera and stores it using the current timestamp'
params do
optional :notes, type: String, desc: "Optional text note for this snapshot"
end
post 'snapshots' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new if !rights.allow?(AccessRight::SNAPSHOT)
outcome = Actors::SnapshotFetch.run(params)
unless outcome.success?
raise OutcomeError, outcome.to_json
end
CameraActivity.create(
camera: camera,
access_token: access_token,
action: 'captured',
done_at: Time.now,
ip: request.ip
)
present Array(outcome.result), with: Presenters::Snapshot
end
#-------------------------------------------------------------------
# POST /cameras/:id/snapshots/:timestamp
#-------------------------------------------------------------------
desc 'Stores the supplied snapshot image data for the given timestamp'
params do
requires :timestamp, type: Integer, desc: "Snapshot Unix timestamp."
requires :data, type: File, desc: "Image file."
optional :notes, type: String, desc: "Optional text note for this snapshot"
end
post 'snapshots/:timestamp' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera)
raise AuthorizationError.new if !rights.allow?(AccessRight::SNAPSHOT)
outcome = Actors::SnapshotCreate.run(params)
unless outcome.success?
raise OutcomeError, outcome.to_json
end
CameraActivity.create(
camera: camera,
access_token: access_token,
action: 'captured',
done_at: Time.now,
ip: request.ip
)
present Array(outcome.result), with: Presenters::Snapshot
end
#-------------------------------------------------------------------
# DELETE /cameras/:id/snapshots/:timestamp
#-------------------------------------------------------------------
desc 'Deletes any snapshot for this camera which exactly matches the timestamp'
params do
requires :timestamp, type: Integer, desc: "Snapshot Unix timestamp."
end
delete 'snapshots/:timestamp' do
camera = get_cam(params[:id])
rights = requester_rights_for(camera.owner, AccessRight::SNAPSHOTS)
raise AuthorizationError.new if !rights.allow?(AccessRight::DELETE)
CameraActivity.create(
camera: camera,
access_token: access_token,
action: 'deleted snapshot',
done_at: Time.now,
ip: request.ip
)
camera.snapshot_by_ts!(Time.at(params[:timestamp].to_i)).destroy
{}
end
end
end
end
end
|
class Formatter
def output_report(title, text)
raise NotImplementedError, "Not implemented"
end
end
class Html_formatter < Formatter
def output_report(title, text)
puts "<html>"
puts " <head>"
puts " <title>#{title}</title>"
puts " </head>"
puts " <body>"
text.each { |x|
puts " <p> #{x} </p>"
}
puts " </body>"
puts "</html>"
end
end
class Text_formatter < Formatter
def output_report(title, text)
puts "--- Begin report ---"
puts " Title #{title}"
text.each { |x|
puts x
}
end
end
class Report
def initialize(formatter, title, text)
@formatter = formatter
@title = title
@text = text
end
def print
@formatter.output_report(@title, @text)
end
attr_accessor :formatter
end
report = Report.new(Text_formatter.new, "Status", ["Everything sucks", "badly"])
report.print
report.formatter = Html_formatter.new
report.print
Strategy with context
class Formatter
def output_report(report)
raise NotImplementedError, "Not implemented"
end
end
class Html_formatter < Formatter
def output_report(report)
puts "<html>"
puts " <head>"
puts " <title>#{report.title}</title>"
puts " </head>"
puts " <body>"
report.text.each { |x|
puts " <p> #{x} </p>"
}
puts " </body>"
puts "</html>"
end
end
class Text_formatter < Formatter
def output_report(report)
puts "--- Begin report ---"
puts " Title #{report.title}"
report.text.each { |x|
puts x
}
end
end
class Report
def initialize(formatter, title, text)
@formatter = formatter
@title = title
@text = text
end
def print
@formatter.output_report(self)
end
attr_accessor :formatter
attr_reader :title
attr_reader :text
end
report = Report.new(Text_formatter.new, "Status", ["Everything sucks", "badly"])
report.print
report.formatter = Html_formatter.new
report.print
|
# encoding: utf-8
class Service::Datadog < Service
def receive_logs
raise_config_error 'Missing API Key' if settings[:api_key].to_s.empty?
raise_config_error 'Missing metric name' if settings[:metric].to_s.empty?
unless settings[:tags].to_s.empty?
tags = settings[:tags].to_s.split(/,\s+/)
end
# values[hostname][time]
values = Hash.new do |h,k|
h[k] = Hash.new do |i,l|
i[l] = 0
end
end
payload[:events].each do |event|
time = Time.iso8601(event[:received_at]).to_i
values[event[:source_name]][time] += 1
end
serieses = []
values.each do |hostname, points|
serieses << {
:metric => settings[:metric],
:points => points.to_a,
:host => hostname,
:tags => tags,
:type => 'counter'
}
end
http_post "https://app.datadoghq.com/api/v1/series" do |req|
req.params = {
:api_key => settings[:api_key]
}
req.body = {
:series => serieses
}.to_json
end
end
end
Report an error if metrics couldn't be sent
# encoding: utf-8
class Service::Datadog < Service
def receive_logs
raise_config_error 'Missing API Key' if settings[:api_key].to_s.empty?
raise_config_error 'Missing metric name' if settings[:metric].to_s.empty?
unless settings[:tags].to_s.empty?
tags = settings[:tags].to_s.split(/,\s+/)
end
# values[hostname][time]
values = Hash.new do |h,k|
h[k] = Hash.new do |i,l|
i[l] = 0
end
end
payload[:events].each do |event|
time = Time.iso8601(event[:received_at]).to_i
values[event[:source_name]][time] += 1
end
serieses = []
values.each do |hostname, points|
serieses << {
:metric => settings[:metric],
:points => points.to_a,
:host => hostname,
:tags => tags,
:type => 'counter'
}
end
resp = http_post "https://app.datadoghq.com/api/v1/series" do |req|
req.params = {
:api_key => settings[:api_key]
}
req.body = {
:series => serieses
}.to_json
end
unless resp.success?
puts "datadog: #{payload[:saved_search][:id]}: #{resp.status}: #{resp.body}"
raise_config_error "Could not submit metrics"
end
end
end
|
service :service_name do |data, payload|
end
first version of integration with test data, log generated json
service :freckle do |data, payload|
data = {
"subdomain" => "foo",
"token" => "bar",
"project" => "baz"
}
payload = {
"after" => "a47fd41f3aa4610ea527dcc1669dfdb9c15c5425",
"ref" => "refs/heads/master",
"before" => "4c8124ffcf4039d292442eeccabdeca5af5c5017",
"repository" => {
"name" => "grit",
"url" => "http://github.com/mojombo/grit",
"owner" => { "name" => "mojombo", "email" => "tom@mojombo.com" }
},
"commits" => [
{
"removed" => [],
"message" => "stub git call for Grit#heads test f:15",
"added" => [],
"timestamp" => "2007-10-10T00:11:02-07:00",
"modified" => ["lib/grit/grit.rb", "test/helper.rb", "test/test_grit.rb"],
"url" => "http://github.com/mojombo/grit/commit/06f63b43050935962f84fe54473a7c5de7977325",
"author" => { "name" => "Tom Preston-Werner", "email" => "tom@mojombo.com" },
"id" => "06f63b43050935962f84fe54473a7c5de7977325"
},
{
"removed" => [],
"message" => "clean up heads test f:2hrs",
"added" => [],
"timestamp" => "2007-10-10T00:18:20-07:00",
"modified" => ["test/test_grit.rb"],
"url" => "http://github.com/mojombo/grit/commit/5057e76a11abd02e83b7d3d3171c4b68d9c88480",
"author" => { "name" => "Tom Preston-Werner", "email" => "tom@mojombo.com" },
"id" => "5057e76a11abd02e83b7d3d3171c4b68d9c88480"
},
{
"removed" => [],
"message" => "add more comments throughout",
"added" => [],
"timestamp" => "2007-10-10T00:50:39-07:00",
"modified" => ["lib/grit.rb", "lib/grit/commit.rb", "lib/grit/grit.rb"],
"url" => "http://github.com/mojombo/grit/commit/a47fd41f3aa4610ea527dcc1669dfdb9c15c5425",
"author" => { "name" => "Tom Preston-Werner", "email" => "tom@mojombo.com" },
"id" => "a47fd41f3aa4610ea527dcc1669dfdb9c15c5425"
}
]
}
entries, subdomain, token, project =
[], data['subdomain'].strip, data['token'].strip, data['project'].strip;
payload['commits'].each do |commit|
minutes = (commit["message"].split(/\s/).find{|item| /^f:/ =~ item }||'')[2,100]
next unless minutes
entries << {
:date => Date.parse(commit["timestamp"]),
:minutes => minutes,
:description => commit["message"].gsub(/(\s|^)f:.*(\s|$)/){ $3 }.strip,
:url => commit['url'],
:project_name => project,
:user => commit['author']['email']
}
end
File.open('temp.log','w'){|w| w.write entries.to_json}
# todo add freckle gem/import call
end |
require "test_helper"
require "down/net_http"
require "http"
require "stringio"
require "json"
require "base64"
describe Down do
describe "#download" do
it "downloads content from url" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}?seed=0")
assert_equal HTTP.get("#{$httpbin}/bytes/#{20*1024}?seed=0").to_s, tempfile.read
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{1024}?seed=0")
assert_equal HTTP.get("#{$httpbin}/bytes/#{1024}?seed=0").to_s, tempfile.read
end
it "returns a Tempfile" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}")
assert_instance_of Tempfile, tempfile
# open-uri returns a StringIO on files with 10KB or less
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{1024}")
assert_instance_of Tempfile, tempfile
end
it "saves Tempfile to disk" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}")
assert File.exist?(tempfile.path)
# open-uri returns a StringIO on files with 10KB or less
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{1024}")
assert File.exist?(tempfile.path)
end
it "opens the Tempfile in binary mode" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}")
assert tempfile.binmode?
# open-uri returns a StringIO on files with 10KB or less
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{1024}")
assert tempfile.binmode?
end
it "gives the Tempfile a file extension" do
tempfile = Down::NetHttp.download("#{$httpbin}/robots.txt")
assert_equal ".txt", File.extname(tempfile.path)
tempfile = Down::NetHttp.download("#{$httpbin}/robots.txt?foo=bar")
assert_equal ".txt", File.extname(tempfile.path)
tempfile = Down::NetHttp.download("#{$httpbin}/redirect-to?url=#{$httpbin}/robots.txt")
assert_equal ".txt", File.extname(tempfile.path)
end
it "accepts an URI object" do
tempfile = Down::NetHttp.download(URI("#{$httpbin}/bytes/100"))
assert_equal 100, tempfile.size
end
it "uses a default User-Agent" do
tempfile = Down::NetHttp.download("#{$httpbin}/user-agent")
assert_equal "Down/#{Down::VERSION}", JSON.parse(tempfile.read)["user-agent"]
end
it "accepts max size" do
assert_raises(Down::TooLarge) do
Down::NetHttp.download("#{$httpbin}/bytes/10", max_size: 5)
end
assert_raises(Down::TooLarge) do
Down::NetHttp.download("#{$httpbin}/stream-bytes/10", max_size: 5)
end
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/10", max_size: 10)
assert File.exist?(tempfile.path)
tempfile = Down::NetHttp.download("#{$httpbin}/stream-bytes/10", max_size: 15)
assert File.exist?(tempfile.path)
end
it "accepts content length proc" do
Down::NetHttp.download "#{$httpbin}/bytes/100",
content_length_proc: ->(n) { @content_length = n }
assert_equal 100, @content_length
end
it "accepts progress proc" do
Down::NetHttp.download "#{$httpbin}/stream-bytes/100?chunk_size=10",
progress_proc: ->(n) { (@progress ||= []) << n }
assert_equal [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], @progress
end
it "detects and applies basic authentication from URL" do
tempfile = Down::NetHttp.download("#{$httpbin.sub("http://", '\0user:password@')}/basic-auth/user/password")
assert_equal true, JSON.parse(tempfile.read)["authenticated"]
end
it "follows redirects" do
tempfile = Down::NetHttp.download("#{$httpbin}/redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
tempfile = Down::NetHttp.download("#{$httpbin}/redirect/2")
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
assert_raises(Down::TooManyRedirects) { Down::NetHttp.download("#{$httpbin}/redirect/3") }
tempfile = Down::NetHttp.download("#{$httpbin}/redirect/3", max_redirects: 3)
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
assert_raises(Down::TooManyRedirects) { Down::NetHttp.download("#{$httpbin}/redirect/4", max_redirects: 3) }
tempfile = Down::NetHttp.download("#{$httpbin}/absolute-redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
tempfile = Down::NetHttp.download("#{$httpbin}/relative-redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
# We also want to test that cookies are being forwarded on redirects, but
# httpbin doesn't have an endpoint which can both redirect and return a
# "Set-Cookie" header.
end
# I don't know how to test that the proxy is actually used
it "accepts proxy" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/100", proxy: $httpbin)
assert_equal 100, tempfile.size
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/100", proxy: $httpbin.sub("http://", '\0user:password@'))
assert_equal 100, tempfile.size
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/100", proxy: URI($httpbin.sub("http://", '\0user:password@')))
assert_equal 100, tempfile.size
end
it "forwards other options to open-uri" do
tempfile = Down::NetHttp.download("#{$httpbin}/user-agent", {"User-Agent" => "Custom/Agent"})
assert_equal "Custom/Agent", JSON.parse(tempfile.read)["user-agent"]
tempfile = Down::NetHttp.download("#{$httpbin}/basic-auth/user/password", http_basic_authentication: ["user", "password"])
assert_equal true, JSON.parse(tempfile.read)["authenticated"]
end
it "applies default options" do
net_http = Down::NetHttp.new("User-Agent" => "Janko")
tempfile = net_http.download("#{$httpbin}/user-agent")
assert_equal "Janko", JSON.parse(tempfile.read)["user-agent"]
end
it "adds #original_filename extracted from Content-Disposition" do
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=\"my%20filename.ext\"")
assert_equal "my filename.ext", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=\"my%2520filename.ext\"")
assert_equal "my filename.ext", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=myfilename.ext%20")
assert_equal "myfilename.ext", tempfile.original_filename
end
it "adds #original_filename extracted from URI path if Content-Disposition is blank" do
tempfile = Down::NetHttp.download("#{$httpbin}/robots.txt")
assert_equal "robots.txt", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/basic-auth/user/pass%20word", http_basic_authentication: ["user", "pass word"])
assert_equal "pass word", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=")
assert_equal "response-headers", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=\"\"")
assert_equal "response-headers", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/")
assert_nil tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}")
assert_nil tempfile.original_filename
end
it "adds #content_type extracted from Content-Type" do
tempfile = Down::NetHttp.download("#{$httpbin}/image/png")
assert_equal "image/png", tempfile.content_type
tempfile = Down::NetHttp.download("#{$httpbin}/encoding/utf8")
assert_equal "text/html; charset=utf-8", tempfile.meta["content-type"]
assert_equal "text/html", tempfile.content_type
tempfile.meta.delete("content-type")
assert_nil tempfile.content_type
tempfile.meta["content-type"] = nil
assert_nil tempfile.content_type
tempfile.meta["content-type"] = ""
assert_nil tempfile.content_type
end
it "accepts download destination" do
tempfile = Tempfile.new("destination")
result = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}?seed=0", destination: tempfile.path)
assert_equal HTTP.get("#{$httpbin}/bytes/#{20*1024}?seed=0").to_s, File.binread(tempfile.path)
assert_nil result
end
it "raises on HTTP error responses" do
error = assert_raises(Down::ClientError) { Down::NetHttp.download("#{$httpbin}/status/404") }
assert_equal "404 Not Found", error.message
assert_kind_of Net::HTTPResponse, error.response
error = assert_raises(Down::ServerError) { Down::NetHttp.download("#{$httpbin}/status/500") }
assert_equal "500 Internal Server Error", error.message
assert_kind_of Net::HTTPResponse, error.response
end
it "raises on invalid URLs" do
assert_raises(Down::InvalidUrl) { Down::NetHttp.download("http:\\example.org") }
assert_raises(Down::InvalidUrl) { Down::NetHttp.download("foo://example.org") }
assert_raises(Down::InvalidUrl) { Down::NetHttp.download("| ls") }
end
it "raises on connection errors" do
assert_raises(Down::ConnectionError) { Down::NetHttp.download("http://localhost:99999") }
end
it "raises on timeout errors" do
assert_raises(Down::TimeoutError) { Down::NetHttp.download("#{$httpbin}/delay/0.5", read_timeout: 0, open_timeout: 0) }
end
end
describe "#open" do
it "streams response body in chunks" do
io = Down::NetHttp.open("#{$httpbin}/stream/10")
assert_equal 10, io.each_chunk.count
end
it "accepts an URI object" do
io = Down::NetHttp.open(URI("#{$httpbin}/stream/10"))
assert_equal 10, io.each_chunk.count
end
it "downloads on demand" do
start = Time.now
io = Down::NetHttp.open("#{$httpbin}/drip?duration=0.5&delay=0")
io.close
assert_operator Time.now - start, :<, 0.5
end
it "follows redirects" do
io = Down::NetHttp.open("#{$httpbin}/redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
io = Down::NetHttp.open("#{$httpbin}/redirect/2")
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
assert_raises(Down::TooManyRedirects) { Down::NetHttp.open("#{$httpbin}/redirect/3") }
io = Down::NetHttp.open("#{$httpbin}/redirect/3", max_redirects: 3)
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
assert_raises(Down::TooManyRedirects) { Down::NetHttp.open("#{$httpbin}/redirect/4", max_redirects: 3) }
io = Down::NetHttp.open("#{$httpbin}/absolute-redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
io = Down::NetHttp.open("#{$httpbin}/relative-redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
end
it "returns content in encoding specified by charset" do
io = Down::NetHttp.open("#{$httpbin}/stream/10")
assert_equal Encoding::BINARY, io.read.encoding
io = Down::NetHttp.open("#{$httpbin}/get")
assert_equal Encoding::BINARY, io.read.encoding
io = Down::NetHttp.open("#{$httpbin}/encoding/utf8")
assert_equal Encoding::UTF_8, io.read.encoding
end
it "uses a default User-Agent" do
io = Down::NetHttp.open("#{$httpbin}/user-agent")
assert_equal "Down/#{Down::VERSION}", JSON.parse(io.read)["user-agent"]
end
it "doesn't have to be rewindable" do
io = Down::NetHttp.open("#{$httpbin}/stream/10", rewindable: false)
io.read
assert_raises(IOError) { io.rewind }
end
it "extracts size from Content-Length" do
io = Down::NetHttp.open(URI("#{$httpbin}/bytes/100"))
assert_equal 100, io.size
io = Down::NetHttp.open(URI("#{$httpbin}/stream-bytes/100"))
assert_nil io.size
end
it "closes the connection on #close" do
io = Down::NetHttp.open("#{$httpbin}/bytes/100")
Net::HTTP.any_instance.expects(:do_finish)
io.close
end
it "accepts request headers" do
io = Down::NetHttp.open("#{$httpbin}/headers", {"Key" => "Value"})
assert_equal "Value", JSON.parse(io.read)["headers"]["Key"]
end
# I don't know how to test that the proxy is actually used
it "accepts proxy" do
io = Down::NetHttp.open("#{$httpbin}/bytes/100", proxy: $httpbin)
assert_equal 100, io.size
io = Down::NetHttp.open("#{$httpbin}/bytes/100", proxy: $httpbin.sub("http://", '\0user:password@'))
assert_equal 100, io.size
io = Down::NetHttp.open("#{$httpbin}/bytes/100", proxy: URI($httpbin.sub("http://", '\0user:password@')))
assert_equal 100, io.size
end
it "detects and applies basic authentication from URL" do
io = Down::NetHttp.open("#{$httpbin.sub("http://", '\0user:password@')}/basic-auth/user/password")
assert_equal true, JSON.parse(io.read)["authenticated"]
end
it "applies default options" do
net_http = Down::NetHttp.new("User-Agent" => "Janko")
io = net_http.open("#{$httpbin}/user-agent")
assert_equal "Janko", JSON.parse(io.read)["user-agent"]
end
it "saves response data" do
io = Down::NetHttp.open("#{$httpbin}/response-headers?Key=Value")
assert_equal "Value", io.data[:headers]["Key"]
assert_equal 200, io.data[:status]
assert_kind_of Net::HTTPResponse, io.data[:response]
end
it "raises on HTTP error responses" do
error = assert_raises(Down::ClientError) { Down::NetHttp.open("#{$httpbin}/status/404") }
assert_equal "404 Not Found", error.message
assert_kind_of Net::HTTPResponse, error.response
error = assert_raises(Down::ServerError) { Down::NetHttp.open("#{$httpbin}/status/500") }
assert_equal "500 Internal Server Error", error.message
assert_kind_of Net::HTTPResponse, error.response
end
it "raises on invalid URLs" do
assert_raises(Down::InvalidUrl) { Down::NetHttp.open("http:\\example.org") }
assert_raises(Down::InvalidUrl) { Down::NetHttp.open("foo://example.org") }
end
it "raises on connection errors" do
assert_raises(Down::ConnectionError) { Down::NetHttp.open("http://localhost:99999") }
end
it "raises on timeout errors" do
assert_raises(Down::TimeoutError) { Down::NetHttp.open("#{$httpbin}/delay/0.5", read_timeout: 0).read }
end
it "re-raises SSL errors" do
TCPSocket.expects(:open).raises(OpenSSL::SSL::SSLError)
assert_raises(Down::SSLError) { Down::NetHttp.open($httpbin) }
end
it "re-raises other exceptions" do
assert_raises(TypeError) { Down::NetHttp.open($httpbin, read_timeout: "foo") }
end
end
end
Fix failing test on JRuby
require "test_helper"
require "down/net_http"
require "http"
require "stringio"
require "json"
require "base64"
describe Down do
describe "#download" do
it "downloads content from url" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}?seed=0")
assert_equal HTTP.get("#{$httpbin}/bytes/#{20*1024}?seed=0").to_s, tempfile.read
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{1024}?seed=0")
assert_equal HTTP.get("#{$httpbin}/bytes/#{1024}?seed=0").to_s, tempfile.read
end
it "returns a Tempfile" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}")
assert_instance_of Tempfile, tempfile
# open-uri returns a StringIO on files with 10KB or less
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{1024}")
assert_instance_of Tempfile, tempfile
end
it "saves Tempfile to disk" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}")
assert File.exist?(tempfile.path)
# open-uri returns a StringIO on files with 10KB or less
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{1024}")
assert File.exist?(tempfile.path)
end
it "opens the Tempfile in binary mode" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}")
assert tempfile.binmode?
# open-uri returns a StringIO on files with 10KB or less
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{1024}")
assert tempfile.binmode?
end
it "gives the Tempfile a file extension" do
tempfile = Down::NetHttp.download("#{$httpbin}/robots.txt")
assert_equal ".txt", File.extname(tempfile.path)
tempfile = Down::NetHttp.download("#{$httpbin}/robots.txt?foo=bar")
assert_equal ".txt", File.extname(tempfile.path)
tempfile = Down::NetHttp.download("#{$httpbin}/redirect-to?url=#{$httpbin}/robots.txt")
assert_equal ".txt", File.extname(tempfile.path)
end
it "accepts an URI object" do
tempfile = Down::NetHttp.download(URI("#{$httpbin}/bytes/100"))
assert_equal 100, tempfile.size
end
it "uses a default User-Agent" do
tempfile = Down::NetHttp.download("#{$httpbin}/user-agent")
assert_equal "Down/#{Down::VERSION}", JSON.parse(tempfile.read)["user-agent"]
end
it "accepts max size" do
assert_raises(Down::TooLarge) do
Down::NetHttp.download("#{$httpbin}/bytes/10", max_size: 5)
end
assert_raises(Down::TooLarge) do
Down::NetHttp.download("#{$httpbin}/stream-bytes/10", max_size: 5)
end
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/10", max_size: 10)
assert File.exist?(tempfile.path)
tempfile = Down::NetHttp.download("#{$httpbin}/stream-bytes/10", max_size: 15)
assert File.exist?(tempfile.path)
end
it "accepts content length proc" do
Down::NetHttp.download "#{$httpbin}/bytes/100",
content_length_proc: ->(n) { @content_length = n }
assert_equal 100, @content_length
end
it "accepts progress proc" do
Down::NetHttp.download "#{$httpbin}/stream-bytes/100?chunk_size=10",
progress_proc: ->(n) { (@progress ||= []) << n }
assert_equal [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], @progress
end
it "detects and applies basic authentication from URL" do
tempfile = Down::NetHttp.download("#{$httpbin.sub("http://", '\0user:password@')}/basic-auth/user/password")
assert_equal true, JSON.parse(tempfile.read)["authenticated"]
end
it "follows redirects" do
tempfile = Down::NetHttp.download("#{$httpbin}/redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
tempfile = Down::NetHttp.download("#{$httpbin}/redirect/2")
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
assert_raises(Down::TooManyRedirects) { Down::NetHttp.download("#{$httpbin}/redirect/3") }
tempfile = Down::NetHttp.download("#{$httpbin}/redirect/3", max_redirects: 3)
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
assert_raises(Down::TooManyRedirects) { Down::NetHttp.download("#{$httpbin}/redirect/4", max_redirects: 3) }
tempfile = Down::NetHttp.download("#{$httpbin}/absolute-redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
tempfile = Down::NetHttp.download("#{$httpbin}/relative-redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
# We also want to test that cookies are being forwarded on redirects, but
# httpbin doesn't have an endpoint which can both redirect and return a
# "Set-Cookie" header.
end
# I don't know how to test that the proxy is actually used
it "accepts proxy" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/100", proxy: $httpbin)
assert_equal 100, tempfile.size
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/100", proxy: $httpbin.sub("http://", '\0user:password@'))
assert_equal 100, tempfile.size
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/100", proxy: URI($httpbin.sub("http://", '\0user:password@')))
assert_equal 100, tempfile.size
end
it "forwards other options to open-uri" do
tempfile = Down::NetHttp.download("#{$httpbin}/user-agent", {"User-Agent" => "Custom/Agent"})
assert_equal "Custom/Agent", JSON.parse(tempfile.read)["user-agent"]
tempfile = Down::NetHttp.download("#{$httpbin}/basic-auth/user/password", http_basic_authentication: ["user", "password"])
assert_equal true, JSON.parse(tempfile.read)["authenticated"]
end
it "applies default options" do
net_http = Down::NetHttp.new("User-Agent" => "Janko")
tempfile = net_http.download("#{$httpbin}/user-agent")
assert_equal "Janko", JSON.parse(tempfile.read)["user-agent"]
end
it "adds #original_filename extracted from Content-Disposition" do
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=\"my%20filename.ext\"")
assert_equal "my filename.ext", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=\"my%2520filename.ext\"")
assert_equal "my filename.ext", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=myfilename.ext%20")
assert_equal "myfilename.ext", tempfile.original_filename
end
it "adds #original_filename extracted from URI path if Content-Disposition is blank" do
tempfile = Down::NetHttp.download("#{$httpbin}/robots.txt")
assert_equal "robots.txt", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/basic-auth/user/pass%20word", http_basic_authentication: ["user", "pass word"])
assert_equal "pass word", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=")
assert_equal "response-headers", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=\"\"")
assert_equal "response-headers", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/")
assert_nil tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}")
assert_nil tempfile.original_filename
end
it "adds #content_type extracted from Content-Type" do
tempfile = Down::NetHttp.download("#{$httpbin}/image/png")
assert_equal "image/png", tempfile.content_type
tempfile = Down::NetHttp.download("#{$httpbin}/encoding/utf8")
assert_equal "text/html; charset=utf-8", tempfile.meta["content-type"]
assert_equal "text/html", tempfile.content_type
tempfile.meta.delete("content-type")
assert_nil tempfile.content_type
tempfile.meta["content-type"] = nil
assert_nil tempfile.content_type
tempfile.meta["content-type"] = ""
assert_nil tempfile.content_type
end
it "accepts download destination" do
tempfile = Tempfile.new("destination")
result = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}?seed=0", destination: tempfile.path)
assert_equal HTTP.get("#{$httpbin}/bytes/#{20*1024}?seed=0").to_s, File.binread(tempfile.path)
assert_nil result
end
it "raises on HTTP error responses" do
error = assert_raises(Down::ClientError) { Down::NetHttp.download("#{$httpbin}/status/404") }
assert_equal "404 Not Found", error.message
assert_kind_of Net::HTTPResponse, error.response
error = assert_raises(Down::ServerError) { Down::NetHttp.download("#{$httpbin}/status/500") }
assert_equal "500 Internal Server Error", error.message
assert_kind_of Net::HTTPResponse, error.response
end
it "raises on invalid URLs" do
assert_raises(Down::InvalidUrl) { Down::NetHttp.download("http:\\example.org") }
assert_raises(Down::InvalidUrl) { Down::NetHttp.download("foo://example.org") }
assert_raises(Down::InvalidUrl) { Down::NetHttp.download("| ls") }
end
it "raises on connection errors" do
assert_raises(Down::ConnectionError) { Down::NetHttp.download("http://localhost:99999") }
end
it "raises on timeout errors" do
assert_raises(Down::TimeoutError) { Down::NetHttp.download("#{$httpbin}/delay/0.5", read_timeout: 0, open_timeout: 0) }
end
end
describe "#open" do
it "streams response body in chunks" do
io = Down::NetHttp.open("#{$httpbin}/stream/10")
assert_equal 10, io.each_chunk.count
end
it "accepts an URI object" do
io = Down::NetHttp.open(URI("#{$httpbin}/stream/10"))
assert_equal 10, io.each_chunk.count
end
it "downloads on demand" do
start = Time.now
io = Down::NetHttp.open("#{$httpbin}/drip?duration=0.5&delay=0")
io.close
assert_operator Time.now - start, :<, 0.5
end
it "follows redirects" do
io = Down::NetHttp.open("#{$httpbin}/redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
io = Down::NetHttp.open("#{$httpbin}/redirect/2")
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
assert_raises(Down::TooManyRedirects) { Down::NetHttp.open("#{$httpbin}/redirect/3") }
io = Down::NetHttp.open("#{$httpbin}/redirect/3", max_redirects: 3)
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
assert_raises(Down::TooManyRedirects) { Down::NetHttp.open("#{$httpbin}/redirect/4", max_redirects: 3) }
io = Down::NetHttp.open("#{$httpbin}/absolute-redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
io = Down::NetHttp.open("#{$httpbin}/relative-redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
end
it "returns content in encoding specified by charset" do
io = Down::NetHttp.open("#{$httpbin}/stream/10")
assert_equal Encoding::BINARY, io.read.encoding
io = Down::NetHttp.open("#{$httpbin}/get")
assert_equal Encoding::BINARY, io.read.encoding
io = Down::NetHttp.open("#{$httpbin}/encoding/utf8")
assert_equal Encoding::UTF_8, io.read.encoding
end
it "uses a default User-Agent" do
io = Down::NetHttp.open("#{$httpbin}/user-agent")
assert_equal "Down/#{Down::VERSION}", JSON.parse(io.read)["user-agent"]
end
it "doesn't have to be rewindable" do
io = Down::NetHttp.open("#{$httpbin}/stream/10", rewindable: false)
io.read
assert_raises(IOError) { io.rewind }
end
it "extracts size from Content-Length" do
io = Down::NetHttp.open(URI("#{$httpbin}/bytes/100"))
assert_equal 100, io.size
io = Down::NetHttp.open(URI("#{$httpbin}/stream-bytes/100"))
assert_nil io.size
end
it "closes the connection on #close" do
io = Down::NetHttp.open("#{$httpbin}/bytes/100")
Net::HTTP.any_instance.expects(:do_finish)
io.close
end
it "accepts request headers" do
io = Down::NetHttp.open("#{$httpbin}/headers", {"Key" => "Value"})
assert_equal "Value", JSON.parse(io.read)["headers"]["Key"]
end
# I don't know how to test that the proxy is actually used
it "accepts proxy" do
io = Down::NetHttp.open("#{$httpbin}/bytes/100", proxy: $httpbin)
assert_equal 100, io.size
io = Down::NetHttp.open("#{$httpbin}/bytes/100", proxy: $httpbin.sub("http://", '\0user:password@'))
assert_equal 100, io.size
io = Down::NetHttp.open("#{$httpbin}/bytes/100", proxy: URI($httpbin.sub("http://", '\0user:password@')))
assert_equal 100, io.size
end
it "detects and applies basic authentication from URL" do
io = Down::NetHttp.open("#{$httpbin.sub("http://", '\0user:password@')}/basic-auth/user/password")
assert_equal true, JSON.parse(io.read)["authenticated"]
end
it "applies default options" do
net_http = Down::NetHttp.new("User-Agent" => "Janko")
io = net_http.open("#{$httpbin}/user-agent")
assert_equal "Janko", JSON.parse(io.read)["user-agent"]
end
it "saves response data" do
io = Down::NetHttp.open("#{$httpbin}/response-headers?Key=Value")
assert_equal "Value", io.data[:headers]["Key"]
assert_equal 200, io.data[:status]
assert_kind_of Net::HTTPResponse, io.data[:response]
end
it "raises on HTTP error responses" do
error = assert_raises(Down::ClientError) { Down::NetHttp.open("#{$httpbin}/status/404") }
assert_equal "404 Not Found", error.message
assert_kind_of Net::HTTPResponse, error.response
error = assert_raises(Down::ServerError) { Down::NetHttp.open("#{$httpbin}/status/500") }
assert_equal "500 Internal Server Error", error.message
assert_kind_of Net::HTTPResponse, error.response
end
it "raises on invalid URLs" do
assert_raises(Down::InvalidUrl) { Down::NetHttp.open("http:\\example.org") }
assert_raises(Down::InvalidUrl) { Down::NetHttp.open("foo://example.org") }
end
it "raises on connection errors" do
assert_raises(Down::ConnectionError) { Down::NetHttp.open("http://localhost:99999") }
end
it "raises on timeout errors" do
assert_raises(Down::TimeoutError) { Down::NetHttp.open("#{$httpbin}/delay/0.5", read_timeout: 0).read }
end
it "re-raises SSL errors" do
TCPSocket.expects(:open).raises(OpenSSL::SSL::SSLError)
assert_raises(Down::SSLError) { Down::NetHttp.open($httpbin) }
end
it "re-raises other exceptions" do
TCPSocket.expects(:open).raises(ArgumentError)
assert_raises(ArgumentError) { Down::NetHttp.open($httpbin) }
end
end
end
|
Blocklet.new do
control = instance || "Master"
type = control == "Mic" ? :input : :output
def parse(data)
volume, is_muted = nil, nil
data.scan(/\[(\S+)\]/).flatten.each do |s|
break unless volume.nil? or is_muted.nil?
if s.end_with? "%"
volume = s.sub(/%/, "").to_i
next
end
is_muted = false if s == "on"
is_muted = true if s == "off"
end
return volume, is_muted
end
def update(type, volume, is_muted)
if is_muted
if type == :output
icon ""
else
icon ""
end
text "Muted"
color :yellow
else
if type == :output
icon ""
else
icon ""
end
text "#{volume}%"
color :normal
end
end
on :mouse do |button|
result = case button
when 1 then `amixer set #{control} toggle`
when 4 then `amixer set #{control} 5%+ unmute`
when 5 then `amixer set #{control} 5%- unmute`
end
volume, is_muted = parse(result)
update(type, volume, is_muted)
end
volume, is_muted = parse(`amixer get #{control}`)
update(type, volume, is_muted)
end
Detect current sound card from ~/.asoundrc
Blocklet.new do
control = instance || "Master"
type = control == "Mic" ? :input : :output
def get_card_id
begin
File.open(File.expand_path("~/.asoundrc"), "r").each_line do |line|
return $~[1].to_i unless (/card\s+(\d)/ =~ line) == nil
end
rescue
# Do nothing
end
return 0
end
def parse(data)
volume, is_muted = nil, nil
data.scan(/\[(\S+)\]/).flatten.each do |s|
break unless volume.nil? or is_muted.nil?
if s.end_with? "%"
volume = s.sub(/%/, "").to_i
next
end
is_muted = false if s == "on"
is_muted = true if s == "off"
end
return volume, is_muted
end
def update(type, volume, is_muted)
if is_muted
if type == :output
icon ""
else
icon ""
end
text "Muted"
color :yellow
else
if type == :output
icon ""
else
icon ""
end
text "#{volume}%"
color :normal
end
end
on :mouse do |button|
result = case button
when 1 then `amixer set #{control} -c #{get_card_id} toggle`
when 4 then `amixer set #{control} -c #{get_card_id} 5%+ unmute`
when 5 then `amixer set #{control} -c #{get_card_id} 5%- unmute`
end
volume, is_muted = parse(result)
update(type, volume, is_muted)
end
volume, is_muted = parse(`amixer get #{control} -c #{get_card_id}`)
update(type, volume, is_muted)
end
|
LebowskiApi::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
config.cache_store = :memory_store, { size: 64.megabytes }
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
Added specific require in production.rb
require 'active_support/core_ext/numeric/bytes'
LebowskiApi::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
config.cache_store = :memory_store, { size: 64.megabytes }
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
|
Skyderby::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
Rails.application.config.middleware.use ExceptionNotification::Rack,
slack: {
webhook_url: ENV['slack.webhook_url'],
channel: ENV['slack.channel']
}
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { host: 'skyderby.ru' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: ENV['smtp.address'],
port: ENV['smtp.port'],
domain: ENV['smtp.domain'],
user_name: ENV['smtp.user_name'],
password: ENV['smtp.password']
}
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
nested properties replaced with simple
Skyderby::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
Rails.application.config.middleware.use ExceptionNotification::Rack,
slack: {
webhook_url: ENV['slack_webhook_url'],
channel: ENV['slack_channel']
}
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { host: 'skyderby.ru' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: ENV['smtp_address'],
port: ENV['smtp_port'],
domain: ENV['smtp_domain'],
user_name: ENV['smtp_user_name'],
password: ENV['smtp_password']
}
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
|
#encoding: utf-8
#############################################################################
#
# Estimancy, Open Source project estimation web application
# Copyright (c) 2014 Estimancy (http://www.estimancy.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# ======================================================================
#
# ProjEstimate, Open Source project estimation web application
# Copyright (c) 2013 Spirula (http://www.spirula.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
Projestimate::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
#default url
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"
end
bugs groups on groups_users
#encoding: utf-8
#############################################################################
#
# Estimancy, Open Source project estimation web application
# Copyright (c) 2014 Estimancy (http://www.estimancy.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# ======================================================================
#
# ProjEstimate, Open Source project estimation web application
# Copyright (c) 2013 Spirula (http://www.spirula.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
Projestimate::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
#default url
config.action_mailer.default_url_options = { host: "stelsia.estimancy.com" }
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
config.action_controller.default_url_options = { host: 'blog.com' }
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
config.assets.precompile += %w( clear_form.scss clean_form.js.coffee markdown_converter.js.coffee medium.js medium.min.css medium-editor-insert-plugin.min.js sortable.min.js sortable.min.js jquery.ui.widget.min.js jquery.iframe_transport.js jquery.fileupload.min.js commons.scss fonts.scss)
config.assets.precompile += %w( patricia_carmona_colors.scss patricia_carmona.scss modal_link_observer.js.coffee font-families.css mobile.scss patricia_carmona_mobile.scss)
config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
config.assets.paths << Rails.root.join("public", "post", "images")
config.assets.paths << Rails.root.join("public", "uploads", "tmp")
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Action Cable endpoint configuration
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :request_id ]
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "Blog_#{Rails.env}"
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
public folder like server assets
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
config.action_controller.default_url_options = { host: 'patriciacarmona.com' }
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
config.assets.precompile += %w( clear_form.scss clean_form.js.coffee markdown_converter.js.coffee medium.js medium.min.css medium-editor-insert-plugin.min.js sortable.min.js sortable.min.js jquery.ui.widget.min.js jquery.iframe_transport.js jquery.fileupload.min.js commons.scss fonts.scss)
config.assets.precompile += %w( patricia_carmona_colors.scss patricia_carmona.scss modal_link_observer.js.coffee font-families.css mobile.scss patricia_carmona_mobile.scss)
config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
config.assets.paths << Rails.root.join("public", "post", "images")
config.assets.paths << Rails.root.join("public", "uploads", "tmp")
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Action Cable endpoint configuration
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :request_id ]
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "Blog_#{Rails.env}"
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# memcached exists in this image
config.cache_store = :dalli_store, "http://127.0.0.1:11211",
{ :namespace => 'artsapi', :expires_in => 1.year, :compress => true }
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
# config.active_record.dump_schema_after_migration = false
end
Tripod.configure do |config|
config.update_endpoint = ENV['FUSEKI_UPDATE_ENDPOINT'].nil? ? "http://#{ARTSAPI_FUSEKI_TCP_ADDR}:3030/artsapi-dev/update" : "#{ENV['FUSEKI_UPDATE_ENDPOINT']}" # check if we're in staging
config.query_endpoint = ENV['FUSEKI_QUERY_ENDPOINT'].nil? ? "http://#{ARTSAPI_FUSEKI_TCP_ADDR}:3030/artsapi-dev/sparql" : "#{ENV['FUSEKI_QUERY_ENDPOINT']}" # check if we're in staging
# memcached exists in this image
config.cache_store = Tripod::CacheStores::MemcachedCacheStore.new("http://127.0.0.1:11211")
end
# Sidekiq.configure_server do |config|
# config.redis = { url: "redis://#{ENV['ARTSAPI_REDIS_TCP_ADDR']}:6379", namespace: 'artsapi' }
# end
Correct typo.
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# memcached exists in this image
config.cache_store = :dalli_store, "http://127.0.0.1:11211",
{ :namespace => 'artsapi', :expires_in => 1.year, :compress => true }
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
# config.active_record.dump_schema_after_migration = false
end
Tripod.configure do |config|
config.update_endpoint = ENV['FUSEKI_UPDATE_ENDPOINT'].nil? ? "http://#{ENV['ARTSAPI_FUSEKI_TCP_ADDR']}:3030/artsapi-dev/update" : "#{ENV['FUSEKI_UPDATE_ENDPOINT']}" # check if we're in staging
config.query_endpoint = ENV['FUSEKI_QUERY_ENDPOINT'].nil? ? "http://#{ENV['ARTSAPI_FUSEKI_TCP_ADDR']}:3030/artsapi-dev/sparql" : "#{ENV['FUSEKI_QUERY_ENDPOINT']}" # check if we're in staging
# memcached exists in this image
config.cache_store = Tripod::CacheStores::MemcachedCacheStore.new("http://127.0.0.1:11211")
end
# Sidekiq.configure_server do |config|
# config.redis = { url: "redis://#{ENV['ARTSAPI_REDIS_TCP_ADDR']}:6379", namespace: 'artsapi' }
# end
|
Ready4rails4::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
config.action_controller.asset_host = ENV['CDN_SUMO_URL']
config.static_cache_control = "public, max-age=2592000"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
ActionMailer::Base.smtp_settings = {
:address => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'heroku.com',
:enable_starttls_auto => true
}
config.action_mailer.default_url_options = { host: 'ready4rails4.net' }
end
Use config.action_mailer namespace to set Action Mailer configs
Ready4rails4::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
config.action_controller.asset_host = ENV['CDN_SUMO_URL']
config.static_cache_control = "public, max-age=2592000"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
config.action_mailer.smtp_settings = {
address: 'smtp.sendgrid.net',
port: '587',
authentication: :plain,
user_name: ENV['SENDGRID_USERNAME'],
password: ENV['SENDGRID_PASSWORD'],
domain: 'heroku.com',
enable_starttls_auto: true
}
config.action_mailer.default_url_options = { host: 'ready4rails4.net' }
end
|
Whogoesfirst::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
adds default url options for production
Whogoesfirst::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
config.action_mailer.default_url_options = {:host => 'whogoesfirst.herokuapp.com'}
end
|
# encoding: utf-8
Keks::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w( die-ie-die.css )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
config.action_mailer.default_url_options = { :host => "www.mathi.uni-heidelberg.de", :protocol => "https:" }
# make production more like development
#~ config.cache_classes = false
config.whiny_nils = true
config.consider_all_requests_local = true
#~ config.action_controller.perform_caching = false
end
compile print.css in production
# encoding: utf-8
Keks::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w( die-ie-die.css print.css )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
config.action_mailer.default_url_options = { :host => "www.mathi.uni-heidelberg.de", :protocol => "https:" }
# make production more like development
#~ config.cache_classes = false
config.whiny_nils = true
config.consider_all_requests_local = true
#~ config.action_controller.perform_caching = false
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# `config.assets.precompile` has moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.smtp_settings = {
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'womenrising.co',
:address => 'smtp.sendgrid.net',
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true
}
config.action_mailer.default_options = {
:reply_to => 'info@womenrising.co'
}
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
From instead of reply-to
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# `config.assets.precompile` has moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.smtp_settings = {
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'womenrising.co',
:address => 'smtp.sendgrid.net',
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true
}
config.action_mailer.default_options = {
:from => 'info@womenrising.co'
}
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
ENV['S3_ACCESS_KEY'] = "AKIAJJFST2PYIY4S2BZQ"
ENV['S3_BUCKET'] = "rails-blog-system"
ENV['S3_SECRET_KEY'] = "fa24ff8d346c924a01b100c7902b8ab7444d791f277eca4b1e3d429d8a54988a221f73f0c0c5fe3a65bb49814dc41c1b0cb567be3ae0cfc0d0937c5c12ffb3e4"
end
Upload aws keys
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
ENV['S3_ACCESS_KEY'] = "AKIAJIGIC3NTDMXE7OZA"
ENV['S3_BUCKET'] = "rails-blog-system"
ENV['S3_SECRET_KEY'] = "Jned2Aht81IAeFM8pD1RLBsvlO"
end
|
require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = CONFIG["secure"]
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :warn
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "moebooru_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Log disallowed deprecations.
config.active_support.disallowed_deprecation = :log
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if true || ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_mailer.delivery_method = :sendmail
config.middleware.use ExceptionNotification::Rack,
:ignore_exceptions => %w(ActionController::BadRequest ActionController::ParameterMissing) + ExceptionNotifier.ignored_exceptions,
:email => {
:email_prefix => "[#{CONFIG["app_name"]}] ",
:sender_address => "notifier <#{CONFIG["email_from"]}>",
:exception_recipients => CONFIG["admin_contact"]
}
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
Don't report invalid token errors
require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = CONFIG["secure"]
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :warn
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "moebooru_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Log disallowed deprecations.
config.active_support.disallowed_deprecation = :log
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if true || ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_mailer.delivery_method = :sendmail
config.middleware.use ExceptionNotification::Rack,
:ignore_exceptions => %w(ActionController::BadRequest ActionController::ParameterMissing ActionController::InvalidAuthenticityToken) + ExceptionNotifier.ignored_exceptions,
:email => {
:email_prefix => "[#{CONFIG["app_name"]}] ",
:sender_address => "notifier <#{CONFIG["email_from"]}>",
:exception_recipients => CONFIG["admin_contact"]
}
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
fixing assets
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
Rails.application.routes.default_url_options[:host] = "beertrade.herokuapp.com"
Proper production domain
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
Rails.application.routes.default_url_options[:host] = "rbeertrade.com"
|
require 'travis'
TravisCi::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The production environment is meant for finished, 'live' apps.
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.threadsafe!
# Specifies the header that your server uses for sending files
#config.action_dispatch.x_sendfile_header = 'X-Sendfile'
# For nginx:
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
# If you have no front-end server that supports something like X-Sendfile,
# just comment this out and Rails will serve the files
config.logger = Logger.new(STDOUT)
config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = 'http://assets.example.com'
config.action_mailer.default_url_options = {
:host => Travis.config.domain
}
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.smtp_settings = {
:address => Travis.config.smtp.address,
:port => '25',
:authentication => :cram_md5,
:user_name => Travis.config.smtp.user_name,
:password => Travis.config.smtp.password,
:domain => Travis.config.smtp.domain,
:enable_starttls_auto => true
}
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
config.middleware.insert_before(::Rack::Runtime, 'Refraction')
end
Revert "production env should run in threadsafe mode with puma"
This reverts commit 55d4985e0ff1db7a1cdfcb8803dadd5d77e92b9b.
require 'travis'
TravisCi::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The production environment is meant for finished, 'live' apps.
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Specifies the header that your server uses for sending files
#config.action_dispatch.x_sendfile_header = 'X-Sendfile'
# For nginx:
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
# If you have no front-end server that supports something like X-Sendfile,
# just comment this out and Rails will serve the files
config.logger = Logger.new(STDOUT)
config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = 'http://assets.example.com'
config.action_mailer.default_url_options = {
:host => Travis.config.domain
}
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.smtp_settings = {
:address => Travis.config.smtp.address,
:port => '25',
:authentication => :cram_md5,
:user_name => Travis.config.smtp.user_name,
:password => Travis.config.smtp.password,
:domain => Travis.config.smtp.domain,
:enable_starttls_auto => true
}
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
config.middleware.insert_before(::Rack::Runtime, 'Refraction')
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "whats_opt_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
fix relative url root in production
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "whats_opt_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
# set the relative root, because we're deploying to /whatsopt
config.relative_url_root = "/whatsopt"
end
|
Balances::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Enables Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = true
config.static_cache_control = "public, max-age=#{1.day.to_i}"
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# We'll use the Heroku add-on `memcachier` with dalli:
config.cache_store = :dalli_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = ENV['ASSET_HOST']
# config.action_mailer.asset_host = ENV['ASSET_HOST']
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
config.assets.precompile += %w(
landing/landing_app.css
landing/landing.js
)
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = { host: 'balances.io' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
port: '587',
address: 'smtp.mandrillapp.com',
user_name: ENV['MANDRILL_USERNAME'],
password: ENV['MANDRILL_APIKEY'],
domain: 'heroku.com',
authentication: :plain
}
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
uhh asset versions idk?
Balances::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Enables Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = true
config.static_cache_control = "public, max-age=#{1.day.to_i}"
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.1'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# We'll use the Heroku add-on `memcachier` with dalli:
config.cache_store = :dalli_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = ENV['ASSET_HOST']
# config.action_mailer.asset_host = ENV['ASSET_HOST']
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
config.assets.precompile += %w(
landing/landing_app.css
landing/landing.js
)
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = { host: 'balances.io' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
port: '587',
address: 'smtp.mandrillapp.com',
user_name: ENV['MANDRILL_USERNAME'],
password: ENV['MANDRILL_APIKEY'],
domain: 'heroku.com',
authentication: :plain
}
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
|
Coursemology::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
#disable name mangling during JavaScript minification
config.assets.js_compressor = Uglifier.new(mangle: false)
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
config.log_level = :info
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
config.cache_store = :dalli_store, { pool_size: 5 }
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
#config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
# Config mailer
config.action_mailer.default_url_options = { :host => 'https://edutech.comp.nus.edu.sg' }
# ActionMailer Config
# Setup for production - deliveries, no errors raised
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default :charset => "utf-8"
#Setting host mail MANDRILL
#ActionMailer::Base.smtp_settings = {
# :address => "smtp.mandrillapp.com",
# :port => 587,
# :authentication => :plain,
# :domain => ENV['MANDRILL_SMTP_USER'],
# :user_name => ENV['MANDRILL_SMTP_USER'],
# :password => ENV['MANDRILL_SMTP_PASSWORD'],
#}
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:authentication => :plain,
:domain => ENV['GMAIL_SMTP_USER'],
:user_name => ENV['GMAIL_SMTP_USER'],
:password => ENV['GMAIL_SMTP_PASSWORD'],
}
#Setting for paperclip with s3 - amazon cloud storage (Not used for local storage)
#config.paperclip_defaults = {
# preserve_files: true,
# storage: :s3,
# s3_credentials: {
# bucket: ENV['AWS_BUCKET'],
# access_key_id: ENV['AWS_ACCESS_KEY_ID'],
# secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']
# }
#}
config.middleware.use ExceptionNotification::Rack,
:email => {
:email_prefix => "[ERROR]",
:sender_address => %{"Coursemology Exception" <exception.notifier@coursemology.com>},
:exception_recipients => "nusedutech@gmail.com"
}
#ivle login, NUS openID login
config.middleware.use OmniAuth::Builder do
provider :ivle, api_key: "mHy1mEcwwWvlHYqc9bNdO"
provider :open_id, :identifier => "https://openid.nus.edu.sg"
end
config.ivle_api_key = "mHy1mEcwwWvlHYqc9bNdO"
end
update protocol for production
Coursemology::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
#disable name mangling during JavaScript minification
config.assets.js_compressor = Uglifier.new(mangle: false)
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
config.log_level = :info
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
config.cache_store = :dalli_store, { pool_size: 5 }
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
#config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
# Config mailer
config.action_mailer.default_url_options = { :host => 'edutech.comp.nus.edu.sg', :protocol => 'https' }
# ActionMailer Config
# Setup for production - deliveries, no errors raised
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default :charset => "utf-8"
#Setting host mail MANDRILL
#ActionMailer::Base.smtp_settings = {
# :address => "smtp.mandrillapp.com",
# :port => 587,
# :authentication => :plain,
# :domain => ENV['MANDRILL_SMTP_USER'],
# :user_name => ENV['MANDRILL_SMTP_USER'],
# :password => ENV['MANDRILL_SMTP_PASSWORD'],
#}
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:authentication => :plain,
:domain => ENV['COMP_SMTP_USER'],
:user_name => ENV['GMAIL_SMTP_USER'],
:password => ENV['GMAIL_SMTP_PASSWORD'],
}
#Setting for paperclip with s3 - amazon cloud storage (Not used for local storage)
#config.paperclip_defaults = {
# preserve_files: true,
# storage: :s3,
# s3_credentials: {
# bucket: ENV['AWS_BUCKET'],
# access_key_id: ENV['AWS_ACCESS_KEY_ID'],
# secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']
# }
#}
config.middleware.use ExceptionNotification::Rack,
:email => {
:email_prefix => "[ERROR]",
:sender_address => %{"Coursemology Exception" <exception.notifier@coursemology.com>},
:exception_recipients => "nusedutech@gmail.com"
}
#ivle login, NUS openID login
config.middleware.use OmniAuth::Builder do
provider :ivle, api_key: "mHy1mEcwwWvlHYqc9bNdO"
provider :open_id, :identifier => "https://openid.nus.edu.sg"
end
config.ivle_api_key = "mHy1mEcwwWvlHYqc9bNdO"
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV["RAILS_SERVE_STATIC_FILES"].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = Uglifier.new(harmony: true)
# config.assets.css_compressor = :sass
# include svg in the precompile
config.assets.precompile += [".svg"]
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [:request_id]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Read the product config
config.x.product.name = Rails.root.join("PRODUCT").read
config.x.product.version = Rails.root.join("VERSION").read
end
require uglifier only during packaging
the constant `Uglifier` is not accessible when opening a
rails console or running a rake command
fix#uglifier
Signed-off-by: Maximilian Meister <d082c6e85b1479677ce48cb91ac104a594c00930@suse.de>
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV["RAILS_SERVE_STATIC_FILES"].present?
# Compress JavaScripts and CSS.
if ENV["RPM_BUILD_ROOT"]
config.assets.js_compressor = Uglifier.new(harmony: true)
end
# config.assets.css_compressor = :sass
# include svg in the precompile
config.assets.precompile += [".svg"]
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [:request_id]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Read the product config
config.x.product.name = Rails.root.join("PRODUCT").read
config.x.product.version = Rails.root.join("VERSION").read
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "cfp_app_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_mailer.default_url_options = { host: ENV['MAIL_HOST'] }
config.action_mailer.default_options = {from: ENV['MAIL_FROM']}
config.action_mailer.smtp_settings = {
:address => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'heroku.com',
:enable_starttls_auto => true
}
config.exceptions_app = self.routes
config.time_zone = ENV.fetch('TIMEZONE') {'Pacific Time (US & Canada)'}
end
Makes it possible to configure the SMTP settings
Enable using non-SendGrid mail providers
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "cfp_app_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_mailer.default_url_options = { host: ENV['MAIL_HOST'] }
config.action_mailer.default_options = {from: ENV['MAIL_FROM']}
config.action_mailer.smtp_settings = {
:address => ENV.fetch('SMTP_ADDRESS', 'smtp.sendgrid.net'),
:port => ENV.fetch('SMTP_PORT', '587'),
:authentication => :plain,
:user_name => ENV.fetch('SMTP_USERNAME', ENV['SENDGRID_USERNAME']),
:password => ENV.fetch('SMTP_PASSWORD', ENV['SENDGRID_PASSWORD']),
:domain => 'heroku.com',
:enable_starttls_auto => true
}
config.exceptions_app = self.routes
config.time_zone = ENV.fetch('TIMEZONE') {'Pacific Time (US & Canada)'}
end
|
SignInWithLinkedin::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end
Updated config for heroku
SignInWithLinkedin::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
config.action_dispatch.x_sendfile_header = nil
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end
|
Sifaca::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "gmail.com",
authentication: "plain",
enable_starttls_auto: true,
user_name: "waldix86@gmail.com",
password: "patito86"
}
config.action_mailer.default :charset => "utf-8"
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :silence
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
[ODLG] Configuracion de Heroku.
Sifaca::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "gmail.com",
authentication: "plain",
enable_starttls_auto: true,
user_name: "waldix86@gmail.com",
password: "patito86"
}
config.action_mailer.default :charset => "utf-8"
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
|
Anotar::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = false
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
config.assets.initialize_on_precompile = false
# ActionMailer Config
# Setup for production - deliveries, no errors raised
config.action_mailer.default_url_options = { :host => 'anotar.herokuapp.com' }
#ActionMailer::Base.smtp_settings[:enable_starttls_auto] = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default :charset => "utf-8"
#config.action_mailer.smtp_settings = {
# address: "smtp.gmail.com",
# port: 587,
# domain: "anotar.herokuapp.com",
# authentication: "plain",
# enable_starttls_auto: true,
# user_name: ENV["GMAIL_USERNAME"],
# password: ENV["GMAIL_PASSWORD"]
#}
end
More changes to email
Anotar::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = false
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
config.assets.initialize_on_precompile = false
# ActionMailer Config
# Setup for production - deliveries, no errors raised
config.action_mailer.default_url_options = { :host => 'anotar.herokuapp.com' }
#ActionMailer::Base.smtp_settings[:enable_starttls_auto] = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"
#config.action_mailer.smtp_settings = {
# address: "smtp.gmail.com",
# port: 587,
# domain: "anotar.herokuapp.com",
# authentication: "plain",
# enable_starttls_auto: true,
# user_name: ENV["GMAIL_USERNAME"],
# password: ENV["GMAIL_PASSWORD"]
#}
end
# ActionMailer::Base.smtp_settings[:enable_starttls_auto] = false |
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
Diggest false
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
# config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# use lograge and log in single-line heroku router style
config.lograge.enabled = true
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [:request_id]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "telephone_appointment_planner_#{Rails.env}"
config.active_job.queue_adapter = :sidekiq
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV['RAILS_LOG_TO_STDOUT'].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Configure email delivery using Mailgun
config.action_mailer.smtp_settings = {
port: ENV['MAILGUN_SMTP_PORT'],
address: ENV['MAILGUN_SMTP_SERVER'],
user_name: ENV['MAILGUN_SMTP_LOGIN'],
password: ENV['MAILGUN_SMTP_PASSWORD'],
domain: 'pensionwise.gov.uk',
authentication: :plain
}
end
Reduce log-level to `info`
If production issues arise we can bump the log level temporarily to
diagnose issues, rather than noisily and needlessly logging with debug
verbosity.
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# use lograge and log in single-line heroku router style
config.lograge.enabled = true
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :info
# Prepend all log lines with the following tags.
config.log_tags = [:request_id]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "telephone_appointment_planner_#{Rails.env}"
config.active_job.queue_adapter = :sidekiq
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV['RAILS_LOG_TO_STDOUT'].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Configure email delivery using Mailgun
config.action_mailer.smtp_settings = {
port: ENV['MAILGUN_SMTP_PORT'],
address: ENV['MAILGUN_SMTP_SERVER'],
user_name: ENV['MAILGUN_SMTP_LOGIN'],
password: ENV['MAILGUN_SMTP_PASSWORD'],
domain: 'pensionwise.gov.uk',
authentication: :plain
}
end
|
secrets = Rails.application.secrets.mailer
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# config.webpacker.check_yarn_integrity = true
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
config.enable_dependency_loading = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.read_encrypted_secrets = false
# Use a different cache store in production.
config.cache_store = :dalli_store
# http://wcmc.io/heroku_memcached for reference
client = Dalli::Client.new(Rails.application.secrets.memcache_servers, {value_max_bytes: 10485760})
config.action_dispatch.rack_cache = {:metastore => client, :entitystore => client }
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_files = false
# Compress JavaScripts and CSS.
config.assets.compress = true
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = ""
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => secrets[:host] }
config.action_mailer.smtp_settings = {
:enable_starttls_auto => true,
:address => secrets[:address],
:port => 587,
:domain => secrets[:domain],
:authentication => :login,
:user_name => secrets[:username],
:password => secrets[:password]
}
config.active_storage.service = :local
end
Change active_storage service for production env
secrets = Rails.application.secrets.mailer
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# config.webpacker.check_yarn_integrity = true
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
config.enable_dependency_loading = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.read_encrypted_secrets = false
# Use a different cache store in production.
config.cache_store = :dalli_store
# http://wcmc.io/heroku_memcached for reference
client = Dalli::Client.new(Rails.application.secrets.memcache_servers, {value_max_bytes: 10485760})
config.action_dispatch.rack_cache = {:metastore => client, :entitystore => client }
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_files = false
# Compress JavaScripts and CSS.
config.assets.compress = true
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = ""
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => secrets[:host] }
config.action_mailer.smtp_settings = {
:enable_starttls_auto => true,
:address => secrets[:address],
:port => 587,
:domain => secrets[:domain],
:authentication => :login,
:user_name => secrets[:username],
:password => secrets[:password]
}
config.active_storage.service = :production
end
|
# frozen_string_literal: true
MushroomObserver::Application.configure do
# Settings specified here take precedence over those in config/application.rb
# ----------------------------
# MO configuration.
# ----------------------------
config.domain = "mushroomobserver.org"
config.http_domain = "http://mushroomobserver.org"
# List of alternate server domains.
# We redirect from each of these to the real one.
config.bad_domains = ["www.#{config.domain}"]
# Date after which votes become public.
config.vote_cutoff = "20100405"
# Code appended to ids to make "sync_id". Must start with letter.
config.server_code = "us1"
# Time zone of the server.
config.time_zone = "America/New_York"
ENV["TZ"] = "Eastern Time (US & Canada)"
# Enable queued email.
config.queue_email = true
# Testing
config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.image_precedence = {
default: [:mycolab, :local]
# For use when testing live server in parallel with production server.
# :default => [:mycolab, :local, :mo]
}
config.image_fallback_source = :mycolab
config.robots_dot_text_file = "#{config.root}/public/robots.txt"
# ----------------------------
# Rails configuration.
# The production environment is meant for finished, "live" apps.
# ----------------------------
# Code is not reloaded between requests
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.public_file_server.enabled = false
# Compress JavaScripts and CSS
config.assets.compress = true
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = "1.0"
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # For nginx
# If you have no front-end server that supports something like X-Sendfile,
# just comment this out and Rails will serve the files
# Force all access to the app over SSL, use Strict-Transport-Security,
# and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets
# folder are already added.
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery
# to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = [I18n.default_locale]
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new if defined?(::Logger)
# Combine files using the "require" directives at the top of included files
# See http://guides.rubyonrails.org/asset_pipeline.html#turning-debugging-off
config.assets.debug = false
# Rails 5.2 credentials - add the master.key in production
# config.require_master_key = true
end
file = File.expand_path("../consts-site.rb", __dir__)
require(file) if File.exist?(file)
Missed one instance of "http"!
# frozen_string_literal: true
MushroomObserver::Application.configure do
# Settings specified here take precedence over those in config/application.rb
# ----------------------------
# MO configuration.
# ----------------------------
config.domain = "mushroomobserver.org"
config.http_domain = "https://mushroomobserver.org"
# List of alternate server domains.
# We redirect from each of these to the real one.
config.bad_domains = ["www.#{config.domain}"]
# Date after which votes become public.
config.vote_cutoff = "20100405"
# Code appended to ids to make "sync_id". Must start with letter.
config.server_code = "us1"
# Time zone of the server.
config.time_zone = "America/New_York"
ENV["TZ"] = "Eastern Time (US & Canada)"
# Enable queued email.
config.queue_email = true
# Testing
config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.image_precedence = {
default: [:mycolab, :local]
# For use when testing live server in parallel with production server.
# :default => [:mycolab, :local, :mo]
}
config.image_fallback_source = :mycolab
config.robots_dot_text_file = "#{config.root}/public/robots.txt"
# ----------------------------
# Rails configuration.
# The production environment is meant for finished, "live" apps.
# ----------------------------
# Code is not reloaded between requests
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.public_file_server.enabled = false
# Compress JavaScripts and CSS
config.assets.compress = true
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = "1.0"
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # For nginx
# If you have no front-end server that supports something like X-Sendfile,
# just comment this out and Rails will serve the files
# Force all access to the app over SSL, use Strict-Transport-Security,
# and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets
# folder are already added.
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery
# to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = [I18n.default_locale]
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new if defined?(::Logger)
# Combine files using the "require" directives at the top of included files
# See http://guides.rubyonrails.org/asset_pipeline.html#turning-debugging-off
config.assets.debug = false
# Rails 5.2 credentials - add the master.key in production
# config.require_master_key = true
end
file = File.expand_path("../consts-site.rb", __dir__)
require(file) if File.exist?(file)
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
true to assets compiling
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
|
Whitehall::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned off
config.consider_all_requests_local = false
config.action_controller.perform_caching = false
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Enable lograge
config.lograge.enabled = true
# Enable JSON-style logging
config.logstasher.enabled = true
config.logstasher.logger = Logger.new("#{Rails.root}/log/#{Rails.env}.json.log")
config.logstasher.supress_app_log = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use per-process in memory store in production
config.cache_store = :memory_cache, { size: 32.megabytes }
# Enable serving of images, stylesheets, and JavaScripts from an asset server
config.action_controller.asset_host = Whitehall.asset_host
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w(
admin.css
admin-ie8.css
admin-ie7.css
admin-ie6.css
frontend/base.css
frontend/base-ie8.css
frontend/base-ie7.css
frontend/base-ie6.css
frontend/right-to-left.css
frontend/right-to-left-ie8.css
frontend/right-to-left-ie7.css
frontend/right-to-left-ie6.css
frontend/html-publication.css
frontend/html-publication-ie8.css
frontend/html-publication-ie7.css
frontend/html-publication-ie6.css
frontend/print.css
admin.js
tour/tour_pano.js
)
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
config.action_mailer.delivery_method = :ses
config.slimmer.use_cache = true
end
Use the correct cache type identifier
Whitehall::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned off
config.consider_all_requests_local = false
config.action_controller.perform_caching = false
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Enable lograge
config.lograge.enabled = true
# Enable JSON-style logging
config.logstasher.enabled = true
config.logstasher.logger = Logger.new("#{Rails.root}/log/#{Rails.env}.json.log")
config.logstasher.supress_app_log = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use per-process in memory store in production
config.cache_store = :memory_store, { size: 32.megabytes }
# Enable serving of images, stylesheets, and JavaScripts from an asset server
config.action_controller.asset_host = Whitehall.asset_host
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w(
admin.css
admin-ie8.css
admin-ie7.css
admin-ie6.css
frontend/base.css
frontend/base-ie8.css
frontend/base-ie7.css
frontend/base-ie6.css
frontend/right-to-left.css
frontend/right-to-left-ie8.css
frontend/right-to-left-ie7.css
frontend/right-to-left-ie6.css
frontend/html-publication.css
frontend/html-publication-ie8.css
frontend/html-publication-ie7.css
frontend/html-publication-ie6.css
frontend/print.css
admin.js
tour/tour_pano.js
)
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
config.action_mailer.delivery_method = :ses
config.slimmer.use_cache = true
end
|
WebLapine::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Specifies the header that your server uses for sending files
# (comment out if your front-end server doesn't support this)
config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { :host => ENV['ACTION_MAILER_HOST'] }
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end
Add Sendgrid smtp config for heroku
WebLapine::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Specifies the header that your server uses for sending files
# (comment out if your front-end server doesn't support this)
config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { :host => ENV['ACTION_MAILER_HOST'] }
config.action_mailer.smtp_settings = {
:address => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'heroku.com',
:enable_starttls_auto => true
}
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end
|
ISSAD::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
added mailer config for production env
ISSAD::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'mail.metamaps.cc',
port: 587,
user_name: 'team@metamaps.cc',
password: 'RcxX+s:fht49UX',
authentication: 'plain',
enable_starttls_auto: true,
openssl_verify_mode: 'none' }
config.action_mailer.default_url_options = { :host => 'metamaps.cc' }
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
|
Loomio::Application.configure do
config.action_dispatch.tld_length = (ENV['TLD_LENGTH'] || 1).to_i
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.static_cache_control = 'public, max-age=31536000'
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
#config.assets.css_compressor = :sass
config.assets.js_compressor = :uglifier
# Generate digests for assets URLs
config.assets.digest = true
config.eager_load = true
config.action_dispatch.x_sendfile_header = nil
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
config.cache_store = :dalli_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
config.action_mailer.perform_deliveries = true
# Send emails using SMTP service
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => ENV['SMTP_SERVER'],
:port => ENV['SMTP_PORT'],
:authentication => :plain,
:user_name => ENV['SMTP_USERNAME'],
:password => ENV['SMTP_PASSWORD'],
:domain => ENV['SMTP_DOMAIN']
}
config.action_mailer.raise_delivery_errors = true
# Store avatars on Amazon S3
config.paperclip_defaults = {
:storage => :fog,
:fog_credentials => {
:provider => 'AWS',
:aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
},
:fog_directory => ENV['AWS_UPLOADS_BUCKET'],
:fog_public => true,
:fog_host => ENV['FOG_HOST']
}
end
usa usa usa
Loomio::Application.configure do
config.action_dispatch.tld_length = (ENV['TLD_LENGTH'] || 1).to_i
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.static_cache_control = 'public, max-age=31536000'
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
#config.assets.css_compressor = :sass
config.assets.js_compressor = :uglifier
# Generate digests for assets URLs
config.assets.digest = true
config.eager_load = true
config.action_dispatch.x_sendfile_header = nil
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
if ENV['FORCE_SSL']
config.force_ssl = true
else
config.force_ssl = false
end
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
config.cache_store = :dalli_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
config.action_mailer.perform_deliveries = true
# Send emails using SMTP service
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => ENV['SMTP_SERVER'],
:port => ENV['SMTP_PORT'],
:authentication => :plain,
:user_name => ENV['SMTP_USERNAME'],
:password => ENV['SMTP_PASSWORD'],
:domain => ENV['SMTP_DOMAIN']
}
config.action_mailer.raise_delivery_errors = true
# Store avatars on Amazon S3
config.paperclip_defaults = {
:storage => :fog,
:fog_credentials => {
:provider => 'AWS',
:aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
},
:fog_directory => ENV['AWS_UPLOADS_BUCKET'],
:fog_public => true,
:fog_host => ENV['FOG_HOST']
}
end
|
Rails.application.configure do
client = Dalli::Client.new(ENV['MEMCACHED_SERVERS'], value_max_bytes: 10_485_760)
config.action_controller.perform_caching = true
config.active_record.dump_schema_after_migration = false
config.active_support.deprecation = :notify
config.assets.cache_store = :dalli_store
config.assets.compile = true
config.assets.compress = true
config.assets.digest = true
config.assets.js_compressor = :uglifier
config.assets.version = '1.0'
config.cache_classes = true
config.cache_store = :dalli_store
config.consider_all_requests_local = false
config.eager_load = true
config.force_ssl = true
config.i18n.fallbacks = true
config.log_formatter = ::Logger::Formatter.new
config.log_level = :info
config.serve_static_assets = true
config.static_cache_control = 'public, max-age=31536000'
config.action_mailer.default_url_options = { host: 'ugl.st' }
ActionMailer::Base.smtp_settings = {
port: '587',
address: 'smtp.mandrillapp.com',
user_name: ENV['MANDRILL_USERNAME'],
password: ENV['MANDRILL_APIKEY'],
domain: 'heroku.com',
authentication: :plain
}
ActionMailer::Base.delivery_method = :smtp
end
Don't serve static assets from Rails
Rails.application.configure do
client = Dalli::Client.new(ENV['MEMCACHED_SERVERS'], value_max_bytes: 10_485_760)
config.action_controller.perform_caching = true
config.active_record.dump_schema_after_migration = false
config.active_support.deprecation = :notify
config.assets.cache_store = :dalli_store
config.assets.compile = true
config.assets.compress = true
config.assets.digest = true
config.assets.js_compressor = :uglifier
config.assets.version = '1.0'
config.cache_classes = true
config.cache_store = :dalli_store
config.consider_all_requests_local = false
config.eager_load = true
config.force_ssl = true
config.i18n.fallbacks = true
config.log_formatter = ::Logger::Formatter.new
config.log_level = :info
config.serve_static_assets = false
config.static_cache_control = 'public, max-age=31536000'
config.action_mailer.default_url_options = { host: 'ugl.st' }
ActionMailer::Base.smtp_settings = {
port: '587',
address: 'smtp.mandrillapp.com',
user_name: ENV['MANDRILL_USERNAME'],
password: ENV['MANDRILL_APIKEY'],
domain: 'heroku.com',
authentication: :plain
}
ActionMailer::Base.delivery_method = :smtp
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => 'cryptic-beyond-59326.heroku.com' }
ActionMailer::Base.smtp_settings = {
:address => "smtp.sendgrid.net",
:port => 25,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => ENV['SENDGRID_DOMAIN'],
:authentication => :plain
}
config.paperclip_defaults = {
:storage => :s3,
:s3_region => ENV['AWS_REGION'],
:s3_protocol => :https,
:path => ":attachment/:id/:style.:extension",
:bucket => ENV['S3_BUCKET_NAME'],
:s3_host_name => 'https://rorproj.s3-us-west-1.amazonaws.com',
:s3_credentials => {
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'],
}
}
end
implementing aws s3
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => 'cryptic-beyond-59326.heroku.com' }
ActionMailer::Base.smtp_settings = {
:address => "smtp.sendgrid.net",
:port => 25,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => ENV['SENDGRID_DOMAIN'],
:authentication => :plain
}
config.paperclip_defaults = {
:storage => :s3,
:s3_region => ENV['AWS_REGION'],
:s3_protocol => :https,
:path => ":attachment/:id/:style.:extension",
:bucket => ENV['S3_BUCKET_NAME'],
:s3_host_name => 'rorproj.s3-us-west-1.amazonaws.com',
:s3_credentials => {
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'],
}
}
end
|
# encoding: utf-8
Sugar::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Specify the default JavaScript compressor
config.assets.js_compressor = :uglifier
# Generate digests for assets URLs.
config.assets.digest = true
# Specifies the header that your server uses for sending files
# (comment out if your front-end server doesn't support this)
config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w( mobile.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Store all page caches in a subfolder of public
config.action_controller.page_cache_directory = File.join(File.dirname(__FILE__), '../../public/cache')
end
Disable force_ssl for now
# encoding: utf-8
Sugar::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Specify the default JavaScript compressor
config.assets.js_compressor = :uglifier
# Generate digests for assets URLs.
config.assets.digest = true
# Specifies the header that your server uses for sending files
# (comment out if your front-end server doesn't support this)
config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = false
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w( mobile.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Store all page caches in a subfolder of public
config.action_controller.page_cache_directory = File.join(File.dirname(__FILE__), '../../public/cache')
end |
# Settings specified here will take precedence over those in config/environment.rb
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# Enable threaded mode
# config.threadsafe!
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Full error reports are disabled and caching is turned on
config.action_controller.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
added smtp configuration to the production environment. the smtp_password is stored in the database.yml file which is generated at cap deploy:setup
# Settings specified here will take precedence over those in config/environment.rb
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# Enable threaded mode
# config.threadsafe!
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Full error reports are disabled and caching is turned on
config.action_controller.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
smtp_password = YAML.load(File.open(File.join(File.dirname(__FILE__), '../database.yml')))['production']['smtp_password']
ActionMailer::Base.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "jobs@rubyjobs.ie",
:authentication => :plain,
:user_name => "jobs@rubyjobs.ie",
:password => smtp_password
} |
FB_APP_ID = '142620335789256'
FB_API_KEY = '1c90ca2a0e842d27780f5217c56190d0'
FB_SECRET = '2d59e7d4faf3ead8c10c3ce6314564ee'
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_files = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { :host => 'dreamcatcher.net' }
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
Try serving static files...
FB_APP_ID = '142620335789256'
FB_API_KEY = '1c90ca2a0e842d27780f5217c56190d0'
FB_SECRET = '2d59e7d4faf3ead8c10c3ce6314564ee'
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_files = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { :host => 'dreamcatcher.net' }
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
|
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true
config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' }
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
config.cache_store = :memory_store, { size: 10.megabytes }
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
AppConfig = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "email-smtp.us-east-1.amazonaws.com",
:port => 587, # Port 25 is throttled on AWS
:user_name => AppConfig["ses_smtp_credentials"]["username"],
:password => AppConfig["ses_smtp_credentials"]["password"],
:authentication => :login
}
config.action_mailer.default_url_options = { :host => 'metasmoke.erwaysoftware.com' }
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_cable.url = "ws://ws.metasmoke.erwaysoftware.com"
end
Allow origins for ActionCable
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true
config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' }
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
config.cache_store = :memory_store, { size: 10.megabytes }
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
AppConfig = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "email-smtp.us-east-1.amazonaws.com",
:port => 587, # Port 25 is throttled on AWS
:user_name => AppConfig["ses_smtp_credentials"]["username"],
:password => AppConfig["ses_smtp_credentials"]["password"],
:authentication => :login
}
config.action_mailer.default_url_options = { :host => 'metasmoke.erwaysoftware.com' }
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_cable.url = "ws://ws.metasmoke.erwaysoftware.com"
config.action_cable.allowed_request_origins = ['http://metasmoke.erwaysoftware.com', 'https://metasmoke.erwaysoftware.com']
end
|
Iso::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Other caching configuration
config.cache_store = :dalli_store
config.action_controller.perform_caching = true
config.action_dispatch.rack_cache = {
metastore: Dalli::Client.new,
entitystore: 'file:tmp/cache/rack/body',
allow_reload: false
}
config.static_cache_control = "public, max-age=2592000"
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Whether to fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = false
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
config.logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
# config.logger = Logger.new(STDOUT)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
config.assets.precompile += %w( custom.modernizr.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.delivery_method = :postmark
config.action_mailer.postmark_settings = { api_key: ENV['POSTMARK_API_KEY'] }
config.action_mailer.default_url_options = { host: ENV['DOMAIN'], locale: "en" }
config.action_mailer.asset_host = ENV['DOMAIN']
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
if ENV['CDN_HOST'].present?
config.action_controller.asset_host = ENV['CDN_HOST']
config.action_mailer.asset_host = ENV['CDN_HOST']
end
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
Update dalli settings for larger items
Iso::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Other caching configuration
config.cache_store = :dalli_store, {
value_max_bytes: 10.megabytes,
compress: true
}
config.action_controller.perform_caching = true
config.action_dispatch.rack_cache = {
metastore: Dalli::Client.new,
entitystore: 'file:tmp/cache/rack/body',
allow_reload: false
}
config.static_cache_control = "public, max-age=2592000"
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Whether to fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = false
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
config.logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
# config.logger = Logger.new(STDOUT)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
config.assets.precompile += %w( custom.modernizr.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.delivery_method = :postmark
config.action_mailer.postmark_settings = { api_key: ENV['POSTMARK_API_KEY'] }
config.action_mailer.default_url_options = { host: ENV['DOMAIN'], locale: "en" }
config.action_mailer.asset_host = ENV['DOMAIN']
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
if ENV['CDN_HOST'].present?
config.action_controller.asset_host = ENV['CDN_HOST']
config.action_mailer.asset_host = ENV['CDN_HOST']
end
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
|
Loomio::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
config.assets.precompile += %w(active_admin.css active_admin.js frontpage.js frontpage.css)
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
config.action_mailer.perform_deliveries = true
# Send emails using SendGrid
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'loomio.org'
}
config.action_mailer.raise_delivery_errors = true
# Email admin when server gets exceptions!
config.middleware.use ExceptionNotifier,
:email_prefix => "[Loomio Exception] ",
:sender_address => %{"Exception Notifier" <dudley@loomio.org>},
:exception_recipients => [ENV['EXCEPTION_RECIPIENT']]
config.action_mailer.default_url_options = {
:host => 'www.loomio.org',
}
# Store avatars on Amazon S3
config.paperclip_defaults = {
:storage => :s3,
:s3_protocol => 'https',
:s3_credentials => {
:bucket => ENV['AWS_UPLOADS_BUCKET'],
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
}
end
Temporarily enable asset pipeline on production.
Loomio::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
# config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
config.assets.precompile += %w(active_admin.css active_admin.js frontpage.js frontpage.css)
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
config.action_mailer.perform_deliveries = true
# Send emails using SendGrid
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'loomio.org'
}
config.action_mailer.raise_delivery_errors = true
# Email admin when server gets exceptions!
config.middleware.use ExceptionNotifier,
:email_prefix => "[Loomio Exception] ",
:sender_address => %{"Exception Notifier" <dudley@loomio.org>},
:exception_recipients => [ENV['EXCEPTION_RECIPIENT']]
config.action_mailer.default_url_options = {
:host => 'www.loomio.org',
}
# Store avatars on Amazon S3
config.paperclip_defaults = {
:storage => :s3,
:s3_protocol => 'https',
:s3_credentials => {
:bucket => ENV['AWS_UPLOADS_BUCKET'],
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
}
end
|
Lounas::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
Reduce production logging.
Lounas::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
config.log_level = :warn
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
|
Add initialize settings
class Settings < Settingslogic
source "#{Rails.root}/config/settings.yml"
namespace Rails.env
end
|
require 'gitlab' # Load lib/gitlab.rb as soon as possible
class Settings < Settingslogic
source ENV.fetch('GITLAB_CONFIG') { "#{Rails.root}/config/gitlab.yml" }
namespace Rails.env
class << self
def gitlab_on_standard_port?
gitlab.port.to_i == (gitlab.https ? 443 : 80)
end
# get host without www, thanks to http://stackoverflow.com/a/6674363/1233435
def get_host_without_www(url)
url = URI.encode(url)
uri = URI.parse(url)
uri = URI.parse("http://#{url}") if uri.scheme.nil?
host = uri.host.downcase
host.start_with?('www.') ? host[4..-1] : host
end
def build_gitlab_ci_url
if gitlab_on_standard_port?
custom_port = nil
else
custom_port = ":#{gitlab.port}"
end
[ gitlab.protocol,
"://",
gitlab.host,
custom_port,
gitlab.relative_url_root
].join('')
end
def build_gitlab_shell_ssh_path_prefix
if gitlab_shell.ssh_port != 22
"ssh://#{gitlab_shell.ssh_user}@#{gitlab_shell.ssh_host}:#{gitlab_shell.ssh_port}/"
else
if gitlab_shell.ssh_host.include? ':'
"[#{gitlab_shell.ssh_user}@#{gitlab_shell.ssh_host}]:"
else
"#{gitlab_shell.ssh_user}@#{gitlab_shell.ssh_host}:"
end
end
end
def build_base_gitlab_url
base_gitlab_url.join('')
end
def build_gitlab_url
(base_gitlab_url + [gitlab.relative_url_root]).join('')
end
# check that values in `current` (string or integer) is a contant in `modul`.
def verify_constant_array(modul, current, default)
values = default || []
if !current.nil?
values = []
current.each do |constant|
values.push(verify_constant(modul, constant, nil))
end
values.delete_if { |value| value.nil? }
end
values
end
# check that `current` (string or integer) is a contant in `modul`.
def verify_constant(modul, current, default)
constant = modul.constants.find{ |name| modul.const_get(name) == current }
value = constant.nil? ? default : modul.const_get(constant)
if current.is_a? String
value = modul.const_get(current.upcase) rescue default
end
value
end
private
def base_gitlab_url
custom_port = gitlab_on_standard_port? ? nil : ":#{gitlab.port}"
[ gitlab.protocol,
"://",
gitlab.host,
custom_port
]
end
end
end
# Default settings
Settings['ldap'] ||= Settingslogic.new({})
Settings.ldap['enabled'] = false if Settings.ldap['enabled'].nil?
# backwards compatibility, we only have one host
if Settings.ldap['enabled'] || Rails.env.test?
if Settings.ldap['host'].present?
# We detected old LDAP configuration syntax. Update the config to make it
# look like it was entered with the new syntax.
server = Settings.ldap.except('sync_time')
Settings.ldap['servers'] = {
'main' => server
}
end
Settings.ldap['servers'].each do |key, server|
server['label'] ||= 'LDAP'
server['block_auto_created_users'] = false if server['block_auto_created_users'].nil?
server['allow_username_or_email_login'] = false if server['allow_username_or_email_login'].nil?
server['active_directory'] = true if server['active_directory'].nil?
server['attributes'] = {} if server['attributes'].nil?
server['provider_name'] ||= "ldap#{key}".downcase
server['provider_class'] = OmniAuth::Utils.camelize(server['provider_name'])
end
end
Settings['omniauth'] ||= Settingslogic.new({})
Settings.omniauth['enabled'] = false if Settings.omniauth['enabled'].nil?
Settings.omniauth['auto_sign_in_with_provider'] = false if Settings.omniauth['auto_sign_in_with_provider'].nil?
Settings.omniauth['allow_single_sign_on'] = false if Settings.omniauth['allow_single_sign_on'].nil?
Settings.omniauth['block_auto_created_users'] = true if Settings.omniauth['block_auto_created_users'].nil?
Settings.omniauth['auto_link_ldap_user'] = false if Settings.omniauth['auto_link_ldap_user'].nil?
Settings.omniauth['providers'] ||= []
Settings['issues_tracker'] ||= {}
#
# GitLab
#
Settings['gitlab'] ||= Settingslogic.new({})
Settings.gitlab['default_projects_limit'] ||= 10
Settings.gitlab['default_branch_protection'] ||= 2
Settings.gitlab['default_can_create_group'] = true if Settings.gitlab['default_can_create_group'].nil?
Settings.gitlab['default_theme'] = Gitlab::Themes::APPLICATION_DEFAULT if Settings.gitlab['default_theme'].nil?
Settings.gitlab['host'] ||= 'localhost'
Settings.gitlab['ssh_host'] ||= Settings.gitlab.host
Settings.gitlab['https'] = false if Settings.gitlab['https'].nil?
Settings.gitlab['port'] ||= Settings.gitlab.https ? 443 : 80
Settings.gitlab['relative_url_root'] ||= ENV['RAILS_RELATIVE_URL_ROOT'] || ''
Settings.gitlab['protocol'] ||= Settings.gitlab.https ? "https" : "http"
Settings.gitlab['email_enabled'] ||= true if Settings.gitlab['email_enabled'].nil?
Settings.gitlab['email_from'] ||= "gitlab@#{Settings.gitlab.host}"
Settings.gitlab['email_display_name'] ||= "GitLab"
Settings.gitlab['email_reply_to'] ||= "noreply@#{Settings.gitlab.host}"
Settings.gitlab['base_url'] ||= Settings.send(:build_base_gitlab_url)
Settings.gitlab['url'] ||= Settings.send(:build_gitlab_url)
Settings.gitlab['user'] ||= 'git'
Settings.gitlab['user_home'] ||= begin
Etc.getpwnam(Settings.gitlab['user']).dir
rescue ArgumentError # no user configured
'/home/' + Settings.gitlab['user']
end
Settings.gitlab['time_zone'] ||= nil
Settings.gitlab['signup_enabled'] ||= true if Settings.gitlab['signup_enabled'].nil?
Settings.gitlab['signin_enabled'] ||= true if Settings.gitlab['signin_enabled'].nil?
Settings.gitlab['twitter_sharing_enabled'] ||= true if Settings.gitlab['twitter_sharing_enabled'].nil?
Settings.gitlab['restricted_visibility_levels'] = Settings.send(:verify_constant_array, Gitlab::VisibilityLevel, Settings.gitlab['restricted_visibility_levels'], [])
Settings.gitlab['username_changing_enabled'] = true if Settings.gitlab['username_changing_enabled'].nil?
Settings.gitlab['issue_closing_pattern'] = '((?:[Cc]los(?:e[sd]?|ing)|[Ff]ix(?:e[sd]|ing)?|[Rr]esolv(?:e[sd]?|ing)) +(?:(?:issues? +)?#\d+(?:(?:, *| +and +)?))+)' if Settings.gitlab['issue_closing_pattern'].nil?
Settings.gitlab['default_projects_features'] ||= {}
Settings.gitlab['webhook_timeout'] ||= 10
Settings.gitlab['max_attachment_size'] ||= 10
Settings.gitlab['session_expire_delay'] ||= 10080
Settings.gitlab.default_projects_features['issues'] = true if Settings.gitlab.default_projects_features['issues'].nil?
Settings.gitlab.default_projects_features['merge_requests'] = true if Settings.gitlab.default_projects_features['merge_requests'].nil?
Settings.gitlab.default_projects_features['wiki'] = true if Settings.gitlab.default_projects_features['wiki'].nil?
Settings.gitlab.default_projects_features['snippets'] = false if Settings.gitlab.default_projects_features['snippets'].nil?
Settings.gitlab.default_projects_features['visibility_level'] = Settings.send(:verify_constant, Gitlab::VisibilityLevel, Settings.gitlab.default_projects_features['visibility_level'], Gitlab::VisibilityLevel::PRIVATE)
Settings.gitlab['repository_downloads_path'] = File.absolute_path(Settings.gitlab['repository_downloads_path'] || 'tmp/repositories', Rails.root)
Settings.gitlab['restricted_signup_domains'] ||= []
Settings.gitlab['import_sources'] ||= ['github','bitbucket','gitlab','gitorious','google_code','fogbugz','git']
#
# CI
#
Settings['gitlab_ci'] ||= Settingslogic.new({})
Settings.gitlab_ci['all_broken_builds'] = true if Settings.gitlab_ci['all_broken_builds'].nil?
Settings.gitlab_ci['add_pusher'] = false if Settings.gitlab_ci['add_pusher'].nil?
Settings.gitlab_ci['url'] ||= Settings.send(:build_gitlab_ci_url)
Settings.gitlab_ci['builds_path'] = File.expand_path(Settings.gitlab_ci['builds_path'] || "builds/", Rails.root)
#
# Reply by email
#
Settings['incoming_email'] ||= Settingslogic.new({})
Settings.incoming_email['enabled'] = false if Settings.incoming_email['enabled'].nil?
Settings.incoming_email['port'] = 143 if Settings.incoming_email['port'].nil?
Settings.incoming_email['ssl'] = 143 if Settings.incoming_email['ssl'].nil?
Settings.incoming_email['start_tls'] = 143 if Settings.incoming_email['start_tls'].nil?
Settings.incoming_email['mailbox'] = "inbox" if Settings.incoming_email['mailbox'].nil?
#
# Gravatar
#
Settings['gravatar'] ||= Settingslogic.new({})
Settings.gravatar['enabled'] = true if Settings.gravatar['enabled'].nil?
Settings.gravatar['plain_url'] ||= 'http://www.gravatar.com/avatar/%{hash}?s=%{size}&d=identicon'
Settings.gravatar['ssl_url'] ||= 'https://secure.gravatar.com/avatar/%{hash}?s=%{size}&d=identicon'
Settings.gravatar['host'] = Settings.get_host_without_www(Settings.gravatar['plain_url'])
#
# GitLab Shell
#
Settings['gitlab_shell'] ||= Settingslogic.new({})
Settings.gitlab_shell['path'] ||= Settings.gitlab['user_home'] + '/gitlab-shell/'
Settings.gitlab_shell['hooks_path'] ||= Settings.gitlab['user_home'] + '/gitlab-shell/hooks/'
Settings.gitlab_shell['secret_file'] ||= Rails.root.join('.gitlab_shell_secret')
Settings.gitlab_shell['receive_pack'] = true if Settings.gitlab_shell['receive_pack'].nil?
Settings.gitlab_shell['upload_pack'] = true if Settings.gitlab_shell['upload_pack'].nil?
Settings.gitlab_shell['repos_path'] ||= Settings.gitlab['user_home'] + '/repositories/'
Settings.gitlab_shell['ssh_host'] ||= Settings.gitlab.ssh_host
Settings.gitlab_shell['ssh_port'] ||= 22
Settings.gitlab_shell['ssh_user'] ||= Settings.gitlab.user
Settings.gitlab_shell['owner_group'] ||= Settings.gitlab.user
Settings.gitlab_shell['ssh_path_prefix'] ||= Settings.send(:build_gitlab_shell_ssh_path_prefix)
#
# Backup
#
Settings['backup'] ||= Settingslogic.new({})
Settings.backup['keep_time'] ||= 0
Settings.backup['pg_schema'] = nil
Settings.backup['path'] = File.expand_path(Settings.backup['path'] || "tmp/backups/", Rails.root)
Settings.backup['archive_permissions'] ||= 0600
Settings.backup['upload'] ||= Settingslogic.new({ 'remote_directory' => nil, 'connection' => nil })
# Convert upload connection settings to use symbol keys, to make Fog happy
if Settings.backup['upload']['connection']
Settings.backup['upload']['connection'] = Hash[Settings.backup['upload']['connection'].map { |k, v| [k.to_sym, v] }]
end
Settings.backup['upload']['multipart_chunk_size'] ||= 104857600
Settings.backup['upload']['encryption'] ||= nil
#
# Git
#
Settings['git'] ||= Settingslogic.new({})
Settings.git['max_size'] ||= 20971520 # 20.megabytes
Settings.git['bin_path'] ||= '/usr/bin/git'
Settings.git['timeout'] ||= 10
Settings['satellites'] ||= Settingslogic.new({})
Settings.satellites['path'] = File.expand_path(Settings.satellites['path'] || "tmp/repo_satellites/", Rails.root)
Settings.satellites['timeout'] ||= 30
#
# Extra customization
#
Settings['extra'] ||= Settingslogic.new({})
#
# Rack::Attack settings
#
Settings['rack_attack'] ||= Settingslogic.new({})
Settings.rack_attack['git_basic_auth'] ||= Settingslogic.new({})
Settings.rack_attack.git_basic_auth['enabled'] = true if Settings.rack_attack.git_basic_auth['enabled'].nil?
Settings.rack_attack.git_basic_auth['ip_whitelist'] ||= %w{127.0.0.1}
Settings.rack_attack.git_basic_auth['maxretry'] ||= 10
Settings.rack_attack.git_basic_auth['findtime'] ||= 1.minute
Settings.rack_attack.git_basic_auth['bantime'] ||= 1.hour
#
# Testing settings
#
if Rails.env.test?
Settings.gitlab['default_projects_limit'] = 42
Settings.gitlab['default_can_create_group'] = true
Settings.gitlab['default_can_create_team'] = false
end
Shut up, Rubocop
[ci skip]
require 'gitlab' # Load lib/gitlab.rb as soon as possible
class Settings < Settingslogic
source ENV.fetch('GITLAB_CONFIG') { "#{Rails.root}/config/gitlab.yml" }
namespace Rails.env
class << self
def gitlab_on_standard_port?
gitlab.port.to_i == (gitlab.https ? 443 : 80)
end
# get host without www, thanks to http://stackoverflow.com/a/6674363/1233435
def get_host_without_www(url)
url = URI.encode(url)
uri = URI.parse(url)
uri = URI.parse("http://#{url}") if uri.scheme.nil?
host = uri.host.downcase
host.start_with?('www.') ? host[4..-1] : host
end
def build_gitlab_ci_url
if gitlab_on_standard_port?
custom_port = nil
else
custom_port = ":#{gitlab.port}"
end
[ gitlab.protocol,
"://",
gitlab.host,
custom_port,
gitlab.relative_url_root
].join('')
end
def build_gitlab_shell_ssh_path_prefix
if gitlab_shell.ssh_port != 22
"ssh://#{gitlab_shell.ssh_user}@#{gitlab_shell.ssh_host}:#{gitlab_shell.ssh_port}/"
else
if gitlab_shell.ssh_host.include? ':'
"[#{gitlab_shell.ssh_user}@#{gitlab_shell.ssh_host}]:"
else
"#{gitlab_shell.ssh_user}@#{gitlab_shell.ssh_host}:"
end
end
end
def build_base_gitlab_url
base_gitlab_url.join('')
end
def build_gitlab_url
(base_gitlab_url + [gitlab.relative_url_root]).join('')
end
# check that values in `current` (string or integer) is a contant in `modul`.
def verify_constant_array(modul, current, default)
values = default || []
if !current.nil?
values = []
current.each do |constant|
values.push(verify_constant(modul, constant, nil))
end
values.delete_if { |value| value.nil? }
end
values
end
# check that `current` (string or integer) is a contant in `modul`.
def verify_constant(modul, current, default)
constant = modul.constants.find{ |name| modul.const_get(name) == current }
value = constant.nil? ? default : modul.const_get(constant)
if current.is_a? String
value = modul.const_get(current.upcase) rescue default
end
value
end
private
def base_gitlab_url
custom_port = gitlab_on_standard_port? ? nil : ":#{gitlab.port}"
[ gitlab.protocol,
"://",
gitlab.host,
custom_port
]
end
end
end
# Default settings
Settings['ldap'] ||= Settingslogic.new({})
Settings.ldap['enabled'] = false if Settings.ldap['enabled'].nil?
# backwards compatibility, we only have one host
if Settings.ldap['enabled'] || Rails.env.test?
if Settings.ldap['host'].present?
# We detected old LDAP configuration syntax. Update the config to make it
# look like it was entered with the new syntax.
server = Settings.ldap.except('sync_time')
Settings.ldap['servers'] = {
'main' => server
}
end
Settings.ldap['servers'].each do |key, server|
server['label'] ||= 'LDAP'
server['block_auto_created_users'] = false if server['block_auto_created_users'].nil?
server['allow_username_or_email_login'] = false if server['allow_username_or_email_login'].nil?
server['active_directory'] = true if server['active_directory'].nil?
server['attributes'] = {} if server['attributes'].nil?
server['provider_name'] ||= "ldap#{key}".downcase
server['provider_class'] = OmniAuth::Utils.camelize(server['provider_name'])
end
end
Settings['omniauth'] ||= Settingslogic.new({})
Settings.omniauth['enabled'] = false if Settings.omniauth['enabled'].nil?
Settings.omniauth['auto_sign_in_with_provider'] = false if Settings.omniauth['auto_sign_in_with_provider'].nil?
Settings.omniauth['allow_single_sign_on'] = false if Settings.omniauth['allow_single_sign_on'].nil?
Settings.omniauth['block_auto_created_users'] = true if Settings.omniauth['block_auto_created_users'].nil?
Settings.omniauth['auto_link_ldap_user'] = false if Settings.omniauth['auto_link_ldap_user'].nil?
Settings.omniauth['providers'] ||= []
Settings['issues_tracker'] ||= {}
#
# GitLab
#
Settings['gitlab'] ||= Settingslogic.new({})
Settings.gitlab['default_projects_limit'] ||= 10
Settings.gitlab['default_branch_protection'] ||= 2
Settings.gitlab['default_can_create_group'] = true if Settings.gitlab['default_can_create_group'].nil?
Settings.gitlab['default_theme'] = Gitlab::Themes::APPLICATION_DEFAULT if Settings.gitlab['default_theme'].nil?
Settings.gitlab['host'] ||= 'localhost'
Settings.gitlab['ssh_host'] ||= Settings.gitlab.host
Settings.gitlab['https'] = false if Settings.gitlab['https'].nil?
Settings.gitlab['port'] ||= Settings.gitlab.https ? 443 : 80
Settings.gitlab['relative_url_root'] ||= ENV['RAILS_RELATIVE_URL_ROOT'] || ''
Settings.gitlab['protocol'] ||= Settings.gitlab.https ? "https" : "http"
Settings.gitlab['email_enabled'] ||= true if Settings.gitlab['email_enabled'].nil?
Settings.gitlab['email_from'] ||= "gitlab@#{Settings.gitlab.host}"
Settings.gitlab['email_display_name'] ||= "GitLab"
Settings.gitlab['email_reply_to'] ||= "noreply@#{Settings.gitlab.host}"
Settings.gitlab['base_url'] ||= Settings.send(:build_base_gitlab_url)
Settings.gitlab['url'] ||= Settings.send(:build_gitlab_url)
Settings.gitlab['user'] ||= 'git'
Settings.gitlab['user_home'] ||= begin
Etc.getpwnam(Settings.gitlab['user']).dir
rescue ArgumentError # no user configured
'/home/' + Settings.gitlab['user']
end
Settings.gitlab['time_zone'] ||= nil
Settings.gitlab['signup_enabled'] ||= true if Settings.gitlab['signup_enabled'].nil?
Settings.gitlab['signin_enabled'] ||= true if Settings.gitlab['signin_enabled'].nil?
Settings.gitlab['twitter_sharing_enabled'] ||= true if Settings.gitlab['twitter_sharing_enabled'].nil?
Settings.gitlab['restricted_visibility_levels'] = Settings.send(:verify_constant_array, Gitlab::VisibilityLevel, Settings.gitlab['restricted_visibility_levels'], [])
Settings.gitlab['username_changing_enabled'] = true if Settings.gitlab['username_changing_enabled'].nil?
Settings.gitlab['issue_closing_pattern'] = '((?:[Cc]los(?:e[sd]?|ing)|[Ff]ix(?:e[sd]|ing)?|[Rr]esolv(?:e[sd]?|ing)) +(?:(?:issues? +)?#\d+(?:(?:, *| +and +)?))+)' if Settings.gitlab['issue_closing_pattern'].nil?
Settings.gitlab['default_projects_features'] ||= {}
Settings.gitlab['webhook_timeout'] ||= 10
Settings.gitlab['max_attachment_size'] ||= 10
Settings.gitlab['session_expire_delay'] ||= 10080
Settings.gitlab.default_projects_features['issues'] = true if Settings.gitlab.default_projects_features['issues'].nil?
Settings.gitlab.default_projects_features['merge_requests'] = true if Settings.gitlab.default_projects_features['merge_requests'].nil?
Settings.gitlab.default_projects_features['wiki'] = true if Settings.gitlab.default_projects_features['wiki'].nil?
Settings.gitlab.default_projects_features['snippets'] = false if Settings.gitlab.default_projects_features['snippets'].nil?
Settings.gitlab.default_projects_features['visibility_level'] = Settings.send(:verify_constant, Gitlab::VisibilityLevel, Settings.gitlab.default_projects_features['visibility_level'], Gitlab::VisibilityLevel::PRIVATE)
Settings.gitlab['repository_downloads_path'] = File.absolute_path(Settings.gitlab['repository_downloads_path'] || 'tmp/repositories', Rails.root)
Settings.gitlab['restricted_signup_domains'] ||= []
Settings.gitlab['import_sources'] ||= ['github','bitbucket','gitlab','gitorious','google_code','fogbugz','git']
#
# CI
#
Settings['gitlab_ci'] ||= Settingslogic.new({})
Settings.gitlab_ci['all_broken_builds'] = true if Settings.gitlab_ci['all_broken_builds'].nil?
Settings.gitlab_ci['add_pusher'] = false if Settings.gitlab_ci['add_pusher'].nil?
Settings.gitlab_ci['url'] ||= Settings.send(:build_gitlab_ci_url)
Settings.gitlab_ci['builds_path'] = File.expand_path(Settings.gitlab_ci['builds_path'] || "builds/", Rails.root)
#
# Reply by email
#
Settings['incoming_email'] ||= Settingslogic.new({})
Settings.incoming_email['enabled'] = false if Settings.incoming_email['enabled'].nil?
Settings.incoming_email['port'] = 143 if Settings.incoming_email['port'].nil?
Settings.incoming_email['ssl'] = 143 if Settings.incoming_email['ssl'].nil?
Settings.incoming_email['start_tls'] = 143 if Settings.incoming_email['start_tls'].nil?
Settings.incoming_email['mailbox'] = "inbox" if Settings.incoming_email['mailbox'].nil?
#
# Gravatar
#
Settings['gravatar'] ||= Settingslogic.new({})
Settings.gravatar['enabled'] = true if Settings.gravatar['enabled'].nil?
Settings.gravatar['plain_url'] ||= 'http://www.gravatar.com/avatar/%{hash}?s=%{size}&d=identicon'
Settings.gravatar['ssl_url'] ||= 'https://secure.gravatar.com/avatar/%{hash}?s=%{size}&d=identicon'
Settings.gravatar['host'] = Settings.get_host_without_www(Settings.gravatar['plain_url'])
#
# GitLab Shell
#
Settings['gitlab_shell'] ||= Settingslogic.new({})
Settings.gitlab_shell['path'] ||= Settings.gitlab['user_home'] + '/gitlab-shell/'
Settings.gitlab_shell['hooks_path'] ||= Settings.gitlab['user_home'] + '/gitlab-shell/hooks/'
Settings.gitlab_shell['secret_file'] ||= Rails.root.join('.gitlab_shell_secret')
Settings.gitlab_shell['receive_pack'] = true if Settings.gitlab_shell['receive_pack'].nil?
Settings.gitlab_shell['upload_pack'] = true if Settings.gitlab_shell['upload_pack'].nil?
Settings.gitlab_shell['repos_path'] ||= Settings.gitlab['user_home'] + '/repositories/'
Settings.gitlab_shell['ssh_host'] ||= Settings.gitlab.ssh_host
Settings.gitlab_shell['ssh_port'] ||= 22
Settings.gitlab_shell['ssh_user'] ||= Settings.gitlab.user
Settings.gitlab_shell['owner_group'] ||= Settings.gitlab.user
Settings.gitlab_shell['ssh_path_prefix'] ||= Settings.send(:build_gitlab_shell_ssh_path_prefix)
#
# Backup
#
Settings['backup'] ||= Settingslogic.new({})
Settings.backup['keep_time'] ||= 0
Settings.backup['pg_schema'] = nil
Settings.backup['path'] = File.expand_path(Settings.backup['path'] || "tmp/backups/", Rails.root)
Settings.backup['archive_permissions'] ||= 0600
Settings.backup['upload'] ||= Settingslogic.new({ 'remote_directory' => nil, 'connection' => nil })
# Convert upload connection settings to use symbol keys, to make Fog happy
if Settings.backup['upload']['connection']
Settings.backup['upload']['connection'] = Hash[Settings.backup['upload']['connection'].map { |k, v| [k.to_sym, v] }]
end
Settings.backup['upload']['multipart_chunk_size'] ||= 104857600
Settings.backup['upload']['encryption'] ||= nil
#
# Git
#
Settings['git'] ||= Settingslogic.new({})
Settings.git['max_size'] ||= 20971520 # 20.megabytes
Settings.git['bin_path'] ||= '/usr/bin/git'
Settings.git['timeout'] ||= 10
Settings['satellites'] ||= Settingslogic.new({})
Settings.satellites['path'] = File.expand_path(Settings.satellites['path'] || "tmp/repo_satellites/", Rails.root)
Settings.satellites['timeout'] ||= 30
#
# Extra customization
#
Settings['extra'] ||= Settingslogic.new({})
#
# Rack::Attack settings
#
Settings['rack_attack'] ||= Settingslogic.new({})
Settings.rack_attack['git_basic_auth'] ||= Settingslogic.new({})
Settings.rack_attack.git_basic_auth['enabled'] = true if Settings.rack_attack.git_basic_auth['enabled'].nil?
Settings.rack_attack.git_basic_auth['ip_whitelist'] ||= %w{127.0.0.1}
Settings.rack_attack.git_basic_auth['maxretry'] ||= 10
Settings.rack_attack.git_basic_auth['findtime'] ||= 1.minute
Settings.rack_attack.git_basic_auth['bantime'] ||= 1.hour
#
# Testing settings
#
if Rails.env.test?
Settings.gitlab['default_projects_limit'] = 42
Settings.gitlab['default_can_create_group'] = true
Settings.gitlab['default_can_create_team'] = false
end
|
require_dependency Rails.root.join('lib/gitlab') # Load Gitlab as soon as possible
class Settings < Settingslogic
source ENV.fetch('GITLAB_CONFIG') { "#{Rails.root}/config/gitlab.yml" }
namespace Rails.env
class << self
def gitlab_on_standard_port?
gitlab.port.to_i == (gitlab.https ? 443 : 80)
end
def host_without_www(url)
host(url).sub('www.', '')
end
def build_gitlab_ci_url
if gitlab_on_standard_port?
custom_port = nil
else
custom_port = ":#{gitlab.port}"
end
[ gitlab.protocol,
"://",
gitlab.host,
custom_port,
gitlab.relative_url_root
].join('')
end
def build_gitlab_shell_ssh_path_prefix
user_host = "#{gitlab_shell.ssh_user}@#{gitlab_shell.ssh_host}"
if gitlab_shell.ssh_port != 22
"ssh://#{user_host}:#{gitlab_shell.ssh_port}/"
else
if gitlab_shell.ssh_host.include? ':'
"[#{user_host}]:"
else
"#{user_host}:"
end
end
end
def build_base_gitlab_url
base_gitlab_url.join('')
end
def build_gitlab_url
(base_gitlab_url + [gitlab.relative_url_root]).join('')
end
# check that values in `current` (string or integer) is a contant in `modul`.
def verify_constant_array(modul, current, default)
values = default || []
unless current.nil?
values = []
current.each do |constant|
values.push(verify_constant(modul, constant, nil))
end
values.delete_if { |value| value.nil? }
end
values
end
# check that `current` (string or integer) is a contant in `modul`.
def verify_constant(modul, current, default)
constant = modul.constants.find{ |name| modul.const_get(name) == current }
value = constant.nil? ? default : modul.const_get(constant)
if current.is_a? String
value = modul.const_get(current.upcase) rescue default
end
value
end
private
def base_gitlab_url
custom_port = gitlab_on_standard_port? ? nil : ":#{gitlab.port}"
[ gitlab.protocol,
"://",
gitlab.host,
custom_port
]
end
# Extract the host part of the given +url+.
def host(url)
url = url.downcase
url = "http://#{url}" unless url.start_with?('http')
# Get rid of the path so that we don't even have to encode it
url_without_path = url.sub(%r{(https?://[^\/]+)/?.*}, '\1')
URI.parse(url_without_path).host
end
end
end
# Default settings
Settings['ldap'] ||= Settingslogic.new({})
Settings.ldap['enabled'] = false if Settings.ldap['enabled'].nil?
# backwards compatibility, we only have one host
if Settings.ldap['enabled'] || Rails.env.test?
if Settings.ldap['host'].present?
# We detected old LDAP configuration syntax. Update the config to make it
# look like it was entered with the new syntax.
server = Settings.ldap.except('sync_time')
Settings.ldap['servers'] = {
'main' => server
}
end
Settings.ldap['servers'].each do |key, server|
server['label'] ||= 'LDAP'
server['timeout'] ||= 10.seconds
server['block_auto_created_users'] = false if server['block_auto_created_users'].nil?
server['allow_username_or_email_login'] = false if server['allow_username_or_email_login'].nil?
server['active_directory'] = true if server['active_directory'].nil?
server['attributes'] = {} if server['attributes'].nil?
server['provider_name'] ||= "ldap#{key}".downcase
server['provider_class'] = OmniAuth::Utils.camelize(server['provider_name'])
end
end
Settings['omniauth'] ||= Settingslogic.new({})
Settings.omniauth['enabled'] = false if Settings.omniauth['enabled'].nil?
Settings.omniauth['auto_sign_in_with_provider'] = false if Settings.omniauth['auto_sign_in_with_provider'].nil?
Settings.omniauth['allow_single_sign_on'] = false if Settings.omniauth['allow_single_sign_on'].nil?
Settings.omniauth['external_providers'] = [] if Settings.omniauth['external_providers'].nil?
Settings.omniauth['block_auto_created_users'] = true if Settings.omniauth['block_auto_created_users'].nil?
Settings.omniauth['auto_link_ldap_user'] = false if Settings.omniauth['auto_link_ldap_user'].nil?
Settings.omniauth['auto_link_saml_user'] = false if Settings.omniauth['auto_link_saml_user'].nil?
Settings.omniauth['providers'] ||= []
Settings.omniauth['cas3'] ||= Settingslogic.new({})
Settings.omniauth.cas3['session_duration'] ||= 8.hours
Settings.omniauth['session_tickets'] ||= Settingslogic.new({})
Settings.omniauth.session_tickets['cas3'] = 'ticket'
# Fill out omniauth-gitlab settings. It is needed for easy set up GHE or GH by just specifying url.
github_default_url = "https://github.com"
github_settings = Settings.omniauth['providers'].find { |provider| provider["name"] == "github" }
if github_settings
# For compatibility with old config files (before 7.8)
# where people dont have url in github settings
if github_settings['url'].blank?
github_settings['url'] = github_default_url
end
github_settings["args"] ||= Settingslogic.new({})
if github_settings["url"].include?(github_default_url)
github_settings["args"]["client_options"] = OmniAuth::Strategies::GitHub.default_options[:client_options]
else
github_settings["args"]["client_options"] = {
"site" => File.join(github_settings["url"], "api/v3"),
"authorize_url" => File.join(github_settings["url"], "login/oauth/authorize"),
"token_url" => File.join(github_settings["url"], "login/oauth/access_token")
}
end
end
Settings['shared'] ||= Settingslogic.new({})
Settings.shared['path'] = File.expand_path(Settings.shared['path'] || "shared", Rails.root)
Settings['issues_tracker'] ||= {}
#
# GitLab
#
Settings['gitlab'] ||= Settingslogic.new({})
Settings.gitlab['default_projects_limit'] ||= 10
Settings.gitlab['default_branch_protection'] ||= 2
Settings.gitlab['default_can_create_group'] = true if Settings.gitlab['default_can_create_group'].nil?
Settings.gitlab['default_theme'] = Gitlab::Themes::APPLICATION_DEFAULT if Settings.gitlab['default_theme'].nil?
Settings.gitlab['host'] ||= ENV['GITLAB_HOST'] || 'localhost'
Settings.gitlab['ssh_host'] ||= Settings.gitlab.host
Settings.gitlab['https'] = false if Settings.gitlab['https'].nil?
Settings.gitlab['port'] ||= Settings.gitlab.https ? 443 : 80
Settings.gitlab['relative_url_root'] ||= ENV['RAILS_RELATIVE_URL_ROOT'] || ''
Settings.gitlab['protocol'] ||= Settings.gitlab.https ? "https" : "http"
Settings.gitlab['email_enabled'] ||= true if Settings.gitlab['email_enabled'].nil?
Settings.gitlab['email_from'] ||= ENV['GITLAB_EMAIL_FROM'] || "gitlab@#{Settings.gitlab.host}"
Settings.gitlab['email_display_name'] ||= ENV['GITLAB_EMAIL_DISPLAY_NAME'] || 'GitLab'
Settings.gitlab['email_reply_to'] ||= ENV['GITLAB_EMAIL_REPLY_TO'] || "noreply@#{Settings.gitlab.host}"
Settings.gitlab['base_url'] ||= Settings.send(:build_base_gitlab_url)
Settings.gitlab['url'] ||= Settings.send(:build_gitlab_url)
Settings.gitlab['user'] ||= 'git'
Settings.gitlab['user_home'] ||= begin
Etc.getpwnam(Settings.gitlab['user']).dir
rescue ArgumentError # no user configured
'/home/' + Settings.gitlab['user']
end
Settings.gitlab['time_zone'] ||= nil
Settings.gitlab['signup_enabled'] ||= true if Settings.gitlab['signup_enabled'].nil?
Settings.gitlab['signin_enabled'] ||= true if Settings.gitlab['signin_enabled'].nil?
Settings.gitlab['restricted_visibility_levels'] = Settings.send(:verify_constant_array, Gitlab::VisibilityLevel, Settings.gitlab['restricted_visibility_levels'], [])
Settings.gitlab['username_changing_enabled'] = true if Settings.gitlab['username_changing_enabled'].nil?
Settings.gitlab['issue_closing_pattern'] = '((?:[Cc]los(?:e[sd]?|ing)|[Ff]ix(?:e[sd]|ing)?|[Rr]esolv(?:e[sd]?|ing))(:?) +(?:(?:issues? +)?%{issue_ref}(?:(?:, *| +and +)?)|([A-Z][A-Z0-9_]+-\d+))+)' if Settings.gitlab['issue_closing_pattern'].nil?
Settings.gitlab['default_projects_features'] ||= {}
Settings.gitlab['webhook_timeout'] ||= 10
Settings.gitlab['max_attachment_size'] ||= 10
Settings.gitlab['session_expire_delay'] ||= 10080
Settings.gitlab.default_projects_features['issues'] = true if Settings.gitlab.default_projects_features['issues'].nil?
Settings.gitlab.default_projects_features['merge_requests'] = true if Settings.gitlab.default_projects_features['merge_requests'].nil?
Settings.gitlab.default_projects_features['wiki'] = true if Settings.gitlab.default_projects_features['wiki'].nil?
Settings.gitlab.default_projects_features['snippets'] = false if Settings.gitlab.default_projects_features['snippets'].nil?
Settings.gitlab.default_projects_features['builds'] = true if Settings.gitlab.default_projects_features['builds'].nil?
Settings.gitlab.default_projects_features['container_registry'] = true if Settings.gitlab.default_projects_features['container_registry'].nil?
Settings.gitlab.default_projects_features['visibility_level'] = Settings.send(:verify_constant, Gitlab::VisibilityLevel, Settings.gitlab.default_projects_features['visibility_level'], Gitlab::VisibilityLevel::PRIVATE)
Settings.gitlab['repository_downloads_path'] = File.join(Settings.shared['path'], 'cache/archive') if Settings.gitlab['repository_downloads_path'].nil?
Settings.gitlab['domain_whitelist'] ||= []
Settings.gitlab['import_sources'] ||= %w[github bitbucket gitlab gitorious google_code fogbugz git gitlab_project]
Settings.gitlab['trusted_proxies'] ||= []
#
# CI
#
Settings['gitlab_ci'] ||= Settingslogic.new({})
Settings.gitlab_ci['shared_runners_enabled'] = true if Settings.gitlab_ci['shared_runners_enabled'].nil?
Settings.gitlab_ci['all_broken_builds'] = true if Settings.gitlab_ci['all_broken_builds'].nil?
Settings.gitlab_ci['add_pusher'] = false if Settings.gitlab_ci['add_pusher'].nil?
Settings.gitlab_ci['builds_path'] = File.expand_path(Settings.gitlab_ci['builds_path'] || "builds/", Rails.root)
Settings.gitlab_ci['url'] ||= Settings.send(:build_gitlab_ci_url)
#
# Reply by email
#
Settings['incoming_email'] ||= Settingslogic.new({})
Settings.incoming_email['enabled'] = false if Settings.incoming_email['enabled'].nil?
#
# Build Artifacts
#
Settings['artifacts'] ||= Settingslogic.new({})
Settings.artifacts['enabled'] = true if Settings.artifacts['enabled'].nil?
Settings.artifacts['path'] = File.expand_path(Settings.artifacts['path'] || File.join(Settings.shared['path'], "artifacts"), Rails.root)
Settings.artifacts['max_size'] ||= 100 # in megabytes
#
# Registry
#
Settings['registry'] ||= Settingslogic.new({})
Settings.registry['enabled'] ||= false
Settings.registry['host'] ||= "example.com"
Settings.registry['port'] ||= nil
Settings.registry['api_url'] ||= "http://localhost:5000/"
Settings.registry['key'] ||= nil
Settings.registry['issuer'] ||= nil
Settings.registry['host_port'] ||= [Settings.registry['host'], Settings.registry['port']].compact.join(':')
Settings.registry['path'] = File.expand_path(Settings.registry['path'] || File.join(Settings.shared['path'], 'registry'), Rails.root)
#
# Git LFS
#
Settings['lfs'] ||= Settingslogic.new({})
Settings.lfs['enabled'] = true if Settings.lfs['enabled'].nil?
Settings.lfs['storage_path'] = File.expand_path(Settings.lfs['storage_path'] || File.join(Settings.shared['path'], "lfs-objects"), Rails.root)
#
# Gravatar
#
Settings['gravatar'] ||= Settingslogic.new({})
Settings.gravatar['enabled'] = true if Settings.gravatar['enabled'].nil?
Settings.gravatar['plain_url'] ||= 'http://www.gravatar.com/avatar/%{hash}?s=%{size}&d=identicon'
Settings.gravatar['ssl_url'] ||= 'https://secure.gravatar.com/avatar/%{hash}?s=%{size}&d=identicon'
Settings.gravatar['host'] = Settings.host_without_www(Settings.gravatar['plain_url'])
#
# Cron Jobs
#
Settings['cron_jobs'] ||= Settingslogic.new({})
Settings.cron_jobs['stuck_ci_builds_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['stuck_ci_builds_worker']['cron'] ||= '0 0 * * *'
Settings.cron_jobs['stuck_ci_builds_worker']['job_class'] = 'StuckCiBuildsWorker'
Settings.cron_jobs['expire_build_artifacts_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['expire_build_artifacts_worker']['cron'] ||= '50 * * * *'
Settings.cron_jobs['expire_build_artifacts_worker']['job_class'] = 'ExpireBuildArtifactsWorker'
Settings.cron_jobs['repository_check_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['repository_check_worker']['cron'] ||= '20 * * * *'
Settings.cron_jobs['repository_check_worker']['job_class'] = 'RepositoryCheck::BatchWorker'
Settings.cron_jobs['admin_email_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['admin_email_worker']['cron'] ||= '0 0 * * 0'
Settings.cron_jobs['admin_email_worker']['job_class'] = 'AdminEmailWorker'
Settings.cron_jobs['repository_archive_cache_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['repository_archive_cache_worker']['cron'] ||= '0 * * * *'
Settings.cron_jobs['repository_archive_cache_worker']['job_class'] = 'RepositoryArchiveCacheWorker'
Settings.cron_jobs['gitlab_remove_project_export_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['gitlab_remove_project_export_worker']['cron'] ||= '0 * * * *'
Settings.cron_jobs['gitlab_remove_project_export_worker']['job_class'] = 'GitlabRemoveProjectExportWorker'
#
# GitLab Shell
#
Settings['gitlab_shell'] ||= Settingslogic.new({})
Settings.gitlab_shell['path'] ||= Settings.gitlab['user_home'] + '/gitlab-shell/'
Settings.gitlab_shell['hooks_path'] ||= Settings.gitlab['user_home'] + '/gitlab-shell/hooks/'
Settings.gitlab_shell['secret_file'] ||= Rails.root.join('.gitlab_shell_secret')
Settings.gitlab_shell['receive_pack'] = true if Settings.gitlab_shell['receive_pack'].nil?
Settings.gitlab_shell['upload_pack'] = true if Settings.gitlab_shell['upload_pack'].nil?
Settings.gitlab_shell['ssh_host'] ||= Settings.gitlab.ssh_host
Settings.gitlab_shell['ssh_port'] ||= 22
Settings.gitlab_shell['ssh_user'] ||= Settings.gitlab.user
Settings.gitlab_shell['owner_group'] ||= Settings.gitlab.user
Settings.gitlab_shell['ssh_path_prefix'] ||= Settings.send(:build_gitlab_shell_ssh_path_prefix)
#
# Repositories
#
Settings['repositories'] ||= Settingslogic.new({})
Settings.repositories['storages'] ||= {}
# Setting gitlab_shell.repos_path is DEPRECATED and WILL BE REMOVED in version 9.0
Settings.repositories.storages['default'] ||= Settings.gitlab_shell['repos_path'] || Settings.gitlab['user_home'] + '/repositories/'
#
# Backup
#
Settings['backup'] ||= Settingslogic.new({})
Settings.backup['keep_time'] ||= 0
Settings.backup['pg_schema'] = nil
Settings.backup['path'] = File.expand_path(Settings.backup['path'] || "tmp/backups/", Rails.root)
Settings.backup['archive_permissions'] ||= 0600
Settings.backup['upload'] ||= Settingslogic.new({ 'remote_directory' => nil, 'connection' => nil })
# Convert upload connection settings to use symbol keys, to make Fog happy
if Settings.backup['upload']['connection']
Settings.backup['upload']['connection'] = Hash[Settings.backup['upload']['connection'].map { |k, v| [k.to_sym, v] }]
end
Settings.backup['upload']['multipart_chunk_size'] ||= 104857600
Settings.backup['upload']['encryption'] ||= nil
#
# Git
#
Settings['git'] ||= Settingslogic.new({})
Settings.git['max_size'] ||= 20971520 # 20.megabytes
Settings.git['bin_path'] ||= '/usr/bin/git'
Settings.git['timeout'] ||= 10
# Important: keep the satellites.path setting until GitLab 9.0 at
# least. This setting is fed to 'rm -rf' in
# db/migrate/20151023144219_remove_satellites.rb
Settings['satellites'] ||= Settingslogic.new({})
Settings.satellites['path'] = File.expand_path(Settings.satellites['path'] || "tmp/repo_satellites/", Rails.root)
#
# Extra customization
#
Settings['extra'] ||= Settingslogic.new({})
#
# Rack::Attack settings
#
Settings['rack_attack'] ||= Settingslogic.new({})
Settings.rack_attack['git_basic_auth'] ||= Settingslogic.new({})
Settings.rack_attack.git_basic_auth['enabled'] = true if Settings.rack_attack.git_basic_auth['enabled'].nil?
Settings.rack_attack.git_basic_auth['ip_whitelist'] ||= %w{127.0.0.1}
Settings.rack_attack.git_basic_auth['maxretry'] ||= 10
Settings.rack_attack.git_basic_auth['findtime'] ||= 1.minute
Settings.rack_attack.git_basic_auth['bantime'] ||= 1.hour
#
# Testing settings
#
if Rails.env.test?
Settings.gitlab['default_projects_limit'] = 42
Settings.gitlab['default_can_create_group'] = true
Settings.gitlab['default_can_create_team'] = false
end
# Force a refresh of application settings at startup
begin
ApplicationSetting.expire
Ci::ApplicationSetting.expire
rescue
# Gracefully handle when Redis is not available. For example,
# omnibus may fail here during assets:precompile.
end
Avoid data-integrity issue when repository_downloads_path is incorrectly
require_dependency Rails.root.join('lib/gitlab') # Load Gitlab as soon as possible
class Settings < Settingslogic
source ENV.fetch('GITLAB_CONFIG') { "#{Rails.root}/config/gitlab.yml" }
namespace Rails.env
class << self
def gitlab_on_standard_port?
gitlab.port.to_i == (gitlab.https ? 443 : 80)
end
def host_without_www(url)
host(url).sub('www.', '')
end
def build_gitlab_ci_url
if gitlab_on_standard_port?
custom_port = nil
else
custom_port = ":#{gitlab.port}"
end
[ gitlab.protocol,
"://",
gitlab.host,
custom_port,
gitlab.relative_url_root
].join('')
end
def build_gitlab_shell_ssh_path_prefix
user_host = "#{gitlab_shell.ssh_user}@#{gitlab_shell.ssh_host}"
if gitlab_shell.ssh_port != 22
"ssh://#{user_host}:#{gitlab_shell.ssh_port}/"
else
if gitlab_shell.ssh_host.include? ':'
"[#{user_host}]:"
else
"#{user_host}:"
end
end
end
def build_base_gitlab_url
base_gitlab_url.join('')
end
def build_gitlab_url
(base_gitlab_url + [gitlab.relative_url_root]).join('')
end
# check that values in `current` (string or integer) is a contant in `modul`.
def verify_constant_array(modul, current, default)
values = default || []
unless current.nil?
values = []
current.each do |constant|
values.push(verify_constant(modul, constant, nil))
end
values.delete_if { |value| value.nil? }
end
values
end
# check that `current` (string or integer) is a contant in `modul`.
def verify_constant(modul, current, default)
constant = modul.constants.find{ |name| modul.const_get(name) == current }
value = constant.nil? ? default : modul.const_get(constant)
if current.is_a? String
value = modul.const_get(current.upcase) rescue default
end
value
end
private
def base_gitlab_url
custom_port = gitlab_on_standard_port? ? nil : ":#{gitlab.port}"
[ gitlab.protocol,
"://",
gitlab.host,
custom_port
]
end
# Extract the host part of the given +url+.
def host(url)
url = url.downcase
url = "http://#{url}" unless url.start_with?('http')
# Get rid of the path so that we don't even have to encode it
url_without_path = url.sub(%r{(https?://[^\/]+)/?.*}, '\1')
URI.parse(url_without_path).host
end
end
end
# Default settings
Settings['ldap'] ||= Settingslogic.new({})
Settings.ldap['enabled'] = false if Settings.ldap['enabled'].nil?
# backwards compatibility, we only have one host
if Settings.ldap['enabled'] || Rails.env.test?
if Settings.ldap['host'].present?
# We detected old LDAP configuration syntax. Update the config to make it
# look like it was entered with the new syntax.
server = Settings.ldap.except('sync_time')
Settings.ldap['servers'] = {
'main' => server
}
end
Settings.ldap['servers'].each do |key, server|
server['label'] ||= 'LDAP'
server['timeout'] ||= 10.seconds
server['block_auto_created_users'] = false if server['block_auto_created_users'].nil?
server['allow_username_or_email_login'] = false if server['allow_username_or_email_login'].nil?
server['active_directory'] = true if server['active_directory'].nil?
server['attributes'] = {} if server['attributes'].nil?
server['provider_name'] ||= "ldap#{key}".downcase
server['provider_class'] = OmniAuth::Utils.camelize(server['provider_name'])
end
end
Settings['omniauth'] ||= Settingslogic.new({})
Settings.omniauth['enabled'] = false if Settings.omniauth['enabled'].nil?
Settings.omniauth['auto_sign_in_with_provider'] = false if Settings.omniauth['auto_sign_in_with_provider'].nil?
Settings.omniauth['allow_single_sign_on'] = false if Settings.omniauth['allow_single_sign_on'].nil?
Settings.omniauth['external_providers'] = [] if Settings.omniauth['external_providers'].nil?
Settings.omniauth['block_auto_created_users'] = true if Settings.omniauth['block_auto_created_users'].nil?
Settings.omniauth['auto_link_ldap_user'] = false if Settings.omniauth['auto_link_ldap_user'].nil?
Settings.omniauth['auto_link_saml_user'] = false if Settings.omniauth['auto_link_saml_user'].nil?
Settings.omniauth['providers'] ||= []
Settings.omniauth['cas3'] ||= Settingslogic.new({})
Settings.omniauth.cas3['session_duration'] ||= 8.hours
Settings.omniauth['session_tickets'] ||= Settingslogic.new({})
Settings.omniauth.session_tickets['cas3'] = 'ticket'
# Fill out omniauth-gitlab settings. It is needed for easy set up GHE or GH by just specifying url.
github_default_url = "https://github.com"
github_settings = Settings.omniauth['providers'].find { |provider| provider["name"] == "github" }
if github_settings
# For compatibility with old config files (before 7.8)
# where people dont have url in github settings
if github_settings['url'].blank?
github_settings['url'] = github_default_url
end
github_settings["args"] ||= Settingslogic.new({})
if github_settings["url"].include?(github_default_url)
github_settings["args"]["client_options"] = OmniAuth::Strategies::GitHub.default_options[:client_options]
else
github_settings["args"]["client_options"] = {
"site" => File.join(github_settings["url"], "api/v3"),
"authorize_url" => File.join(github_settings["url"], "login/oauth/authorize"),
"token_url" => File.join(github_settings["url"], "login/oauth/access_token")
}
end
end
Settings['shared'] ||= Settingslogic.new({})
Settings.shared['path'] = File.expand_path(Settings.shared['path'] || "shared", Rails.root)
Settings['issues_tracker'] ||= {}
#
# GitLab
#
Settings['gitlab'] ||= Settingslogic.new({})
Settings.gitlab['default_projects_limit'] ||= 10
Settings.gitlab['default_branch_protection'] ||= 2
Settings.gitlab['default_can_create_group'] = true if Settings.gitlab['default_can_create_group'].nil?
Settings.gitlab['default_theme'] = Gitlab::Themes::APPLICATION_DEFAULT if Settings.gitlab['default_theme'].nil?
Settings.gitlab['host'] ||= ENV['GITLAB_HOST'] || 'localhost'
Settings.gitlab['ssh_host'] ||= Settings.gitlab.host
Settings.gitlab['https'] = false if Settings.gitlab['https'].nil?
Settings.gitlab['port'] ||= Settings.gitlab.https ? 443 : 80
Settings.gitlab['relative_url_root'] ||= ENV['RAILS_RELATIVE_URL_ROOT'] || ''
Settings.gitlab['protocol'] ||= Settings.gitlab.https ? "https" : "http"
Settings.gitlab['email_enabled'] ||= true if Settings.gitlab['email_enabled'].nil?
Settings.gitlab['email_from'] ||= ENV['GITLAB_EMAIL_FROM'] || "gitlab@#{Settings.gitlab.host}"
Settings.gitlab['email_display_name'] ||= ENV['GITLAB_EMAIL_DISPLAY_NAME'] || 'GitLab'
Settings.gitlab['email_reply_to'] ||= ENV['GITLAB_EMAIL_REPLY_TO'] || "noreply@#{Settings.gitlab.host}"
Settings.gitlab['base_url'] ||= Settings.send(:build_base_gitlab_url)
Settings.gitlab['url'] ||= Settings.send(:build_gitlab_url)
Settings.gitlab['user'] ||= 'git'
Settings.gitlab['user_home'] ||= begin
Etc.getpwnam(Settings.gitlab['user']).dir
rescue ArgumentError # no user configured
'/home/' + Settings.gitlab['user']
end
Settings.gitlab['time_zone'] ||= nil
Settings.gitlab['signup_enabled'] ||= true if Settings.gitlab['signup_enabled'].nil?
Settings.gitlab['signin_enabled'] ||= true if Settings.gitlab['signin_enabled'].nil?
Settings.gitlab['restricted_visibility_levels'] = Settings.send(:verify_constant_array, Gitlab::VisibilityLevel, Settings.gitlab['restricted_visibility_levels'], [])
Settings.gitlab['username_changing_enabled'] = true if Settings.gitlab['username_changing_enabled'].nil?
Settings.gitlab['issue_closing_pattern'] = '((?:[Cc]los(?:e[sd]?|ing)|[Ff]ix(?:e[sd]|ing)?|[Rr]esolv(?:e[sd]?|ing))(:?) +(?:(?:issues? +)?%{issue_ref}(?:(?:, *| +and +)?)|([A-Z][A-Z0-9_]+-\d+))+)' if Settings.gitlab['issue_closing_pattern'].nil?
Settings.gitlab['default_projects_features'] ||= {}
Settings.gitlab['webhook_timeout'] ||= 10
Settings.gitlab['max_attachment_size'] ||= 10
Settings.gitlab['session_expire_delay'] ||= 10080
Settings.gitlab.default_projects_features['issues'] = true if Settings.gitlab.default_projects_features['issues'].nil?
Settings.gitlab.default_projects_features['merge_requests'] = true if Settings.gitlab.default_projects_features['merge_requests'].nil?
Settings.gitlab.default_projects_features['wiki'] = true if Settings.gitlab.default_projects_features['wiki'].nil?
Settings.gitlab.default_projects_features['snippets'] = false if Settings.gitlab.default_projects_features['snippets'].nil?
Settings.gitlab.default_projects_features['builds'] = true if Settings.gitlab.default_projects_features['builds'].nil?
Settings.gitlab.default_projects_features['container_registry'] = true if Settings.gitlab.default_projects_features['container_registry'].nil?
Settings.gitlab.default_projects_features['visibility_level'] = Settings.send(:verify_constant, Gitlab::VisibilityLevel, Settings.gitlab.default_projects_features['visibility_level'], Gitlab::VisibilityLevel::PRIVATE)
Settings.gitlab['domain_whitelist'] ||= []
Settings.gitlab['import_sources'] ||= %w[github bitbucket gitlab gitorious google_code fogbugz git gitlab_project]
Settings.gitlab['trusted_proxies'] ||= []
#
# CI
#
Settings['gitlab_ci'] ||= Settingslogic.new({})
Settings.gitlab_ci['shared_runners_enabled'] = true if Settings.gitlab_ci['shared_runners_enabled'].nil?
Settings.gitlab_ci['all_broken_builds'] = true if Settings.gitlab_ci['all_broken_builds'].nil?
Settings.gitlab_ci['add_pusher'] = false if Settings.gitlab_ci['add_pusher'].nil?
Settings.gitlab_ci['builds_path'] = File.expand_path(Settings.gitlab_ci['builds_path'] || "builds/", Rails.root)
Settings.gitlab_ci['url'] ||= Settings.send(:build_gitlab_ci_url)
#
# Reply by email
#
Settings['incoming_email'] ||= Settingslogic.new({})
Settings.incoming_email['enabled'] = false if Settings.incoming_email['enabled'].nil?
#
# Build Artifacts
#
Settings['artifacts'] ||= Settingslogic.new({})
Settings.artifacts['enabled'] = true if Settings.artifacts['enabled'].nil?
Settings.artifacts['path'] = File.expand_path(Settings.artifacts['path'] || File.join(Settings.shared['path'], "artifacts"), Rails.root)
Settings.artifacts['max_size'] ||= 100 # in megabytes
#
# Registry
#
Settings['registry'] ||= Settingslogic.new({})
Settings.registry['enabled'] ||= false
Settings.registry['host'] ||= "example.com"
Settings.registry['port'] ||= nil
Settings.registry['api_url'] ||= "http://localhost:5000/"
Settings.registry['key'] ||= nil
Settings.registry['issuer'] ||= nil
Settings.registry['host_port'] ||= [Settings.registry['host'], Settings.registry['port']].compact.join(':')
Settings.registry['path'] = File.expand_path(Settings.registry['path'] || File.join(Settings.shared['path'], 'registry'), Rails.root)
#
# Git LFS
#
Settings['lfs'] ||= Settingslogic.new({})
Settings.lfs['enabled'] = true if Settings.lfs['enabled'].nil?
Settings.lfs['storage_path'] = File.expand_path(Settings.lfs['storage_path'] || File.join(Settings.shared['path'], "lfs-objects"), Rails.root)
#
# Gravatar
#
Settings['gravatar'] ||= Settingslogic.new({})
Settings.gravatar['enabled'] = true if Settings.gravatar['enabled'].nil?
Settings.gravatar['plain_url'] ||= 'http://www.gravatar.com/avatar/%{hash}?s=%{size}&d=identicon'
Settings.gravatar['ssl_url'] ||= 'https://secure.gravatar.com/avatar/%{hash}?s=%{size}&d=identicon'
Settings.gravatar['host'] = Settings.host_without_www(Settings.gravatar['plain_url'])
#
# Cron Jobs
#
Settings['cron_jobs'] ||= Settingslogic.new({})
Settings.cron_jobs['stuck_ci_builds_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['stuck_ci_builds_worker']['cron'] ||= '0 0 * * *'
Settings.cron_jobs['stuck_ci_builds_worker']['job_class'] = 'StuckCiBuildsWorker'
Settings.cron_jobs['expire_build_artifacts_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['expire_build_artifacts_worker']['cron'] ||= '50 * * * *'
Settings.cron_jobs['expire_build_artifacts_worker']['job_class'] = 'ExpireBuildArtifactsWorker'
Settings.cron_jobs['repository_check_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['repository_check_worker']['cron'] ||= '20 * * * *'
Settings.cron_jobs['repository_check_worker']['job_class'] = 'RepositoryCheck::BatchWorker'
Settings.cron_jobs['admin_email_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['admin_email_worker']['cron'] ||= '0 0 * * 0'
Settings.cron_jobs['admin_email_worker']['job_class'] = 'AdminEmailWorker'
Settings.cron_jobs['repository_archive_cache_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['repository_archive_cache_worker']['cron'] ||= '0 * * * *'
Settings.cron_jobs['repository_archive_cache_worker']['job_class'] = 'RepositoryArchiveCacheWorker'
Settings.cron_jobs['gitlab_remove_project_export_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['gitlab_remove_project_export_worker']['cron'] ||= '0 * * * *'
Settings.cron_jobs['gitlab_remove_project_export_worker']['job_class'] = 'GitlabRemoveProjectExportWorker'
#
# GitLab Shell
#
Settings['gitlab_shell'] ||= Settingslogic.new({})
Settings.gitlab_shell['path'] ||= Settings.gitlab['user_home'] + '/gitlab-shell/'
Settings.gitlab_shell['hooks_path'] ||= Settings.gitlab['user_home'] + '/gitlab-shell/hooks/'
Settings.gitlab_shell['secret_file'] ||= Rails.root.join('.gitlab_shell_secret')
Settings.gitlab_shell['receive_pack'] = true if Settings.gitlab_shell['receive_pack'].nil?
Settings.gitlab_shell['upload_pack'] = true if Settings.gitlab_shell['upload_pack'].nil?
Settings.gitlab_shell['ssh_host'] ||= Settings.gitlab.ssh_host
Settings.gitlab_shell['ssh_port'] ||= 22
Settings.gitlab_shell['ssh_user'] ||= Settings.gitlab.user
Settings.gitlab_shell['owner_group'] ||= Settings.gitlab.user
Settings.gitlab_shell['ssh_path_prefix'] ||= Settings.send(:build_gitlab_shell_ssh_path_prefix)
#
# Repositories
#
Settings['repositories'] ||= Settingslogic.new({})
Settings.repositories['storages'] ||= {}
# Setting gitlab_shell.repos_path is DEPRECATED and WILL BE REMOVED in version 9.0
Settings.repositories.storages['default'] ||= Settings.gitlab_shell['repos_path'] || Settings.gitlab['user_home'] + '/repositories/'
#
# The repository_downloads_path is used to remove outdated repository
# archives, if someone has it configured incorrectly, and it points
# to the path where repositories are stored this can cause some
# data-integrity issue. In this case, we sets it to the default
# repository_downloads_path value.
#
repositories_storages_path = Settings.repositories.storages.values
repository_downloads_path = Settings.gitlab['repository_downloads_path'].to_s.gsub(/\/$/, '')
repository_downloads_full_path = File.expand_path(repository_downloads_path, Settings.gitlab['user_home'])
if repository_downloads_path.blank? || repositories_storages_path.any? { |path| [repository_downloads_path, repository_downloads_full_path].include?(path.gsub(/\/$/, '')) }
Settings.gitlab['repository_downloads_path'] = File.join(Settings.shared['path'], 'cache/archive')
end
#
# Backup
#
Settings['backup'] ||= Settingslogic.new({})
Settings.backup['keep_time'] ||= 0
Settings.backup['pg_schema'] = nil
Settings.backup['path'] = File.expand_path(Settings.backup['path'] || "tmp/backups/", Rails.root)
Settings.backup['archive_permissions'] ||= 0600
Settings.backup['upload'] ||= Settingslogic.new({ 'remote_directory' => nil, 'connection' => nil })
# Convert upload connection settings to use symbol keys, to make Fog happy
if Settings.backup['upload']['connection']
Settings.backup['upload']['connection'] = Hash[Settings.backup['upload']['connection'].map { |k, v| [k.to_sym, v] }]
end
Settings.backup['upload']['multipart_chunk_size'] ||= 104857600
Settings.backup['upload']['encryption'] ||= nil
#
# Git
#
Settings['git'] ||= Settingslogic.new({})
Settings.git['max_size'] ||= 20971520 # 20.megabytes
Settings.git['bin_path'] ||= '/usr/bin/git'
Settings.git['timeout'] ||= 10
# Important: keep the satellites.path setting until GitLab 9.0 at
# least. This setting is fed to 'rm -rf' in
# db/migrate/20151023144219_remove_satellites.rb
Settings['satellites'] ||= Settingslogic.new({})
Settings.satellites['path'] = File.expand_path(Settings.satellites['path'] || "tmp/repo_satellites/", Rails.root)
#
# Extra customization
#
Settings['extra'] ||= Settingslogic.new({})
#
# Rack::Attack settings
#
Settings['rack_attack'] ||= Settingslogic.new({})
Settings.rack_attack['git_basic_auth'] ||= Settingslogic.new({})
Settings.rack_attack.git_basic_auth['enabled'] = true if Settings.rack_attack.git_basic_auth['enabled'].nil?
Settings.rack_attack.git_basic_auth['ip_whitelist'] ||= %w{127.0.0.1}
Settings.rack_attack.git_basic_auth['maxretry'] ||= 10
Settings.rack_attack.git_basic_auth['findtime'] ||= 1.minute
Settings.rack_attack.git_basic_auth['bantime'] ||= 1.hour
#
# Testing settings
#
if Rails.env.test?
Settings.gitlab['default_projects_limit'] = 42
Settings.gitlab['default_can_create_group'] = true
Settings.gitlab['default_can_create_team'] = false
end
# Force a refresh of application settings at startup
begin
ApplicationSetting.expire
Ci::ApplicationSetting.expire
rescue
# Gracefully handle when Redis is not available. For example,
# omnibus may fail here during assets:precompile.
end
|
module Grack
class Auth < Rack::Auth::Basic
def valid?
# Authentication with username and password
email, password = @auth.credentials
user = User.find_by_email(email)
return false unless user.try(:valid_password?, password)
# Set GL_USER env variable
ENV['GL_USER'] = email
# Pass Gitolite update hook
ENV['GL_BYPASS_UPDATE_HOOK'] = "true"
# Need this patch because the rails mount
@env['PATH_INFO'] = @env['REQUEST_PATH']
# Find project by PATH_INFO from env
if m = /^\/([\w-]+).git/.match(@env['PATH_INFO']).to_a
return false unless project = Project.find_by_path(m.last)
end
# Git upload and receive
if @env['REQUEST_METHOD'] == 'GET'
true
elsif @env['REQUEST_METHOD'] == 'POST'
if @env['REQUEST_URI'].end_with?('git-upload-pack')
return project.dev_access_for?(user)
elsif @env['REQUEST_URI'].end_with?('git-receive-pack')
if project.protected_branches.map(&:name).include?(current_ref)
project.master_access_for?(user)
else
project.dev_access_for?(user)
end
else
false
end
else
false
end
end# valid?
def current_ref
if @env["HTTP_CONTENT_ENCODING"] =~ /gzip/
input = Zlib::GzipReader.new(@request.body).string
else
input = @request.body.string
end
oldrev, newrev, ref = input.split(' ')
/refs\/heads\/([\w-]+)/.match(ref).to_a.last
end
end# Auth
end# Grack
fix git push body bigger than 112k problem
module Grack
class Auth < Rack::Auth::Basic
def valid?
# Authentication with username and password
email, password = @auth.credentials
user = User.find_by_email(email)
return false unless user.try(:valid_password?, password)
# Set GL_USER env variable
ENV['GL_USER'] = email
# Pass Gitolite update hook
ENV['GL_BYPASS_UPDATE_HOOK'] = "true"
# Need this patch because the rails mount
@env['PATH_INFO'] = @env['REQUEST_PATH']
# Find project by PATH_INFO from env
if m = /^\/([\w-]+).git/.match(@env['PATH_INFO']).to_a
return false unless project = Project.find_by_path(m.last)
end
# Git upload and receive
if @env['REQUEST_METHOD'] == 'GET'
true
elsif @env['REQUEST_METHOD'] == 'POST'
if @env['REQUEST_URI'].end_with?('git-upload-pack')
return project.dev_access_for?(user)
elsif @env['REQUEST_URI'].end_with?('git-receive-pack')
if project.protected_branches.map(&:name).include?(current_ref)
project.master_access_for?(user)
else
project.dev_access_for?(user)
end
else
false
end
else
false
end
end# valid?
def current_ref
if @env["HTTP_CONTENT_ENCODING"] =~ /gzip/
input = Zlib::GzipReader.new(@request.body).read
else
input = @request.body.read
end
# Need to reset seek point
@request.body.rewind
/refs\/heads\/([\w-]+)/.match(input).to_a.first
end
end# Auth
end# Grack
|
rgeo patch should have be in spatial engine
# the following initializer is to deal with this issue with the schema dumper
# https://github.com/rgeo/rgeo-activerecord/issues/23
module RGeo
module ActiveRecord
RGeo::ActiveRecord.send(:remove_const, :SpatialIndexDefinition)
class SpatialIndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths, :orders, :where, :spatial, :using, :type)
end
end
end |
#
# Copyright 2014 Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
name "perl_pg_driver"
default_version "3.14.2"
dependency "perl"
dependency "cpanminus"
dependency "postgresql"
license "Artistic"
license_file "README"
license_file "LICENSES/artistic.txt"
# version_list: url=https://cpan.metacpan.org/authors/id/T/TU/TURNSTEP/ filter=*.tar.gz
version("3.14.2") { source sha256: "c973e98458960a78ec54032a71b3840f178418dd7e69d063e462a0f10ec68e4d" }
version("3.5.3") { source sha256: "7e98a9b975256a4733db1c0e974cad5ad5cb821489323e395ed97bd058e0a90e" }
version("3.3.0") { source sha256: "52f43de5b2d916d447d7ed252b127f728b226dc88db57d4fe9712e21d3586ffe" }
source url: "http://search.cpan.org/CPAN/authors/id/T/TU/TURNSTEP/DBD-Pg-#{version}.tar.gz"
relative_path "DBD-Pg-#{version}"
build do
env = with_standard_compiler_flags(with_embedded_path)
command "cpanm -v --notest .", env: env
end
Updating checksums
Signed-off-by: Swati Keshari <c680b5d9955c46c8dad4ecc06b5bea9588d924c3@msystechnologies.com>
#
# Copyright 2014 Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
name "perl_pg_driver"
default_version "3.14.2"
dependency "perl"
dependency "cpanminus"
dependency "postgresql"
license "Artistic"
license_file "README"
license_file "LICENSES/artistic.txt"
# version_list: url=https://cpan.metacpan.org/authors/id/T/TU/TURNSTEP/ filter=*.tar.gz
version("3.14.2") { source md5: "6b8fe657f8cc0be8cc2c178f42c1d4ed" }
version("3.5.3") { source md5: "21cdf31a8d1f77466920375aa766c164" }
version("3.3.0") { source md5: "547de1382a47d66872912fe64282ff55" }
source url: "http://search.cpan.org/CPAN/authors/id/T/TU/TURNSTEP/DBD-Pg-#{version}.tar.gz"
relative_path "DBD-Pg-#{version}"
build do
env = with_standard_compiler_flags(with_embedded_path)
command "cpanm -v --notest .", env: env
end
|
class AdminsController < ApplicationController
def new
@admin = Admin.new
end
def create
@admin = Admin.new(params[:user])
if @admin.save
redirect_to home_path, :notice => "Signed up!"
else
render :new
end
end
end
Corrects typo
class AdminsController < ApplicationController
def new
@admin = Admin.new
end
def create
@admin = Admin.new(params[:admin])
if @admin.save
redirect_to home_path, :notice => "Signed up!"
else
render :new
end
end
end
|
class AlbumsController < ApplicationController
load_and_authorize_resource :album, :except => [:show]
load_resource :album, :only => [:show]
def index
authorize!(:manage, Album)
@albums = @albums.includes([:images])
end
def show
@images = @album.images.page(params[:page]).per(18)
end
def new
end
def create
if @album.save
redirect_to albums_path
else
render :edit
end
end
def edit
end
def update
if @album.update_attributes(params[:album])
redirect_to album_path(@album)
else
render :edit
end
end
def destroy
@album.destroy
redirect_to albums_path
end
end
show only published images on Album#show
class AlbumsController < ApplicationController
load_and_authorize_resource :album, :except => [:show]
load_resource :album, :only => [:show]
def index
authorize!(:manage, Album)
@albums = @albums.includes([:images])
end
def show
@images = @album.images.published.page(params[:page]).per(18)
end
def new
end
def create
if @album.save
redirect_to albums_path
else
render :edit
end
end
def edit
end
def update
if @album.update_attributes(params[:album])
redirect_to album_path(@album)
else
render :edit
end
end
def destroy
@album.destroy
redirect_to albums_path
end
end |
module AnnotatorsHelper
############ SEARCH ANNOTATION BY LOCATION ############
def getAnnotationsByLocation
search_term = params[:location]
@location = Location.search(search_term).order("created_at DESC") ## pulls location IDs
if @location.present?
@videos = Video.select("id", "title", "author", "location_ID").where(:location_ID => @location)
@annos = []
if @videos.present?
for v in @videos
@annotations = Annotation.select("beginTime", "endTime", "annotation", "ID", "video_ID", "location_ID", "user_ID", "pointsArray", "deprecated", "tags").where(:video_ID => v.id)
for x in @annotations
## WRAP this next bit in an if/else: if not deprecated, do this, else call function on next newest
if x.deprecated
next
end
tag_strings = x.semantic_tags.collect(&:tag)
#@annos.push(getAnnotationInfo(x)) <-- originally started pulling functionality into private function, added complexity seemed to outweigh readability
video = Video.select("title", "location_ID").where(:ID => x.video_id)
location = Location.select("location").where(:ID => x.location_id)
user = User.select("name", "email").where(:ID => x.user_id)
anno = {}
data = {}
data[:text] = x.annotation
data[:beginTime] = x.beginTime
data[:endTime] = x.endTime
data[:pointsArray] = x.pointsArray
data[:tags] = tag_strings
meta = {}
meta[:id] = x.id
meta[:title] = video[0].title
meta[:location] = location[0].location
unless user[0].nil?
meta[:userName] = user[0].name
meta[:userEmail] = user[0].email
end
anno[:data] = data
anno[:metadata] = meta
@annos.push(anno)
end #end for x
end #end for v
end #end if @videos
@annohash = {}
@annohash[:annotations] = @annos
render :json => @annohash
end #end if @location
end #end def getAnnotationsByLocation
############ ADD ANNOTATION BY VIDEO LOCATION ############
# Add check if annotation text and time and shape match any extant annotations?
def addAnnotation
@x = params[:annotation]
### Create a new Annotation instance
@annotation = Annotation.new
@annotation.annotation = params[:annotation]
@annotation.pointsArray = params[:pointsArray]
@annotation.beginTime = params[:beginTime]
@annotation.endTime = params[:endTime]
#@annotation.tags = params[:tags]
@annotation.user_id = nil#session[:user_id]
edit_mode = false
if params[:id] ## if an old annotation id is supplied, this is an edit and we should create a pointer to the old annotation
edit_mode = true
@annotation.prev_anno_ID = params[:id]
end
#logger.info params[:semantic_tag]
# Find the Location entry for the URL
@location = Location.search(params[:location]).order("created_at DESC") ## pulls location IDs
# Find the Video entries for the found Location
@videos = Video.select("id", "title", "author", "location_ID").where(:location_ID => @location)
#@videos = Video.search(params[:video_title]).order("created_at DESC")
if @videos.empty?
### If there is no Video associated with the Location, create a new one
# Make and populate Video
@video = Video.new
@video.title = params[:video_title]
@video.author = params[:video_author]
# Make and populate Location
@new_location = Location.new
@new_location.location = params[:location]
@new_location.save
@video.save
@video.location_id = @new_location.id
@annotation.video_id = @video.id
@annotation.location_id = @new_location.id
@video.save
@annotation.save
else # if video is already present
### If there are Videos associated with the Location, update the annotation to reference these.
for video in @videos
@annotation.video_id = video.id
@annotation.location_id = video.location_id
@annotation.save
end
end
### Handle tags
# Create SemanticTags for new tags
Array(params[:tags]).each do |tagStr|
# Check to see if the tag already exists
#tag_check = SemanticTag.search(t).order("created_at DESC")
tag_check = SemanticTag.find_by(tag: tagStr)
# If it doesn't, make a new SemanticTag and relate it to the annotation.
if tag_check.nil?
new_tag = SemanticTag.new
new_tag.tag = tagStr
new_tag.save
@tag_annotation.semantic_tag_id = new_tag.id
@tag_annotation.annotation_id = @annotation.id
@annotation.save
@tag_annotation.save
@semantic_tags.save
end
end
# Remove SemanticTags that are not represented by the tag list (remove deleted tags).
# unless @semantic_tag_check_old.empty?
# # iterate through tags that were previously in the db, edit
# @semantic_tag_check_old.each do |t|
# #@annotation.tag_id = t.id
# @tag_annotation.semantic_tag_id = t.id
# @tag_annotation.annotation_id = @annotation.id
# @annotation.save
# @tag_annotation.save
# end
# end
# unless @semantic_tag_check_new.empty?
# # iterate through tags that are new to the db, create/edit
# @semantic_tag_check_new.each do |t|
# new_tag = SemanticTag.new
# new_tag.tag = t
# @tag_annotation.semantic_tag_id = new_tag.id
# @tag_annotation.annotation_id = @annotation.id
# @annotation.save
# @tag_annotation.save
# @semantic_tags.save
# end
# end #end if @semantic_tags
@ret = {}
@ret[:id] = @annotation.id
#@ret[:status] = 200
render :json => @ret
end #end def addAnnotation
############ EDIT ANNOTATION ############
def editAnnotation ## accepts annotation id
# Deprecate the old annotation
deleteAnnotation
# Create a new annotation linking back to the old one.
addAnnotation
end #end def editAnnotation
############ DELETE ANNOTATION ############
def deleteAnnotation ## accepts annotation id
search_term = params[:id]
# Find the annotation with the given ID
anno = Annotation.find_by(id: search_term)
anno.update(deprecated: true)
end
end #end module
Fix missing reference
module AnnotatorsHelper
############ SEARCH ANNOTATION BY LOCATION ############
def getAnnotationsByLocation
search_term = params[:location]
@location = Location.search(search_term).order("created_at DESC") ## pulls location IDs
if @location.present?
@videos = Video.select("id", "title", "author", "location_ID").where(:location_ID => @location)
@annos = []
if @videos.present?
for v in @videos
@annotations = Annotation.select("beginTime", "endTime", "annotation", "ID", "video_ID", "location_ID", "user_ID", "pointsArray", "deprecated", "tags").where(:video_ID => v.id)
for x in @annotations
## WRAP this next bit in an if/else: if not deprecated, do this, else call function on next newest
if x.deprecated
next
end
tag_strings = x.semantic_tags.collect(&:tag)
#@annos.push(getAnnotationInfo(x)) <-- originally started pulling functionality into private function, added complexity seemed to outweigh readability
video = Video.select("title", "location_ID").where(:ID => x.video_id)
location = Location.select("location").where(:ID => x.location_id)
user = User.select("name", "email").where(:ID => x.user_id)
anno = {}
data = {}
data[:text] = x.annotation
data[:beginTime] = x.beginTime
data[:endTime] = x.endTime
data[:pointsArray] = x.pointsArray
data[:tags] = tag_strings
meta = {}
meta[:id] = x.id
meta[:title] = video[0].title
meta[:location] = location[0].location
unless user[0].nil?
meta[:userName] = user[0].name
meta[:userEmail] = user[0].email
end
anno[:data] = data
anno[:metadata] = meta
@annos.push(anno)
end #end for x
end #end for v
end #end if @videos
@annohash = {}
@annohash[:annotations] = @annos
render :json => @annohash
end #end if @location
end #end def getAnnotationsByLocation
############ ADD ANNOTATION BY VIDEO LOCATION ############
# Add check if annotation text and time and shape match any extant annotations?
def addAnnotation
@x = params[:annotation]
### Create a new Annotation instance
@annotation = Annotation.new
@annotation.annotation = params[:annotation]
@annotation.pointsArray = params[:pointsArray]
@annotation.beginTime = params[:beginTime]
@annotation.endTime = params[:endTime]
#@annotation.tags = params[:tags]
@annotation.user_id = nil#session[:user_id]
edit_mode = false
if params[:id] ## if an old annotation id is supplied, this is an edit and we should create a pointer to the old annotation
edit_mode = true
@annotation.prev_anno_ID = params[:id]
end
#logger.info params[:semantic_tag]
# Find the Location entry for the URL
@location = Location.search(params[:location]).order("created_at DESC") ## pulls location IDs
# Find the Video entries for the found Location
@videos = Video.select("id", "title", "author", "location_ID").where(:location_ID => @location)
#@videos = Video.search(params[:video_title]).order("created_at DESC")
if @videos.empty?
### If there is no Video associated with the Location, create a new one
# Make and populate Video
@video = Video.new
@video.title = params[:video_title]
@video.author = params[:video_author]
# Make and populate Location
@new_location = Location.new
@new_location.location = params[:location]
@new_location.save
@video.save
@video.location_id = @new_location.id
@annotation.video_id = @video.id
@annotation.location_id = @new_location.id
@video.save
@annotation.save
else # if video is already present
### If there are Videos associated with the Location, update the annotation to reference these.
for video in @videos
@annotation.video_id = video.id
@annotation.location_id = video.location_id
@annotation.save
end
end
### Handle tags
# Create SemanticTags for new tags
Array(params[:tags]).each do |tagStr|
# Check to see if the tag already exists
#tag_check = SemanticTag.search(t).order("created_at DESC")
tag_check = SemanticTag.find_by(tag: tagStr)
# If it doesn't, make a new SemanticTag and relate it to the annotation.
if tag_check.nil?
new_tag = SemanticTag.new
new_tag.tag = tagStr
new_tag.save
tag_annotation = TagAnnotation.new
tag_annotation.semantic_tag_id = new_tag.id
tag_annotation.annotation_id = @annotation.id
tag_annotation.save
@semantic_tags.save
@annotation.save
end
end
# Remove SemanticTags that are not represented by the tag list (remove deleted tags).
# unless @semantic_tag_check_old.empty?
# # iterate through tags that were previously in the db, edit
# @semantic_tag_check_old.each do |t|
# #@annotation.tag_id = t.id
# @tag_annotation.semantic_tag_id = t.id
# @tag_annotation.annotation_id = @annotation.id
# @annotation.save
# @tag_annotation.save
# end
# end
# unless @semantic_tag_check_new.empty?
# # iterate through tags that are new to the db, create/edit
# @semantic_tag_check_new.each do |t|
# new_tag = SemanticTag.new
# new_tag.tag = t
# @tag_annotation.semantic_tag_id = new_tag.id
# @tag_annotation.annotation_id = @annotation.id
# @annotation.save
# @tag_annotation.save
# @semantic_tags.save
# end
# end #end if @semantic_tags
@ret = {}
@ret[:id] = @annotation.id
#@ret[:status] = 200
render :json => @ret
end #end def addAnnotation
############ EDIT ANNOTATION ############
def editAnnotation ## accepts annotation id
# Deprecate the old annotation
deleteAnnotation
# Create a new annotation linking back to the old one.
addAnnotation
end #end def editAnnotation
############ DELETE ANNOTATION ############
def deleteAnnotation ## accepts annotation id
search_term = params[:id]
# Find the annotation with the given ID
anno = Annotation.find_by(id: search_term)
anno.update(deprecated: true)
end
end #end module
|
class ArtistController < ApplicationController
def statements
@rooftops = rooftops_subcategory.compact!
@factories = factories_subcategory.compact!
@cabinet_shop = Painting.find(21)
@apple_trees = apple_trees_subcategory.compact!
end
def reviews
@reviewed_paintings = [Painting.find(9), Painting.find(10), Painting.find(12), Painting.find(3)]
end
def cv
end
def contact
end
def links
end
private
def rooftops_subcategory
Category.find(6).paintings.map {|p| p if !p.title.include? "Tree"}
end
def factories_subcategory
Category.find(5).paintings.map {|p| p if p.title.include? "Factory"}
end
def people_subcategory
end
def apple_trees_subcategory
Category.find(2).paintings.map {|painting| painting if painting.title.include? "Apple"}
end
end
change methods to use new categories
class ArtistController < ApplicationController
def statements
@rooftops = rooftops_subcategory.compact!
@factories = factories_subcategory.compact!
@cabinet_shop =
@apple_trees = apple_trees_subcategory.compact!
end
def reviews
@reviewed_paintings = [Painting.find(9), Painting.find(10), Painting.find(12), Painting.find(3)]
end
def cv
end
def contact
end
def links
end
private
def rooftops_subcategory
Category.find(2).paintings.map {|p| p if !p.title.include? "Factory"}
end
def factories_subcategory
Category.find(2).paintings.map {|p| p if p.title.include? "Factory"}
end
def people_subcategory
end
def apple_trees_subcategory
Category.find(1).paintings.map {|painting| painting if painting.title.include? "Apple"}
end
end |
class AssetsController < AssetAwareController
add_breadcrumb "Home", :root_path
# Set the view variabless form the params @asset_type, @asset_subtype, @search_text, @spatial_filter, @view
before_action :set_view_vars, :only => [:index, :map]
# set the @asset variable before any actions are invoked
before_action :get_asset, :only => [:tag, :show, :edit, :copy, :update, :destroy, :summary_info, :add_to_group, :remove_from_group, :popup, :get_dependents, :add_dependents, :get_dependent_subform, :get_subheader]
before_action :reformat_date_fields, :only => [:create, :update]
# Update the vendor_id param if the user is using the vendor_name parameter
before_action :update_vendor_param, :only => [:create, :update]
# Lock down the controller
authorize_resource only: [:index, :show, :new, :create, :edit, :update, :destroy]
STRING_TOKENIZER = '|'
# Session Variables
INDEX_KEY_LIST_VAR = "asset_key_list_cache_var"
# Returns a JSON array of matching asset subtypes based on a typeahead name or description
def filter(klass=Rails.application.config.asset_base_class_name.constantize)
query = params[:query]
query_str = "%" + query + "%"
Rails.logger.debug query_str
matches = []
assets = klass.where(organization_id: current_user.viewable_organization_ids)
.where(params[:search_params])
.where("(asset_tag LIKE ? OR object_key LIKE ? OR description LIKE ?)", query_str, query_str, query_str)
assets.each do |asset|
matches << {
"id" => asset.object_key,
"name" => "#{asset.to_s}: #{asset.description}"
}
end
respond_to do |format|
format.js { render :json => matches.to_json }
format.json { render :json => matches.to_json }
end
end
# Adds the asset to the specified group
def add_to_group
asset_group = AssetGroup.find_by_object_key(params[:asset_group])
if asset_group.nil?
notify_user(:alert, "Can't find the asset group selected.")
else
if @asset.asset_groups.exists? asset_group.id
notify_user(:alert, "Asset #{@asset.name} is already a member of '#{asset_group}'.")
else
@asset.asset_groups << asset_group
notify_user(:notice, "Asset #{@asset.name} was added to '#{asset_group}'.")
end
end
# Always display the last view
redirect_back(fallback_location: root_path)
end
# Removes the asset from the specified group
def remove_from_group
asset_group = AssetGroup.find_by_object_key(params[:asset_group])
if asset_group.nil?
notify_user(:alert, "Can't find the asset group selected.")
else
if @asset.asset_groups.exists? asset_group.id
@asset.asset_groups.delete asset_group
notify_user(:notice, "Asset #{@asset.name} was removed from '#{asset_group}'.")
else
notify_user(:alert, "Asset #{@asset.name} is not a member of '#{asset_group}'.")
end
end
# Always display the last view
redirect_back(fallback_location: root_path)
end
# NOT USED
def parent
parent_asset = @organization.assets.find_by_object_key(params[:parent_key])
respond_to do |format|
format.js {render :partial => 'assets/asset_details', :locals => { :asset => parent_asset} }
end
end
def get_summary
asset_type_id = params[:asset_type_id]
if asset_type_id.blank?
results = ActiveRecord::Base.connection.exec_query(Rails.application.config.asset_base_class_name.constantize.operational.select('organization_id, asset_subtypes.asset_type_id, organizations.short_name AS org_short_name, asset_types.name AS subtype_name, COUNT(*) AS assets_count, SUM(purchase_cost) AS sum_purchase_cost').joins(:organization, asset_subtype: :asset_type).where(organization_id: @organization_list).group(:organization_id, :asset_type_id).to_sql)
level = 'type'
else
asset_subtype_ids = AssetType.includes(:asset_subtypes).find_by(id: asset_type_id).asset_subtypes.ids
results = ActiveRecord::Base.connection.exec_query(Rails.application.config.asset_base_class_name.constantize.operational.select('organization_id, asset_subtype_id, organizations.short_name AS org_short_name, asset_subtypes.name AS subtype_name, COUNT(*) AS assets_count, SUM(purchase_cost) AS sum_purchase_cost').joins(:organization, :asset_subtype).where(organization_id: (params[:org] || @organization_list), asset_subtype_id: asset_subtype_ids).group(:organization_id, :asset_subtype_id).to_sql)
level = 'subtype'
end
respond_to do |format|
format.js {
if params[:org]
render partial: 'dashboards/assets_widget_table_rows', locals: {results: results, level: level }
else
render partial: 'dashboards/assets_widget_table', locals: {results: results, level: level }
end
}
end
end
# renders either a table or map view of a selected list of assets
#
# Parameters include asset_type, asset_subtype, id_list, box, or search_text
#
def index
add_index_breadcrumbs
# disable any spatial filters for this view
@spatial_filter = nil
@assets = get_assets
terminal_crumb = nil
if @early_disposition
terminal_crumb = "Early disposition proposed"
elsif @transferred_assets
terminal_crumb = "Transferred Assets"
elsif @asset_group.present?
asset_group = AssetGroup.find_by_object_key(@asset_group)
terminal_crumb = asset_group
elsif @search_text.present?
terminal_crumb = "Search '#{@search_text}'"
elsif @asset_subtype > 0
subtype = AssetSubtype.find(@asset_subtype)
add_breadcrumb subtype.asset_type.name.pluralize(2), inventory_index_path(:asset_type => subtype.asset_type, :asset_subtype => 0)
terminal_crumb = subtype.name
elsif @manufacturer_id > 0
add_breadcrumb "Manufacturers", manufacturers_path
manufacturer = Manufacturer.find(@manufacturer_id)
terminal_crumb = manufacturer.name
elsif @asset_type > 0
asset_type = AssetType.find(@asset_type)
terminal_crumb = asset_type.name.pluralize(2)
end
add_breadcrumb terminal_crumb if terminal_crumb
# check that an order param was provided otherwise use asset_tag as the default
params[:sort] ||= 'transam_assets.asset_tag'
# fix sorting on organizations to be alphabetical not by index
params[:sort] = 'organizations.short_name' if params[:sort] == 'organization_id'
respond_to do |format|
format.html
format.js
format.json {
render :json => {
:total => @assets.count,
:rows => index_rows_as_json
}
}
format.xls do
filename = (terminal_crumb || "unknown").gsub(" ", "_").underscore
response.headers['Content-Disposition'] = "attachment; filename=#{filename}.xls"
end
format.xlsx do
filename = (terminal_crumb || "unknown").gsub(" ", "_").underscore
response.headers['Content-Disposition'] = "attachment; filename=#{filename}.xlsx"
end
end
end
def index_rows_as_json
multi_sort = params[:multiSort]
unless (multi_sort.nil?)
sorting_string = ""
multi_sort.each { |x|
sorting_string = sorting_string + "#{x[0]}: :#{x[1]}"
}
else
sorting_string = "#{params[:sort]} #{params[:order]}"
end
@assets.order(sorting_string).limit(params[:limit]).offset(params[:offset]).as_json(user: current_user, include_early_disposition: @early_disposition)
end
def fire_asset_event_workflow_events
event_name = params[:event]
asset_event_type = AssetEventType.find_by(id: params[:asset_event_type_id])
if asset_event_type && params[:targets]
notification_enabled = asset_event_type.class_name.constantize.workflow_notification_enabled?
events = asset_event_type.class_name.constantize.where(object_key: params[:targets].split(','))
failed = 0
events.each do |evt|
if evt.fire_state_event(event_name)
workflow_event = WorkflowEvent.new
workflow_event.creator = current_user
workflow_event.accountable = evt
workflow_event.event_type = event_name
workflow_event.save
if notification_enabled
evt.notify_event_by(current_user, event_name)
end
else
failed += 1
end
end
end
redirect_back(fallback_location: root_path)
end
# makes a copy of an asset and renders it. The new asset is not saved
# and has any identifying chracteristics identified as CLEANSABLE_FIELDS are nilled
def copy
# add_breadcrumb "#{@asset.asset_type.name}".pluralize(2), inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
# add_breadcrumb "#{@asset.asset_subtype.name}", inventory_index_path(:asset_subtype => @asset.asset_subtype)
# add_breadcrumb @asset.asset_tag, inventory_path(@asset)
# add_breadcrumb "Copy"
# create a copy of the asset and null out all the fields that are identified as cleansable
new_asset = @asset.copy(true)
notify_user(:notice, "Complete the master record to copy Asset #{@asset.to_s}.")
@asset = new_asset
# render the edit view
respond_to do |format|
format.html { render :action => "edit" }
format.json { render :json => @asset }
end
end
# not used
def summary_info
respond_to do |format|
format.js # show.html.erb
format.json { render :json => @asset }
end
end
def show
add_breadcrumbs
# add_breadcrumb "#{@asset.asset_subtype.name}", inventory_index_path(:asset_subtype => @asset.asset_subtype)
# add_breadcrumb @asset.asset_tag, inventory_path(@asset)
# Set the asset class view var. This can be used to determine which view components
# are rendered, for example, which tabs and action items the user sees
@asset_class_name = @asset.class.name.underscore
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @asset }
end
end
def edit
# add_breadcrumb "#{@asset.asset_type.name}".pluralize(2), inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
# add_breadcrumb "#{@asset.asset_subtype.name}", inventory_index_path(:asset_subtype => @asset.asset_subtype)
# When editing a newly transferred asset this link is invalid so we don't want to show it.
if @asset.asset_tag == @asset.object_key
@asset.asset_tag = nil
else
add_breadcrumb @asset.asset_tag, inventory_path(@asset)
end
add_breadcrumb "Update master record", edit_inventory_path(@asset)
end
def update
#add_breadcrumb "#{@asset.asset_type.name}".pluralize(2), inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
#add_breadcrumb @asset.name, inventory_path(@asset)
#add_breadcrumb "Modify", edit_inventory_path(@asset)
# transfered assets need to remove notification if exists
# if @asset.asset_tag == @asset.object_key
# notification = Notification.where("text = 'A new asset has been transferred to you. Please update the asset.' AND link LIKE ?" , "%#{@asset.object_key}%").first
# notification.update(active: false) if notification.present?
# end
respond_to do |format|
if @asset.update_attributes(new_form_params(@asset))
# If the asset was successfully updated, schedule update the condition and disposition asynchronously
#Delayed::Job.enqueue AssetUpdateJob.new(@asset.asset.object_key), :priority => 0
# See if this asset has any dependents that use its spatial reference
if @asset.geometry and @asset.occupants.count > 0
# schedule an update to the spatial references of the dependent assets
Delayed::Job.enqueue AssetDependentSpatialReferenceUpdateJob.new(@asset.object_key), :priority => 0
end
notify_user(:notice, "Asset #{@asset.to_s} was successfully updated.")
format.html { redirect_to inventory_url(@asset) }
format.js { notify_user(:notice, "#{@asset} successfully updated.") }
format.json { head :no_content }
else
format.html { render :action => "edit" }
format.js { render :action => "edit" }
format.json { render :json => @asset.errors, :status => :unprocessable_entity }
end
end
end
def get_subheader
respond_to do |format|
format.js
end
end
def get_dependents
respond_to do |format|
format.js
format.json { render :json => @asset.to_json }
end
end
def add_dependents
params[:asset][:dependents_attributes].each do |key, val|
unless val[:id]
dependent = TransamAsset.find_by(object_key: val[:object_key])
if dependent
@asset.dependents << dependent
@asset.update_condition # might need to change to run full AssetUpdateJob
end
end
end
redirect_back(fallback_location: root_path)
end
def get_dependent_subform
@dependent_subform_target_model = params[:dependent_subform_target_model]
@dependent = @dependent_subform_target_model.constantize.find_by(object_key: params[:dependent_object_key])
@dependent_subform_target = params[:dependent_subform_target]
@dependent_subform_view = params[:dependent_subform_view]
respond_to do |format|
format.js
end
end
def new_asset
authorize! :new, Rails.application.config.asset_base_class_name.constantize
add_breadcrumb "Add Asset", new_asset_inventory_index_path
end
def new
asset_class_name = params[:asset_seed_class_name] || 'AssetType'
@asset_class_instance = asset_class_name.constantize.find_by(id: params[:asset_base_class_id])
if @asset_class_instance.nil?
notify_user(:alert, "Asset class '#{params[:asset_base_class_id]}' not found. Can't create new asset!")
redirect_to(root_url)
return
end
#add_breadcrumb "#{asset_subtype.asset_type.name}".pluralize(2), inventory_index_path(:asset_type => asset_subtype.asset_type)
#add_breadcrumb "#{asset_subtype.name}", inventory_index_path(:asset_subtype => asset_subtype)
#add_breadcrumb "New", new_inventory_path(asset_subtype)
# Use the asset class to create an asset of the correct type
@asset = Rails.application.config.asset_base_class_name.constantize.new_asset(@asset_class_instance, params)
# See if the user selected an org to associate the asset with
if params[:organization_id].present?
@asset.organization = Organization.find(params[:organization_id])
else
@asset.organization_id = @organization_list.first
end
if params[:parent_id].present?
@asset.parent_id = params[:parent_id].to_i
end
respond_to do |format|
format.html # new.html.haml this had been an erb and is now an haml the change should just be caught
format.json { render :json => @asset }
end
end
def create
asset_class_name = params[:asset_seed_class_name] || 'AssetType'
if asset_class_name == 'AssetType' && params[:asset][:asset_type_id].blank?
asset_subtype = AssetSubtype.find_by(id: params[:asset][:asset_subtype_id])
asset_class_instance = asset_class_name.constantize.find_by(id: asset_subtype.try(:asset_type_id))
else
asset_class_instance = asset_class_name.constantize.find_by(id: params[:asset][asset_class_name.foreign_key.to_sym])
end
if asset_class_instance.nil?
notify_user(:alert, "Asset class '#{params[:asset][asset_class_name.foreign_key.to_sym]}' not found. Can't create new asset!")
redirect_to(root_url)
return
end
# Use the asset class to create an asset of the correct type
@asset = Rails.application.config.asset_base_class_name.constantize.new_asset(asset_class_instance, params)
@asset.attributes = new_form_params(@asset)
# If the asset does not have an org already defined, set to the default for
# the user
if @asset.organization.blank?
@asset.organization_id = @organization_list.first
end
#@asset.creator = current_user
#@asset.updator = current_user
#Rails.logger.debug @asset.inspect
# add_breadcrumb "#{asset_type.name}".pluralize(2), inventory_index_path(:asset_type => asset_subtype.asset_type)
# add_breadcrumb "#{asset_subtype.name}", inventory_index_path(:asset_subtype => asset_subtype)
# add_breadcrumb "New", new_inventory_path(asset_subtype)
respond_to do |format|
if @asset.save
# If the asset was successfully saved, schedule update the condition and disposition asynchronously
#Delayed::Job.enqueue AssetUpdateJob.new(@asset.object_key), :priority => 0
notify_user(:notice, "Asset #{@asset.to_s} was successfully created.")
format.html { redirect_to inventory_url(@asset) }
format.json { render :json => @asset, :status => :created, :location => @asset }
else
#Rails.logger.debug @asset.errors.inspect
format.html { render :action => "new" }
format.json { render :json => @asset.errors, :status => :unprocessable_entity }
end
end
end
# called when the user wants to delete an asset
def destroy
# make sure we can find the asset we are supposed to be removing and that it belongs to us.
if @asset.nil?
redirect_to(root_path, :flash => { :alert => t(:error_404) })
return
end
# Destroy this asset, call backs to remove each associated object will be made
@asset.destroy
notify_user(:notice, "Asset was successfully removed.")
respond_to do |format|
format.html { redirect_to(inventory_index_url(@asset.class.asset_seed_class_name.foreign_key => @asset.send(@asset.class.asset_seed_class_name.foreign_key))) }
format.json { head :no_content }
end
end
# Adds the assets to the user's tag list or removes it if the asset
# is already tagged. called by ajax so no response is rendered
# NOT USED
def tag
if @asset.tagged? current_user
@asset.users.delete current_user
else
@asset.tag current_user
end
# No response needed
render :nothing => true
end
# Called via AJAX to get dynamic content via AJAX
# NOT USED (I think)
def popup
str = ""
if @asset
str = render_to_string(:partial => "popup", :locals => { :asset => @asset })
end
render json: str.to_json
end
#------------------------------------------------------------------------------
#
# Protected Methods
#
#------------------------------------------------------------------------------
protected
#
# Sets the view variables. This is used to set up the vars before a call to get_assets
# @asset_type
# @asset_subtype
# @search_text
# @id_filter_list
# @spatial_filter
# @fmt
# @view
# @asset_class_name
# @filter
#
def set_view_vars
# Check to see if we got an asset group to sub select on. This occurs when the user
# selects an asset group from the menu selector
if params[:asset_group].nil? or params[:asset_group] == '0'
@asset_group = ''
else
@asset_group = params[:asset_group]
end
# Check to see if we got an asset type to sub select on. This occurs when the user
# selects an asset type from the drop down
if params[:asset_type].nil?
@asset_type = 0
else
@asset_type = params[:asset_type].to_i
end
# Check to see if we got an asset subtype to sub select on. This will happen if an asset type is selected
# already and the user selected a subtype from the dropdown.
if params[:asset_subtype].nil?
@asset_subtype = 0
else
@asset_subtype = params[:asset_subtype].to_i
end
# Check to see if we got an organization to sub select on.
if params[:org_id].nil?
@org_id = 0
else
@org_id = params[:org_id].to_i
end
# Check to see if we got a manufacturer to sub select on.
if params[:manufacturer_id].nil?
@manufacturer_id = 0
else
@manufacturer_id = params[:manufacturer_id].to_i
end
# Check to see if we got a service status to sub select on.
if params[:service_status].nil?
@service_status = 0
else
@service_status = params[:service_status].to_i
end
# Check to see if we got a search text and search param to filter on
if params[:search_text].nil?
# See if one is stored in the session
@search_text = session[:search_text].blank? ? nil : session[:search_text]
@search_param = session[:search_param].blank? ? nil : session[:search_param]
else
@search_text = params[:search_text]
@search_param = params[:search_param]
end
# Check to see if we got list of assets to filter on
if params[:ids]
#Checks to see if the id list is already an array. Converts a string to
# an array if necessary.
if params[:ids].is_a?(Array)
@id_filter_list = params[:ids]
else
@id_filter_list = params[:ids].split("|")
end
else
@id_filter_list = []
end
# Check to see if we got spatial filter. This session variable is managed
# by the spatial_filter method
@spatial_filter = session[:spatial_filter]
# Check to see if we got a different format to render
if params[:format]
@fmt = params[:format]
else
@fmt = 'html'
end
# Check to see if search for early disposition proposed assets only
if params[:early_disposition] == '1'
@early_disposition = true
end
if params[:transferred_assets] == '1'
@transferred_assets = true
end
# If the asset type is not set we default to the asset base class
if @id_filter_list.present? or (@asset_type == 0)
# THIS WILL NO LONGER WORK
# asset base class name should really be seed to pull typed asset class
# base class here is just Asset or the new TransamAsset
@asset_class_name = 'TransamAsset'
elsif @asset_subtype > 0
# we have an asset subtype so get it and get the asset type from it. We also set the filter form
# to the name of the selected subtype
subtype = AssetSubtype.find(@asset_subtype)
@asset_type = subtype.asset_type.id
@asset_class_name = subtype.asset_type.class_name
@filter = subtype.name
else
asset_type = AssetType.find(@asset_type)
@asset_class_name = asset_type.class_name
end
@view = "#{@asset_class_name.underscore}_index"
Rails.logger.debug "@fmt = #{@fmt}"
Rails.logger.debug "@asset_type = #{@asset_type}"
Rails.logger.debug "@asset_subtype = #{@asset_subtype}"
Rails.logger.debug "@asset_class_name = #{@asset_class_name}"
Rails.logger.debug "@view = #{@view}"
Rails.logger.debug "@view = #{@fta_asset_class_id}"
end
def add_index_breadcrumbs
# placeholder
end
def add_breadcrumbs
add_breadcrumb "#{@asset.asset_type.name}".pluralize, inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
add_breadcrumb "#{@asset.asset_type.name.singularize} Profile"
end
# returns a list of assets for an index view (index, map) based on user selections. Called after
# a call to set_view_vars
def get_assets
# Create a class instance of the asset type which can be used to perform
# active record queries
klass = Object.const_get @asset_class_name
@asset_class = klass.name
# here we build the query one clause at a time based on the input params
clauses = {}
unless @org_id == 0
clauses[:organization_id] = @org_id
else
clauses[:organization_id] = @organization_list
end
unless @manufacturer_id == 0
clauses[:manufacturer_id] = @manufacturer_id
end
if @asset_class_name.constantize.new.respond_to? :disposition_date
if @disposition_year.blank?
clauses[:disposition_date] = nil
else
clauses['YEAR(disposition_date)'] = @disposition_year
end
end
unless @search_text.blank?
search_clauses = []
search_values = []
# get the list of searchable fields from the asset class
searchable_fields = klass.new.searchable_fields
# create an OR query for each field
query_str = []
first = true
# parameterize the search based on the selected search parameter
search_value = get_search_value(@search_text, @search_param)
# Construct the query based on the searchable fields for the model
searchable_fields.each do |field|
if first
first = false
query_str << '('
else
query_str << ' OR '
end
query_str << field
query_str << ' LIKE ? '
# add the value in for this sub clause
search_values << search_value
end
query_str << ')' unless searchable_fields.empty?
search_clauses << [query_str.join]
klass = klass.where(search_clauses.join(' AND '), *search_values)
end
unless @id_filter_list.blank?
clauses[:object_key] = @id_filter_list
end
unless @asset_subtype == 0
clauses[:asset_subtype_id] = [@asset_subtype]
end
unless @asset_type == 0
clauses[:asset_types] = {id: @asset_type}
end
if klass.respond_to? :in_transfer
klass = @transferred_assets ? klass.in_transfer : klass.not_in_transfer
end
unless @spatial_filter.blank?
gis_service = GisService.new
search_box = gis_service.search_box_from_bbox(@spatial_filter)
wkt = "#{search_box.as_wkt}"
klass = klass.where('MBRContains(GeomFromText("' + wkt + '"), geometry) = ?', 1)
end
# See if we got an asset group. If we did then we can
# use the asset group collection to filter on instead of creating
# a new query. This is kind of a hack but works!
unless @asset_group.blank?
asset_group = AssetGroup.find_by_object_key(@asset_group)
klass = asset_group.assets unless asset_group.nil?
end
# Search for only early dispostion proposed assets if flag is on
if @early_disposition
klass = klass.joins(:early_disposition_requests).where(asset_events: {state: 'new'})
end
# send the query
if @asset_class_name == 'TransamAsset'
klass = klass.includes({asset_subtype: :asset_type},:organization, :manufacturer)
else
join_relations = klass.actable_hierarchy
join_relations[join_relations.key(:transam_asset)] = {transam_asset: [{asset_subtype: :asset_type},:organization, :manufacturer]}
klass = klass.includes(join_relations)
end
klass.where(clauses)
end
# stores the just-created list of asset ids in the session
def cache_assets(assets)
list = []
unless assets.nil?
assets.each do |a|
list << a.object_key
end
end
cache_objects(ASSET_KEY_LIST_VAR, list)
end
#------------------------------------------------------------------------------
#
# Private Methods
#
#------------------------------------------------------------------------------
private
# Never trust parameters from the scary internet, only allow the white list through.
def form_params
params.require(:asset).permit(asset_allowable_params)
end
def new_form_params(asset)
params.require(:asset).permit(asset.allowable_params)
end
#
# Overrides the utility method in the base class
#
def get_selected_asset(convert=true)
selected_asset = Rails.application.config.asset_base_class_name.constantize.find_by(:organization_id => @organization_list, :object_key => params[:id]) unless params[:id].blank?
if convert
asset = Rails.application.config.asset_base_class_name.constantize.get_typed_asset(selected_asset)
else
asset = selected_asset
end
return asset
end
def reformat_date(date_str)
# See if it's already in iso8601 format first
return date_str if date_str.match(/\A\d{4}-\d{2}-\d{2}\z/)
Date.strptime(date_str, '%m/%d/%Y').strftime('%Y-%m-%d')
end
def reformat_date_fields
params[:asset][:purchase_date] = reformat_date(params[:asset][:purchase_date]) unless params[:asset][:purchase_date].blank?
params[:asset][:in_service_date] = reformat_date(params[:asset][:in_service_date]) unless params[:asset][:in_service_date].blank?
params[:asset][:warranty_date] = reformat_date(params[:asset][:warranty_date]) unless params[:asset][:warranty_date].blank?
end
# Manage the vendor_id/vendor_name
def update_vendor_param
# If the vendor_name is set in the params then the model needs to override the
# vendor_id param. If both the vendor_id and vendor_name are unset then the
# model needs to remove the vendor. If the vendor_id is set, leave it alone
if params[:asset][:vendor_name].present?
vendor = Vendor.find_or_create_by(:name => params[:asset][:vendor_name], :organization => @organization)
params[:asset][:vendor_id] = vendor.id
elsif params[:asset][:vendor_id].blank? and params[:asset][:vendor_name].blank?
params[:asset][:vendor_id] = nil
end
# vendor_name has served its purpose (find/set vendor_id), so remove from hash
params[:asset].delete :vendor_name
end
end
Fixing the table views and the facility and component creation.
class AssetsController < AssetAwareController
add_breadcrumb "Home", :root_path
# Set the view variabless form the params @asset_type, @asset_subtype, @search_text, @spatial_filter, @view
before_action :set_view_vars, :only => [:index, :map]
# set the @asset variable before any actions are invoked
before_action :get_asset, :only => [:tag, :show, :edit, :copy, :update, :destroy, :summary_info, :add_to_group, :remove_from_group, :popup, :get_dependents, :add_dependents, :get_dependent_subform, :get_subheader]
before_action :reformat_date_fields, :only => [:create, :update]
# Update the vendor_id param if the user is using the vendor_name parameter
before_action :update_vendor_param, :only => [:create, :update]
# Lock down the controller
authorize_resource only: [:index, :show, :new, :create, :edit, :update, :destroy]
STRING_TOKENIZER = '|'
# Session Variables
INDEX_KEY_LIST_VAR = "asset_key_list_cache_var"
# Returns a JSON array of matching asset subtypes based on a typeahead name or description
def filter(klass=Rails.application.config.asset_base_class_name.constantize)
query = params[:query]
query_str = "%" + query + "%"
Rails.logger.debug query_str
matches = []
assets = klass.where(organization_id: current_user.viewable_organization_ids)
.where(params[:search_params])
.where("(asset_tag LIKE ? OR object_key LIKE ? OR description LIKE ?)", query_str, query_str, query_str)
assets.each do |asset|
matches << {
"id" => asset.object_key,
"name" => "#{asset.to_s}: #{asset.description}"
}
end
respond_to do |format|
format.js { render :json => matches.to_json }
format.json { render :json => matches.to_json }
end
end
# Adds the asset to the specified group
def add_to_group
asset_group = AssetGroup.find_by_object_key(params[:asset_group])
if asset_group.nil?
notify_user(:alert, "Can't find the asset group selected.")
else
if @asset.asset_groups.exists? asset_group.id
notify_user(:alert, "Asset #{@asset.name} is already a member of '#{asset_group}'.")
else
@asset.asset_groups << asset_group
notify_user(:notice, "Asset #{@asset.name} was added to '#{asset_group}'.")
end
end
# Always display the last view
redirect_back(fallback_location: root_path)
end
# Removes the asset from the specified group
def remove_from_group
asset_group = AssetGroup.find_by_object_key(params[:asset_group])
if asset_group.nil?
notify_user(:alert, "Can't find the asset group selected.")
else
if @asset.asset_groups.exists? asset_group.id
@asset.asset_groups.delete asset_group
notify_user(:notice, "Asset #{@asset.name} was removed from '#{asset_group}'.")
else
notify_user(:alert, "Asset #{@asset.name} is not a member of '#{asset_group}'.")
end
end
# Always display the last view
redirect_back(fallback_location: root_path)
end
# NOT USED
def parent
parent_asset = @organization.assets.find_by_object_key(params[:parent_key])
respond_to do |format|
format.js {render :partial => 'assets/asset_details', :locals => { :asset => parent_asset} }
end
end
def get_summary
asset_type_id = params[:asset_type_id]
if asset_type_id.blank?
results = ActiveRecord::Base.connection.exec_query(Rails.application.config.asset_base_class_name.constantize.operational.select('organization_id, asset_subtypes.asset_type_id, organizations.short_name AS org_short_name, asset_types.name AS subtype_name, COUNT(*) AS assets_count, SUM(purchase_cost) AS sum_purchase_cost').joins(:organization, asset_subtype: :asset_type).where(organization_id: @organization_list).group(:organization_id, :asset_type_id).to_sql)
level = 'type'
else
asset_subtype_ids = AssetType.includes(:asset_subtypes).find_by(id: asset_type_id).asset_subtypes.ids
results = ActiveRecord::Base.connection.exec_query(Rails.application.config.asset_base_class_name.constantize.operational.select('organization_id, asset_subtype_id, organizations.short_name AS org_short_name, asset_subtypes.name AS subtype_name, COUNT(*) AS assets_count, SUM(purchase_cost) AS sum_purchase_cost').joins(:organization, :asset_subtype).where(organization_id: (params[:org] || @organization_list), asset_subtype_id: asset_subtype_ids).group(:organization_id, :asset_subtype_id).to_sql)
level = 'subtype'
end
respond_to do |format|
format.js {
if params[:org]
render partial: 'dashboards/assets_widget_table_rows', locals: {results: results, level: level }
else
render partial: 'dashboards/assets_widget_table', locals: {results: results, level: level }
end
}
end
end
# renders either a table or map view of a selected list of assets
#
# Parameters include asset_type, asset_subtype, id_list, box, or search_text
#
def index
add_index_breadcrumbs
# disable any spatial filters for this view
@spatial_filter = nil
@assets = get_assets
terminal_crumb = nil
if @early_disposition
terminal_crumb = "Early disposition proposed"
elsif @transferred_assets
terminal_crumb = "Transferred Assets"
elsif @asset_group.present?
asset_group = AssetGroup.find_by_object_key(@asset_group)
terminal_crumb = asset_group
elsif @search_text.present?
terminal_crumb = "Search '#{@search_text}'"
elsif @asset_subtype > 0
subtype = AssetSubtype.find(@asset_subtype)
add_breadcrumb subtype.asset_type.name.pluralize(2), inventory_index_path(:asset_type => subtype.asset_type, :asset_subtype => 0)
terminal_crumb = subtype.name
elsif @manufacturer_id > 0
add_breadcrumb "Manufacturers", manufacturers_path
manufacturer = Manufacturer.find(@manufacturer_id)
terminal_crumb = manufacturer.name
elsif @asset_type > 0
asset_type = AssetType.find(@asset_type)
terminal_crumb = asset_type.name.pluralize(2)
end
add_breadcrumb terminal_crumb if terminal_crumb
# check that an order param was provided otherwise use asset_tag as the default
# params[:sort] ||= 'transam_assets.asset_tag'
#
# # fix sorting on organizations to be alphabetical not by index
# params[:sort] = 'organizations.short_name' if params[:sort] == 'organization_id'
#
respond_to do |format|
format.html
format.js
format.json {
render :json => {
:total => @assets.count,
:rows => index_rows_as_json
}
}
format.xls do
filename = (terminal_crumb || "unknown").gsub(" ", "_").underscore
response.headers['Content-Disposition'] = "attachment; filename=#{filename}.xls"
end
format.xlsx do
filename = (terminal_crumb || "unknown").gsub(" ", "_").underscore
response.headers['Content-Disposition'] = "attachment; filename=#{filename}.xlsx"
end
end
end
def index_rows_as_json
multi_sort = params[:multiSort]
unless (multi_sort.nil?)
sorting_string = ""
multi_sort.each { |x|
sorting_string = sorting_string + "#{x[0]}: :#{x[1]}"
}
else
sorting_string = "#{params[:sort]} #{params[:order]}"
end
@assets.order(sorting_string).limit(params[:limit]).offset(params[:offset]).as_json(user: current_user, include_early_disposition: @early_disposition)
end
def fire_asset_event_workflow_events
event_name = params[:event]
asset_event_type = AssetEventType.find_by(id: params[:asset_event_type_id])
if asset_event_type && params[:targets]
notification_enabled = asset_event_type.class_name.constantize.workflow_notification_enabled?
events = asset_event_type.class_name.constantize.where(object_key: params[:targets].split(','))
failed = 0
events.each do |evt|
if evt.fire_state_event(event_name)
workflow_event = WorkflowEvent.new
workflow_event.creator = current_user
workflow_event.accountable = evt
workflow_event.event_type = event_name
workflow_event.save
if notification_enabled
evt.notify_event_by(current_user, event_name)
end
else
failed += 1
end
end
end
redirect_back(fallback_location: root_path)
end
# makes a copy of an asset and renders it. The new asset is not saved
# and has any identifying chracteristics identified as CLEANSABLE_FIELDS are nilled
def copy
# add_breadcrumb "#{@asset.asset_type.name}".pluralize(2), inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
# add_breadcrumb "#{@asset.asset_subtype.name}", inventory_index_path(:asset_subtype => @asset.asset_subtype)
# add_breadcrumb @asset.asset_tag, inventory_path(@asset)
# add_breadcrumb "Copy"
# create a copy of the asset and null out all the fields that are identified as cleansable
new_asset = @asset.copy(true)
notify_user(:notice, "Complete the master record to copy Asset #{@asset.to_s}.")
@asset = new_asset
# render the edit view
respond_to do |format|
format.html { render :action => "edit" }
format.json { render :json => @asset }
end
end
# not used
def summary_info
respond_to do |format|
format.js # show.html.erb
format.json { render :json => @asset }
end
end
def show
add_breadcrumbs
# add_breadcrumb "#{@asset.asset_subtype.name}", inventory_index_path(:asset_subtype => @asset.asset_subtype)
# add_breadcrumb @asset.asset_tag, inventory_path(@asset)
# Set the asset class view var. This can be used to determine which view components
# are rendered, for example, which tabs and action items the user sees
@asset_class_name = @asset.class.name.underscore
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @asset }
end
end
def edit
# add_breadcrumb "#{@asset.asset_type.name}".pluralize(2), inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
# add_breadcrumb "#{@asset.asset_subtype.name}", inventory_index_path(:asset_subtype => @asset.asset_subtype)
# When editing a newly transferred asset this link is invalid so we don't want to show it.
if @asset.asset_tag == @asset.object_key
@asset.asset_tag = nil
else
add_breadcrumb @asset.asset_tag, inventory_path(@asset)
end
add_breadcrumb "Update master record", edit_inventory_path(@asset)
end
def update
#add_breadcrumb "#{@asset.asset_type.name}".pluralize(2), inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
#add_breadcrumb @asset.name, inventory_path(@asset)
#add_breadcrumb "Modify", edit_inventory_path(@asset)
# transfered assets need to remove notification if exists
# if @asset.asset_tag == @asset.object_key
# notification = Notification.where("text = 'A new asset has been transferred to you. Please update the asset.' AND link LIKE ?" , "%#{@asset.object_key}%").first
# notification.update(active: false) if notification.present?
# end
respond_to do |format|
if @asset.update_attributes(new_form_params(@asset))
# If the asset was successfully updated, schedule update the condition and disposition asynchronously
#Delayed::Job.enqueue AssetUpdateJob.new(@asset.asset.object_key), :priority => 0
# See if this asset has any dependents that use its spatial reference
if @asset.geometry and @asset.occupants.count > 0
# schedule an update to the spatial references of the dependent assets
Delayed::Job.enqueue AssetDependentSpatialReferenceUpdateJob.new(@asset.object_key), :priority => 0
end
notify_user(:notice, "Asset #{@asset.to_s} was successfully updated.")
format.html { redirect_to inventory_url(@asset) }
format.js { notify_user(:notice, "#{@asset} successfully updated.") }
format.json { head :no_content }
else
format.html { render :action => "edit" }
format.js { render :action => "edit" }
format.json { render :json => @asset.errors, :status => :unprocessable_entity }
end
end
end
def get_subheader
respond_to do |format|
format.js
end
end
def get_dependents
respond_to do |format|
format.js
format.json { render :json => @asset.to_json }
end
end
def add_dependents
params[:asset][:dependents_attributes].each do |key, val|
unless val[:id]
dependent = TransamAsset.find_by(object_key: val[:object_key])
if dependent
@asset.dependents << dependent
@asset.update_condition # might need to change to run full AssetUpdateJob
end
end
end
redirect_back(fallback_location: root_path)
end
def get_dependent_subform
@dependent_subform_target_model = params[:dependent_subform_target_model]
@dependent = @dependent_subform_target_model.constantize.find_by(object_key: params[:dependent_object_key])
@dependent_subform_target = params[:dependent_subform_target]
@dependent_subform_view = params[:dependent_subform_view]
respond_to do |format|
format.js
end
end
def new_asset
authorize! :new, Rails.application.config.asset_base_class_name.constantize
add_breadcrumb "Add Asset", new_asset_inventory_index_path
end
def new
asset_class_name = params[:asset_seed_class_name] || 'AssetType'
@asset_class_instance = asset_class_name.constantize.find_by(id: params[:asset_base_class_id])
if @asset_class_instance.nil?
notify_user(:alert, "Asset class '#{params[:asset_base_class_id]}' not found. Can't create new asset!")
redirect_to(root_url)
return
end
#add_breadcrumb "#{asset_subtype.asset_type.name}".pluralize(2), inventory_index_path(:asset_type => asset_subtype.asset_type)
#add_breadcrumb "#{asset_subtype.name}", inventory_index_path(:asset_subtype => asset_subtype)
#add_breadcrumb "New", new_inventory_path(asset_subtype)
# Use the asset class to create an asset of the correct type
@asset = Rails.application.config.asset_base_class_name.constantize.new_asset(@asset_class_instance, params)
# See if the user selected an org to associate the asset with
if params[:organization_id].present?
@asset.organization = Organization.find(params[:organization_id])
else
@asset.organization_id = @organization_list.first
end
if params[:parent_id].present?
@asset.parent_id = params[:parent_id].to_i
end
respond_to do |format|
format.html # new.html.haml this had been an erb and is now an haml the change should just be caught
format.json { render :json => @asset }
end
end
def create
asset_class_name = params[:asset_seed_class_name] || 'AssetType'
if asset_class_name == 'AssetType' && params[:asset][:asset_type_id].blank?
asset_subtype = AssetSubtype.find_by(id: params[:asset][:asset_subtype_id])
asset_class_instance = asset_class_name.constantize.find_by(id: asset_subtype.try(:asset_type_id))
else
asset_class_instance = asset_class_name.constantize.find_by(id: params[:asset][asset_class_name.foreign_key.to_sym])
end
if asset_class_instance.nil?
notify_user(:alert, "Asset class '#{params[:asset][asset_class_name.foreign_key.to_sym]}' not found. Can't create new asset!")
redirect_to(root_url)
return
end
# Use the asset class to create an asset of the correct type
@asset = Rails.application.config.asset_base_class_name.constantize.new_asset(asset_class_instance, params)
@asset.attributes = new_form_params(@asset)
# If the asset does not have an org already defined, set to the default for
# the user
if @asset.organization.blank?
@asset.organization_id = @organization_list.first
end
#@asset.creator = current_user
#@asset.updator = current_user
#Rails.logger.debug @asset.inspect
# add_breadcrumb "#{asset_type.name}".pluralize(2), inventory_index_path(:asset_type => asset_subtype.asset_type)
# add_breadcrumb "#{asset_subtype.name}", inventory_index_path(:asset_subtype => asset_subtype)
# add_breadcrumb "New", new_inventory_path(asset_subtype)
respond_to do |format|
if @asset.save
# If the asset was successfully saved, schedule update the condition and disposition asynchronously
#Delayed::Job.enqueue AssetUpdateJob.new(@asset.object_key), :priority => 0
notify_user(:notice, "Asset #{@asset.to_s} was successfully created.")
format.html { redirect_to inventory_url(@asset) }
format.json { render :json => @asset, :status => :created, :location => @asset }
else
#Rails.logger.debug @asset.errors.inspect
format.html { render :action => "new" }
format.json { render :json => @asset.errors, :status => :unprocessable_entity }
end
end
end
# called when the user wants to delete an asset
def destroy
# make sure we can find the asset we are supposed to be removing and that it belongs to us.
if @asset.nil?
redirect_to(root_path, :flash => { :alert => t(:error_404) })
return
end
# Destroy this asset, call backs to remove each associated object will be made
@asset.destroy
notify_user(:notice, "Asset was successfully removed.")
respond_to do |format|
format.html { redirect_to(inventory_index_url(@asset.class.asset_seed_class_name.foreign_key => @asset.send(@asset.class.asset_seed_class_name.foreign_key))) }
format.json { head :no_content }
end
end
# Adds the assets to the user's tag list or removes it if the asset
# is already tagged. called by ajax so no response is rendered
# NOT USED
def tag
if @asset.tagged? current_user
@asset.users.delete current_user
else
@asset.tag current_user
end
# No response needed
render :nothing => true
end
# Called via AJAX to get dynamic content via AJAX
# NOT USED (I think)
def popup
str = ""
if @asset
str = render_to_string(:partial => "popup", :locals => { :asset => @asset })
end
render json: str.to_json
end
#------------------------------------------------------------------------------
#
# Protected Methods
#
#------------------------------------------------------------------------------
protected
#
# Sets the view variables. This is used to set up the vars before a call to get_assets
# @asset_type
# @asset_subtype
# @search_text
# @id_filter_list
# @spatial_filter
# @fmt
# @view
# @asset_class_name
# @filter
#
def set_view_vars
# Check to see if we got an asset group to sub select on. This occurs when the user
# selects an asset group from the menu selector
if params[:asset_group].nil? or params[:asset_group] == '0'
@asset_group = ''
else
@asset_group = params[:asset_group]
end
# Check to see if we got an asset type to sub select on. This occurs when the user
# selects an asset type from the drop down
if params[:asset_type].nil?
@asset_type = 0
else
@asset_type = params[:asset_type].to_i
end
# Check to see if we got an asset subtype to sub select on. This will happen if an asset type is selected
# already and the user selected a subtype from the dropdown.
if params[:asset_subtype].nil?
@asset_subtype = 0
else
@asset_subtype = params[:asset_subtype].to_i
end
# Check to see if we got an organization to sub select on.
if params[:org_id].nil?
@org_id = 0
else
@org_id = params[:org_id].to_i
end
# Check to see if we got a manufacturer to sub select on.
if params[:manufacturer_id].nil?
@manufacturer_id = 0
else
@manufacturer_id = params[:manufacturer_id].to_i
end
# Check to see if we got a service status to sub select on.
if params[:service_status].nil?
@service_status = 0
else
@service_status = params[:service_status].to_i
end
# Check to see if we got a search text and search param to filter on
if params[:search_text].nil?
# See if one is stored in the session
@search_text = session[:search_text].blank? ? nil : session[:search_text]
@search_param = session[:search_param].blank? ? nil : session[:search_param]
else
@search_text = params[:search_text]
@search_param = params[:search_param]
end
# Check to see if we got list of assets to filter on
if params[:ids]
#Checks to see if the id list is already an array. Converts a string to
# an array if necessary.
if params[:ids].is_a?(Array)
@id_filter_list = params[:ids]
else
@id_filter_list = params[:ids].split("|")
end
else
@id_filter_list = []
end
# Check to see if we got spatial filter. This session variable is managed
# by the spatial_filter method
@spatial_filter = session[:spatial_filter]
# Check to see if we got a different format to render
if params[:format]
@fmt = params[:format]
else
@fmt = 'html'
end
# Check to see if search for early disposition proposed assets only
if params[:early_disposition] == '1'
@early_disposition = true
end
if params[:transferred_assets] == '1'
@transferred_assets = true
end
# If the asset type is not set we default to the asset base class
if @id_filter_list.present? or (@asset_type == 0)
# THIS WILL NO LONGER WORK
# asset base class name should really be seed to pull typed asset class
# base class here is just Asset or the new TransamAsset
@asset_class_name = 'TransamAsset'
elsif @asset_subtype > 0
# we have an asset subtype so get it and get the asset type from it. We also set the filter form
# to the name of the selected subtype
subtype = AssetSubtype.find(@asset_subtype)
@asset_type = subtype.asset_type.id
@asset_class_name = subtype.asset_type.class_name
@filter = subtype.name
else
asset_type = AssetType.find(@asset_type)
@asset_class_name = asset_type.class_name
end
@view = "#{@asset_class_name.underscore}_index"
Rails.logger.debug "@fmt = #{@fmt}"
Rails.logger.debug "@asset_type = #{@asset_type}"
Rails.logger.debug "@asset_subtype = #{@asset_subtype}"
Rails.logger.debug "@asset_class_name = #{@asset_class_name}"
Rails.logger.debug "@view = #{@view}"
Rails.logger.debug "@view = #{@fta_asset_class_id}"
end
def add_index_breadcrumbs
# placeholder
end
def add_breadcrumbs
add_breadcrumb "#{@asset.asset_type.name}".pluralize, inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
add_breadcrumb "#{@asset.asset_type.name.singularize} Profile"
end
# returns a list of assets for an index view (index, map) based on user selections. Called after
# a call to set_view_vars
def get_assets
# Create a class instance of the asset type which can be used to perform
# active record queries
klass = Object.const_get @asset_class_name
@asset_class = klass.name
# here we build the query one clause at a time based on the input params
clauses = {}
unless @org_id == 0
clauses[:organization_id] = @org_id
else
clauses[:organization_id] = @organization_list
end
unless @manufacturer_id == 0
clauses[:manufacturer_id] = @manufacturer_id
end
if @asset_class_name.constantize.new.respond_to? :disposition_date
if @disposition_year.blank?
clauses[:disposition_date] = nil
else
clauses['YEAR(disposition_date)'] = @disposition_year
end
end
unless @search_text.blank?
search_clauses = []
search_values = []
# get the list of searchable fields from the asset class
searchable_fields = klass.new.searchable_fields
# create an OR query for each field
query_str = []
first = true
# parameterize the search based on the selected search parameter
search_value = get_search_value(@search_text, @search_param)
# Construct the query based on the searchable fields for the model
searchable_fields.each do |field|
if first
first = false
query_str << '('
else
query_str << ' OR '
end
query_str << field
query_str << ' LIKE ? '
# add the value in for this sub clause
search_values << search_value
end
query_str << ')' unless searchable_fields.empty?
search_clauses << [query_str.join]
klass = klass.where(search_clauses.join(' AND '), *search_values)
end
unless @id_filter_list.blank?
clauses[:object_key] = @id_filter_list
end
unless @asset_subtype == 0
clauses[:asset_subtype_id] = [@asset_subtype]
end
unless @asset_type == 0
clauses[:asset_types] = {id: @asset_type}
end
if klass.respond_to? :in_transfer
klass = @transferred_assets ? klass.in_transfer : klass.not_in_transfer
end
unless @spatial_filter.blank?
gis_service = GisService.new
search_box = gis_service.search_box_from_bbox(@spatial_filter)
wkt = "#{search_box.as_wkt}"
klass = klass.where('MBRContains(GeomFromText("' + wkt + '"), geometry) = ?', 1)
end
# See if we got an asset group. If we did then we can
# use the asset group collection to filter on instead of creating
# a new query. This is kind of a hack but works!
unless @asset_group.blank?
asset_group = AssetGroup.find_by_object_key(@asset_group)
klass = asset_group.assets unless asset_group.nil?
end
# Search for only early dispostion proposed assets if flag is on
if @early_disposition
klass = klass.joins(:early_disposition_requests).where(asset_events: {state: 'new'})
end
# send the query
if @asset_class_name == 'TransamAsset'
klass = klass.includes({asset_subtype: :asset_type},:organization, :manufacturer)
else
join_relations = klass.actable_hierarchy
join_relations[join_relations.key(:transam_asset)] = {transam_asset: [{asset_subtype: :asset_type},:organization, :manufacturer]}
klass = klass.includes(join_relations)
end
klass.where(clauses)
end
# stores the just-created list of asset ids in the session
def cache_assets(assets)
list = []
unless assets.nil?
assets.each do |a|
list << a.object_key
end
end
cache_objects(ASSET_KEY_LIST_VAR, list)
end
#------------------------------------------------------------------------------
#
# Private Methods
#
#------------------------------------------------------------------------------
private
# Never trust parameters from the scary internet, only allow the white list through.
def form_params
params.require(:asset).permit(asset_allowable_params)
end
def new_form_params(asset)
params.require(:asset).permit(asset.allowable_params)
end
#
# Overrides the utility method in the base class
#
def get_selected_asset(convert=true)
selected_asset = Rails.application.config.asset_base_class_name.constantize.find_by(:organization_id => @organization_list, :object_key => params[:id]) unless params[:id].blank?
if convert
asset = Rails.application.config.asset_base_class_name.constantize.get_typed_asset(selected_asset)
else
asset = selected_asset
end
return asset
end
def reformat_date(date_str)
# See if it's already in iso8601 format first
return date_str if date_str.match(/\A\d{4}-\d{2}-\d{2}\z/)
Date.strptime(date_str, '%m/%d/%Y').strftime('%Y-%m-%d')
end
def reformat_date_fields
params[:asset][:purchase_date] = reformat_date(params[:asset][:purchase_date]) unless params[:asset][:purchase_date].blank?
params[:asset][:in_service_date] = reformat_date(params[:asset][:in_service_date]) unless params[:asset][:in_service_date].blank?
params[:asset][:warranty_date] = reformat_date(params[:asset][:warranty_date]) unless params[:asset][:warranty_date].blank?
end
# Manage the vendor_id/vendor_name
def update_vendor_param
# If the vendor_name is set in the params then the model needs to override the
# vendor_id param. If both the vendor_id and vendor_name are unset then the
# model needs to remove the vendor. If the vendor_id is set, leave it alone
if params[:asset][:vendor_name].present?
vendor = Vendor.find_or_create_by(:name => params[:asset][:vendor_name], :organization => @organization)
params[:asset][:vendor_id] = vendor.id
elsif params[:asset][:vendor_id].blank? and params[:asset][:vendor_name].blank?
params[:asset][:vendor_id] = nil
end
# vendor_name has served its purpose (find/set vendor_id), so remove from hash
params[:asset].delete :vendor_name
end
end
|
# Sequreisp - Copyright 2010, 2011 Luciano Ruete
#
# This file is part of Sequreisp.
#
# Sequreisp is free software: you can redistribute it and/or modify
# it under the terms of the GNU Afero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Sequreisp is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Afero General Public License for more details.
#
# You should have received a copy of the GNU Afero General Public License
# along with Sequreisp. If not, see <http://www.gnu.org/licenses/>.
class AuditsController < ApplicationController
before_filter :require_user
permissions :audits
def index
params[:search][:order] ||= 'descend_by_created_at'
@search = Audit.search(params[:search])
if params[:search] && !params[:search][:auditable_id_equals].blank?
#search by id
@audits = Audit.paginate :page => params[:page], :per_page => 10,
:conditions => {
:auditable_type => params[:search][:auditable_type_is],
:auditable_id => params[:search][:auditable_id_equals]
}
else
@audits = @search.paginate(:page => params[:page], :per_page => 10)
end
@models = Audit.all(:select => "DISTINCT auditable_type", :order => "auditable_type ASC").map(&:auditable_type)
end
end
Fixed bug in audits search.
# Sequreisp - Copyright 2010, 2011 Luciano Ruete
#
# This file is part of Sequreisp.
#
# Sequreisp is free software: you can redistribute it and/or modify
# it under the terms of the GNU Afero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Sequreisp is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Afero General Public License for more details.
#
# You should have received a copy of the GNU Afero General Public License
# along with Sequreisp. If not, see <http://www.gnu.org/licenses/>.
class AuditsController < ApplicationController
before_filter :require_user
permissions :audits
def index
params[:search] ||= {}
@search = Audit.search(params[:search])
if !params[:search][:auditable_id_equals].blank?
#search by id
@audits = Audit.paginate :page => params[:page], :per_page => 10,
:conditions => {
:auditable_type => params[:search][:auditable_type_is],
:auditable_id => params[:search][:auditable_id_equals]
}
else
@audits = @search.paginate(:page => params[:page], :per_page => 10, :order => 'created_at DESC')
end
@models = Audit.all(:select => "DISTINCT auditable_type", :order => "auditable_type ASC").map(&:auditable_type)
end
end
|
class CitiesController < ApplicationController
def create
@user = User.find(session[:user_id]) if session[:user_id]
# binding.pry
@city = City.find_or_create_by(lat: city_params[:lat], lon: city_params[:lon]) do |city|
city.name = city_params[:name]
# binding.pry
city.bigger_thing = city_params[:bigger_thing]
# binding.pry
city.country = city_params[:country]
# binding.pry
end
if !@user
# binding.pry
render json: @city
else
unless @user.cities.find_by(lat: city_params[:lat], lon: city_params[:lon])
# binding.pry
@user.cities << @city if @user
del_city_id = city_params[:lastClock].to_i
CityUser.find_by(user_id: @user.id, city_id: del_city_id).destroy if @user
render json: @city
else
render json: "this city already exists".to_json
end
end
end
def get_city
@user = User.find(session[:user_id]) if session[:user_id]
if @user != nil
@user_info = {
articles: user_articles(current_user),
photos: user_photos(current_user),
tweets: user_tweets(current_user)
}
else @user_info = []
end
@city = City.find(params[:id])
response = {
city: @city,
user_vars: @user_info
}
render json: response.to_json
end
private
def city_params
params.require(:city).permit(:name, :id, :bigger_thing, :lat, :lon, :country, :lastClock)
end
end
added into city controller to create new user when city added if not logged in.
class CitiesController < ApplicationController
def create
@user = User.find(session[:user_id]) if session[:user_id]
# binding.pry
@city = City.find_or_create_by(lat: city_params[:lat], lon: city_params[:lon]) do |city|
city.name = city_params[:name]
# binding.pry
city.bigger_thing = city_params[:bigger_thing]
# binding.pry
city.country = city_params[:country]
# binding.pry
end
if !@user
# binding.pry
@user = User.create (name: 'Guest', provider: 'anon', uid: session[:user_id], image: 'https://origin.ih.constantcontact.com/fs197/1110193228531/img/301.jpg?a=1115291249439')
render json: @city
end
unless @user.cities.find_by(lat: city_params[:lat], lon: city_params[:lon])
# binding.pry
@user.cities << @city if @user
del_city_id = city_params[:lastClock].to_i
CityUser.find_by(user_id: @user.id, city_id: del_city_id).destroy if @user
render json: @city
else
render json: "this city already exists".to_json
end
end
def get_city
@user = User.find(session[:user_id]) if session[:user_id]
if @user != nil
@user_info = {
articles: user_articles(current_user),
photos: user_photos(current_user),
tweets: user_tweets(current_user)
}
else @user_info = []
end
@city = City.find(params[:id])
response = {
city: @city,
user_vars: @user_info
}
render json: response.to_json
end
private
def city_params
params.require(:city).permit(:name, :id, :bigger_thing, :lat, :lon, :country, :lastClock)
end
end
|
require 'app/controllers/app_controller'
require 'app/models/dispute'
require 'active_support/core_ext/object/to_query'
require 'sinatra/twitter-bootstrap'
require 'slim'
require 'rest'
module Pod
module TrunkApp
class ClaimsController < HTMLController
configure do
set :views, settings.root + '/app/views/claims'
end
configure :development do
register Sinatra::Reloader
end
# --- Claims --------------------------------------------------------------------------------
get '/new' do
@owner = Owner.new
@pods = []
slim :'new'
end
post '/' do
find_owner
find_pods
if @owner.valid? && valid_pods?
change_ownership
if all_pods_already_claimed?
query = {
:claimer_email => @owner.email,
:pods => @already_claimed_pods
}
redirect to("/disputes/new?#{query.to_query}")
else
query = {
:claimer_email => @owner.email,
:successfully_claimed => @successfully_claimed_pods,
:already_claimed => @already_claimed_pods
}
redirect to("/thanks?#{query.to_query}")
end
end
prepare_errors
slim :'new'
end
get '/thanks' do
slim :'thanks'
end
# --- Disputes ------------------------------------------------------------------------------
get '/disputes/new' do
@pods = params[:pods].map { |name| Pod.find(:name => name) }
slim :'disputes/new'
end
post '/disputes' do
claimer = Owner.find_by_email(params[:dispute][:claimer_email])
dispute = Dispute.create(:claimer => claimer, :message => params[:dispute][:message])
notify_slack_of_dispute(dispute)
redirect to('/disputes/thanks')
end
get '/disputes/thanks' do
slim :'disputes/thanks'
end
# --- Assets ------------------------------------------------------------------------------
get '/claims.css' do
scss :claims, :style => :expanded
end
private
def find_owner
owner_email, owner_name = params[:owner].values_at('email', 'name')
@owner = Owner.find_or_initialize_by_email_and_update_name(owner_email, owner_name)
end
def find_pods
@pods = []
@invalid_pods = []
unless params[:pods].blank?
params[:pods].map(&:strip).uniq.each do |pod_name|
next if pod_name.blank?
if pod = Pod.find(:name => pod_name)
@pods << pod
else
@invalid_pods << pod_name
end
end
end
end
def valid_pods?
!@pods.empty? && @invalid_pods.empty?
end
def all_pods_already_claimed?
@successfully_claimed_pods.empty? && !@already_claimed_pods.empty?
end
def prepare_errors
@errors = @owner.errors.full_messages.map { |message| "Owner #{message}." }
if !@invalid_pods.empty?
@errors << "Unknown #{'Pod'.pluralize(@invalid_pods.size)} #{@invalid_pods.to_sentence}."
elsif @pods.empty?
@errors << 'No Pods specified.'
end
end
def change_ownership
@successfully_claimed_pods = []
@already_claimed_pods = []
DB.test_safe_transaction do
@owner.save_changes(:raise_on_save_failure => true)
unclaimed_owner = Owner.unclaimed
@pods.each do |pod|
if pod.owners == [unclaimed_owner]
@owner.add_pod(pod)
pod.remove_owner(unclaimed_owner)
@successfully_claimed_pods << pod.name
else
@already_claimed_pods << pod.name
end
end
end
end
SLACK_DISPUTE_URL = 'https://cocoapods.slack.com/services/hooks/' \
"incoming-webhook?token=#{ENV['SLACK_DISPUTE_TOKEN']}"
def notify_slack_of_dispute(dispute)
link = "https://trunk.cocoapods.org/manage/disputes/#{dispute.id}"
REST.post(SLACK_DISPUTE_URL,
{
attachments: [{
fallback: "New dispute on trunk [Urgent]: <#{link}>",
pretext: "There's a new dispute on trunk [Urgent]: <#{link}>",
color: :warning,
fields: [{
title: 'Dispute by ' \
"#{dispute.claimer.name} (#{dispute.claimer.email})",
value: dispute.message,
short: false
}]
}]
}.to_json)
end
end
end
end
[Rubocop] Format notify_slack_of_dispute
require 'app/controllers/app_controller'
require 'app/models/dispute'
require 'active_support/core_ext/object/to_query'
require 'sinatra/twitter-bootstrap'
require 'slim'
require 'rest'
module Pod
module TrunkApp
class ClaimsController < HTMLController
configure do
set :views, settings.root + '/app/views/claims'
end
configure :development do
register Sinatra::Reloader
end
# --- Claims --------------------------------------------------------------------------------
get '/new' do
@owner = Owner.new
@pods = []
slim :'new'
end
post '/' do
find_owner
find_pods
if @owner.valid? && valid_pods?
change_ownership
if all_pods_already_claimed?
query = {
:claimer_email => @owner.email,
:pods => @already_claimed_pods
}
redirect to("/disputes/new?#{query.to_query}")
else
query = {
:claimer_email => @owner.email,
:successfully_claimed => @successfully_claimed_pods,
:already_claimed => @already_claimed_pods
}
redirect to("/thanks?#{query.to_query}")
end
end
prepare_errors
slim :'new'
end
get '/thanks' do
slim :'thanks'
end
# --- Disputes ------------------------------------------------------------------------------
get '/disputes/new' do
@pods = params[:pods].map { |name| Pod.find(:name => name) }
slim :'disputes/new'
end
post '/disputes' do
claimer = Owner.find_by_email(params[:dispute][:claimer_email])
dispute = Dispute.create(:claimer => claimer, :message => params[:dispute][:message])
notify_slack_of_dispute(dispute)
redirect to('/disputes/thanks')
end
get '/disputes/thanks' do
slim :'disputes/thanks'
end
# --- Assets ------------------------------------------------------------------------------
get '/claims.css' do
scss :claims, :style => :expanded
end
private
def find_owner
owner_email, owner_name = params[:owner].values_at('email', 'name')
@owner = Owner.find_or_initialize_by_email_and_update_name(owner_email, owner_name)
end
def find_pods
@pods = []
@invalid_pods = []
unless params[:pods].blank?
params[:pods].map(&:strip).uniq.each do |pod_name|
next if pod_name.blank?
if pod = Pod.find(:name => pod_name)
@pods << pod
else
@invalid_pods << pod_name
end
end
end
end
def valid_pods?
!@pods.empty? && @invalid_pods.empty?
end
def all_pods_already_claimed?
@successfully_claimed_pods.empty? && !@already_claimed_pods.empty?
end
def prepare_errors
@errors = @owner.errors.full_messages.map { |message| "Owner #{message}." }
if !@invalid_pods.empty?
@errors << "Unknown #{'Pod'.pluralize(@invalid_pods.size)} #{@invalid_pods.to_sentence}."
elsif @pods.empty?
@errors << 'No Pods specified.'
end
end
def change_ownership
@successfully_claimed_pods = []
@already_claimed_pods = []
DB.test_safe_transaction do
@owner.save_changes(:raise_on_save_failure => true)
unclaimed_owner = Owner.unclaimed
@pods.each do |pod|
if pod.owners == [unclaimed_owner]
@owner.add_pod(pod)
pod.remove_owner(unclaimed_owner)
@successfully_claimed_pods << pod.name
else
@already_claimed_pods << pod.name
end
end
end
end
SLACK_DISPUTE_URL = 'https://cocoapods.slack.com/services/hooks/' \
"incoming-webhook?token=#{ENV['SLACK_DISPUTE_TOKEN']}"
def notify_slack_of_dispute(dispute)
link = "https://trunk.cocoapods.org/manage/disputes/#{dispute.id}"
REST.post(SLACK_DISPUTE_URL,
{
:attachments => [{
:fallback => "New dispute on trunk [Urgent]: <#{link}>",
:pretext => "There's a new dispute on trunk [Urgent]: <#{link}>",
:color => :warning,
:fields => [{
:title => 'Dispute by ' \
"#{dispute.claimer.name} (#{dispute.claimer.email})",
:value => dispute.message,
:short => false
}]
}]
}.to_json)
end
end
end
end
|
# frozen_string_literal: true
class ErrorsController < ApplicationController
def not_found
redirect_path = nil
split = params[:any].split("/")
redirect_path = case split[0].downcase
when "programmes"
if split.size == 1
about_index_path
elsif "blue-carbon" == split[1]
Activity.programmes.where(title: "Blue Carbon").first
elsif "environmental-crime" == split[1]
Activity.programmes.
where(title: "Environmental Crime").first
elsif "green-economy" == split[1]
Activity.programmes.
where(title: "Ecosystems Economies and Sustainable Development").first
elsif "marine-coastal" == split[1]
Activity.programmes.
where(title: "Ocean Governance and Geological Resources").first
elsif "polar-mountain" == split[1]
Activity.programmes.
where(title: "Polar and Mountain Environments").first
elsif "soe-reporting" == split[1]
Activity.programmes.
where(title: "State of the Environment and Spatial Planning").first
end
when "publications"
if split.size < 3
publications_path
else
case params[:any]
when "publications/et/ep2/page/2501.aspx"
Publication.where(title: "The Environment and Poverty Times #2").first
when "publications/et/ep4/page/2632.aspx"
Publication.where(title: "Environment and Poverty Times #4").first
when "publications/et/ep4/page/2638.aspx"
Publication.where(title: "Environment and Poverty Times #4").first
when "publications/other/ipcc_tar/default.aspx", "/publications/other/ipcc_tar/default.aspx?src=/climate/ipcc_tar/", "/publications/other/ipcc_tar/default.aspx?src=/climate/ipcc_tar/wg1/index.htm"
Publication.where(title: "IPCC - Climate Change 2001: Synthesis Report").first
end
end
when "environmental_crime"
Activity.programmes.where(title: "Environmental Crime").first
when "bluecarbon"
Activity.programmes.where(title: "Blue Carbon").first
when "africa"
Activity.where(title: "Africa").first
when "comms"
Activity.where(title: "Communication and Outreach").first
when "eesd"
Activity.where(title: "Ecosystems Economies and Sustainable Development").first
when "oceangov"
Activity.programmes.where(title: "Ocean Governance and Geological Resources").first
when "polar"
Activity.programmes.where(title: "Polar and Mountain Environments").first
when "soe"
Activity.programmes.
where(title: "State of the Environment and Spatial Planning").first
when "blueforests"
Activity.where(title: "Blue Forests Project").first
when "mastrec"
"http://news.grida.no/mastrec"
when "bluesolutions"
Activity.where(title: "Blue Solutions").first
when "uarctic"
Activity.where(title: "University of the Arctic").first
when "crimfish"
Activity.find(275) # exists in production
when "graphicslib"
if split.size < 3
resources_path(media: "Graphic")
else
g = case split[2]
when "difference-between-eia-and-sea_5148"
Graphic.where(title: "Difference between EIA and SEA").first
when "major-river-basins-of-africa_1ac3"
Graphic.where(title: "Major river basins of Africa").first
when "mediterranean-sea-water-masses-vertical-distribution_d84b"
Graphic.where(title: "Mediterranean Sea water masses: vertical distribution").first
when "total-global-saltwater-and-freshwater-estimates_39f6"
Graphic.where(title: "Total global saltwater and freshwater estimates").first
when "trends-in-population-developed-and-developing-countries-1750-2050-estimates-and-projections_1616"
Graphic.where(title: "Trends in population, developed and developing countries, 1750-2050 (estimates and projections)").first
end
resource_path(g)
end
when "photolib"
resources_path(media: "Photo")
when "video"
resources_path(media: "Video")
end
if redirect_path
redirect_to redirect_path, :status => :moved_permanently,
notice: "You have been redirected to GRID Arendal's new website. If this is not the content you are looking for, please use our new search by clicking the magnifying glass on the top right hand side."
else
respond_to do |format|
format.html { render status: 404 }
end
end
rescue ActionController::UnknownFormat
render status: 404
end
end
Adds a few more redirects and updates note text
# frozen_string_literal: true
class ErrorsController < ApplicationController
def not_found
redirect_path = nil
split = params[:any].split("/")
redirect_path = case split[0].downcase
when "programmes"
if split.size == 1
about_index_path
elsif "blue-carbon" == split[1]
Activity.programmes.where(title: "Blue Carbon").first
elsif "environmental-crime" == split[1]
Activity.programmes.
where(title: "Environmental Crime").first
elsif "green-economy" == split[1]
Activity.programmes.
where(title: "Ecosystems Economies and Sustainable Development").first
elsif "marine-coastal" == split[1]
Activity.programmes.
where(title: "Ocean Governance and Geological Resources").first
elsif "polar-mountain" == split[1]
Activity.programmes.
where(title: "Polar and Mountain Environments").first
elsif "soe-reporting" == split[1]
Activity.programmes.
where(title: "State of the Environment and Spatial Planning").first
end
when "publications"
if split.size < 3
publications_path
elsif split[1] == "et"
case split[2]
when "ep2"
Publication.where(title: "The Environment and Poverty Times #2").first
when "ep4"
Publication.where(title: "Environment and Poverty Times #4").first
end
elsif split[2] == "ipcc_tar"
Publication.where(title: "IPCC - Climate Change 2001: Synthesis Report").first
elsif split[2] == "food-crisis"
Publication.where(title: "The Environmental Food Crisis").first
elsif split[2] == "natural-fix"
Publication.where(title: "The Natural Fix? The Role of Ecosystems in Climate Mitigation").first
elsif split[2] == "orangutan"
Publication.where(title: "The Last Stand of the Orangutang").first
end
when "environmental_crime"
Activity.programmes.where(title: "Environmental Crime").first
when "bluecarbon"
Activity.programmes.where(title: "Blue Carbon").first
when "africa"
Activity.where(title: "Africa").first
when "comms"
Activity.where(title: "Communication and Outreach").first
when "eesd"
Activity.where(title: "Ecosystems Economies and Sustainable Development").first
when "oceangov"
Activity.programmes.where(title: "Ocean Governance and Geological Resources").first
when "polar"
Activity.programmes.where(title: "Polar and Mountain Environments").first
when "soe"
Activity.programmes.
where(title: "State of the Environment and Spatial Planning").first
when "blueforests"
Activity.where(title: "Blue Forests Project").first
when "mastrec"
"http://news.grida.no/mastrec"
when "bluesolutions"
Activity.where(title: "Blue Solutions").first
when "uarctic"
Activity.where(title: "University of the Arctic").first
when "crimfish"
Activity.find(275) # exists in production
when "graphicslib"
if split.size < 3
resources_path(media: "Graphic")
else
g = case split[2]
when "difference-between-eia-and-sea_5148"
Graphic.where(title: "Difference between EIA and SEA").first
when "major-river-basins-of-africa_1ac3"
Graphic.where(title: "Major river basins of Africa").first
when "mediterranean-sea-water-masses-vertical-distribution_d84b"
Graphic.where(title: "Mediterranean Sea water masses: vertical distribution").first
when "total-global-saltwater-and-freshwater-estimates_39f6"
Graphic.where(title: "Total global saltwater and freshwater estimates").first
when "trends-in-population-developed-and-developing-countries-1750-2050-estimates-and-projections_1616"
Graphic.where(title: "Trends in population, developed and developing countries, 1750-2050 (estimates and projections)").first
end
resource_path(g)
end
when "photolib"
resources_path(media: "Photo")
when "video"
resources_path(media: "Video")
end
if redirect_path
redirect_to redirect_path, :status => :moved_permanently,
notice: "You have been redirected to GRID Arendal's new website. If this is not the content you are looking for, please use our new search by clicking the magnifying glass on the right hand side."
else
respond_to do |format|
format.html { render status: 404 }
end
end
rescue ActionController::UnknownFormat
render status: 404
end
end
|
class ErrorsController < ApplicationController
def case_submitted
@tribunal_case = current_tribunal_case
respond_with_status(:unprocessable_entity)
end
def case_not_found
respond_with_status(:not_found)
end
def not_found
respond_with_status(:not_found)
end
def unhandled
respond_with_status(:internal_server_error)
end
private
def respond_with_status(status)
respond_to do |format|
format.html
format.json { head status }
end
end
end
Respond to all formats in errors controller. (#320)
Probably a bit too late as the pentesting is well undergoing but for the future I think
it is a good idea to catch all formats in the `errors controller`, specially 404, so for
example robots/crawlers scanning for vulnerabilities don't raise a Sentry excetion due to
our app not responding to `.xml` or `.ini`
class ErrorsController < ApplicationController
def case_submitted
@tribunal_case = current_tribunal_case
respond_with_status(:unprocessable_entity)
end
def case_not_found
respond_with_status(:not_found)
end
def not_found
respond_with_status(:not_found)
end
def unhandled
respond_with_status(:internal_server_error)
end
private
def respond_with_status(status)
respond_to do |format|
format.html
format.all { head status }
end
end
end
|
class EventsController < ApplicationController
before_action :find_user
def index
if user_signed_in?
session[:user_id] = current_user.id
if current_user.user_addresses.length > 0
@addressStatus = "true"
else
@addressStatus = "false"
end
@user_profile = {
id: current_user.id,
addressStatus: @addressStatus,
friends: current_user.friends,
addresses: current_user.user_addresses,
token: form_authenticity_token,
open_invites: current_user.open_invites,
open_events: current_user.open_events,
upcoming_events: current_user.upcoming_events
}
else
redirect_to root_path
end
end
def show
@allEvents = Event.all
# binding.pry
if !user_signed_in?
redirect_to root_path
else
@event = Event.find_by(id: params[:id])
if !@event.invitees.include?(current_user)
redirect_to root_path
else
@possibleVenues = @event.venue_choices
@bookmarks = current_user.bookmarks
end
end
end
def search
render json: @possibleVenues
end
def new
@event = Event.new
@friends = current_user.friends
end
def create
form = params[:event]
@event = Event.new({
host_id: form[:host_id],
title: form[:title],
host_address_id: form[:host_address_id].to_i,
date: form[:date],
event_type: form[:event_type]
})
if @event.save
Invitation.create(guest_id: params[:invitation][:guest_id], event: @event)
redirect_to root_path
else
render 'new'
end
end
def update
event = Event.find_by(id: params[:id])
response = params[:invitation][:response]
if response == "Accept"
event.update_attributes(:status => response, :guest_address_id => params[:event][:guest_address_id])
else
event.update_attributes(:status => response)
end
event.save
redirect_to events_path
end
def confirm
event = Event.find_by(id: params[:id])
if event.status == "Open"
event.update_attributes(venue: params[:name], venue_address: params[:address],status: "Confirmed")
else
render json: {errors:["This event has already been confirmed or doesn't exist."]}
end
# event.update_attributes()
# event.save
# redirect_to event_path
end
private
def find_user
@user = current_user
end
def event_params
params.require(:event).permit(:host_id, :title, :type, :host_address_id, :date)
end
end
w/ note
class EventsController < ApplicationController
before_action :find_user
def index
if user_signed_in?
session[:user_id] = current_user.id
if current_user.user_addresses.length > 0
@addressStatus = "true"
else
@addressStatus = "false"
end
@user_profile = {
id: current_user.id,
addressStatus: @addressStatus,
friends: current_user.friends,
addresses: current_user.user_addresses,
token: form_authenticity_token,
open_invites: current_user.open_invites,
open_events: current_user.open_events,
upcoming_events: current_user.upcoming_events
}
else
redirect_to root_path
end
end
def show
@allEvents = Event.all
# binding.pry
if !user_signed_in?
redirect_to root_path
else
@event = Event.find_by(id: params[:id])
if !@event.invitees.include?(current_user)
redirect_to root_path
else
@possibleVenues = @event.venue_choices
@bookmarks = current_user.bookmarks
end
end
end
def search
render json: @possibleVenues
end
def new
@event = Event.new
@friends = current_user.friends
end
def create
form = params[:event]
@event = Event.new({
host_id: form[:host_id],
title: form[:title],
host_address_id: form[:host_address_id].to_i,
date: form[:date],
event_type: form[:event_type]
})
if @event.save
Invitation.create(guest_id: params[:invitation][:guest_id], event: @event)
redirect_to root_path
else
render 'new'
end
end
def update
event = Event.find_by(id: params[:id])
response = params[:invitation][:response]
if response == "Accept"
event.update_attributes(:status => response, :guest_address_id => params[:event][:guest_address_id])
else
event.update_attributes(:status => response)
end
event.save
redirect_to events_path
end
def confirm
event = Event.find_by(id: params[:id])
if event.status == "Open"
event.update_attributes(venue: params[:name], venue_address: params[:address],status: "Confirmed")
else
render json: {errors:["This event has already been confirmed or doesn't exist."]}
end
# event.update_attributes()
# event.save
# redirect_to event_path
end
private
def find_user
@user = current_user
end
def event_params
params.require(:event).permit(:host_id, :title, :type, :host_address_id, :date)
end
#a note
end
|
class ImagesController < ApplicationController
before_filter :require_user
# GET /images
# GET /images.json
def index
if params[:artist] && params[:album]
@images = Image.sectioned(params[:section]).where(artist: params[:artist], album: params[:album])
elsif params[:q] # search
@images = Image.sectioned(params[:section]).search(params) # takes filters etc as well
elsif params[:ids]
@images = Image.where(id: params[:ids].split(','))
else
@images = Image.sectioned(params[:section]).all
end
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @images }
end
end
# GET /images/manage
def manage
respond_to do |format|
format.html # manage.html.erb
# format.json { render :json => @images }
end
end
# GET /images/1
# GET /images/1.json
def show
@image = Image.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @image }
end
end
# # GET /images/new
# # GET /images/new.json
# def new
# @image = Image.new
#
# respond_to do |format|
# format.html # new.html.erb
# format.json { render :json => @image }
# end
# end
# # GET /images/1/edit
# def edit
# @image = Image.find(params[:id])
# end
# POST /images
# POST /images.json
def create
@image = Image.new(params[:image].merge({
incoming_filename: params[:qqfile],
uploaded_by: current_user
}))
respond_to do |format|
if !@image.save
format.html { render :action => "new" }
format.json { render :json => @image.errors, :status => :unprocessable_entity }
elsif (e = @image.write(request.body.read)).is_a?(Exception)
format.html { render :action => "new" }
format.json { render :json => e.message, :status => :unprocessable_entity }
else
format.html { redirect_to(@image, :notice => 'Image was successfully created.') }
thumb_size = '120x120'
@image.resize(thumb_size)
format.json { render :json => {image_url: @image.url(thumb_size), image: @image}.to_json, :status => :created }
end
end
end
# PUT /images/1
# PUT /images/1.json
def update
@image = Image.find(params[:id])
respond_to do |format|
if @image.update_attributes(params[:image])
format.html { redirect_to(@image, :notice => 'Image was successfully updated.') }
format.json { head :ok }
else
format.html { render :action => "edit" }
format.json { render :json => @image.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /images/1
# DELETE /images/1.json
def destroy
@image = Image.find(params[:id])
@image.destroy
respond_to do |format|
format.html { redirect_to(images_url) }
format.json { head :ok }
end
end
# this method is called when a url for a size image that has not yet been generated is requested.
# it expects a binary response.
# this may be a prime place for optimization.
def resize
raise "Realtime resizing not yet implemented."
end
end
If an ajax request to /images, return just the image_browser partial.
Otherwise, render the templates as usual.
class ImagesController < ApplicationController
before_filter :require_user
# GET /images
# GET /images.json
def index
if params[:artist] && params[:album]
@images = Image.sectioned(params[:section]).where(artist: params[:artist], album: params[:album])
elsif params[:q] # search
@images = Image.sectioned(params[:section]).search(params) # takes filters etc as well
elsif params[:ids]
@images = Image.where(id: params[:ids].split(','))
else
@images = Image.sectioned(params[:section]).all
end
respond_to do |format|
format.html do
render :partial => 'image_browser' if request.xhr?
# otherwise, index.html.erb
end
format.json { render :json => @images }
end
end
# GET /images/manage
def manage
respond_to do |format|
format.html # manage.html.erb
# format.json { render :json => @images }
end
end
# GET /images/1
# GET /images/1.json
def show
@image = Image.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @image }
end
end
# # GET /images/new
# # GET /images/new.json
# def new
# @image = Image.new
#
# respond_to do |format|
# format.html # new.html.erb
# format.json { render :json => @image }
# end
# end
# # GET /images/1/edit
# def edit
# @image = Image.find(params[:id])
# end
# POST /images
# POST /images.json
def create
@image = Image.new(params[:image].merge({
incoming_filename: params[:qqfile],
uploaded_by: current_user
}))
respond_to do |format|
if !@image.save
format.html { render :action => "new" }
format.json { render :json => @image.errors, :status => :unprocessable_entity }
elsif (e = @image.write(request.body.read)).is_a?(Exception)
format.html { render :action => "new" }
format.json { render :json => e.message, :status => :unprocessable_entity }
else
format.html { redirect_to(@image, :notice => 'Image was successfully created.') }
thumb_size = '120x120'
@image.resize(thumb_size)
format.json { render :json => {image_url: @image.url(thumb_size), image: @image}.to_json, :status => :created }
end
end
end
# PUT /images/1
# PUT /images/1.json
def update
@image = Image.find(params[:id])
respond_to do |format|
if @image.update_attributes(params[:image])
format.html { redirect_to(@image, :notice => 'Image was successfully updated.') }
format.json { head :ok }
else
format.html { render :action => "edit" }
format.json { render :json => @image.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /images/1
# DELETE /images/1.json
def destroy
@image = Image.find(params[:id])
@image.destroy
respond_to do |format|
format.html { redirect_to(images_url) }
format.json { head :ok }
end
end
# this method is called when a url for a size image that has not yet been generated is requested.
# it expects a binary response.
# this may be a prime place for optimization.
def resize
raise "Realtime resizing not yet implemented."
end
end
|
class InviteController < ApplicationController
before_action :set_app_details
before_action :check_disabled_text
def index
if user and password
# default
else
render 'environment_error'
end
end
def submit
if @message # from a `before_action`
render :index
return
end
email = params[:email]
first_name = params[:first_name]
last_name = params[:last_name]
if ENV["RESTRICTED_DOMAIN"]
if email.split("@").last != ENV["RESTRICTED_DOMAIN"]
@message = "Sorry! Early access is currently restricted to people within the #{ENV["RESTRICTED_DOMAIN"]} domain. We will be opening it up soon, though!"
@type = "warning"
render :index
return
end
end
if ENV["ITC_TOKEN"]
if ENV["ITC_TOKEN"] != params[:token]
@message = t(:message_invalid_password)
@type = "danger"
render :index
return
end
end
if email.length == 0 || first_name.length == 0 || last_name.length == 0
render :index
return
end
if ENV["ITC_IS_DEMO"]
@message = t(:message_demo_page)
@type = "success"
render :index
return
end
logger.info "Going to create a new tester: #{email} - #{first_name} #{last_name}"
begin
login
tester = Spaceship::Tunes::Tester::Internal.find(config[:email])
tester ||= Spaceship::Tunes::Tester::External.find(config[:email])
Helper.log.info "Existing tester #{tester.email}".green if tester
tester ||= Spaceship::Tunes::Tester::External.create!(email: email,
first_name: first_name,
last_name: last_name)
logger.info "Successfully created tester #{tester.email}"
if apple_id.length > 0
logger.info "Addding tester to application"
tester.add_to_app!(apple_id)
logger.info "Done"
end
if testing_is_live?
@message = t(:message_success_live)
else
@message = t(:message_success_pending)
end
@type = "success"
rescue => ex
if ex.inspect.to_s.include?"EmailExists"
@message = t(:message_email_exists)
@type = "danger"
else
Rails.logger.fatal ex.inspect
Rails.logger.fatal ex.backtrace.join("\n")
@message = t(:message_error)
@type = "danger"
end
end
render :index
end
private
def user
ENV["ITC_USER"] || ENV["FASTLANE_USER"]
end
def password
ENV["ITC_PASSWORD"] || ENV["FASTLANE_PASSWORD"]
end
def apple_id
Rails.logger.error "No app to add this tester to provided, use the `ITC_APP_ID` environment variable" unless ENV["ITC_APP_ID"]
Rails.cache.fetch('AppID', expires_in: 10.minutes) do
if ENV["ITC_APP_ID"].include?"." # app identifier
login
app = Spaceship::Application.find(ENV["ITC_APP_ID"])
app.apple_id
else
ENV["ITC_APP_ID"].to_s
end
end
end
def app
login
@app ||= Spaceship::Tunes::Application.find(ENV["ITC_APP_ID"])
raise "Could not find app with ID #{apple_id}" unless @app
@app
end
def app_metadata
Rails.cache.fetch('appMetadata', expires_in: 10.minutes) do
{
icon_url: app.app_icon_preview_url,
title: app.name
}
end
end
def login
return if @spaceship
@spaceship = Spaceship::Tunes.login(user, password)
end
def set_app_details
@metadata = app_metadata
@title = @metadata[:title]
end
def check_disabled_text
if ENV["ITC_CLOSED_TEXT"]
@message = ENV["ITC_CLOSED_TEXT"]
@type = "warning"
end
end
# @return [Boolean] Is at least one TestFlight beta testing build available?
def testing_is_live?
app.build_trains.each do |version, train|
if train.external_testing_enabled
train.builds.each do |build|
return true if build.external_testing_enabled
end
end
end
return false
end
end
Notify slack if a new user signed up
class InviteController < ApplicationController
before_action :set_app_details
before_action :check_disabled_text
def index
if user and password
# default
else
render 'environment_error'
end
end
def submit
if @message # from a `before_action`
render :index
return
end
email = params[:email]
first_name = params[:first_name]
last_name = params[:last_name]
if ENV["RESTRICTED_DOMAIN"]
if email.split("@").last != ENV["RESTRICTED_DOMAIN"]
@message = "Sorry! Early access is currently restricted to people within the #{ENV["RESTRICTED_DOMAIN"]} domain. We will be opening it up soon, though!"
@type = "warning"
render :index
return
end
end
if ENV["ITC_TOKEN"]
if ENV["ITC_TOKEN"] != params[:token]
@message = t(:message_invalid_password)
@type = "danger"
render :index
return
end
end
if email.length == 0 || first_name.length == 0 || last_name.length == 0
render :index
return
end
if ENV["ITC_IS_DEMO"]
@message = t(:message_demo_page)
@type = "success"
render :index
return
end
logger.info "Going to create a new tester: #{email} - #{first_name} #{last_name}"
begin
login
tester = Spaceship::Tunes::Tester::Internal.find(config[:email])
tester ||= Spaceship::Tunes::Tester::External.find(config[:email])
Helper.log.info "Existing tester #{tester.email}".green if tester
tester ||= Spaceship::Tunes::Tester::External.create!(email: email,
first_name: first_name,
last_name: last_name)
logger.info "Successfully created tester #{tester.email}"
if apple_id.length > 0
logger.info "Addding tester to application"
tester.add_to_app!(apple_id)
logger.info "Done"
end
if testing_is_live?
@message = t(:message_success_live)
else
@message = t(:message_success_pending)
end
if ENV["SLACK_HOOK"]
notifier = Slack::Notifier.new ENV["SLACK_HOOK"], channel: '#boarding', username: 'praisepop'
notifier.ping notifier.escape("#{first_name} #{last_name} <#{email}> just signed up for testing!"), icon_url: "https://s3.amazonaws.com/praisepop/assets/images/prof.png"
end
@type = "success"
rescue => ex
if ex.inspect.to_s.include?"EmailExists"
@message = t(:message_email_exists)
@type = "danger"
else
Rails.logger.fatal ex.inspect
Rails.logger.fatal ex.backtrace.join("\n")
@message = t(:message_error)
@type = "danger"
end
end
render :index
end
private
def user
ENV["ITC_USER"] || ENV["FASTLANE_USER"]
end
def password
ENV["ITC_PASSWORD"] || ENV["FASTLANE_PASSWORD"]
end
def apple_id
Rails.logger.error "No app to add this tester to provided, use the `ITC_APP_ID` environment variable" unless ENV["ITC_APP_ID"]
Rails.cache.fetch('AppID', expires_in: 10.minutes) do
if ENV["ITC_APP_ID"].include?"." # app identifier
login
app = Spaceship::Application.find(ENV["ITC_APP_ID"])
app.apple_id
else
ENV["ITC_APP_ID"].to_s
end
end
end
def app
login
@app ||= Spaceship::Tunes::Application.find(ENV["ITC_APP_ID"])
raise "Could not find app with ID #{apple_id}" unless @app
@app
end
def app_metadata
Rails.cache.fetch('appMetadata', expires_in: 10.minutes) do
{
icon_url: app.app_icon_preview_url,
title: app.name
}
end
end
def login
return if @spaceship
@spaceship = Spaceship::Tunes.login(user, password)
end
def set_app_details
@metadata = app_metadata
@title = @metadata[:title]
end
def check_disabled_text
if ENV["ITC_CLOSED_TEXT"]
@message = ENV["ITC_CLOSED_TEXT"]
@type = "warning"
end
end
# @return [Boolean] Is at least one TestFlight beta testing build available?
def testing_is_live?
app.build_trains.each do |version, train|
if train.external_testing_enabled
train.builds.each do |build|
return true if build.external_testing_enabled
end
end
end
return false
end
end
|
class LightsController < ApplicationController
include AdminHelper
before_action :check_lock_state, except: [:index]
def change_logger
@@change_logger ||= Logger.new("#{Rails.root}/log/change.log")
end
#Creates sites
def index
begin
@lights = Huey::Bulb.all
rescue Huey::Errors::CouldNotFindHue
end
end
def edit
@light = Huey::Bulb.find(params[:id])
for light in @lights
light.set_state({
:hue => [0,12750,36210,46920,56100].sample,
:saturation => 254
}, 0)
end
end
def new
#@lights.sample.set_state({
# :hue => [0,12750,36210,46920,56100].sample,
# :saturation => 255}, 0)
redirect_to(:action => 'index')
end
def create
@lights = Huey::Bulb.all
if (params[:newhue0].to_i != 0) then
if (params[:newsat0].to_i != 0) then
@lights[params[:id].to_i-1].update(hue: params[:newhue0].to_i,
sat: params[:newsat0].to_i)
# {
#:hue => params[:newhue0].to_i,
#:sat => params[:newsat0].to_i})
else
@lights[params[:id].to_i-1].set_state({
:hue => params[:newhue0].to_i}, 0)
end
else
if (params[:newsat0].to_i != 0) then
@lights[params[:id].to_i-1].set_state({
:saturation => params[:newsat0].to_i}, 0)
end
end
redirect_to(:action => 'index')
end
#Changes lights
def multi_update
lights = params[:lights].keys
@changedLights = ""
lights.each do |light|
bulb = Huey::Bulb.find light.to_i
if bulb.on
bulb.update(sat: (params[:sat_text]).to_i, hue: (params[:hue_text].to_i), bri: (params[:bri_text].to_i))
bulb.save
@changedLights += light.to_s+" "
end
end
@lights = Huey::Bulb.all
respond_to do |format|
format.js
end
@user = User.find_by_token cookies[:chalmersItAuth]
change_logger.info "#{@user.cid}: Lamps ##{@changedLights}values changed to hue:#{(params[:hue_text]).to_s} sat: #{(params[:sat_text]).to_s} bri: #{(params[:bri_text]).to_s}"
log "Lamps ##{@changedLights}color changed to hue:#{(params[:hue_text]).to_s} sat: #{(params[:sat_text]).to_s} bri: #{(params[:bri_text]).to_s}"
end
#shows a specific lamp (lights/1)
def show
render plain: params[:id]
end
#Set standard light
def reset_lights
lights = Huey::Bulb.all
lights.each do |light|
if light.on
light.update(rgb: '#cff974', bri: 200)
light.save
end
end
@user = User.find_by_token cookies[:chalmersItAuth]
change_logger.info "#{@user.cid}: All lamps reset"
log("All lamps reset")
@lights = Huey::Bulb.all
respond_to do |format|
format.js
end
end
def turnOff
@light = Huey::Bulb.find(params[:id].to_i)
@light.update(on: false)
@light.save
redirect_to(:action => 'index')
end
def turnOn
@light = Huey::Bulb.find(params[:id].to_i)
@light.update(on: true)
@light.save
redirect_to(:action => 'index')
end
def turn_all_off
lights_group = Huey::Group.new(Huey::Bulb.find(1),Huey::Bulb.find(2),Huey::Bulb.find(3),
Huey::Bulb.find(4), Huey::Bulb.find(5), Huey::Bulb.find(6))
lights_group.update(on: false, bri: 200, transitiontime: 0)
@lights = Huey::Bulb.all
respond_to do |format|
format.js
end
log("All lights OFF")
end
def turn_all_on
lights_group = Huey::Group.new(Huey::Bulb.find(1),Huey::Bulb.find(2),Huey::Bulb.find(3),
Huey::Bulb.find(4), Huey::Bulb.find(5), Huey::Bulb.find(6))
lights_group.update(on: true, bri: 200, transitiontime: 0)
@lights = Huey::Bulb.all
respond_to do |format|
format.js
end
log("All lights ON")
end
#Toggles light state
def switchOnOff
@light = Huey::Bulb.find(params[:id].to_i)
@light.on = !@light.on
@light.save
log("Lamp ##{params[:id]} toggled")
end
private
def log(change)
entry = LogEntry.new
@user = User.find_by_token cookies[:chalmersItAuth]
entry.cid = @user.cid
entry.change = change
entry.save
end
end
Moved respond_to last in methods, fixes #12
class LightsController < ApplicationController
include AdminHelper
before_action :check_lock_state, except: [:index]
def change_logger
@@change_logger ||= Logger.new("#{Rails.root}/log/change.log")
end
#Creates sites
def index
begin
@lights = Huey::Bulb.all
rescue Huey::Errors::CouldNotFindHue
end
end
def edit
@light = Huey::Bulb.find(params[:id])
for light in @lights
light.set_state({
:hue => [0,12750,36210,46920,56100].sample,
:saturation => 254
}, 0)
end
end
def new
#@lights.sample.set_state({
# :hue => [0,12750,36210,46920,56100].sample,
# :saturation => 255}, 0)
redirect_to(:action => 'index')
end
def create
@lights = Huey::Bulb.all
if (params[:newhue0].to_i != 0) then
if (params[:newsat0].to_i != 0) then
@lights[params[:id].to_i-1].update(hue: params[:newhue0].to_i,
sat: params[:newsat0].to_i)
# {
#:hue => params[:newhue0].to_i,
#:sat => params[:newsat0].to_i})
else
@lights[params[:id].to_i-1].set_state({
:hue => params[:newhue0].to_i}, 0)
end
else
if (params[:newsat0].to_i != 0) then
@lights[params[:id].to_i-1].set_state({
:saturation => params[:newsat0].to_i}, 0)
end
end
redirect_to(:action => 'index')
end
#Changes lights
def multi_update
lights = params[:lights].keys
@changedLights = ""
lights.each do |light|
bulb = Huey::Bulb.find light.to_i
if bulb.on
bulb.update(sat: (params[:sat_text]).to_i, hue: (params[:hue_text].to_i), bri: (params[:bri_text].to_i))
bulb.save
@changedLights += light.to_s+" "
end
end
@user = User.find_by_token cookies[:chalmersItAuth]
change_logger.info "#{@user.cid}: Lamps ##{@changedLights}values changed to hue:#{(params[:hue_text]).to_s} sat: #{(params[:sat_text]).to_s} bri: #{(params[:bri_text]).to_s}"
log "Lamps ##{@changedLights}color changed to hue:#{(params[:hue_text]).to_s} sat: #{(params[:sat_text]).to_s} bri: #{(params[:bri_text]).to_s}"
@lights = Huey::Bulb.all
respond_to do |format|
format.js
end
end
#shows a specific lamp (lights/1)
def show
render plain: params[:id]
end
#Set standard light
def reset_lights
lights = Huey::Bulb.all
lights.each do |light|
if light.on
light.update(rgb: '#cff974', bri: 200)
light.save
end
end
@user = User.find_by_token cookies[:chalmersItAuth]
change_logger.info "#{@user.cid}: All lamps reset"
log("All lamps reset")
@lights = Huey::Bulb.all
respond_to do |format|
format.js
end
end
def turnOff
@light = Huey::Bulb.find(params[:id].to_i)
@light.update(on: false)
@light.save
redirect_to(:action => 'index')
end
def turnOn
@light = Huey::Bulb.find(params[:id].to_i)
@light.update(on: true)
@light.save
redirect_to(:action => 'index')
end
def turn_all_off
lights_group = Huey::Group.new(Huey::Bulb.find(1),Huey::Bulb.find(2),Huey::Bulb.find(3),
Huey::Bulb.find(4), Huey::Bulb.find(5), Huey::Bulb.find(6))
lights_group.update(on: false, bri: 200, transitiontime: 0)
log("All lights OFF")
@lights = Huey::Bulb.all
respond_to do |format|
format.js
end
end
def turn_all_on
lights_group = Huey::Group.new(Huey::Bulb.find(1),Huey::Bulb.find(2),Huey::Bulb.find(3),
Huey::Bulb.find(4), Huey::Bulb.find(5), Huey::Bulb.find(6))
lights_group.update(on: true, bri: 200, transitiontime: 0)
log("All lights ON")
@lights = Huey::Bulb.all
respond_to do |format|
format.js
end
end
#Toggles light state
def switchOnOff
@light = Huey::Bulb.find(params[:id].to_i)
@light.on = !@light.on
@light.save
log("Lamp ##{params[:id]} toggled")
end
private
def log(change)
entry = LogEntry.new
@user = User.find_by_token cookies[:chalmersItAuth]
entry.cid = @user.cid
entry.change = change
entry.save
end
end
|
#
# Controller for Logics
#
class LogicsController < InheritedResources::Base
respond_to :json, :xml
has_pagination
has_scope :search
load_and_authorize_resource :except => [:index, :show]
def index
super do |format|
format.html do
@search = params[:search]
@search = nil if @search.blank?
end
end
end
def create
@logic.user = current_user
super
end
def show
super do |format|
format.html do
@mappings_from = resource.mappings_from
@mappings_to = resource.mappings_to
@ontologies = resource.ontologies
@relation_list ||= RelationList.new [resource, :supports],
:model => Support,
:collection => resource.supports,
:association => :language,
:scope => [Language]
end
end
end
protected
def authorize_parent
#not needed
end
end
fix display of current graph depth.
#
# Controller for Logics
#
class LogicsController < InheritedResources::Base
respond_to :json, :xml
has_pagination
has_scope :search
load_and_authorize_resource :except => [:index, :show]
def index
super do |format|
format.html do
@search = params[:search]
@search = nil if @search.blank?
end
end
end
def create
@logic.user = current_user
super
end
def show
super do |format|
format.html do
@depth = params[:depth] ? params[:depth].to_i : 3
@mappings_from = resource.mappings_from
@mappings_to = resource.mappings_to
@ontologies = resource.ontologies
@relation_list ||= RelationList.new [resource, :supports],
:model => Support,
:collection => resource.supports,
:association => :language,
:scope => [Language]
end
end
end
protected
def authorize_parent
#not needed
end
end
|
class MoviesController < ApplicationController
before_action :set_movie, only: [:show, :edit, :update, :destroy]
helper_method :sort_column, :sort_direciton
# GET /movies
# GET /movies.json
def index
@movies = Movie.order(sort_column + " " + sort_direciton)
end
# GET /movies/1
# GET /movies/1.json
def show
end
# GET /movies/new
def new
@movie = Movie.new
end
# GET /movies/1/edit
def edit
end
# POST /movies
# POST /movies.json
def create
@movie = Movie.new(movie_params)
respond_to do |format|
if @movie.save
format.html { redirect_to @movie, notice: 'Movie was successfully created.' }
format.json { render :show, status: :created, location: @movie }
else
format.html { render :new }
format.json { render json: @movie.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /movies/1
# PATCH/PUT /movies/1.json
def update
respond_to do |format|
if @movie.update(movie_params)
format.html { redirect_to @movie, notice: 'Movie was successfully updated.' }
format.json { render :show, status: :ok, location: @movie }
else
format.html { render :edit }
format.json { render json: @movie.errors, status: :unprocessable_entity }
end
end
end
# DELETE /movies/1
# DELETE /movies/1.json
def destroy
@movie.destroy
respond_to do |format|
format.html { redirect_to movies_url, notice: 'Movie was successfully destroyed.' }
format.json { head :no_content }
end
end
def sync
print "movie sync in progress"
uri = URI.parse('http://172.16.0.15:5050/api/0c7afb2c910d49b2aa98b5f762e62b98/movie.list')
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
output = JSON.parse response.body
output['movies'].compact.each do |movie_info|
print movie_info['info']['original_title'].to_yaml
print movie_info['info']['directors'].to_yaml
print movie_info['info']['genres'].to_yaml
print movie_info['info']['year'].to_yaml
Movie.find_or_create_by(:imdb_id => movie_info['info']['imdb']).update(:title => movie_info['info']['original_title'],
:director => movie_info['info']['directors'],
:genre => movie_info['info']['genres'],
:year => movie_info['info']['year'],
:quality => 'N/A',
:imdb_id => movie_info['info']['imdb'])
end
end
private
def sort_column
Movie.column_names.include?(params[:sort]) ? params[:sort] : "title"
end
def sort_direciton
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
# Use callbacks to share common setup or constraints between actions.
def set_movie
@movie = Movie.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def movie_params
params.require(:movie).permit(:title, :director, :genre, :year, :quality)
end
end
trying quality again
class MoviesController < ApplicationController
before_action :set_movie, only: [:show, :edit, :update, :destroy]
helper_method :sort_column, :sort_direciton
# GET /movies
# GET /movies.json
def index
@movies = Movie.order(sort_column + " " + sort_direciton)
end
# GET /movies/1
# GET /movies/1.json
def show
end
# GET /movies/new
def new
@movie = Movie.new
end
# GET /movies/1/edit
def edit
end
# POST /movies
# POST /movies.json
def create
@movie = Movie.new(movie_params)
respond_to do |format|
if @movie.save
format.html { redirect_to @movie, notice: 'Movie was successfully created.' }
format.json { render :show, status: :created, location: @movie }
else
format.html { render :new }
format.json { render json: @movie.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /movies/1
# PATCH/PUT /movies/1.json
def update
respond_to do |format|
if @movie.update(movie_params)
format.html { redirect_to @movie, notice: 'Movie was successfully updated.' }
format.json { render :show, status: :ok, location: @movie }
else
format.html { render :edit }
format.json { render json: @movie.errors, status: :unprocessable_entity }
end
end
end
# DELETE /movies/1
# DELETE /movies/1.json
def destroy
@movie.destroy
respond_to do |format|
format.html { redirect_to movies_url, notice: 'Movie was successfully destroyed.' }
format.json { head :no_content }
end
end
def sync
print "movie sync in progress"
uri = URI.parse('http://172.16.0.15:5050/api/0c7afb2c910d49b2aa98b5f762e62b98/movie.list')
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
output = JSON.parse response.body
output['movies'].compact.each do |movie_info|
print movie_info['info']['original_title'].to_yaml
print movie_info['info']['directors'].to_yaml
print movie_info['info']['genres'].to_yaml
print movie_info['info']['year'].to_yaml
print movie_info['releases'][0]['quality']
print movie_info.to_yaml
Movie.find_or_create_by(:imdb_id => movie_info['info']['imdb']).update(:title => movie_info['info']['original_title'],
:director => movie_info['info']['directors'],
:genre => movie_info['info']['genres'],
:year => movie_info['info']['year'],
:quality => movie_info['releases'][0]['quality'],
:imdb_id => movie_info['info']['imdb'])
end
end
private
def sort_column
Movie.column_names.include?(params[:sort]) ? params[:sort] : "title"
end
def sort_direciton
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
# Use callbacks to share common setup or constraints between actions.
def set_movie
@movie = Movie.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def movie_params
params.require(:movie).permit(:title, :director, :genre, :year, :quality)
end
end
|
class OrdersController < ApplicationController
before_filter :authenticate_user!
before_filter :find_order, except: [:create, :index, :latest]
def index
@orders = Order.past.page(params[:page]).includes(:dishes).decorate
render json: @orders, shallow: true
end
def create
@order = Order.new order_params.merge(date: Date.today)
if @order.save
render json: @order.decorate
else
render json: {errors: @order.errors}, status: :unprocessable_entity
end
end
def show
@order = @order.includes(:dishes, :user).decorate
render json: @order
end
def update
if @order.update(order_params)
render json: @order.decorate
else
render json: {errors: @order.errors}, status: :unprocessable_entity
end
end
def change_status
@order.change_status!
render json: @order.decorate
end
def latest
@order = Order.todays_order.try(:decorate)
render json: @order
end
private
def order_params
params.permit(:user_id, :from, :shipping)
end
def find_order
@order = Order.find params[:id]
end
end
Remove model includes
class OrdersController < ApplicationController
before_filter :authenticate_user!
before_filter :find_order, except: [:create, :index, :latest]
def index
@orders = Order.past.page(params[:page]).includes(:dishes).decorate
render json: @orders, shallow: true
end
def create
@order = Order.new order_params.merge(date: Date.today)
if @order.save
render json: @order.decorate
else
render json: {errors: @order.errors}, status: :unprocessable_entity
end
end
def show
@order = @order.decorate
render json: @order
end
def update
if @order.update(order_params)
render json: @order.decorate
else
render json: {errors: @order.errors}, status: :unprocessable_entity
end
end
def change_status
@order.change_status!
render json: @order.decorate
end
def latest
@order = Order.todays_order.try(:decorate)
render json: @order
end
private
def order_params
params.permit(:user_id, :from, :shipping)
end
def find_order
@order = Order.find params[:id]
end
end
|
class OrdersController < ApplicationController
def new
@order = Order.new
end
def show
@order = Order.find(params[:id])
end
def create
if params[:box_and_location]
set = params[:box_and_location].split('-')
location = set[0]
box_in = set[1]
elsif params[:orders][:pick_up_address]
location = params[:orders][:pick_up_address]
box_in = params[:orders][:box_id]
end
@order = Order.create(client_id: current_client.id, business_id: 1, box_in: box_in.to_i, status: "In Box", paid: false)
redirect_to new_charge_path
end
def update
@order = Order.find(params[:id])
if params[:commit] == "Add order to History"
@order.history = true
@order.save
elsif params[:order][:order_status] == nil
if params[:order][:delivered_address] == ""
redirect_to root_path and return
else
@box = Box.find_by(address: params[:order][:delivered_address])
@order.update_attributes(:status => "Delivered", :box_out => @box.id)
@order.save
UserNotifier.send_update_email(@order.client).deliver
end
else
if shipper = Shipper.find_by(name: params[:order][:assign_shipper_to_order])
@order.update_attributes(status: params[:order][:order_status], shipper_id: shipper.id)
@order.save
else
@order.update_attributes(status: params[:order][:order_status])
@order.save
end
end
redirect_to root_path
end
def shippers
render "shippers.html.erb"
end
def update_status
if request.xhr?
status = params[:order][:order_status]
case status
when 'In Box'
orders = Order.where(status: 'In Box')
when 'Incomming'
orders = Order.where(status: 'Incomming')
when 'Processing'
orders = Order.where(status: 'Processing')
when 'Shipping'
orders = Order.where(status: 'Shipping')
when 'Delivered'
orders = Order.where(status: 'Delivered')
else
orders = Order.all
end
@orders = orders
respond_to do |format|
format.html { render partial:'businesses/orders', layout:false }
end
else
@orders = Order.all
end
end
def history
end
end
fixed dropdown order create bug
class OrdersController < ApplicationController
def new
@order = Order.new
end
def show
@order = Order.find(params[:id])
end
def create
if params[:box_and_location]
set = params[:box_and_location].split('-')
location = set[0]
b = Box.find_by(address: location)
elsif params[:orders][:pick_up_address]
location = params[:orders][:pick_up_address]
b = Box.find_by(address: location)
end
@order = Order.create(client_id: current_client.id, business_id: 1, box_in: b.id , status: "In Box", paid: false)
binding.pry
redirect_to new_charge_path
end
def update
@order = Order.find(params[:id])
if params[:commit] == "Add order to History"
@order.history = true
@order.save
elsif params[:order][:order_status] == nil
if params[:order][:delivered_address] == ""
redirect_to root_path and return
else
@box = Box.find_by(address: params[:order][:delivered_address])
@order.update_attributes(:status => "Delivered", :box_out => @box.id)
@order.save
UserNotifier.send_update_email(@order.client).deliver
end
else
if shipper = Shipper.find_by(name: params[:order][:assign_shipper_to_order])
@order.update_attributes(status: params[:order][:order_status], shipper_id: shipper.id)
@order.save
else
@order.update_attributes(status: params[:order][:order_status])
@order.save
end
end
redirect_to root_path
end
def shippers
render "shippers.html.erb"
end
def update_status
if request.xhr?
status = params[:order][:order_status]
case status
when 'In Box'
orders = Order.where(status: 'In Box')
when 'Incomming'
orders = Order.where(status: 'Incomming')
when 'Processing'
orders = Order.where(status: 'Processing')
when 'Shipping'
orders = Order.where(status: 'Shipping')
when 'Delivered'
orders = Order.where(status: 'Delivered')
else
orders = Order.all
end
@orders = orders
respond_to do |format|
format.html { render partial:'businesses/orders', layout:false }
end
else
@orders = Order.all
end
end
def history
end
end
|
class OrdersController < ApplicationController
customer_tab :all
before_filter :authenticate_user!
before_filter :check_acting_as, :except => [:cart, :add, :choose_account, :show, :remove, :purchase, :receipt, :update]
before_filter :init_order, :except => [:cart, :index, :receipt]
before_filter :protect_purchased_orders, :except => [:cart, :receipt, :confirmed, :index]
def initialize
@active_tab = 'orders'
super
end
def init_order
@order = Order.find(params[:id])
end
def protect_purchased_orders
if @order.state == 'purchased'
redirect_to receipt_order_url(@order) and return
end
end
# GET /orders/cart
def cart
@order = acting_user.cart(session_user)
redirect_to order_path(@order) and return
end
# GET /orders/:id
def show
facility_ability = Ability.new(session_user, @order.facility, self)
@order.being_purchased_by_admin = facility_ability.can?(:act_as, @order.facility)
@order.validate_order! if @order.new?
end
# PUT /orders/:id/update
def update
order_detail_updates = {}
params.each do |key, value|
if /^(quantity|note)(\d+)$/ =~ key and value.present?
order_detail_updates[$2.to_i] ||= Hash.new
order_detail_updates[$2.to_i][$1.to_sym] = value
end
end
if @order.update_details(order_detail_updates)
redirect_to order_path(@order) and return
else
logger.debug "errors #{@order.errors.full_messages}"
flash[:error] = @order.errors.full_messages.join("<br/>").html_safe
render :show
end
end
# PUT /orders/:id/clear
def clear
@order.clear!
redirect_to order_path(@order) and return
end
# GET /orders/2/add/
# PUT /orders/2/add/
def add
## get items to add from the form post or from the session
ods_from_params = (params[:order].presence and params[:order][:order_details].presence) || []
items = ods_from_params.presence || session[:add_to_cart].presence || []
session[:add_to_cart] = nil
# ignore ods w/ empty or 0 quantities
items = items.select { |od| od.is_a?(Hash) and od[:quantity].present? and (od[:quantity] = od[:quantity].to_i) > 0 }
return redirect_to(:back, :notice => "Please add at least one quantity to order something") unless items.size > 0
first_product = Product.find(items.first[:product_id])
facility_ability = Ability.new(session_user, first_product.facility, self)
# if acting_as, make sure the session user can place orders for the facility
if acting_as? && facility_ability.cannot?(:act_as, first_product.facility)
flash[:error] = "You are not authorized to place an order on behalf of another user for the facility #{current_facility.try(:name)}."
redirect_to order_url(@order) and return
end
## handle a single instrument reservation
if items.size == 1 and (quantity = items.first[:quantity].to_i) == 1 #only one od w/ quantity of 1
if first_product.respond_to?(:reservations) # and product is reservable
# make a new cart w/ instrument (unless this order is empty.. then use that one)
@order = acting_user.cart(session_user, @order.order_details.empty?)
@order.add(first_product, 1)
# bypass cart kicking user over to new reservation screen
return redirect_to new_order_order_detail_reservation_url(@order.id, @order.order_details.first)
end
end
## make sure the order has an account
if @order.account.nil?
## add auto_assign back here if needed
## save the state to the session and redirect
session[:add_to_cart] = items
redirect_to choose_account_order_url(@order) and return
end
## process each item
@order.transaction do
items.each do |item|
@product = Product.find(item[:product_id])
begin
@order.add(@product, item[:quantity])
@order.invalidate! ## this is because we just added an order_detail
rescue NUCore::MixedFacilityCart
@order.errors.add(:base, "You can not add a product from another facility; please clear your cart or place a separate order.")
rescue Exception => e
@order.errors.add(:base, "An error was encountered while adding the product #{@product}.")
Rails.logger.error(e.message)
Rails.logger.error(e.backtrace.join("\n"))
end
end
if @order.errors.any?
flash[:error] = "There were errors adding to your cart:<br>"+@order.errors.full_messages.join('<br>').html_safe
raise ActiveRecord::Rollback
end
end
redirect_to order_url(@order)
end
# PUT /orders/:id/remove/:order_detail_id
def remove
order_detail = @order.order_details.find(params[:order_detail_id])
# remove bundles
if order_detail.group_id
order_details = @order.order_details.find(:all, :conditions => {:group_id => order_detail.group_id})
OrderDetail.transaction do
if order_details.all?{|od| od.destroy}
flash[:notice] = "The bundle has been removed."
else
flash[:error] = "An error was encountered while removing the bundle."
end
end
# remove single products
else
if order_detail.destroy
flash[:notice] = "The product has been removed."
else
flash[:error] = "An error was encountered while removing the product."
end
end
redirect_to params[:redirect_to].presence || order_url(@order)
# clear out account on the order if its now empty
if @order.order_details.empty?
@order.account_id = nil
@order.save!
end
end
# GET /orders/:id/choose_account
# POST /orders/:id/choose_account
def choose_account
if request.post?
begin
account = Account.find(params[:account_id])
raise ActiveRecord::RecordNotFound unless account.can_be_used_by?(@order.user)
rescue
end
if account
success = true
@order.transaction do
begin
@order.invalidate
@order.update_attributes!(:account_id => account.id)
@order.update_order_detail_accounts
rescue Exception => e
success = false
raise ActiveRecord::Rollback
end
end
end
if success
if session[:add_to_cart].nil?
redirect_to cart_url
else
redirect_to add_order_url(@order)
end
return
else
flash.now[:error] = account.nil? ? 'Please select a payment method.' : 'An error was encountered while selecting a payment method.'
end
end
if params[:reset_account]
@order.order_details.each do |od|
od.account = nil
od.save!
end
end
if session[:add_to_cart].blank?
@product = @order.order_details[0].product
else
@product = Product.find(session[:add_to_cart].first[:product_id])
end
@accounts = acting_user.accounts.for_facility(@product.facility).active
@errors = {}
details = @order.order_details
@accounts.each do |account|
if session[:add_to_cart] and
ods = session[:add_to_cart].presence and
product_id = ods.first[:product_id]
error = account.validate_against_product(Product.find(product_id), acting_user)
@errors[account.id] = error if error
end
unless @errors[account.id]
details.each do |od|
error = account.validate_against_product(od.product, acting_user)
@errors[account.id] = error if error
end
end
end
end
def add_account
flash.now[:notice] = "This page is still in development; please add an account administratively"
end
# PUT /orders/1/purchase
def purchase
#revalidate the cart, but only if the user is not an admin
@order.being_purchased_by_admin = Ability.new(session_user, @order.facility, self).can?(:act_as, @order.facility)
@order.ordered_at = parse_usa_date(params[:order_date], join_time_select_values(params[:order_time])) if params[:order_date].present? && params[:order_time].present? && acting_as?
begin
@order.transaction do
raise NUCore::PurchaseException.new unless @order.validate_order! && @order.purchase!
# update order detail statuses if you've changed it while acting as
if acting_as? && params[:order_status_id].present?
@order.backdate_order_details!(session_user, params[:order_status_id])
elsif can? :order_in_past, @reservation
@order.complete_past_reservations!
end
Notifier.order_receipt(:user => @order.user, :order => @order).deliver unless acting_as? && !params[:send_notification]
# If we're only making a single reservation, we'll redirect
if @order.order_details.size == 1 && @order.order_details[0].product.is_a?(Instrument) && !@order.order_details[0].bundled? && !acting_as?
od=@order.order_details[0]
if od.reservation.can_switch_instrument_on?
redirect_to order_order_detail_reservation_switch_instrument_path(@order, od, od.reservation, :switch => 'on', :redirect_to => reservations_path)
else
redirect_to reservations_path
end
flash[:notice]='Reservation completed successfully'
else
redirect_to receipt_order_url(@order)
end
return
end
rescue Exception => e
flash[:error] = I18n.t('orders.purchase.error')
flash[:error] += " #{e.message}" if e.message
@order.reload.invalidate!
redirect_to order_url(@order) and return
end
end
# GET /orders/1/receipt
def receipt
@order = Order.find(params[:id])
raise ActiveRecord::RecordNotFound unless @order.purchased?
@order_details = @order.order_details.select{|od| od.can_be_viewed_by?(acting_user) }
raise ActiveRecord::RecordNotFound if @order_details.empty?
@accounts = @order_details.collect(&:account)
end
# GET /orders
# all my orders
def index
# new or in process
@order_details = session_user.order_details.non_reservations
@available_statuses = ['pending', 'all']
case params[:status]
when "pending"
@order_details = @order_details.pending
when "all"
@order_details = @order_details.ordered
else
redirect_to orders_status_path(:status => "pending")
return
end
@order_details = @order_details. order('order_details.created_at DESC').paginate(:page => params[:page])
end
# def index_all
# # won't show instrument order_details
# @order_details = session_user.order_details.
# non_reservations.
# where("orders.ordered_at IS NOT NULL").
# order('orders.ordered_at DESC').
# paginate(:page => params[:page])
# end
end
make sure accounts displayed on order receipt are unique
class OrdersController < ApplicationController
customer_tab :all
before_filter :authenticate_user!
before_filter :check_acting_as, :except => [:cart, :add, :choose_account, :show, :remove, :purchase, :receipt, :update]
before_filter :init_order, :except => [:cart, :index, :receipt]
before_filter :protect_purchased_orders, :except => [:cart, :receipt, :confirmed, :index]
def initialize
@active_tab = 'orders'
super
end
def init_order
@order = Order.find(params[:id])
end
def protect_purchased_orders
if @order.state == 'purchased'
redirect_to receipt_order_url(@order) and return
end
end
# GET /orders/cart
def cart
@order = acting_user.cart(session_user)
redirect_to order_path(@order) and return
end
# GET /orders/:id
def show
facility_ability = Ability.new(session_user, @order.facility, self)
@order.being_purchased_by_admin = facility_ability.can?(:act_as, @order.facility)
@order.validate_order! if @order.new?
end
# PUT /orders/:id/update
def update
order_detail_updates = {}
params.each do |key, value|
if /^(quantity|note)(\d+)$/ =~ key and value.present?
order_detail_updates[$2.to_i] ||= Hash.new
order_detail_updates[$2.to_i][$1.to_sym] = value
end
end
if @order.update_details(order_detail_updates)
redirect_to order_path(@order) and return
else
logger.debug "errors #{@order.errors.full_messages}"
flash[:error] = @order.errors.full_messages.join("<br/>").html_safe
render :show
end
end
# PUT /orders/:id/clear
def clear
@order.clear!
redirect_to order_path(@order) and return
end
# GET /orders/2/add/
# PUT /orders/2/add/
def add
## get items to add from the form post or from the session
ods_from_params = (params[:order].presence and params[:order][:order_details].presence) || []
items = ods_from_params.presence || session[:add_to_cart].presence || []
session[:add_to_cart] = nil
# ignore ods w/ empty or 0 quantities
items = items.select { |od| od.is_a?(Hash) and od[:quantity].present? and (od[:quantity] = od[:quantity].to_i) > 0 }
return redirect_to(:back, :notice => "Please add at least one quantity to order something") unless items.size > 0
first_product = Product.find(items.first[:product_id])
facility_ability = Ability.new(session_user, first_product.facility, self)
# if acting_as, make sure the session user can place orders for the facility
if acting_as? && facility_ability.cannot?(:act_as, first_product.facility)
flash[:error] = "You are not authorized to place an order on behalf of another user for the facility #{current_facility.try(:name)}."
redirect_to order_url(@order) and return
end
## handle a single instrument reservation
if items.size == 1 and (quantity = items.first[:quantity].to_i) == 1 #only one od w/ quantity of 1
if first_product.respond_to?(:reservations) # and product is reservable
# make a new cart w/ instrument (unless this order is empty.. then use that one)
@order = acting_user.cart(session_user, @order.order_details.empty?)
@order.add(first_product, 1)
# bypass cart kicking user over to new reservation screen
return redirect_to new_order_order_detail_reservation_url(@order.id, @order.order_details.first)
end
end
## make sure the order has an account
if @order.account.nil?
## add auto_assign back here if needed
## save the state to the session and redirect
session[:add_to_cart] = items
redirect_to choose_account_order_url(@order) and return
end
## process each item
@order.transaction do
items.each do |item|
@product = Product.find(item[:product_id])
begin
@order.add(@product, item[:quantity])
@order.invalidate! ## this is because we just added an order_detail
rescue NUCore::MixedFacilityCart
@order.errors.add(:base, "You can not add a product from another facility; please clear your cart or place a separate order.")
rescue Exception => e
@order.errors.add(:base, "An error was encountered while adding the product #{@product}.")
Rails.logger.error(e.message)
Rails.logger.error(e.backtrace.join("\n"))
end
end
if @order.errors.any?
flash[:error] = "There were errors adding to your cart:<br>"+@order.errors.full_messages.join('<br>').html_safe
raise ActiveRecord::Rollback
end
end
redirect_to order_url(@order)
end
# PUT /orders/:id/remove/:order_detail_id
def remove
order_detail = @order.order_details.find(params[:order_detail_id])
# remove bundles
if order_detail.group_id
order_details = @order.order_details.find(:all, :conditions => {:group_id => order_detail.group_id})
OrderDetail.transaction do
if order_details.all?{|od| od.destroy}
flash[:notice] = "The bundle has been removed."
else
flash[:error] = "An error was encountered while removing the bundle."
end
end
# remove single products
else
if order_detail.destroy
flash[:notice] = "The product has been removed."
else
flash[:error] = "An error was encountered while removing the product."
end
end
redirect_to params[:redirect_to].presence || order_url(@order)
# clear out account on the order if its now empty
if @order.order_details.empty?
@order.account_id = nil
@order.save!
end
end
# GET /orders/:id/choose_account
# POST /orders/:id/choose_account
def choose_account
if request.post?
begin
account = Account.find(params[:account_id])
raise ActiveRecord::RecordNotFound unless account.can_be_used_by?(@order.user)
rescue
end
if account
success = true
@order.transaction do
begin
@order.invalidate
@order.update_attributes!(:account_id => account.id)
@order.update_order_detail_accounts
rescue Exception => e
success = false
raise ActiveRecord::Rollback
end
end
end
if success
if session[:add_to_cart].nil?
redirect_to cart_url
else
redirect_to add_order_url(@order)
end
return
else
flash.now[:error] = account.nil? ? 'Please select a payment method.' : 'An error was encountered while selecting a payment method.'
end
end
if params[:reset_account]
@order.order_details.each do |od|
od.account = nil
od.save!
end
end
if session[:add_to_cart].blank?
@product = @order.order_details[0].product
else
@product = Product.find(session[:add_to_cart].first[:product_id])
end
@accounts = acting_user.accounts.for_facility(@product.facility).active
@errors = {}
details = @order.order_details
@accounts.each do |account|
if session[:add_to_cart] and
ods = session[:add_to_cart].presence and
product_id = ods.first[:product_id]
error = account.validate_against_product(Product.find(product_id), acting_user)
@errors[account.id] = error if error
end
unless @errors[account.id]
details.each do |od|
error = account.validate_against_product(od.product, acting_user)
@errors[account.id] = error if error
end
end
end
end
def add_account
flash.now[:notice] = "This page is still in development; please add an account administratively"
end
# PUT /orders/1/purchase
def purchase
#revalidate the cart, but only if the user is not an admin
@order.being_purchased_by_admin = Ability.new(session_user, @order.facility, self).can?(:act_as, @order.facility)
@order.ordered_at = parse_usa_date(params[:order_date], join_time_select_values(params[:order_time])) if params[:order_date].present? && params[:order_time].present? && acting_as?
begin
@order.transaction do
raise NUCore::PurchaseException.new unless @order.validate_order! && @order.purchase!
# update order detail statuses if you've changed it while acting as
if acting_as? && params[:order_status_id].present?
@order.backdate_order_details!(session_user, params[:order_status_id])
elsif can? :order_in_past, @reservation
@order.complete_past_reservations!
end
Notifier.order_receipt(:user => @order.user, :order => @order).deliver unless acting_as? && !params[:send_notification]
# If we're only making a single reservation, we'll redirect
if @order.order_details.size == 1 && @order.order_details[0].product.is_a?(Instrument) && !@order.order_details[0].bundled? && !acting_as?
od=@order.order_details[0]
if od.reservation.can_switch_instrument_on?
redirect_to order_order_detail_reservation_switch_instrument_path(@order, od, od.reservation, :switch => 'on', :redirect_to => reservations_path)
else
redirect_to reservations_path
end
flash[:notice]='Reservation completed successfully'
else
redirect_to receipt_order_url(@order)
end
return
end
rescue Exception => e
flash[:error] = I18n.t('orders.purchase.error')
flash[:error] += " #{e.message}" if e.message
@order.reload.invalidate!
redirect_to order_url(@order) and return
end
end
# GET /orders/1/receipt
def receipt
@order = Order.find(params[:id])
raise ActiveRecord::RecordNotFound unless @order.purchased?
@order_details = @order.order_details.select{|od| od.can_be_viewed_by?(acting_user) }
raise ActiveRecord::RecordNotFound if @order_details.empty?
@accounts = @order_details.collect(&:account).uniq
end
# GET /orders
# all my orders
def index
# new or in process
@order_details = session_user.order_details.non_reservations
@available_statuses = ['pending', 'all']
case params[:status]
when "pending"
@order_details = @order_details.pending
when "all"
@order_details = @order_details.ordered
else
redirect_to orders_status_path(:status => "pending")
return
end
@order_details = @order_details. order('order_details.created_at DESC').paginate(:page => params[:page])
end
# def index_all
# # won't show instrument order_details
# @order_details = session_user.order_details.
# non_reservations.
# where("orders.ordered_at IS NOT NULL").
# order('orders.ordered_at DESC').
# paginate(:page => params[:page])
# end
end
|
class OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy]
# GET /orders
# GET /orders.json
#def index
# @orders = Order.all
#end
# GET /orders/1
# GET /orders/1.json
def show
@orders = Order.all
end
# GET /orders/new
def new
@order = Order.new
end
# GET /orders/1/edit
def edit
end
# POST /orders
# POST /orders.json
def create
@order = Order.new(order_params)
#@order.user_id = $current_user.id
@order.user_id = session[:user_id]
@order.event_id = $current_event.id
respond_to do |format|
if @order.tickets_purchased <= $current_event.available_tickets && @order.tickets_purchased >= 1
$current_event.available_tickets -= @order.tickets_purchased
if @order.save && $current_event.save
#format.html { render "/users/#{$current_user.id}", notice: 'Order was successfully created.' }
format.html { redirect_to $current_user, notice: 'Order was successfully created.' }
format.json { render :show, status: :created, location: $current_user }
else
format.html { redirect_to $current_user, notice: 'Unable to process order.' } #"/users/#{$current_user.id}" }
format.json { render :show, status: :unprocessable_entity, location: $current_user }
#format.json { render json: @order.errors, status: :unprocessable_entity }
end
else
#flash.now[:danger] = "Unable to process order - ordering more tickets than available"
format.html { redirect_to $current_user, notice: 'Unable to process order - ordering more tickets than available.' }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /orders/1
# PATCH/PUT /orders/1.json
def update
respond_to do |format|
if @order.update(order_params)
format.html { redirect_to @order, notice: 'Order was successfully updated.' }
format.json { render :show, status: :ok, location: @order }
else
format.html { render :edit }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
end
# DELETE /orders/1
# DELETE /orders/1.json
def destroy
@order.destroy
respond_to do |format|
format.html { redirect_to orders_url, notice: 'Order was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order
@order = Order.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_params
params.require(:order).permit(:user_id, :event_id, :tickets_purchased)
end
end
Orders troubleshooting 5
class OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy]
# GET /orders
# GET /orders.json
#def index
# @orders = Order.all
#end
# GET /orders/1
# GET /orders/1.json
def show
@orders = Order.all
end
# GET /orders/new
def new
@order = Order.new
end
# GET /orders/1/edit
def edit
end
# POST /orders
# POST /orders.json
def create
@order = Order.new(order_params)
$current_user ||= User.find_by(id: session[:user_id])
@order.user_id = $current_user.id
#@order.user_id = session[:user_id]
@order.event_id = $current_event.id
respond_to do |format|
if @order.tickets_purchased <= $current_event.available_tickets && @order.tickets_purchased >= 1
$current_event.available_tickets -= @order.tickets_purchased
if @order.save && $current_event.save
#format.html { render "/users/#{$current_user.id}", notice: 'Order was successfully created.' }
format.html { redirect_to $current_user, notice: 'Order was successfully created.' }
format.json { render :show, status: :created, location: $current_user }
else
format.html { redirect_to $current_user, notice: 'Unable to process order.' } #"/users/#{$current_user.id}" }
format.json { render :show, status: :unprocessable_entity, location: $current_user }
#format.json { render json: @order.errors, status: :unprocessable_entity }
end
else
#flash.now[:danger] = "Unable to process order - ordering more tickets than available"
format.html { redirect_to $current_user, notice: 'Unable to process order - ordering more tickets than available.' }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /orders/1
# PATCH/PUT /orders/1.json
def update
respond_to do |format|
if @order.update(order_params)
format.html { redirect_to @order, notice: 'Order was successfully updated.' }
format.json { render :show, status: :ok, location: @order }
else
format.html { render :edit }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
end
# DELETE /orders/1
# DELETE /orders/1.json
def destroy
@order.destroy
respond_to do |format|
format.html { redirect_to orders_url, notice: 'Order was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order
@order = Order.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_params
params.require(:order).permit(:user_id, :event_id, :tickets_purchased)
end
end
|
class PapersController < ApplicationController
before_filter :authenticate_user!
layout 'ember'
def show
respond_to do |format|
@paper = PaperPolicy.new(params[:id], current_user).paper
raise ActiveRecord::RecordNotFound unless @paper
format.html do
redirect_to edit_paper_path(@paper) unless @paper.submitted?
@tasks = TaskPolicy.new(@paper, current_user).tasks
end
format.json do
render json: @paper
end
end
end
def new
@paper = Paper.new
end
def create
@paper = current_user.papers.create!(paper_params)
render status: 201, json: @paper
end
def edit
@paper = PaperPolicy.new(params[:id], current_user).paper
redirect_to paper_path(@paper) if @paper.submitted?
@tasks = TaskPolicy.new(@paper, current_user).tasks
end
def update
@paper = Paper.find(params[:id])
if @paper.update(paper_params)
PaperRole.where(user_id: paper_params[:reviewer_ids]).update_all reviewer: true
head 200
else
# Ember doesn't re-render the paper if there is an error.
# e.g. Fails to update on adding new authors, but new authors stay in
# memory client side even though they aren't persisted in the DB.
render status: 500
end
end
def upload
@paper = Paper.find(params[:id])
manuscript_data = OxgarageParser.parse(params[:upload_file].path)
@paper.update manuscript_data
head :no_content
end
def download
@paper = PaperPolicy.new(params[:id], current_user).paper
epub = EpubConverter.generate_epub @paper
send_data epub[:stream].string, filename: epub[:file_name], disposition: 'attachment'
end
private
def paper_params
params.require(:paper).permit(
:short_title, :title, :abstract,
:body, :paper_type, :submitted,
:decision, :decision_letter,
:journal_id,
authors: [:first_name, :last_name, :affiliation, :email],
declaration_ids: [],
reviewer_ids: [],
phase_ids: [],
assignee_ids: [],
editor_ids: [],
figure_ids: []
)
end
end
Temp. render ember/edit from paper#update
class PapersController < ApplicationController
before_filter :authenticate_user!
layout 'ember'
def show
respond_to do |format|
@paper = PaperPolicy.new(params[:id], current_user).paper
raise ActiveRecord::RecordNotFound unless @paper
format.html do
redirect_to edit_paper_path(@paper) unless @paper.submitted?
@tasks = TaskPolicy.new(@paper, current_user).tasks
end
format.json do
render json: @paper
end
end
end
def new
@paper = Paper.new
end
def create
@paper = current_user.papers.create!(paper_params)
render status: 201, json: @paper
end
def edit
@paper = PaperPolicy.new(params[:id], current_user).paper
redirect_to paper_path(@paper) if @paper.submitted?
@tasks = TaskPolicy.new(@paper, current_user).tasks
render 'ember/index'
end
def update
@paper = Paper.find(params[:id])
if @paper.update(paper_params)
PaperRole.where(user_id: paper_params[:reviewer_ids]).update_all reviewer: true
head 200
else
# Ember doesn't re-render the paper if there is an error.
# e.g. Fails to update on adding new authors, but new authors stay in
# memory client side even though they aren't persisted in the DB.
render status: 500
end
end
def upload
@paper = Paper.find(params[:id])
manuscript_data = OxgarageParser.parse(params[:upload_file].path)
@paper.update manuscript_data
head :no_content
end
def download
@paper = PaperPolicy.new(params[:id], current_user).paper
epub = EpubConverter.generate_epub @paper
send_data epub[:stream].string, filename: epub[:file_name], disposition: 'attachment'
end
private
def paper_params
params.require(:paper).permit(
:short_title, :title, :abstract,
:body, :paper_type, :submitted,
:decision, :decision_letter,
:journal_id,
authors: [:first_name, :last_name, :affiliation, :email],
declaration_ids: [],
reviewer_ids: [],
phase_ids: [],
assignee_ids: [],
editor_ids: [],
figure_ids: []
)
end
end
|
class PeopleController < ApplicationController
include Seek::AnnotationCommon
#before_filter :login_required,:except=>[:select,:userless_project_selected_ajax,:create,:new]
before_filter :find_and_auth, :only => [:show, :edit, :update, :destroy]
before_filter :current_user_exists,:only=>[:select,:userless_project_selected_ajax,:create,:new]
before_filter :is_user_admin_auth,:only=>[:destroy]
before_filter :is_user_admin_or_personless, :only=>[:new]
before_filter :removed_params,:only=>[:update,:create]
before_filter :do_projects_belong_to_project_manager_projects,:only=>[:administer_update]
before_filter :editable_by_user, :only => [:edit, :update]
before_filter :administerable_by_user, :only => [:admin, :administer_update]
skip_before_filter :project_membership_required
skip_before_filter :profile_for_login_required,:only=>[:select,:userless_project_selected_ajax,:create]
cache_sweeper :people_sweeper,:only=>[:update,:create,:destroy]
def auto_complete_for_tools_name
render :json => Person.tool_counts.map(&:name).to_json
end
def auto_complete_for_expertise_name
render :json => Person.expertise_counts.map(&:name).to_json
end
protect_from_forgery :only=>[]
# GET /people
# GET /people.xml
def index
if (params[:discipline_id])
@discipline=Discipline.find(params[:discipline_id])
#FIXME: strips out the disciplines that don't match
@people=Person.find(:all,:include=>:disciplines,:conditions=>["disciplines.id=?",@discipline.id])
#need to reload the people to get their full discipline list - otherwise only get those matched above. Must be a better solution to this
@people.each(&:reload)
elsif (params[:project_role_id])
@project_role=ProjectRole.find(params[:project_role_id])
@people=Person.find(:all,:include=>[:group_memberships])
#FIXME: this needs double checking, (a) not sure its right, (b) can be paged when using find.
@people=@people.select{|p| !(p.group_memberships & @project_role.group_memberships).empty?}
end
unless @people
@people = apply_filters(Person.all).select(&:can_view?)
@people=Person.paginate_after_fetch(@people, :page=>params[:page])
else
@people = @people.select(&:can_view?)
end
respond_to do |format|
format.html # index.html.erb
format.xml
end
end
# GET /people/1
# GET /people/1.xml
def show
respond_to do |format|
format.html # show.html.erb
format.xml
end
end
# GET /people/new
# GET /people/new.xml
def new
@person = Person.new
respond_to do |format|
format.html { render :action=>"new" }
format.xml { render :xml => @person }
end
end
# GET /people/1/edit
def edit
possible_unsaved_data = "unsaved_#{@person.class.name}_#{@person.id}".to_sym
if session[possible_unsaved_data]
# if user was redirected to this 'edit' page from avatar upload page - use session
# data; alternatively, user has followed some other route - hence, unsaved session
# data is most probably not relevant anymore
if params[:use_unsaved_session_data]
# NB! these parameters are admin settings and regular users won't (and MUST NOT)
# be able to use these; admins on the other hand are most likely to never change
# any avatars - therefore, it's better to hide these attributes so they never get
# updated from the session
#
# this was also causing a bug: when "upload new avatar" pressed, then new picture
# uploaded and redirected back to edit profile page; at this poing *new* records
# in the DB for person's work group memberships would already be created, which is an
# error (if the following 3 lines are ever to be removed, the bug needs investigation)
session[possible_unsaved_data][:person].delete(:work_group_ids)
# update those attributes of a person that we want to be updated from the session
@person.attributes = session[possible_unsaved_data][:person]
end
# clear the session data anyway
session[possible_unsaved_data] = nil
end
end
def admin
respond_to do |format|
format.html
end
end
#GET /people/select
#
#Page for after registration that allows you to select yourself from a list of
#people yet to be assigned, or create a new one if you don't exist
def select
@userless_projects=Project.with_userless_people
#strip out project with no people with email addresses
#TODO: can be made more efficient by putting into a direct query in Project.with_userless_people - but not critical as this is only used during registration
@userless_projects = @userless_projects.select do |proj|
!proj.people.find{|person| !person.email.nil? && person.user.nil?}.nil?
end
@userless_projects.sort!{|a,b|a.name<=>b.name}
@person = Person.new(params[:openid_details]) #Add some default values gathered from OpenID, if provided.
render :action=>"select"
end
# POST /people
# POST /people.xml
def create
@person = Person.new(params[:person])
redirect_action="new"
set_tools_and_expertise(@person, params)
registration = false
registration = true if (current_user.person.nil?) #indicates a profile is being created during the registration process
if registration
current_user.person=@person
@userless_projects=Project.with_userless_people
@userless_projects.sort!{|a,b|a.name<=>b.name}
is_sysmo_member=params[:sysmo_member]
if (is_sysmo_member)
member_details = ''
member_details.concat(project_or_institution_details 'projects')
member_details.concat(project_or_institution_details 'institutions')
end
redirect_action="select"
end
respond_to do |format|
if @person.save && current_user.save
if (!current_user.active?)
if_sysmo_member||=false
#send mail to admin
Mailer.deliver_contact_admin_new_user_no_profile(member_details,current_user,base_host) if is_sysmo_member
#send mail to project managers
project_managers = project_managers_of_selected_projects params[:projects]
project_managers.each do |project_manager|
Mailer.deliver_contact_project_manager_new_user_no_profile(project_manager, member_details,current_user,base_host) if is_sysmo_member
end
Mailer.deliver_signup(current_user,base_host)
flash[:notice]="An email has been sent to you to confirm your email address. You need to respond to this email before you can login"
logout_user
format.html {redirect_to :controller=>"users",:action=>"activation_required"}
else
flash[:notice] = 'Person was successfully created.'
format.html { redirect_to(@person) }
format.xml { render :xml => @person, :status => :created, :location => @person }
end
else
format.html { render :action => redirect_action }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end
# PUT /people/1
# PUT /people/1.xml
def update
@person.disciplines.clear if params[:discipline_ids].nil?
# extra check required to see if any avatar was actually selected (or it remains to be the default one)
avatar_id = params[:person].delete(:avatar_id).to_i
@person.avatar_id = ((avatar_id.kind_of?(Numeric) && avatar_id > 0) ? avatar_id : nil)
set_tools_and_expertise(@person,params)
if !@person.notifiee_info.nil?
@person.notifiee_info.receive_notifications = (params[:receive_notifications] ? true : false)
@person.notifiee_info.save if @person.notifiee_info.changed?
end
respond_to do |format|
if @person.update_attributes(params[:person]) && set_group_membership_project_role_ids(@person,params)
@person.save #this seems to be required to get the tags to be set correctly - update_attributes alone doesn't [SYSMO-158]
flash[:notice] = 'Person was successfully updated.'
format.html { redirect_to(@person) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end
# PUT /people/1
# PUT /people/1.xml
def administer_update
passed_params= {:roles => User.admin_logged_in?,
:roles_mask => User.admin_logged_in?,
:can_edit_projects => (User.admin_logged_in? || (User.project_manager_logged_in? && !(@person.projects & current_user.try(:person).try(:projects).to_a).empty?)),
:can_edit_institutions => (User.admin_logged_in? || (User.project_manager_logged_in? && !(@person.projects & current_user.try(:person).try(:projects).to_a).empty?)),
:work_group_ids => (User.admin_logged_in? || User.project_manager_logged_in?)}
temp = params.clone
params[:person] = {}
passed_params.each do |param, allowed|
params[:person]["#{param}"] = temp[:person]["#{param}"] if temp[:person]["#{param}"] and allowed
params["#{param}"] = temp["#{param}"] if temp["#{param}"] and allowed
end
set_roles(@person, params) if User.admin_logged_in?
respond_to do |format|
if @person.update_attributes(params[:person])
@person.save #this seems to be required to get the tags to be set correctly - update_attributes alone doesn't [SYSMO-158]
flash[:notice] = 'Person was successfully updated.'
format.html { redirect_to(@person) }
format.xml { head :ok }
else
format.html { render :action => "admin" }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end
def set_group_membership_project_role_ids person,params
#FIXME: Consider updating to Rails 2.3 and use Nested forms to handle this more cleanly.
prefix="group_membership_role_ids_"
person.group_memberships.each do |gr|
key=prefix+gr.id.to_s
gr.project_roles.clear
if params[key.to_sym]
params[key.to_sym].each do |r|
r=ProjectRole.find(r)
gr.project_roles << r
end
end
end
end
# DELETE /people/1
# DELETE /people/1.xml
def destroy
@person.destroy
respond_to do |format|
format.html { redirect_to(people_url) }
format.xml { head :ok }
end
end
def userless_project_selected_ajax
project_id=params[:project_id]
unless project_id=="0"
proj=Project.find(project_id)
#ignore people with no email address
@people=proj.userless_people.select{|person| !person.email.blank? }
@people.sort!{|a,b| a.last_name<=>b.last_name}
render :partial=>"userless_people_list",:locals=>{:people=>@people}
else
render :text=>""
end
end
def get_work_group
people = nil
project_id=params[:project_id]
institution_id=params[:institution_id]
if institution_id == "0"
project = Project.find(project_id)
people = project.people
else
workgroup = WorkGroup.find_by_project_id_and_institution_id(project_id,institution_id)
people = workgroup.people
end
people_list = people.collect{|p| [p.name, p.email, p.id]}
respond_to do |format|
format.json {
render :json => {:status => 200, :people_list => people_list }
}
end
end
private
def set_tools_and_expertise person,params
exp_changed = person.tag_with_params params,"expertise"
tools_changed = person.tag_with_params params,"tool"
if immediately_clear_tag_cloud?
expire_annotation_fragments("expertise") if exp_changed
expire_annotation_fragments("tool") if tools_changed
else
#TODO: should expire and rebuild in a background task
end
end
def set_roles person, params
roles = person.is_admin? ? ['admin'] : []
if params[:roles]
params[:roles].each_key do |key|
roles << key
end
end
person.roles=roles
end
def is_user_admin_or_personless
unless User.admin_logged_in? || current_user.person.nil?
error("You do not have permission to create new people","Is invalid (not admin)")
return false
end
end
def current_user_exists
if !current_user
redirect_to(:root)
end
!!current_user
end
#checks the params attributes and strips those that cannot be set by non-admins, or other policy
def removed_params
# make sure to update people/_form if this changes
# param => allowed access?
removed_params = [:roles, :roles_mask, :can_edit_projects, :can_edit_institutions, :work_group_ids]
removed_params.each do |param|
params[:person].delete(param) if params[:person]
params.delete param if params
end
end
def project_or_institution_details projects_or_institutions
details = ''
unless params[projects_or_institutions].blank?
params[projects_or_institutions].each do |project_or_institution|
project_or_institution_details= project_or_institution.split(',')
if project_or_institution_details[0] == 'Others'
details.concat("Other #{projects_or_institutions}: #{params["other_#{projects_or_institutions}"]}; ")
else
details.concat("#{projects_or_institutions.singularize.capitalize}: #{project_or_institution_details[0]}, Id: #{project_or_institution_details[1]}; ")
end
end
end
details
end
def project_managers_of_selected_projects projects_param
project_manager_list = []
unless projects_param.blank?
projects_param.each do |project_param|
project_detail = project_param.split(',')
project = Project.find_by_id(project_detail[1])
project_managers = project.try(:project_managers)
project_manager_list |= project_managers unless project_managers.nil?
end
end
project_manager_list
end
def do_projects_belong_to_project_manager_projects
if (params[:person] and params[:person][:work_group_ids])
if User.project_manager_logged_in? && !User.admin_logged_in?
projects = []
params[:person][:work_group_ids].each do |id|
work_group = WorkGroup.find_by_id(id)
project = work_group.try(:project)
projects << project unless project.nil?
end
project_manager_projects = current_user.person.projects
flag = true
projects.each do |project|
flag = false if !project_manager_projects.include? project
end
if flag == false
error("Project manager can not assign person to the projects that they are not in","Is invalid")
end
return flag
end
end
end
def editable_by_user
unless @person.can_be_edited_by?(current_user)
error("Insufficient privileges", "is invalid (insufficient_privileges)")
return false
end
end
def administerable_by_user
@person=Person.find(params[:id])
unless @person.can_be_administered_by?(current_user)
error("Insufficient privileges", "is invalid (insufficient_privileges)")
return false
end
end
end
removed commented code
class PeopleController < ApplicationController
include Seek::AnnotationCommon
before_filter :find_and_auth, :only => [:show, :edit, :update, :destroy]
before_filter :current_user_exists,:only=>[:select,:userless_project_selected_ajax,:create,:new]
before_filter :is_user_admin_auth,:only=>[:destroy]
before_filter :is_user_admin_or_personless, :only=>[:new]
before_filter :removed_params,:only=>[:update,:create]
before_filter :do_projects_belong_to_project_manager_projects,:only=>[:administer_update]
before_filter :editable_by_user, :only => [:edit, :update]
before_filter :administerable_by_user, :only => [:admin, :administer_update]
skip_before_filter :project_membership_required
skip_before_filter :profile_for_login_required,:only=>[:select,:userless_project_selected_ajax,:create]
cache_sweeper :people_sweeper,:only=>[:update,:create,:destroy]
def auto_complete_for_tools_name
render :json => Person.tool_counts.map(&:name).to_json
end
def auto_complete_for_expertise_name
render :json => Person.expertise_counts.map(&:name).to_json
end
protect_from_forgery :only=>[]
# GET /people
# GET /people.xml
def index
if (params[:discipline_id])
@discipline=Discipline.find(params[:discipline_id])
#FIXME: strips out the disciplines that don't match
@people=Person.find(:all,:include=>:disciplines,:conditions=>["disciplines.id=?",@discipline.id])
#need to reload the people to get their full discipline list - otherwise only get those matched above. Must be a better solution to this
@people.each(&:reload)
elsif (params[:project_role_id])
@project_role=ProjectRole.find(params[:project_role_id])
@people=Person.find(:all,:include=>[:group_memberships])
#FIXME: this needs double checking, (a) not sure its right, (b) can be paged when using find.
@people=@people.select{|p| !(p.group_memberships & @project_role.group_memberships).empty?}
end
unless @people
@people = apply_filters(Person.all).select(&:can_view?)
@people=Person.paginate_after_fetch(@people, :page=>params[:page])
else
@people = @people.select(&:can_view?)
end
respond_to do |format|
format.html # index.html.erb
format.xml
end
end
# GET /people/1
# GET /people/1.xml
def show
respond_to do |format|
format.html # show.html.erb
format.xml
end
end
# GET /people/new
# GET /people/new.xml
def new
@person = Person.new
respond_to do |format|
format.html { render :action=>"new" }
format.xml { render :xml => @person }
end
end
# GET /people/1/edit
def edit
possible_unsaved_data = "unsaved_#{@person.class.name}_#{@person.id}".to_sym
if session[possible_unsaved_data]
# if user was redirected to this 'edit' page from avatar upload page - use session
# data; alternatively, user has followed some other route - hence, unsaved session
# data is most probably not relevant anymore
if params[:use_unsaved_session_data]
# NB! these parameters are admin settings and regular users won't (and MUST NOT)
# be able to use these; admins on the other hand are most likely to never change
# any avatars - therefore, it's better to hide these attributes so they never get
# updated from the session
#
# this was also causing a bug: when "upload new avatar" pressed, then new picture
# uploaded and redirected back to edit profile page; at this poing *new* records
# in the DB for person's work group memberships would already be created, which is an
# error (if the following 3 lines are ever to be removed, the bug needs investigation)
session[possible_unsaved_data][:person].delete(:work_group_ids)
# update those attributes of a person that we want to be updated from the session
@person.attributes = session[possible_unsaved_data][:person]
end
# clear the session data anyway
session[possible_unsaved_data] = nil
end
end
def admin
respond_to do |format|
format.html
end
end
#GET /people/select
#
#Page for after registration that allows you to select yourself from a list of
#people yet to be assigned, or create a new one if you don't exist
def select
@userless_projects=Project.with_userless_people
#strip out project with no people with email addresses
#TODO: can be made more efficient by putting into a direct query in Project.with_userless_people - but not critical as this is only used during registration
@userless_projects = @userless_projects.select do |proj|
!proj.people.find{|person| !person.email.nil? && person.user.nil?}.nil?
end
@userless_projects.sort!{|a,b|a.name<=>b.name}
@person = Person.new(params[:openid_details]) #Add some default values gathered from OpenID, if provided.
render :action=>"select"
end
# POST /people
# POST /people.xml
def create
@person = Person.new(params[:person])
redirect_action="new"
set_tools_and_expertise(@person, params)
registration = false
registration = true if (current_user.person.nil?) #indicates a profile is being created during the registration process
if registration
current_user.person=@person
@userless_projects=Project.with_userless_people
@userless_projects.sort!{|a,b|a.name<=>b.name}
is_sysmo_member=params[:sysmo_member]
if (is_sysmo_member)
member_details = ''
member_details.concat(project_or_institution_details 'projects')
member_details.concat(project_or_institution_details 'institutions')
end
redirect_action="select"
end
respond_to do |format|
if @person.save && current_user.save
if (!current_user.active?)
if_sysmo_member||=false
#send mail to admin
Mailer.deliver_contact_admin_new_user_no_profile(member_details,current_user,base_host) if is_sysmo_member
#send mail to project managers
project_managers = project_managers_of_selected_projects params[:projects]
project_managers.each do |project_manager|
Mailer.deliver_contact_project_manager_new_user_no_profile(project_manager, member_details,current_user,base_host) if is_sysmo_member
end
Mailer.deliver_signup(current_user,base_host)
flash[:notice]="An email has been sent to you to confirm your email address. You need to respond to this email before you can login"
logout_user
format.html {redirect_to :controller=>"users",:action=>"activation_required"}
else
flash[:notice] = 'Person was successfully created.'
format.html { redirect_to(@person) }
format.xml { render :xml => @person, :status => :created, :location => @person }
end
else
format.html { render :action => redirect_action }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end
# PUT /people/1
# PUT /people/1.xml
def update
@person.disciplines.clear if params[:discipline_ids].nil?
# extra check required to see if any avatar was actually selected (or it remains to be the default one)
avatar_id = params[:person].delete(:avatar_id).to_i
@person.avatar_id = ((avatar_id.kind_of?(Numeric) && avatar_id > 0) ? avatar_id : nil)
set_tools_and_expertise(@person,params)
if !@person.notifiee_info.nil?
@person.notifiee_info.receive_notifications = (params[:receive_notifications] ? true : false)
@person.notifiee_info.save if @person.notifiee_info.changed?
end
respond_to do |format|
if @person.update_attributes(params[:person]) && set_group_membership_project_role_ids(@person,params)
@person.save #this seems to be required to get the tags to be set correctly - update_attributes alone doesn't [SYSMO-158]
flash[:notice] = 'Person was successfully updated.'
format.html { redirect_to(@person) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end
# PUT /people/1
# PUT /people/1.xml
def administer_update
passed_params= {:roles => User.admin_logged_in?,
:roles_mask => User.admin_logged_in?,
:can_edit_projects => (User.admin_logged_in? || (User.project_manager_logged_in? && !(@person.projects & current_user.try(:person).try(:projects).to_a).empty?)),
:can_edit_institutions => (User.admin_logged_in? || (User.project_manager_logged_in? && !(@person.projects & current_user.try(:person).try(:projects).to_a).empty?)),
:work_group_ids => (User.admin_logged_in? || User.project_manager_logged_in?)}
temp = params.clone
params[:person] = {}
passed_params.each do |param, allowed|
params[:person]["#{param}"] = temp[:person]["#{param}"] if temp[:person]["#{param}"] and allowed
params["#{param}"] = temp["#{param}"] if temp["#{param}"] and allowed
end
set_roles(@person, params) if User.admin_logged_in?
respond_to do |format|
if @person.update_attributes(params[:person])
@person.save #this seems to be required to get the tags to be set correctly - update_attributes alone doesn't [SYSMO-158]
flash[:notice] = 'Person was successfully updated.'
format.html { redirect_to(@person) }
format.xml { head :ok }
else
format.html { render :action => "admin" }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end
def set_group_membership_project_role_ids person,params
#FIXME: Consider updating to Rails 2.3 and use Nested forms to handle this more cleanly.
prefix="group_membership_role_ids_"
person.group_memberships.each do |gr|
key=prefix+gr.id.to_s
gr.project_roles.clear
if params[key.to_sym]
params[key.to_sym].each do |r|
r=ProjectRole.find(r)
gr.project_roles << r
end
end
end
end
# DELETE /people/1
# DELETE /people/1.xml
def destroy
@person.destroy
respond_to do |format|
format.html { redirect_to(people_url) }
format.xml { head :ok }
end
end
def userless_project_selected_ajax
project_id=params[:project_id]
unless project_id=="0"
proj=Project.find(project_id)
#ignore people with no email address
@people=proj.userless_people.select{|person| !person.email.blank? }
@people.sort!{|a,b| a.last_name<=>b.last_name}
render :partial=>"userless_people_list",:locals=>{:people=>@people}
else
render :text=>""
end
end
def get_work_group
people = nil
project_id=params[:project_id]
institution_id=params[:institution_id]
if institution_id == "0"
project = Project.find(project_id)
people = project.people
else
workgroup = WorkGroup.find_by_project_id_and_institution_id(project_id,institution_id)
people = workgroup.people
end
people_list = people.collect{|p| [p.name, p.email, p.id]}
respond_to do |format|
format.json {
render :json => {:status => 200, :people_list => people_list }
}
end
end
private
def set_tools_and_expertise person,params
exp_changed = person.tag_with_params params,"expertise"
tools_changed = person.tag_with_params params,"tool"
if immediately_clear_tag_cloud?
expire_annotation_fragments("expertise") if exp_changed
expire_annotation_fragments("tool") if tools_changed
else
#TODO: should expire and rebuild in a background task
end
end
def set_roles person, params
roles = person.is_admin? ? ['admin'] : []
if params[:roles]
params[:roles].each_key do |key|
roles << key
end
end
person.roles=roles
end
def is_user_admin_or_personless
unless User.admin_logged_in? || current_user.person.nil?
error("You do not have permission to create new people","Is invalid (not admin)")
return false
end
end
def current_user_exists
if !current_user
redirect_to(:root)
end
!!current_user
end
#checks the params attributes and strips those that cannot be set by non-admins, or other policy
def removed_params
# make sure to update people/_form if this changes
# param => allowed access?
removed_params = [:roles, :roles_mask, :can_edit_projects, :can_edit_institutions, :work_group_ids]
removed_params.each do |param|
params[:person].delete(param) if params[:person]
params.delete param if params
end
end
def project_or_institution_details projects_or_institutions
details = ''
unless params[projects_or_institutions].blank?
params[projects_or_institutions].each do |project_or_institution|
project_or_institution_details= project_or_institution.split(',')
if project_or_institution_details[0] == 'Others'
details.concat("Other #{projects_or_institutions}: #{params["other_#{projects_or_institutions}"]}; ")
else
details.concat("#{projects_or_institutions.singularize.capitalize}: #{project_or_institution_details[0]}, Id: #{project_or_institution_details[1]}; ")
end
end
end
details
end
def project_managers_of_selected_projects projects_param
project_manager_list = []
unless projects_param.blank?
projects_param.each do |project_param|
project_detail = project_param.split(',')
project = Project.find_by_id(project_detail[1])
project_managers = project.try(:project_managers)
project_manager_list |= project_managers unless project_managers.nil?
end
end
project_manager_list
end
def do_projects_belong_to_project_manager_projects
if (params[:person] and params[:person][:work_group_ids])
if User.project_manager_logged_in? && !User.admin_logged_in?
projects = []
params[:person][:work_group_ids].each do |id|
work_group = WorkGroup.find_by_id(id)
project = work_group.try(:project)
projects << project unless project.nil?
end
project_manager_projects = current_user.person.projects
flag = true
projects.each do |project|
flag = false if !project_manager_projects.include? project
end
if flag == false
error("Project manager can not assign person to the projects that they are not in","Is invalid")
end
return flag
end
end
end
def editable_by_user
unless @person.can_be_edited_by?(current_user)
error("Insufficient privileges", "is invalid (insufficient_privileges)")
return false
end
end
def administerable_by_user
@person=Person.find(params[:id])
unless @person.can_be_administered_by?(current_user)
error("Insufficient privileges", "is invalid (insufficient_privileges)")
return false
end
end
end
|
class PeopleController < ApplicationController
before_filter :login_required,:except=>[:select,:userless_project_selected_ajax,:create,:new]
before_filter :current_user_exists,:only=>[:select,:userless_project_selected_ajax,:create,:new]
before_filter :profile_belongs_to_current_or_is_admin, :only=>[:edit, :update]
before_filter :profile_is_not_another_admin_except_me, :only=>[:edit,:update]
before_filter :is_user_admin_auth, :only=>[:destroy]
before_filter :is_user_admin_or_personless, :only=>[:new]
before_filter :auth_params,:only=>[:update,:create]
before_filter :set_tagging_parameters,:only=>[:edit,:new,:create,:update]
def auto_complete_for_tools_name
render :json => Person.tool_counts.map(&:name).to_json
end
def auto_complete_for_expertise_name
render :json => Person.expertise_counts.map(&:name).to_json
end
protect_from_forgery :only=>[]
# GET /people
# GET /people.xml
def index
if (!params[:expertise].nil?)
@expertise=params[:expertise]
@people=Person.tagged_with(@expertise, :on=>:expertise)
elsif (!params[:tools].nil?)
@tools=params[:tools]
@people=Person.tagged_with(@tools, :on=>:tools)
elsif (params[:discipline_id])
@discipline=Discipline.find(params[:discipline_id])
#FIXME: strips out the disciplines that don't match
@people=Person.find(:all,:include=>:disciplines,:conditions=>["disciplines.id=?",@discipline.id], :order=>:last_name)
#need to reload the people to get their full discipline list - otherwise only get those matched above. Must be a better solution to this
@people=@people.collect{|p| Person.find(p.id)}
elsif (params[:role_id])
@role=Role.find(params[:role_id])
@people=Person.find(:all,:include=>[:group_memberships], :order=>:last_name)
#FIXME: this needs double checking, (a) not sure its right, (b) can be paged when using find.
@people=@people.select{|p| !(p.group_memberships & @role.group_memberships).empty?}
else
@people=Person.paginate :page=>params[:page]
end
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @people.to_xml}
end
end
# GET /people/1
# GET /people/1.xml
def show
@person = Person.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @person.to_xml}
end
end
# GET /people/new
# GET /people/new.xml
def new
@tags_tools = Person.tool_counts.sort{|a,b| a.name<=>b.name}
@tags_expertise = Person.expertise_counts.sort{|a,b| a.name<=>b.name}
@person = Person.new
respond_to do |format|
format.html { render :action=>"new",:layout=>"logged_out" }
format.xml { render :xml => @person }
end
end
# GET /people/1/edit
def edit
@tags_tools = Person.tool_counts.sort{|a,b| a.name<=>b.name}
@tags_expertise = Person.expertise_counts.sort{|a,b| a.name<=>b.name}
@person = Person.find(params[:id])
possible_unsaved_data = "unsaved_#{@person.class.name}_#{@person.id}".to_sym
if session[possible_unsaved_data]
# if user was redirected to this 'edit' page from avatar upload page - use session
# data; alternatively, user has followed some other route - hence, unsaved session
# data is most probably not relevant anymore
if params[:use_unsaved_session_data]
# NB! these parameters are admin settings and regular users won't (and MUST NOT)
# be able to use these; admins on the other hand are most likely to never change
# any avatars - therefore, it's better to hide these attributes so they never get
# updated from the session
#
# this was also causing a bug: when "upload new avatar" pressed, then new picture
# uploaded and redirected back to edit profile page; at this poing *new* records
# in the DB for person's work group memberships would already be created, which is an
# error (if the following 3 lines are ever to be removed, the bug needs investigation)
session[possible_unsaved_data][:person].delete(:work_group_ids)
session[possible_unsaved_data].delete(:can_edit_projects)
session[possible_unsaved_data].delete(:can_edit_institutions)
# update those attributes of a person that we want to be updated from the session
@person.attributes = session[possible_unsaved_data][:person]
#FIXME: needs updating to handle new tools and expertise tag field
# @person.tool_list = session[possible_unsaved_data][:tool][:list] if session[]
# @person.expertise_list = session[possible_unsaved_data][:expertise][:list]
end
# clear the session data anyway
session[possible_unsaved_data] = nil
end
end
#GET /people/select
#
#Page for after registration that allows you to select yourself from a list of
#people yet to be assigned, or create a new one if you don't exist
def select
@userless_projects=Project.with_userless_people
#strip out project with no people with email addresses
#TODO: can be made more efficient by putting into a direct query in Project.with_userless_people - but not critical as this is only used during registration
@userless_projects = @userless_projects.select do |proj|
!proj.people.find{|person| !person.email.nil? && person.user.nil?}.nil?
end
@userless_projects.sort!{|a,b|a.name<=>b.name}
@person = Person.new
render :action=>"select",:layout=>"logged_out"
end
# POST /people
# POST /people.xml
def create
@person = Person.new(params[:person])
redirect_action="new"
set_tools_and_expertise(@person, params)
if (current_user.person.nil?) #indicates a profile is being created during the registration process
current_user.person=@person
@userless_projects=Project.with_userless_people
@userless_projects.sort!{|a,b|a.name<=>b.name}
is_sysmo_member=params[:sysmo_member]
if (is_sysmo_member)
member_details=params[:sysmo_member_details]
end
redirect_action="select"
end
respond_to do |format|
if @person.save && current_user.save
if (!current_user.active?)
if_sysmo_member||=false
Mailer.deliver_contact_admin_new_user_no_profile(member_details,current_user,base_host) if is_sysmo_member
Mailer.deliver_signup(current_user,base_host)
flash[:notice]="An email has been sent to you to confirm your email address. You need to respond to this email before you can login"
logout_user
format.html {redirect_to :controller=>"users",:action=>"activation_required"}
else
flash[:notice] = 'Person was successfully created.'
format.html { redirect_to(@person) }
format.xml { render :xml => @person, :status => :created, :location => @person }
end
else
format.html { render :action => redirect_action,:layout=>"logged_out" }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end
# PUT /people/1
# PUT /people/1.xml
def update
@person = Person.find(params[:id])
old_tags=@person.tool_list + @person.expertise_list
@person.disciplines.clear if params[:discipline_ids].nil?
# extra check required to see if any avatar was actually selected (or it remains to be the default one)
avatar_id = params[:person].delete(:avatar_id).to_i
@person.avatar_id = ((avatar_id.kind_of?(Numeric) && avatar_id > 0) ? avatar_id : nil)
set_tools_and_expertise(@person,params)
# some "Person" instances might not have a "User" associated with them - because the user didn't register yet
if current_user.is_admin?
unless @person.user.nil?
@person.user.can_edit_projects = (params[:can_edit_projects] ? true : false)
@person.user.can_edit_institutions = (params[:can_edit_institutions] ? true : false)
@person.user.save
end
end
new_tags=@person.tool_list + @person.expertise_list
#FIXME: don't like this, but is a temp solution for handling lack of observer callback when removing a tag
expire_fragment("tag_clouds") if (old_tags != new_tags)
respond_to do |format|
if @person.update_attributes(params[:person]) && set_group_membership_role_ids(@person,params)
@person.save #this seems to be required to get the tags to be set correctly - update_attributes alone doesn't [SYSMO-158]
flash[:notice] = 'Person was successfully updated.'
format.html { redirect_to(@person) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end
def set_group_membership_role_ids person,params
#FIXME: Consider updating to Rails 2.3 and use Nested forms to handle this more cleanly.
prefix="group_membership_role_ids_"
person.group_memberships.each do |gr|
key=prefix+gr.id.to_s
gr.roles.clear
if params[key.to_sym]
params[key.to_sym].each do |r|
r=Role.find(r)
gr.roles << r
end
end
end
end
# DELETE /people/1
# DELETE /people/1.xml
def destroy
@person = Person.find(params[:id])
@person.destroy
respond_to do |format|
format.html { redirect_to(people_url) }
format.xml { head :ok }
end
end
def userless_project_selected_ajax
project_id=params[:project_id]
unless project_id=="0"
proj=Project.find(project_id)
#ignore people with no email address
@people=proj.userless_people.select{|person| !person.email.blank? }
@people.sort!{|a,b| a.last_name<=>b.last_name}
render :partial=>"userless_people_list",:locals=>{:people=>@people}
else
render :text=>""
end
end
private
def set_tools_and_expertise person,params
tags=""
params[:tools_autocompleter_selected_ids].each do |selected_id|
tag=Tag.find(selected_id)
tags << tag.name << ","
end unless params[:tools_autocompleter_selected_ids].nil?
params[:tools_autocompleter_unrecognized_items].each do |item|
tags << item << ","
end unless params[:tools_autocompleter_unrecognized_items].nil?
person.tool_list=tags
tags=""
params[:expertise_autocompleter_selected_ids].each do |selected_id|
tag=Tag.find(selected_id)
tags << tag.name << ","
end unless params[:expertise_autocompleter_selected_ids].nil?
params[:expertise_autocompleter_unrecognized_items].each do |item|
tags << item << ","
end unless params[:expertise_autocompleter_unrecognized_items].nil?
person.expertise_list=tags
end
def profile_belongs_to_current_or_is_admin
@person=Person.find(params[:id])
unless @person == current_user.person || current_user.is_admin?
error("Not the current person", "is invalid (not owner)")
return false
end
end
def profile_is_not_another_admin_except_me
@person=Person.find(params[:id])
if !@person.user.nil? && @person.user!=current_user && @person.user.is_admin?
error("Cannot edit another Admins profile","is invalid(another admin)")
return false
end
end
def is_user_admin_or_personless
unless current_user.is_admin? || current_user.person.nil?
error("You do not have permission to create new people","Is invalid (not admin)")
return false
end
end
def current_user_exists
if !current_user
redirect_to("/")
end
!!current_user
end
#checks the params attributes and strips those that cannot be set by non-admins, or other policy
def auth_params
if !current_user.is_admin?
params[:person].delete(:is_pal) if params[:person]
end
end
def set_tagging_parameters
tools=Person.tool_counts.sort{|a,b| a.id<=>b.id}.collect{|t| {'id'=>t.id,'name'=>t.name}}
@all_tools_as_json=tools.to_json
expertise=Person.expertise_counts.sort{|a,b| a.id<=>b.id}.collect{|t|{'id'=>t.id,'name'=>t.name}}
@all_expertise_as_json=expertise.to_json
end
end
order people pages by surname
class PeopleController < ApplicationController
before_filter :login_required,:except=>[:select,:userless_project_selected_ajax,:create,:new]
before_filter :current_user_exists,:only=>[:select,:userless_project_selected_ajax,:create,:new]
before_filter :profile_belongs_to_current_or_is_admin, :only=>[:edit, :update]
before_filter :profile_is_not_another_admin_except_me, :only=>[:edit,:update]
before_filter :is_user_admin_auth, :only=>[:destroy]
before_filter :is_user_admin_or_personless, :only=>[:new]
before_filter :auth_params,:only=>[:update,:create]
before_filter :set_tagging_parameters,:only=>[:edit,:new,:create,:update]
def auto_complete_for_tools_name
render :json => Person.tool_counts.map(&:name).to_json
end
def auto_complete_for_expertise_name
render :json => Person.expertise_counts.map(&:name).to_json
end
protect_from_forgery :only=>[]
# GET /people
# GET /people.xml
def index
if (!params[:expertise].nil?)
@expertise=params[:expertise]
@people=Person.tagged_with(@expertise, :on=>:expertise)
elsif (!params[:tools].nil?)
@tools=params[:tools]
@people=Person.tagged_with(@tools, :on=>:tools)
elsif (params[:discipline_id])
@discipline=Discipline.find(params[:discipline_id])
#FIXME: strips out the disciplines that don't match
@people=Person.find(:all,:include=>:disciplines,:conditions=>["disciplines.id=?",@discipline.id], :order=>:last_name)
#need to reload the people to get their full discipline list - otherwise only get those matched above. Must be a better solution to this
@people=@people.collect{|p| Person.find(p.id)}
elsif (params[:role_id])
@role=Role.find(params[:role_id])
@people=Person.find(:all,:include=>[:group_memberships], :order=>:last_name)
#FIXME: this needs double checking, (a) not sure its right, (b) can be paged when using find.
@people=@people.select{|p| !(p.group_memberships & @role.group_memberships).empty?}
else
@people=Person.paginate :page=>params[:page], :order=>:last_name
end
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @people.to_xml}
end
end
# GET /people/1
# GET /people/1.xml
def show
@person = Person.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @person.to_xml}
end
end
# GET /people/new
# GET /people/new.xml
def new
@tags_tools = Person.tool_counts.sort{|a,b| a.name<=>b.name}
@tags_expertise = Person.expertise_counts.sort{|a,b| a.name<=>b.name}
@person = Person.new
respond_to do |format|
format.html { render :action=>"new",:layout=>"logged_out" }
format.xml { render :xml => @person }
end
end
# GET /people/1/edit
def edit
@tags_tools = Person.tool_counts.sort{|a,b| a.name<=>b.name}
@tags_expertise = Person.expertise_counts.sort{|a,b| a.name<=>b.name}
@person = Person.find(params[:id])
possible_unsaved_data = "unsaved_#{@person.class.name}_#{@person.id}".to_sym
if session[possible_unsaved_data]
# if user was redirected to this 'edit' page from avatar upload page - use session
# data; alternatively, user has followed some other route - hence, unsaved session
# data is most probably not relevant anymore
if params[:use_unsaved_session_data]
# NB! these parameters are admin settings and regular users won't (and MUST NOT)
# be able to use these; admins on the other hand are most likely to never change
# any avatars - therefore, it's better to hide these attributes so they never get
# updated from the session
#
# this was also causing a bug: when "upload new avatar" pressed, then new picture
# uploaded and redirected back to edit profile page; at this poing *new* records
# in the DB for person's work group memberships would already be created, which is an
# error (if the following 3 lines are ever to be removed, the bug needs investigation)
session[possible_unsaved_data][:person].delete(:work_group_ids)
session[possible_unsaved_data].delete(:can_edit_projects)
session[possible_unsaved_data].delete(:can_edit_institutions)
# update those attributes of a person that we want to be updated from the session
@person.attributes = session[possible_unsaved_data][:person]
#FIXME: needs updating to handle new tools and expertise tag field
# @person.tool_list = session[possible_unsaved_data][:tool][:list] if session[]
# @person.expertise_list = session[possible_unsaved_data][:expertise][:list]
end
# clear the session data anyway
session[possible_unsaved_data] = nil
end
end
#GET /people/select
#
#Page for after registration that allows you to select yourself from a list of
#people yet to be assigned, or create a new one if you don't exist
def select
@userless_projects=Project.with_userless_people
#strip out project with no people with email addresses
#TODO: can be made more efficient by putting into a direct query in Project.with_userless_people - but not critical as this is only used during registration
@userless_projects = @userless_projects.select do |proj|
!proj.people.find{|person| !person.email.nil? && person.user.nil?}.nil?
end
@userless_projects.sort!{|a,b|a.name<=>b.name}
@person = Person.new
render :action=>"select",:layout=>"logged_out"
end
# POST /people
# POST /people.xml
def create
@person = Person.new(params[:person])
redirect_action="new"
set_tools_and_expertise(@person, params)
if (current_user.person.nil?) #indicates a profile is being created during the registration process
current_user.person=@person
@userless_projects=Project.with_userless_people
@userless_projects.sort!{|a,b|a.name<=>b.name}
is_sysmo_member=params[:sysmo_member]
if (is_sysmo_member)
member_details=params[:sysmo_member_details]
end
redirect_action="select"
end
respond_to do |format|
if @person.save && current_user.save
if (!current_user.active?)
if_sysmo_member||=false
Mailer.deliver_contact_admin_new_user_no_profile(member_details,current_user,base_host) if is_sysmo_member
Mailer.deliver_signup(current_user,base_host)
flash[:notice]="An email has been sent to you to confirm your email address. You need to respond to this email before you can login"
logout_user
format.html {redirect_to :controller=>"users",:action=>"activation_required"}
else
flash[:notice] = 'Person was successfully created.'
format.html { redirect_to(@person) }
format.xml { render :xml => @person, :status => :created, :location => @person }
end
else
format.html { render :action => redirect_action,:layout=>"logged_out" }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end
# PUT /people/1
# PUT /people/1.xml
def update
@person = Person.find(params[:id])
old_tags=@person.tool_list + @person.expertise_list
@person.disciplines.clear if params[:discipline_ids].nil?
# extra check required to see if any avatar was actually selected (or it remains to be the default one)
avatar_id = params[:person].delete(:avatar_id).to_i
@person.avatar_id = ((avatar_id.kind_of?(Numeric) && avatar_id > 0) ? avatar_id : nil)
set_tools_and_expertise(@person,params)
# some "Person" instances might not have a "User" associated with them - because the user didn't register yet
if current_user.is_admin?
unless @person.user.nil?
@person.user.can_edit_projects = (params[:can_edit_projects] ? true : false)
@person.user.can_edit_institutions = (params[:can_edit_institutions] ? true : false)
@person.user.save
end
end
new_tags=@person.tool_list + @person.expertise_list
#FIXME: don't like this, but is a temp solution for handling lack of observer callback when removing a tag
expire_fragment("tag_clouds") if (old_tags != new_tags)
respond_to do |format|
if @person.update_attributes(params[:person]) && set_group_membership_role_ids(@person,params)
@person.save #this seems to be required to get the tags to be set correctly - update_attributes alone doesn't [SYSMO-158]
flash[:notice] = 'Person was successfully updated.'
format.html { redirect_to(@person) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
end
end
end
def set_group_membership_role_ids person,params
#FIXME: Consider updating to Rails 2.3 and use Nested forms to handle this more cleanly.
prefix="group_membership_role_ids_"
person.group_memberships.each do |gr|
key=prefix+gr.id.to_s
gr.roles.clear
if params[key.to_sym]
params[key.to_sym].each do |r|
r=Role.find(r)
gr.roles << r
end
end
end
end
# DELETE /people/1
# DELETE /people/1.xml
def destroy
@person = Person.find(params[:id])
@person.destroy
respond_to do |format|
format.html { redirect_to(people_url) }
format.xml { head :ok }
end
end
def userless_project_selected_ajax
project_id=params[:project_id]
unless project_id=="0"
proj=Project.find(project_id)
#ignore people with no email address
@people=proj.userless_people.select{|person| !person.email.blank? }
@people.sort!{|a,b| a.last_name<=>b.last_name}
render :partial=>"userless_people_list",:locals=>{:people=>@people}
else
render :text=>""
end
end
private
def set_tools_and_expertise person,params
tags=""
params[:tools_autocompleter_selected_ids].each do |selected_id|
tag=Tag.find(selected_id)
tags << tag.name << ","
end unless params[:tools_autocompleter_selected_ids].nil?
params[:tools_autocompleter_unrecognized_items].each do |item|
tags << item << ","
end unless params[:tools_autocompleter_unrecognized_items].nil?
person.tool_list=tags
tags=""
params[:expertise_autocompleter_selected_ids].each do |selected_id|
tag=Tag.find(selected_id)
tags << tag.name << ","
end unless params[:expertise_autocompleter_selected_ids].nil?
params[:expertise_autocompleter_unrecognized_items].each do |item|
tags << item << ","
end unless params[:expertise_autocompleter_unrecognized_items].nil?
person.expertise_list=tags
end
def profile_belongs_to_current_or_is_admin
@person=Person.find(params[:id])
unless @person == current_user.person || current_user.is_admin?
error("Not the current person", "is invalid (not owner)")
return false
end
end
def profile_is_not_another_admin_except_me
@person=Person.find(params[:id])
if !@person.user.nil? && @person.user!=current_user && @person.user.is_admin?
error("Cannot edit another Admins profile","is invalid(another admin)")
return false
end
end
def is_user_admin_or_personless
unless current_user.is_admin? || current_user.person.nil?
error("You do not have permission to create new people","Is invalid (not admin)")
return false
end
end
def current_user_exists
if !current_user
redirect_to("/")
end
!!current_user
end
#checks the params attributes and strips those that cannot be set by non-admins, or other policy
def auth_params
if !current_user.is_admin?
params[:person].delete(:is_pal) if params[:person]
end
end
def set_tagging_parameters
tools=Person.tool_counts.sort{|a,b| a.id<=>b.id}.collect{|t| {'id'=>t.id,'name'=>t.name}}
@all_tools_as_json=tools.to_json
expertise=Person.expertise_counts.sort{|a,b| a.id<=>b.id}.collect{|t|{'id'=>t.id,'name'=>t.name}}
@all_expertise_as_json=expertise.to_json
end
end
|
# Leap - Electronic Individual Learning Plan Software
# Copyright (C) 2011 South Devon College
# Leap is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Leap is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with Leap. If not, see <http://www.gnu.org/licenses/>.
require 'misc/misc_dates'
class PeopleController < ApplicationController
skip_before_filter :set_topic
before_filter :person_set_topic, :except => [:search]
before_filter :staff_only, :only => [:search,:select]
layout :set_layout
def show
respond_to do |format|
format.html do
@sidebar_links = parse_sidebar_links
@progress_bar = getProgressData
if Settings.home_page == "progress"
if @topic.staff? && @progress_bar.empty?
## Redirecting to route fails - Needs to use route instead of string eventually.
redirect_to "/people/#{@topic.mis_id}/timetables"
return
end
## TODO fix badges bug
@badges = {:moodle => getMdlBadges, :course => nil}
@aspiration = @topic.aspirations.last.aspiration if @topic.aspirations.present?
@notifications = @topic.notifications.where(:notified => false) if @topic.id == @user.id
@news = Settings.news_modal == 'on' ? true : false
@notify = @user.last_active && (@user.last_active + 2.days) < Date.today ? true : false
@user.last_active = Date.today
@user.save
else
@tiles = @topic.events.where(:eventable_type => "Target",:transition => :overdue).
where(:event_date => (Date.today - 1.week)..(Date.today + 1.month)).limit(8)
@tiles += @topic.events.where(:eventable_type => "Note").limit(8)
@tiles += @topic.events.where(:eventable_type => "MdlBadge").limit(8)
@tiles = @tiles.sort_by(&:event_date).reverse.map(&:to_tile)
@tiles.unshift(SimplePoll.where(:id => Settings.current_simple_poll).first.to_tile) unless Settings.current_simple_poll.blank?
ppdc = Settings.moodle_badge_block_courses.try(:split,",")
@tiles.unshift(@topic.mdl_badges.where(:mdl_course_id => ppdc).last.to_course_tile) if ppdc && @topic.mdl_badges.where(:mdl_course_id => ppdc).any?
tracks = ["core","maths","english"].map{|ct| @topic.mdl_grade_tracks.where(:course_type => ct).last}.reject{|x| x.nil?}
@tiles.unshift(tracks.map{|x| x.to_tile})
misc_dates = MISC::MiscDates.new
attendances = ["overall","core","maths","english"].map{|ct| @topic.attendances.where(:course_type => ct).where(["week_beginning >= ?", misc_dates.start_of_acyr] ).last}.reject{|x| x.nil?}
attendances.select!{|x| x.course_type != "overall"} if attendances.length == 2
@tiles.unshift(attendances.map{|x| x.to_tile})
@tiles.unshift(@topic.timetable_events(:next).first.to_tile) if @topic.timetable_events(:next).any?
for news_item in GlobalNews.where( :active => true, :from_time => [nil,DateTime.new(0)..DateTime.now], :to_time => [nil,DateTime.now..DateTime.new(9999)] ).order("id DESC") do
@tiles.unshift(news_item.to_tile)
end
@tiles = @tiles.flatten.reject{|t| t.nil?} #.uniq{|t| t.object}
end
if Settings.home_page == "new" || Settings.home_page == "progress"
@nextLesson = @topic.timetable_events(:next).first.to_tile if @topic.timetable_events(:next).any?
@on_home_page = true
render :action => "home"
end
end
format.json do
render :json => @topic.as_json(:methods => [:l3va,:gcse_english,:gcse_maths,:target_gcse], :except => [:photo])
end
format.jpg do
if @topic.photo
send_data @topic.photo, :disposition => 'inline', :type => "image/jpg"
else
redirect_to "/assets/noone.png"
end
end
end
end
def getMdlBadges
ppdc = Settings.moodle_badge_block_courses.try(:split,",")
return @topic.mdl_badges.where(:mdl_course_id => ppdc) if ppdc && @topic.mdl_badges.where(:mdl_course_id => ppdc).any?
end
def getCourseBadges
## TODO fix error.
return @topic.events.where(:eventable_type => "MdlBadge").limit(8)
end
def getProgressData
@progresses = @topic.progresses.where(:course_status => 'Active').order("course_type DESC")
data = Array.new
key = 0;
@progresses.each do |progress|
data[key] = {}
data[key]['course'] = progress
data[key]['attendance'] = getAttendance(progress.course_type, progress.course_code)
data[key]['initial'] = progress.initial_reviews.last
data[key]['DIV'] = getDIV(data[key]) if data[key]['initial'].present?
data[key]['DI'] = getDI(progress)
data[key]['reviews'] = getReviews(progress)
data[key]['DR'] = getDR(progress, data[key]['attendance']) unless data[key]['attendance'].nil?
key += 1;
end
return data
end
def getDIV(progress)
values = Array.new
values[0] = progress['initial'].target_grade
values[1] = progress['initial'].body.empty? ? "No comments" : progress['initial'].body.squish
values[2] = progress['initial'].person.name
values[3] = progress['initial'].created_at.to_formatted_s(:long)
values[4] = progress['course'].bksb_maths_ia
values[5] = progress['course'].bksb_english_ia
values[6] = progress['course'].bksb_maths_da
values[7] = progress['course'].bksb_english_da
values[8] = progress['course'].qca_score
values[9] = progress['course'].subject_grade
values.map!{|x| x.to_s.tr(?', ?")}
values.collect!{|x| "'#{x}'"}
return values.join(",")
end
def getDI(course)
values = Array.new
values[0] = course.id
values[1] = course.bksb_maths_ia
values[2] = course.bksb_english_ia
values[3] = course.bksb_maths_da
values[4] = course.bksb_english_da
values[5] = course.qca_score
values[6] = course.subject_grade
values.map!{|x| x.to_s.tr(?', ?")}
values.collect!{|x| "'#{x}'"}
return values.join(",")
end
def getAttendance(type, code)
misc_dates = MISC::MiscDates.new
if ["core", "english", "maths"].include? type
return @topic.attendances.where(:course_type => type).where(["week_beginning >= ?", misc_dates.start_of_acyr]).last
end
return @topic.attendances.where(:enrol_course => code).where(["week_beginning >= ?", misc_dates.start_of_acyr]).last
end
def getReviews(progress)
data = Array.new
reviews = progress.progress_reviews.order("number ASC")
reviews.each do |review|
key = review.number
data[key] = review
data[key]['DRV'] = getDRV(review)
end
return data
end
def getDRV(review)
values = Array.new
values[0] = review.number
values[1] = review.working_at
values[2] = review.attendance
values[3] = review.body.empty? ? "No comments" : review.body.squish
values[4] = review.person.name
values[5] = review.created_at.to_formatted_s(:long)
values.map!{|x| x.to_s.tr(?', ?")}
values.collect!{|x| "'#{x}'"}
return values.join(",")
end
def getDR(course, attendance)
values = Array.new
values[0] = course.course_code
values[1] = attendance.att_year
values[2] = course.id
values.map!{|x| x.to_s.tr(?', ?")}
values.collect!{|x| ",'#{x}'"}
return values.join("")
end
def search
if params[:q]
if params[:mis]
@people = Person.mis_search_for(params[:q])
@courses = Course.mis_search_for(params[:q])
else
@people = Person.search_for(params[:q]).order("surname,forename").limit(50)
@courses = Course.search_for(params[:q]).order("year DESC,title").limit(50)
end
end
@people ||= []
@courses ||= []
@page_title = "Search for #{params[:q]}"
render Settings.home_page == "new" || Settings.home_page == "progress" ? "cl_search" : "search"
end
def select
if params[:q]
@people = Person.search_for(params[:q]).where(:staff => true).order("surname,forename").limit(20)
render :json => @people.map{|p| {:id => p.id,:name => p.name, :readonly => p==@user}}.to_json
end
end
def index
redirect_to person_url(@user)
end
def next_lesson_block
@next_timetable_event = @topic.timetable_events(:next).first
end
def my_courses_block
@my_courses = @topic.my_courses
end
def targets_block
@targets = @topic.targets.limit(8).where("complete_date is null")
end
def moodle_block
begin
mcourses = ActiveResource::Connection.new(Settings.moodle_host).
get("#{Settings.moodle_path}/webservice/rest/server.php?" +
"wstoken=#{Settings.moodle_token}&wsfunction=local_leapwebservices_get_user_courses&username=" +
@topic.username + Settings.moodle_user_postfix).body
@moodle_courses = Nokogiri::XML(mcourses).xpath('//MULTIPLE/SINGLE').map do |course|
Hash[:id, course.xpath("KEY[@name='id']/VALUE").first.content,
:name, course.xpath("KEY[@name='fullname']/VALUE").first.content,
:canedit, course.xpath("KEY[@name='canedit']/VALUE").first.content == "1"
]
end
rescue
logger.error "Can't connect to Moodle: #{$!}"
@moodle_courses = false
end
end
def attendance_block
if @topic.attendances.empty?
@attendances = []
else
@attendances = @topic.attendances.last.siblings_same_year
end
end
def poll_block
@poll = SimplePoll.where(:id => Settings.current_simple_poll).first unless Settings.current_simple_poll.blank?
@myans = @topic.simple_poll_answers.where(:simple_poll_id => @poll.id).first
end
private
def person_set_topic
params[:person_id] = params[:id]
set_topic
end
def set_layout
case action_name
when /\_block$/ then false
when "show" then Settings.home_page == "new" || Settings.home_page == "progress" ? "cloud" : "application"
when "search" then Settings.home_page == "new" || Settings.home_page == "progress" ? "cloud" : "application"
else "application"
end
end
def parse_sidebar_links
Settings.clidebar_links.split(/^\|/).drop(1)
.map{|menu| menu.split("\n").reject(&:blank?).map(&:chomp)}
.map{|menu| menu.first.split("|") + [menu.drop(1).map{|item| item.split("|")}]}
end
end
Only notify if on own page
# Leap - Electronic Individual Learning Plan Software
# Copyright (C) 2011 South Devon College
# Leap is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Leap is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with Leap. If not, see <http://www.gnu.org/licenses/>.
require 'misc/misc_dates'
class PeopleController < ApplicationController
skip_before_filter :set_topic
before_filter :person_set_topic, :except => [:search]
before_filter :staff_only, :only => [:search,:select]
layout :set_layout
def show
respond_to do |format|
format.html do
@sidebar_links = parse_sidebar_links
@progress_bar = getProgressData
if Settings.home_page == "progress"
if @topic.staff? && @progress_bar.empty?
## Redirecting to route fails - Needs to use route instead of string eventually.
redirect_to "/people/#{@topic.mis_id}/timetables"
return
end
## TODO fix badges bug
@badges = {:moodle => getMdlBadges, :course => nil}
@aspiration = @topic.aspirations.last.aspiration if @topic.aspirations.present?
@notifications = @topic.notifications.where(:notified => false) if @topic.id == @user.id
@news = Settings.news_modal == 'on' ? true : false
@notify = @user.last_active && (@user.last_active + 2.days) < Date.today && @user.id == @topic.id ? true : false
@user.last_active = Date.today
@user.save
else
@tiles = @topic.events.where(:eventable_type => "Target",:transition => :overdue).
where(:event_date => (Date.today - 1.week)..(Date.today + 1.month)).limit(8)
@tiles += @topic.events.where(:eventable_type => "Note").limit(8)
@tiles += @topic.events.where(:eventable_type => "MdlBadge").limit(8)
@tiles = @tiles.sort_by(&:event_date).reverse.map(&:to_tile)
@tiles.unshift(SimplePoll.where(:id => Settings.current_simple_poll).first.to_tile) unless Settings.current_simple_poll.blank?
ppdc = Settings.moodle_badge_block_courses.try(:split,",")
@tiles.unshift(@topic.mdl_badges.where(:mdl_course_id => ppdc).last.to_course_tile) if ppdc && @topic.mdl_badges.where(:mdl_course_id => ppdc).any?
tracks = ["core","maths","english"].map{|ct| @topic.mdl_grade_tracks.where(:course_type => ct).last}.reject{|x| x.nil?}
@tiles.unshift(tracks.map{|x| x.to_tile})
misc_dates = MISC::MiscDates.new
attendances = ["overall","core","maths","english"].map{|ct| @topic.attendances.where(:course_type => ct).where(["week_beginning >= ?", misc_dates.start_of_acyr] ).last}.reject{|x| x.nil?}
attendances.select!{|x| x.course_type != "overall"} if attendances.length == 2
@tiles.unshift(attendances.map{|x| x.to_tile})
@tiles.unshift(@topic.timetable_events(:next).first.to_tile) if @topic.timetable_events(:next).any?
for news_item in GlobalNews.where( :active => true, :from_time => [nil,DateTime.new(0)..DateTime.now], :to_time => [nil,DateTime.now..DateTime.new(9999)] ).order("id DESC") do
@tiles.unshift(news_item.to_tile)
end
@tiles = @tiles.flatten.reject{|t| t.nil?} #.uniq{|t| t.object}
end
if Settings.home_page == "new" || Settings.home_page == "progress"
@nextLesson = @topic.timetable_events(:next).first.to_tile if @topic.timetable_events(:next).any?
@on_home_page = true
render :action => "home"
end
end
format.json do
render :json => @topic.as_json(:methods => [:l3va,:gcse_english,:gcse_maths,:target_gcse], :except => [:photo])
end
format.jpg do
if @topic.photo
send_data @topic.photo, :disposition => 'inline', :type => "image/jpg"
else
redirect_to "/assets/noone.png"
end
end
end
end
def getMdlBadges
ppdc = Settings.moodle_badge_block_courses.try(:split,",")
return @topic.mdl_badges.where(:mdl_course_id => ppdc) if ppdc && @topic.mdl_badges.where(:mdl_course_id => ppdc).any?
end
def getCourseBadges
## TODO fix error.
return @topic.events.where(:eventable_type => "MdlBadge").limit(8)
end
def getProgressData
@progresses = @topic.progresses.where(:course_status => 'Active').order("course_type DESC")
data = Array.new
key = 0;
@progresses.each do |progress|
data[key] = {}
data[key]['course'] = progress
data[key]['attendance'] = getAttendance(progress.course_type, progress.course_code)
data[key]['initial'] = progress.initial_reviews.last
data[key]['DIV'] = getDIV(data[key]) if data[key]['initial'].present?
data[key]['DI'] = getDI(progress)
data[key]['reviews'] = getReviews(progress)
data[key]['DR'] = getDR(progress, data[key]['attendance']) unless data[key]['attendance'].nil?
key += 1;
end
return data
end
def getDIV(progress)
values = Array.new
values[0] = progress['initial'].target_grade
values[1] = progress['initial'].body.empty? ? "No comments" : progress['initial'].body.squish
values[2] = progress['initial'].person.name
values[3] = progress['initial'].created_at.to_formatted_s(:long)
values[4] = progress['course'].bksb_maths_ia
values[5] = progress['course'].bksb_english_ia
values[6] = progress['course'].bksb_maths_da
values[7] = progress['course'].bksb_english_da
values[8] = progress['course'].qca_score
values[9] = progress['course'].subject_grade
values.map!{|x| x.to_s.tr(?', ?")}
values.collect!{|x| "'#{x}'"}
return values.join(",")
end
def getDI(course)
values = Array.new
values[0] = course.id
values[1] = course.bksb_maths_ia
values[2] = course.bksb_english_ia
values[3] = course.bksb_maths_da
values[4] = course.bksb_english_da
values[5] = course.qca_score
values[6] = course.subject_grade
values.map!{|x| x.to_s.tr(?', ?")}
values.collect!{|x| "'#{x}'"}
return values.join(",")
end
def getAttendance(type, code)
misc_dates = MISC::MiscDates.new
if ["core", "english", "maths"].include? type
return @topic.attendances.where(:course_type => type).where(["week_beginning >= ?", misc_dates.start_of_acyr]).last
end
return @topic.attendances.where(:enrol_course => code).where(["week_beginning >= ?", misc_dates.start_of_acyr]).last
end
def getReviews(progress)
data = Array.new
reviews = progress.progress_reviews.order("number ASC")
reviews.each do |review|
key = review.number
data[key] = review
data[key]['DRV'] = getDRV(review)
end
return data
end
def getDRV(review)
values = Array.new
values[0] = review.number
values[1] = review.working_at
values[2] = review.attendance
values[3] = review.body.empty? ? "No comments" : review.body.squish
values[4] = review.person.name
values[5] = review.created_at.to_formatted_s(:long)
values.map!{|x| x.to_s.tr(?', ?")}
values.collect!{|x| "'#{x}'"}
return values.join(",")
end
def getDR(course, attendance)
values = Array.new
values[0] = course.course_code
values[1] = attendance.att_year
values[2] = course.id
values.map!{|x| x.to_s.tr(?', ?")}
values.collect!{|x| ",'#{x}'"}
return values.join("")
end
def search
if params[:q]
if params[:mis]
@people = Person.mis_search_for(params[:q])
@courses = Course.mis_search_for(params[:q])
else
@people = Person.search_for(params[:q]).order("surname,forename").limit(50)
@courses = Course.search_for(params[:q]).order("year DESC,title").limit(50)
end
end
@people ||= []
@courses ||= []
@page_title = "Search for #{params[:q]}"
render Settings.home_page == "new" || Settings.home_page == "progress" ? "cl_search" : "search"
end
def select
if params[:q]
@people = Person.search_for(params[:q]).where(:staff => true).order("surname,forename").limit(20)
render :json => @people.map{|p| {:id => p.id,:name => p.name, :readonly => p==@user}}.to_json
end
end
def index
redirect_to person_url(@user)
end
def next_lesson_block
@next_timetable_event = @topic.timetable_events(:next).first
end
def my_courses_block
@my_courses = @topic.my_courses
end
def targets_block
@targets = @topic.targets.limit(8).where("complete_date is null")
end
def moodle_block
begin
mcourses = ActiveResource::Connection.new(Settings.moodle_host).
get("#{Settings.moodle_path}/webservice/rest/server.php?" +
"wstoken=#{Settings.moodle_token}&wsfunction=local_leapwebservices_get_user_courses&username=" +
@topic.username + Settings.moodle_user_postfix).body
@moodle_courses = Nokogiri::XML(mcourses).xpath('//MULTIPLE/SINGLE').map do |course|
Hash[:id, course.xpath("KEY[@name='id']/VALUE").first.content,
:name, course.xpath("KEY[@name='fullname']/VALUE").first.content,
:canedit, course.xpath("KEY[@name='canedit']/VALUE").first.content == "1"
]
end
rescue
logger.error "Can't connect to Moodle: #{$!}"
@moodle_courses = false
end
end
def attendance_block
if @topic.attendances.empty?
@attendances = []
else
@attendances = @topic.attendances.last.siblings_same_year
end
end
def poll_block
@poll = SimplePoll.where(:id => Settings.current_simple_poll).first unless Settings.current_simple_poll.blank?
@myans = @topic.simple_poll_answers.where(:simple_poll_id => @poll.id).first
end
private
def person_set_topic
params[:person_id] = params[:id]
set_topic
end
def set_layout
case action_name
when /\_block$/ then false
when "show" then Settings.home_page == "new" || Settings.home_page == "progress" ? "cloud" : "application"
when "search" then Settings.home_page == "new" || Settings.home_page == "progress" ? "cloud" : "application"
else "application"
end
end
def parse_sidebar_links
Settings.clidebar_links.split(/^\|/).drop(1)
.map{|menu| menu.split("\n").reject(&:blank?).map(&:chomp)}
.map{|menu| menu.first.split("|") + [menu.drop(1).map{|item| item.split("|")}]}
end
end
|
class PeopleController < ApplicationController
# GET /people
# GET /people.json
def index
@people = Person.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @people }
end
end
# GET /people/1
# GET /people/1.json
def show
@person = Person.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @person }
end
end
# GET /people/new
# GET /people/new.json
def new
@person = Person.new
@person.build_contact_datum
@structure = Venue.find(params[:venue_id]) if params[:venue_id]
respond_to do |format|
format.html # new.html.erb
format.json { render json: @person }
end
end
# GET /people/1/edit
def edit
@person = Person.find(params[:id])
@person.build_contact_datum unless @person.contact_datum
@structure = Venue.find(params[:venue_id]) if params[:venue_id]
end
# POST /people
# POST /people.json
def create
@person = Person.new(params[:person])
respond_to do |format|
if @person.save
format.html { redirect_to @person, notice: 'Person was successfully created.' }
format.json { render json: @person, status: :created, location: @person }
else
format.html { render action: "new" }
format.json { render json: @person.errors, status: :unprocessable_entity }
end
end
end
# PUT /people/1
# PUT /people/1.json
def update
@person = Person.find(params[:id])
@person.build_contact_datum unless @person.contact_datum
@structure = Venue.find(params[:venue_id]) if params[:venue_id]
respond_to do |format|
if @person.update_attributes(params[:person])
format.html { redirect_to @person, notice: 'Person was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @person.errors, status: :unprocessable_entity }
end
end
end
# DELETE /people/1
# DELETE /people/1.json
def destroy
@person = Person.find(params[:id])
@person.destroy
respond_to do |format|
format.html { redirect_to people_url }
format.json { head :no_content }
end
end
end
redirect to venue after person creation
class PeopleController < ApplicationController
# GET /people
# GET /people.json
def index
@people = Person.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @people }
end
end
# GET /people/1
# GET /people/1.json
def show
@person = Person.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @person }
end
end
# GET /people/new
# GET /people/new.json
def new
@person = Person.new
@person.build_contact_datum
@structure = Venue.find(params[:venue_id]) if params[:venue_id]
respond_to do |format|
format.html # new.html.erb
format.json { render json: @person }
end
end
# GET /people/1/edit
def edit
@person = Person.find(params[:id])
@person.build_contact_datum unless @person.contact_datum
@structure = Venue.find(params[:venue_id]) if params[:venue_id]
end
# POST /people
# POST /people.json
def create
@person = Person.new(params[:person])
respond_to do |format|
if @person.save
format.html { redirect_to @person.structure, notice: 'Person was successfully created.' }
format.json { render json: @person, status: :created, location: @person }
else
format.html { render action: "new" }
format.json { render json: @person.errors, status: :unprocessable_entity }
end
end
end
# PUT /people/1
# PUT /people/1.json
def update
@person = Person.find(params[:id])
@person.build_contact_datum unless @person.contact_datum
@structure = Venue.find(params[:venue_id]) if params[:venue_id]
respond_to do |format|
if @person.update_attributes(params[:person])
format.html { redirect_to @person, notice: 'Person was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @person.errors, status: :unprocessable_entity }
end
end
end
# DELETE /people/1
# DELETE /people/1.json
def destroy
@person = Person.find(params[:id])
@person.destroy
respond_to do |format|
format.html { redirect_to people_url }
format.json { head :no_content }
end
end
end
|
class PeopleController < ApplicationController
before_action :load_person_and_declarations, only: [:show, :contact]
def index
redirect_to councillors_people_path
end
def show
@contact = Contact.new(person: @person)
end
def contact
@contact = Contact.new(contact_params.merge(person: @person))
if @contact.valid?
Mailer.new_contact(@contact).deliver_now
redirect_to person_path(@person, anchor: :contact), contact_notice: I18n.t("people.contact.success")
else
flash[:contact_alert] = I18n.t('people.contact.error')
render :show
end
end
private
def contact_params
params.require(:contact).permit(:name, :email, :body)
end
def load_person_and_declarations
@person = Person.friendly.find(params[:id])
@assets_declarations = @person.assets_declarations.order(:declaration_date)
@activities_declarations = @person.activities_declarations.order(:declaration_date)
end
end
Adds the actions councillors and directors to PeopleController
class PeopleController < ApplicationController
before_action :load_person_and_declarations, only: [:show, :contact]
def index
redirect_to councillors_people_path
end
def councillors
@people = Person.councillors.includes(:party).sorted_as_councillors
end
def directors
@people = Person.directors.sorted_as_directors
end
def show
@contact = Contact.new(person: @person)
end
def contact
@contact = Contact.new(contact_params.merge(person: @person))
if @contact.valid?
Mailer.new_contact(@contact).deliver_now
redirect_to person_path(@person, anchor: :contact), contact_notice: I18n.t("people.contact.success")
else
flash[:contact_alert] = I18n.t('people.contact.error')
render :show
end
end
private
def contact_params
params.require(:contact).permit(:name, :email, :body)
end
def load_person_and_declarations
@person = Person.friendly.find(params[:id])
@assets_declarations = @person.assets_declarations.order(:declaration_date)
@activities_declarations = @person.activities_declarations.order(:declaration_date)
end
end
|
# Copyright (c) 2010-2011, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3 or later. See
# the COPYRIGHT file.
class PeopleController < ApplicationController
before_action :authenticate_user!, except: [:show, :stream, :last_post]
before_action :find_person, only: [:show, :stream, :hovercard]
layout ->(c){ request.format == :mobile ? "application" : "with_header_with_footer" }
use_bootstrap_for :index, :show, :contacts, :refresh_search
respond_to :html, :except => [:tag_index]
respond_to :json, :only => [:index, :show]
respond_to :js, :only => [:tag_index]
rescue_from ActiveRecord::RecordNotFound do
render :file => Rails.root.join('public', '404').to_s,
:format => :html, :layout => false, :status => 404
end
rescue_from Diaspora::AccountClosed do
respond_to do |format|
format.any { redirect_to :back, :notice => t("people.show.closed_account") }
format.json { render :nothing => true, :status => 410 } # 410 GONE
end
end
helper_method :search_query
def index
@aspect = :search
limit = params[:limit] ? params[:limit].to_i : 15
@people = Person.search(search_query, current_user)
respond_to do |format|
format.json do
@people = @people.limit(limit)
render :json => @people
end
format.any(:html, :mobile) do
#only do it if it is an email address
if diaspora_id?(search_query)
@people = Person.where(:diaspora_handle => search_query.downcase)
if @people.empty?
Webfinger.in_background(search_query)
@background_query = search_query.downcase
end
end
@people = @people.paginate(:page => params[:page], :per_page => 15)
@hashes = hashes_for_people(@people, @aspects)
end
end
end
def refresh_search
@aspect = :search
@people = Person.where(:diaspora_handle => search_query.downcase)
@answer_html = ""
unless @people.empty?
@hashes = hashes_for_people(@people, @aspects)
self.formats = self.formats + [:html]
@answer_html = render_to_string :partial => 'people/person', :locals => @hashes.first
end
render :json => { :search_count => @people.count, :search_html => @answer_html }.to_json
end
def tag_index
profiles = Profile.tagged_with(params[:name]).where(:searchable => true).select('profiles.id, profiles.person_id')
@people = Person.where(:id => profiles.map{|p| p.person_id}).paginate(:page => params[:page], :per_page => 15)
respond_with @people
end
# renders the persons user profile page
def show
mark_corresponding_notifications_read if user_signed_in?
@person_json = PersonPresenter.new(@person, current_user).full_hash_with_profile
respond_to do |format|
format.all do
if user_signed_in?
@contact = current_user.contact_for(@person)
end
gon.preloads[:person] = @person_json
gon.preloads[:photos] = {
count: photos_from(@person).count(:all),
}
gon.preloads[:contacts] = {
count: Contact.contact_contacts_for(current_user, @person).count(:all),
}
respond_with @person
end
format.mobile do
@post_type = :all
person_stream
respond_with @person
end
format.json { render json: @person_json }
end
end
def stream
respond_to do |format|
format.all { redirect_to person_path(@person) }
format.json {
render json: person_stream.stream_posts.map { |p| LastThreeCommentsDecorator.new(PostPresenter.new(p, current_user)) }
}
end
end
# hovercards fetch some the persons public profile data via json and display
# it next to the avatar image in a nice box
def hovercard
respond_to do |format|
format.all do
redirect_to :action => "show", :id => params[:person_id]
end
format.json do
render :json => HovercardPresenter.new(@person)
end
end
end
def last_post
@person = Person.find_from_guid_or_username(params)
last_post = Post.visible_from_author(@person, current_user).order('posts.created_at DESC').first
redirect_to post_path(last_post)
end
def retrieve_remote
if params[:diaspora_handle]
Webfinger.in_background(params[:diaspora_handle], :single_aspect_form => true)
render :nothing => true
else
render :nothing => true, :status => 422
end
end
def contacts
@person = Person.find_by_guid(params[:person_id])
if @person
@contact = current_user.contact_for(@person)
@contacts_of_contact = Contact.contact_contacts_for(current_user, @person)
gon.preloads[:person] = PersonPresenter.new(@person, current_user).full_hash_with_profile
gon.preloads[:photos] = {
count: photos_from(@person).count(:all),
}
gon.preloads[:contacts] = {
count: @contacts_of_contact.count(:all),
}
@contacts_of_contact = @contacts_of_contact.paginate(:page => params[:page], :per_page => (params[:limit] || 15))
@hashes = hashes_for_people @contacts_of_contact, @aspects
respond_with @person
else
flash[:error] = I18n.t 'people.show.does_not_exist'
redirect_to people_path
end
end
# shows the dropdown list of aspects the current user has set for the given person.
# renders "thats you" in case the current user views himself
def aspect_membership_dropdown
@person = Person.find_by_guid(params[:person_id])
# you are not a contact of yourself...
return render :text => I18n.t('people.person.thats_you') if @person == current_user.person
@contact = current_user.contact_for(@person) || Contact.new
@aspect = :profile if params[:create] # let aspect dropdown create new aspects
bootstrap = params[:bootstrap] || false
size = params[:size] || "small"
render :partial => 'aspect_membership_dropdown', :locals => {:contact => @contact, :person => @person, :hang => 'left', :bootstrap => bootstrap, :size => size}
end
private
def find_person
@person = Person.find_from_guid_or_username({
id: params[:id] || params[:person_id],
username: params[:username]
})
# view this profile on the home pod, if you don't want to sign in...
authenticate_user! if remote_profile_with_no_user_session?
raise Diaspora::AccountClosed if @person.closed_account?
end
def hashes_for_people(people, aspects)
ids = people.map{|p| p.id}
contacts = {}
Contact.unscoped.where(:user_id => current_user.id, :person_id => ids).each do |contact|
contacts[contact.person_id] = contact
end
people.map{|p|
{:person => p,
:contact => contacts[p.id],
:aspects => aspects}
}
end
def search_query
@search_query ||= params[:q] || params[:term] || ''
end
def diaspora_id?(query)
!query.try(:match, /^(\w)*@([a-zA-Z0-9]|[-]|[.]|[:])*$/).nil?
end
def remote_profile_with_no_user_session?
@person.try(:remote?) && !user_signed_in?
end
def photos_from(person)
@photos ||= if user_signed_in?
current_user.photos_from(person)
else
Photo.where(author_id: person.id, public: true)
end.order('created_at desc')
end
def mark_corresponding_notifications_read
Notification.where(recipient_id: current_user.id, target_type: "Person", target_id: @person.id, unread: true).each do |n|
n.set_read_state( true )
end
end
def person_stream
@stream ||= Stream::Person.new(current_user, @person, max_time: max_time)
end
end
Remove last_post from PeopleController
# Copyright (c) 2010-2011, Diaspora Inc. This file is
# licensed under the Affero General Public License version 3 or later. See
# the COPYRIGHT file.
class PeopleController < ApplicationController
before_action :authenticate_user!, except: [:show, :stream]
before_action :find_person, only: [:show, :stream, :hovercard]
layout ->(c){ request.format == :mobile ? "application" : "with_header_with_footer" }
use_bootstrap_for :index, :show, :contacts, :refresh_search
respond_to :html, :except => [:tag_index]
respond_to :json, :only => [:index, :show]
respond_to :js, :only => [:tag_index]
rescue_from ActiveRecord::RecordNotFound do
render :file => Rails.root.join('public', '404').to_s,
:format => :html, :layout => false, :status => 404
end
rescue_from Diaspora::AccountClosed do
respond_to do |format|
format.any { redirect_to :back, :notice => t("people.show.closed_account") }
format.json { render :nothing => true, :status => 410 } # 410 GONE
end
end
helper_method :search_query
def index
@aspect = :search
limit = params[:limit] ? params[:limit].to_i : 15
@people = Person.search(search_query, current_user)
respond_to do |format|
format.json do
@people = @people.limit(limit)
render :json => @people
end
format.any(:html, :mobile) do
#only do it if it is an email address
if diaspora_id?(search_query)
@people = Person.where(:diaspora_handle => search_query.downcase)
if @people.empty?
Webfinger.in_background(search_query)
@background_query = search_query.downcase
end
end
@people = @people.paginate(:page => params[:page], :per_page => 15)
@hashes = hashes_for_people(@people, @aspects)
end
end
end
def refresh_search
@aspect = :search
@people = Person.where(:diaspora_handle => search_query.downcase)
@answer_html = ""
unless @people.empty?
@hashes = hashes_for_people(@people, @aspects)
self.formats = self.formats + [:html]
@answer_html = render_to_string :partial => 'people/person', :locals => @hashes.first
end
render :json => { :search_count => @people.count, :search_html => @answer_html }.to_json
end
def tag_index
profiles = Profile.tagged_with(params[:name]).where(:searchable => true).select('profiles.id, profiles.person_id')
@people = Person.where(:id => profiles.map{|p| p.person_id}).paginate(:page => params[:page], :per_page => 15)
respond_with @people
end
# renders the persons user profile page
def show
mark_corresponding_notifications_read if user_signed_in?
@person_json = PersonPresenter.new(@person, current_user).full_hash_with_profile
respond_to do |format|
format.all do
if user_signed_in?
@contact = current_user.contact_for(@person)
end
gon.preloads[:person] = @person_json
gon.preloads[:photos] = {
count: photos_from(@person).count(:all),
}
gon.preloads[:contacts] = {
count: Contact.contact_contacts_for(current_user, @person).count(:all),
}
respond_with @person
end
format.mobile do
@post_type = :all
person_stream
respond_with @person
end
format.json { render json: @person_json }
end
end
def stream
respond_to do |format|
format.all { redirect_to person_path(@person) }
format.json {
render json: person_stream.stream_posts.map { |p| LastThreeCommentsDecorator.new(PostPresenter.new(p, current_user)) }
}
end
end
# hovercards fetch some the persons public profile data via json and display
# it next to the avatar image in a nice box
def hovercard
respond_to do |format|
format.all do
redirect_to :action => "show", :id => params[:person_id]
end
format.json do
render :json => HovercardPresenter.new(@person)
end
end
end
def retrieve_remote
if params[:diaspora_handle]
Webfinger.in_background(params[:diaspora_handle], :single_aspect_form => true)
render :nothing => true
else
render :nothing => true, :status => 422
end
end
def contacts
@person = Person.find_by_guid(params[:person_id])
if @person
@contact = current_user.contact_for(@person)
@contacts_of_contact = Contact.contact_contacts_for(current_user, @person)
gon.preloads[:person] = PersonPresenter.new(@person, current_user).full_hash_with_profile
gon.preloads[:photos] = {
count: photos_from(@person).count(:all),
}
gon.preloads[:contacts] = {
count: @contacts_of_contact.count(:all),
}
@contacts_of_contact = @contacts_of_contact.paginate(:page => params[:page], :per_page => (params[:limit] || 15))
@hashes = hashes_for_people @contacts_of_contact, @aspects
respond_with @person
else
flash[:error] = I18n.t 'people.show.does_not_exist'
redirect_to people_path
end
end
# shows the dropdown list of aspects the current user has set for the given person.
# renders "thats you" in case the current user views himself
def aspect_membership_dropdown
@person = Person.find_by_guid(params[:person_id])
# you are not a contact of yourself...
return render :text => I18n.t('people.person.thats_you') if @person == current_user.person
@contact = current_user.contact_for(@person) || Contact.new
@aspect = :profile if params[:create] # let aspect dropdown create new aspects
bootstrap = params[:bootstrap] || false
size = params[:size] || "small"
render :partial => 'aspect_membership_dropdown', :locals => {:contact => @contact, :person => @person, :hang => 'left', :bootstrap => bootstrap, :size => size}
end
private
def find_person
@person = Person.find_from_guid_or_username({
id: params[:id] || params[:person_id],
username: params[:username]
})
# view this profile on the home pod, if you don't want to sign in...
authenticate_user! if remote_profile_with_no_user_session?
raise Diaspora::AccountClosed if @person.closed_account?
end
def hashes_for_people(people, aspects)
ids = people.map{|p| p.id}
contacts = {}
Contact.unscoped.where(:user_id => current_user.id, :person_id => ids).each do |contact|
contacts[contact.person_id] = contact
end
people.map{|p|
{:person => p,
:contact => contacts[p.id],
:aspects => aspects}
}
end
def search_query
@search_query ||= params[:q] || params[:term] || ''
end
def diaspora_id?(query)
!query.try(:match, /^(\w)*@([a-zA-Z0-9]|[-]|[.]|[:])*$/).nil?
end
def remote_profile_with_no_user_session?
@person.try(:remote?) && !user_signed_in?
end
def photos_from(person)
@photos ||= if user_signed_in?
current_user.photos_from(person)
else
Photo.where(author_id: person.id, public: true)
end.order('created_at desc')
end
def mark_corresponding_notifications_read
Notification.where(recipient_id: current_user.id, target_type: "Person", target_id: @person.id, unread: true).each do |n|
n.set_read_state( true )
end
end
def person_stream
@stream ||= Stream::Person.new(current_user, @person, max_time: max_time)
end
end
|
class ReportController < ApplicationController
before_filter :require_login
def new_inaccuracy
if request.xhr?
@report = Report.new
@report.venue_id = params[:format]
@report.topic = 2
render partial: 'new_inaccuracy'
end
end
def new_inquiry
if request.xhr?
@report = Report.new
@report.topic = 1
render partial: 'new_inquiry'
end
end
def create
@report = Report.new(report_params)
@report.user_id = current_user.id if current_user
binding.pry
if @report.save && @report.topic == "inquiry"
UserMailer.contact_us(@report).deliver_now
redirect_to contact_index_path, flash: { notice: "Message sent"}
elsif @report.save && @report.topic == "inaccuracy"
UserMailer.report_venue_inaccurate(@report).deliver_now
redirect_to venue_path(@report.venue), flash: { notice: "Message sent"}
else
redirect_to root_path, flash: { error: "Error sending message" }
end
end
private
def report_params
params.require(:report).permit(:topic, :content, :venue_id)
end
end
change flash errors and notices to arrays for formatting
class ReportController < ApplicationController
before_filter :require_login
def new_inaccuracy
if request.xhr?
@report = Report.new
@report.venue_id = params[:format]
@report.topic = 2
render partial: 'new_inaccuracy'
end
end
def new_inquiry
if request.xhr?
@report = Report.new
@report.topic = 1
render partial: 'new_inquiry'
end
end
def create
@report = Report.new(report_params)
@report.user_id = current_user.id if current_user
binding.pry
if @report.save && @report.topic == "inquiry"
UserMailer.contact_us(@report).deliver_now
redirect_to contact_index_path, flash: { notice: [ "Message sent"] }
elsif @report.save && @report.topic == "inaccuracy"
UserMailer.report_venue_inaccurate(@report).deliver_now
redirect_to venue_path(@report.venue), flash: { notice: [ "Message sent"] }
else
redirect_to root_path, flash: { error: [ "Error sending message"] }
end
end
private
def report_params
params.require(:report).permit(:topic, :content, :name, :email, :venue_id)
end
end |
class ReviewController < ApplicationController
def index
end
def papers
@incomplete = {}
Body.find_each do |b|
@incomplete[b.state] = []
@incomplete[b.state].concat Paper.where(body: b).where(['published_at > ?', Date.today])
@incomplete[b.state].concat Paper.where(body: b, page_count: nil).limit(50)
@incomplete[b.state].concat Paper.find_by_sql(
['SELECT p.* FROM papers p ' \
"LEFT OUTER JOIN paper_originators o ON (o.paper_id = p.id AND o.originator_type = 'Person') " \
"WHERE p.body_id = ? AND p.doctype != ? AND o.id IS NULL", b.id, Paper::DOCTYPE_MAJOR_INTERPELLATION]
)
@incomplete[b.state].concat Paper.find_by_sql(
['SELECT p.* FROM papers p ' \
"LEFT OUTER JOIN paper_originators o ON (o.paper_id = p.id AND o.originator_type = 'Organization') " \
'WHERE p.body_id = ? AND o.id IS NULL', b.id]
)
@incomplete[b.state].concat Paper.find_by_sql(
['SELECT p.* FROM papers p ' \
"LEFT OUTER JOIN paper_answerers a ON (a.paper_id = p.id AND a.answerer_type = 'Ministry') " \
'WHERE p.body_id = ? AND a.id IS NULL', b.id]
)
@incomplete[b.state].uniq!
@incomplete[b.state].keep_if { |p| p.is_answer == true }
end
end
def ministries
@ministries = Ministry.where('length(name) > 70 OR length(name) < 12')
end
def today
@papers = {}
@ministries = {}
Body.find_each do |b|
@papers[b.id] = b.papers.where(['created_at >= ?', Date.today])
@ministries[b.id] = b.ministries.where(['created_at >= ?', Date.today])
end
@people = Person.where(['created_at >= ?', Date.today])
@organizations = Organization.where(['created_at >= ?', Date.today])
end
end
Review: don't display frozen papers
class ReviewController < ApplicationController
def index
end
def papers
@incomplete = {}
Body.find_each do |b|
@incomplete[b.state] = []
@incomplete[b.state].concat Paper.where(body: b).where(['published_at > ?', Date.today])
@incomplete[b.state].concat Paper.where(body: b, page_count: nil).limit(50)
@incomplete[b.state].concat Paper.find_by_sql(
['SELECT p.* FROM papers p ' \
"LEFT OUTER JOIN paper_originators o ON (o.paper_id = p.id AND o.originator_type = 'Person') " \
"WHERE p.body_id = ? AND p.doctype != ? AND p.frozen_at IS NULL AND o.id IS NULL", b.id, Paper::DOCTYPE_MAJOR_INTERPELLATION]
)
@incomplete[b.state].concat Paper.find_by_sql(
['SELECT p.* FROM papers p ' \
"LEFT OUTER JOIN paper_originators o ON (o.paper_id = p.id AND o.originator_type = 'Organization') " \
'WHERE p.body_id = ? AND p.frozen_at IS NULL AND o.id IS NULL', b.id]
)
@incomplete[b.state].concat Paper.find_by_sql(
['SELECT p.* FROM papers p ' \
"LEFT OUTER JOIN paper_answerers a ON (a.paper_id = p.id AND a.answerer_type = 'Ministry') " \
'WHERE p.body_id = ? AND p.frozen_at IS NULL AND a.id IS NULL', b.id]
)
@incomplete[b.state].uniq!
@incomplete[b.state].keep_if { |p| p.is_answer == true && !p.frozen? }
end
end
def ministries
@ministries = Ministry.where('length(name) > 70 OR length(name) < 12')
end
def today
@papers = {}
@ministries = {}
Body.find_each do |b|
@papers[b.id] = b.papers.where(['created_at >= ?', Date.today])
@ministries[b.id] = b.ministries.where(['created_at >= ?', Date.today])
end
@people = Person.where(['created_at >= ?', Date.today])
@organizations = Organization.where(['created_at >= ?', Date.today])
end
end
|
class RoundsController < ApplicationController
def set_charity
@round = Round.where(url: params[:url]).first
if @round.charity.nil?
@round.charity = Charity.find(params[:charity])
@round.save
end
render :display
end
def display
@round = Round.where(url: params[:url]).first
@donated = cookies['donated_'+@round.url]
if @round.winner
@winner = cookies['donated_'+@round.url] == @round.winner.token
end
if @round.closed
render :closed
end
end
def charge
@round = Round.where(url: params[:round_id]).first
@donation = Donation.new(round: @round, email: params[:email], name: params[:name], stripe_token: params[:stripeToken])
@donation.save
cookies['donated_'+@round.url] = @donation.token
render_status
end
def status
@round = Round.where(url: params[:url]).first
render_status
end
def render_status
@donated = cookies['donated_'+@round.url]
@donations = render_to_string(partial: 'donations')
@payment_info = render_to_string(partial: 'payment_info')
render json: { 'seconds_left' => @round.seconds_left.round, 'donations_template' => @donations, 'payment_info_template' => @payment_info }
end
# GET /rounds
# GET /rounds.json
def index
@rounds = Round.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @rounds }
end
end
# GET /rounds/1
# GET /rounds/1.json
def show
@round = Round.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @round }
end
end
# GET /rounds/new
# GET /rounds/new.json
def new
@round = Round.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @round }
end
end
# GET /rounds/1/edit
def edit
@round = Round.find(params[:id])
end
# POST /rounds
# POST /rounds.json
def create
@round = Round.new(params[:round])
respond_to do |format|
if @round.save
format.html { redirect_to @round, notice: 'Round was successfully created.' }
format.json { render json: @round, status: :created, location: @round }
else
format.html { render action: "new" }
format.json { render json: @round.errors, status: :unprocessable_entity }
end
end
end
# PUT /rounds/1
# PUT /rounds/1.json
def update
@round = Round.find(params[:id])
respond_to do |format|
if @round.update_attributes(params[:round])
format.html { redirect_to @round, notice: 'Round was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @round.errors, status: :unprocessable_entity }
end
end
end
# DELETE /rounds/1
# DELETE /rounds/1.json
def destroy
@round = Round.find(params[:id])
@round.destroy
respond_to do |format|
format.html { redirect_to rounds_url }
format.json { head :no_content }
end
end
end
Return forbidden if trying to update address without url or token
class RoundsController < ApplicationController
def set_charity
@round = Round.where(url: params[:url]).first
if @round.charity.nil?
@round.charity = Charity.find(params[:charity])
@round.save
end
render :display
end
def display
@round = Round.where(url: params[:url]).first
@donated = cookies['donated_'+@round.url]
if @round.winner
@winner = cookies['donated_'+@round.url] == @round.winner.token
end
if @round.closed
render :closed
end
end
def charge
@round = Round.where(url: params[:round_id]).first
@donation = Donation.new(round: @round, email: params[:email], name: params[:name], stripe_token: params[:stripeToken])
@donation.save
cookies['donated_'+@round.url] = @donation.token
render_status
end
def status
@round = Round.where(url: params[:url]).first
render_status
end
def render_status
@donated = cookies['donated_'+@round.url]
@donations = render_to_string(partial: 'donations')
@payment_info = render_to_string(partial: 'payment_info')
render json: { 'seconds_left' => @round.seconds_left.round, 'donations_template' => @donations, 'payment_info_template' => @payment_info }
end
def update_address
if params[:url].nil? or params[:token].nil?
render :nothing => true, :status => 403 and return
end
render :nothing => true
end
# GET /rounds
# GET /rounds.json
def index
@rounds = Round.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @rounds }
end
end
# GET /rounds/1
# GET /rounds/1.json
def show
@round = Round.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @round }
end
end
# GET /rounds/new
# GET /rounds/new.json
def new
@round = Round.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @round }
end
end
# GET /rounds/1/edit
def edit
@round = Round.find(params[:id])
end
# POST /rounds
# POST /rounds.json
def create
@round = Round.new(params[:round])
respond_to do |format|
if @round.save
format.html { redirect_to @round, notice: 'Round was successfully created.' }
format.json { render json: @round, status: :created, location: @round }
else
format.html { render action: "new" }
format.json { render json: @round.errors, status: :unprocessable_entity }
end
end
end
# PUT /rounds/1
# PUT /rounds/1.json
def update
@round = Round.find(params[:id])
respond_to do |format|
if @round.update_attributes(params[:round])
format.html { redirect_to @round, notice: 'Round was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @round.errors, status: :unprocessable_entity }
end
end
end
# DELETE /rounds/1
# DELETE /rounds/1.json
def destroy
@round = Round.find(params[:id])
@round.destroy
respond_to do |format|
format.html { redirect_to rounds_url }
format.json { head :no_content }
end
end
end
|
class SearchController < ApplicationController
include RestrictedController
before_filter :teacher_only, :only => [:index, :show]
before_filter :check_if_teacher, :only => [:get_current_material_unassigned_clazzes, :add_material_to_clazzes]
before_filter :admin_only, :only => [:get_current_material_unassigned_collections, :add_material_to_collections]
protected
def teacher_only
if current_visitor.portal_student
redirect_to(:root)
end
end
def check_if_teacher
if current_visitor.portal_teacher.nil? && request.xhr?
respond_to do |format|
format.js { render :json => "Not Teacher",:status => 401 }
end
end
end
in_place_edit_for :investigation, :search_term
public
def index
return redirect_to action: 'index', include_official: '1' if request.query_parameters.empty?
opts = params.merge(:user_id => current_visitor.id, :skip_search => true)
@form_model = Search.new(opts)
end
def unauthorized_user
notice_msg = 'Please login or register as a teacher'
redirect_url = root_url
# Set notice message
flash[:notice] = notice_msg
# Redirect to the login page
redirect_to redirect_url
end
def setup_material_type
@material_type = param_find(:material_types, (params[:method] == :get)) ||
(current_settings.include_external_activities? ? ['investigation','activity','external_activity'] : ['investigation','activity'])
end
def get_search_suggestions
setup_material_type
search_term = params[:search_term]
ajaxResponseCounter = params[:ajaxRequestCounter]
submitform = params[:submit_form]
other_params = {
:without_teacher_only => current_visitor.anonymous?,
:sort_order => Search::Score,
:user_id => current_visitor.id
}
search = Search.new(params.merge(other_params))
suggestions= search.results[:all]
if request.xhr?
render :update do |page|
page << "if (ajaxRequestCounter == #{ajaxResponseCounter}) {"
page.replace_html 'search_suggestions', {
:partial => 'search/search_suggestions',
:locals=> {
:textlength => search_term.length,
:suggestions => suggestions,
:submit_form => submitform}}
page << "addSuggestionClickHandlers();"
page << '}'
end
end
end
def find_material(type, id)
material = nil
if ["Investigation", "Activity", "Page", "ExternalActivity", "ResourcePage"].include?(type) # this is for safety
material = type.constantize.find(id)
end
return material
end
def get_current_material_unassigned_clazzes
material_type = params[:material_type]
material_ids = params[:material_id]
material_ids = material_ids.split(',')
teacher_clazzes = current_visitor.portal_teacher.teacher_clazzes.sort{|a,b| a.position <=> b.position}
teacher_clazzes = teacher_clazzes.select{|item| item.active == true}
teacher_clazz_ids = teacher_clazzes.map{|item| item.clazz_id}
if material_ids.length == 1 #Check if material to be assigned is a single activity or investigation
@material = [find_material(material_type, params[:material_id])]
teacher_offerings = Portal::Offering.where(:runnable_id=>params[:material_id], :runnable_type=>params[:material_type], :clazz_id=>teacher_clazz_ids)
assigned_clazz_ids = teacher_offerings.map{|item| item.clazz_id}
@assigned_clazzes = Portal::Clazz.where(:id=>assigned_clazz_ids)
@assigned_clazzes = @assigned_clazzes.sort{|a,b| teacher_clazz_ids.index(a.id) <=> teacher_clazz_ids.index(b.id)}
else
@assigned_clazzes = []
assigned_clazz_ids = []
@material = material_ids.collect{|a| ::Activity.find(a)}
end
unassigned_teacher_clazzes = teacher_clazzes.select{|item| assigned_clazz_ids.index(item.clazz_id).nil?}
@unassigned_clazzes = Portal::Clazz.where(:id=>unassigned_teacher_clazzes.map{|item| item.clazz_id})
@unassigned_clazzes = @unassigned_clazzes.sort{|a,b| teacher_clazz_ids.index(a.id) <=> teacher_clazz_ids.index(b.id)}
@teacher_active_clazzes_count = (teacher_clazzes)? teacher_clazzes.length : 0
render :partial => 'material_unassigned_clazzes'
end
def add_material_to_clazzes
clazz_ids = params[:clazz_id] || []
runnable_ids = params[:material_id].split(',')
runnable_type = params[:material_type].classify
assign_summary_data = []
clazz_ids.each do|clazz_id|
already_assigned_material_names = []
newly_assigned_material_names = []
portal_clazz = Portal::Clazz.find(clazz_id)
runnable_ids.each do|runnable_id|
portal_clazz_offerings = portal_clazz.offerings
portal_offering = portal_clazz_offerings.find_by_runnable_id_and_runnable_type(runnable_id,runnable_type)
if portal_offering.nil?
offering = Portal::Offering.find_or_create_by_clazz_id_and_runnable_type_and_runnable_id(portal_clazz.id,runnable_type,runnable_id)
if offering.position == 0
offering.position = portal_clazz.offerings.length
offering.save
end
newly_assigned_material_names << offering.name
else
already_assigned_material_names << portal_offering.name
end
end
assign_summary_data << [portal_clazz.name, newly_assigned_material_names,already_assigned_material_names]
end
if request.xhr?
render :update do |page|
if runnable_ids.length == 1
material_parent = nil
if runnable_type == "Investigation"
material = ::Investigation.find(params[:material_id])
used_in_clazz_count = material.offerings_count
elsif runnable_type == "Activity"
material = ::Activity.find(params[:material_id])
material_parent = material.parent
used_in_clazz_count = (material_parent)? material_parent.offerings_count : material.offerings_count
elsif runnable_type == "ExternalActivity"
material = ::ExternalActivity.find(params[:material_id])
used_in_clazz_count = material.offerings_count
runnable_display_name = material.template_type
end
if(used_in_clazz_count == 0)
class_count_desc = "Not used in any class."
elsif(used_in_clazz_count == 1)
class_count_desc = "Used in 1 class."
else
class_count_desc = "Used in #{used_in_clazz_count} classes."
end
if clazz_ids.count > 0
page << "close_popup()"
page << "getMessagePopup('<div class=\"feedback_message\"><b>#{material.name.gsub("'","\\'")}</b> is assigned to the selected class(es) successfully.</div>')"
page.replace_html "material_clazz_count", class_count_desc
if !material_parent.nil? && runnable_type == "Activity"
used_in_clazz_count = material.offerings_count + material.parent.offerings_count
if(used_in_clazz_count == 0)
class_count_desc = "Not used in any class."
elsif(used_in_clazz_count == 1)
class_count_desc = "Used in 1 class."
else
class_count_desc = "Used in #{used_in_clazz_count} classes."
end
page.replace_html "activity_clazz_count_#{runnable_ids[0]}", class_count_desc
end
if runnable_type == "Investigation"
material.activities.each do|activity|
used_in_clazz_count = activity.offerings_count + material.offerings_count
if(used_in_clazz_count == 0)
class_count_desc = "Not used in any class."
elsif(used_in_clazz_count == 1)
class_count_desc = "Used in 1 class."
else
class_count_desc = "Used in #{used_in_clazz_count} classes."
end
page.replace_html "activity_clazz_count_#{activity.id}", class_count_desc
end
end
#page.replace_html "search_#{runnable_type.downcase}_#{runnable_id}", {:partial => 'result_item', :locals=>{:material=>material}}
else
page << "$('error_message').update('Select at least one class to assign this #{runnable_type}');$('error_message').show()"
end
else
if clazz_ids.count > 0
runnable_ids.each do|runnable_id|
material = ::Activity.find(runnable_id)
used_in_clazz_count = material.offerings_count + material.parent.offerings_count
if(used_in_clazz_count == 0)
class_count_desc = "Not used in any class."
elsif(used_in_clazz_count == 1)
class_count_desc = "Used in 1 class."
else
class_count_desc = "Used in #{used_in_clazz_count} classes."
end
page.replace_html "activity_clazz_count_#{runnable_id}", class_count_desc
end
page.replace_html "clazz_summary_data", {:partial => 'material_assign_summary', :locals=>{:summary_data=>assign_summary_data}}
page << "setPopupHeight()"
else
page << "$('error_message').update('Select at least one class to assign this #{runnable_type}');$('error_message').show()"
end
end
end
end
end
def get_current_material_unassigned_collections
material_type = params[:material_type]
material_ids = params[:material_id]
material_ids = material_ids.split(',')
@collections = MaterialsCollection.includes(:materials_collection_items).all
if material_ids.length == 1 #Check if material to be assigned is a single activity or investigation
@material = [find_material(material_type, params[:material_id])]
@assigned_collections = @collections.select{|c| _collection_has_materials(c, @material) }
else
@material = material_ids.collect{|a| ::Activity.find(a)}
@assigned_collections = []
end
@unassigned_collections = @collections - @assigned_collections
render :partial => 'material_unassigned_collections'
end
def add_material_to_collections
collection_ids = params[:materials_collection_id] || []
runnable_ids = params[:material_id].split(',')
runnable_type = params[:material_type].classify
assign_summary_data = []
collection_ids.each do|collection_id|
already_assigned_material_names = []
newly_assigned_material_names = []
collection = MaterialsCollection.includes(:materials_collection_items).find(collection_id)
runnable_ids.each do|runnable_id|
collection_items = collection.materials_collection_items
item = collection_items.find_by_material_id_and_material_type(runnable_id,runnable_type)
if item.nil?
item = MaterialsCollectionItem.find_or_create_by_materials_collection_id_and_material_type_and_material_id(collection.id,runnable_type,runnable_id)
if item.position.nil?
item.position = collection_items.length
item.save
end
newly_assigned_material_names << collection.name
else
already_assigned_material_names << collection.name
end
end
assign_summary_data << [collection.name, newly_assigned_material_names,already_assigned_material_names]
end
if request.xhr?
render :update do |page|
materials = []
if runnable_ids.length == 1
if runnable_type == "Investigation"
materials.push ::Investigation.find(params[:material_id])
elsif runnable_type == "Activity"
materials.push ::Activity.find(params[:material_id])
elsif runnable_type == "ExternalActivity"
materials.push ::ExternalActivity.find(params[:material_id])
end
else
runnable_ids.each do |id|
materials.push ::Activity.find(id)
end
end
if collection_ids.count > 0
material_names = materials.map {|m| "<b>#{m.name}</b>" }.join(", ").gsub("'","\\'")
page << "close_popup()"
page << "getMessagePopup('<div class=\"feedback_message\">#{material_names} #{'is'.pluralize(runnable_ids.length)} assigned to the selected collection(s) successfully.</div>')"
else
page << "$('error_message').update('Select at least one collection to assign this #{runnable_type}');$('error_message').show()"
end
end
end
end
private
def _collection_has_materials(collection, materials)
items = collection.materials_collection_items.map{|i| [i.material_type, i.material_id] }
material_items = materials.map {|m| [m.class.to_s, m.id] }
has_them_all = (material_items - items).empty? && (material_items & items).length == material_items.length
return has_them_all
end
end
Put search exception detection back in, since we're using the Search model
class SearchController < ApplicationController
include RestrictedController
before_filter :teacher_only, :only => [:index, :show]
before_filter :check_if_teacher, :only => [:get_current_material_unassigned_clazzes, :add_material_to_clazzes]
before_filter :admin_only, :only => [:get_current_material_unassigned_collections, :add_material_to_collections]
protected
def teacher_only
if current_visitor.portal_student
redirect_to(:root)
end
end
def check_if_teacher
if current_visitor.portal_teacher.nil? && request.xhr?
respond_to do |format|
format.js { render :json => "Not Teacher",:status => 401 }
end
end
end
in_place_edit_for :investigation, :search_term
public
def index
return redirect_to action: 'index', include_official: '1' if request.query_parameters.empty?
opts = params.merge(:user_id => current_visitor.id, :skip_search => true)
begin
@form_model = Search.new(opts)
rescue => e
ExceptionNotifier::Notifier.exception_notification(request.env, e).deliver
render :search_unavailable
end
end
def unauthorized_user
notice_msg = 'Please login or register as a teacher'
redirect_url = root_url
# Set notice message
flash[:notice] = notice_msg
# Redirect to the login page
redirect_to redirect_url
end
def setup_material_type
@material_type = param_find(:material_types, (params[:method] == :get)) ||
(current_settings.include_external_activities? ? ['investigation','activity','external_activity'] : ['investigation','activity'])
end
def get_search_suggestions
setup_material_type
search_term = params[:search_term]
ajaxResponseCounter = params[:ajaxRequestCounter]
submitform = params[:submit_form]
other_params = {
:without_teacher_only => current_visitor.anonymous?,
:sort_order => Search::Score,
:user_id => current_visitor.id
}
search = Search.new(params.merge(other_params))
suggestions= search.results[:all]
if request.xhr?
render :update do |page|
page << "if (ajaxRequestCounter == #{ajaxResponseCounter}) {"
page.replace_html 'search_suggestions', {
:partial => 'search/search_suggestions',
:locals=> {
:textlength => search_term.length,
:suggestions => suggestions,
:submit_form => submitform}}
page << "addSuggestionClickHandlers();"
page << '}'
end
end
end
def find_material(type, id)
material = nil
if ["Investigation", "Activity", "Page", "ExternalActivity", "ResourcePage"].include?(type) # this is for safety
material = type.constantize.find(id)
end
return material
end
def get_current_material_unassigned_clazzes
material_type = params[:material_type]
material_ids = params[:material_id]
material_ids = material_ids.split(',')
teacher_clazzes = current_visitor.portal_teacher.teacher_clazzes.sort{|a,b| a.position <=> b.position}
teacher_clazzes = teacher_clazzes.select{|item| item.active == true}
teacher_clazz_ids = teacher_clazzes.map{|item| item.clazz_id}
if material_ids.length == 1 #Check if material to be assigned is a single activity or investigation
@material = [find_material(material_type, params[:material_id])]
teacher_offerings = Portal::Offering.where(:runnable_id=>params[:material_id], :runnable_type=>params[:material_type], :clazz_id=>teacher_clazz_ids)
assigned_clazz_ids = teacher_offerings.map{|item| item.clazz_id}
@assigned_clazzes = Portal::Clazz.where(:id=>assigned_clazz_ids)
@assigned_clazzes = @assigned_clazzes.sort{|a,b| teacher_clazz_ids.index(a.id) <=> teacher_clazz_ids.index(b.id)}
else
@assigned_clazzes = []
assigned_clazz_ids = []
@material = material_ids.collect{|a| ::Activity.find(a)}
end
unassigned_teacher_clazzes = teacher_clazzes.select{|item| assigned_clazz_ids.index(item.clazz_id).nil?}
@unassigned_clazzes = Portal::Clazz.where(:id=>unassigned_teacher_clazzes.map{|item| item.clazz_id})
@unassigned_clazzes = @unassigned_clazzes.sort{|a,b| teacher_clazz_ids.index(a.id) <=> teacher_clazz_ids.index(b.id)}
@teacher_active_clazzes_count = (teacher_clazzes)? teacher_clazzes.length : 0
render :partial => 'material_unassigned_clazzes'
end
def add_material_to_clazzes
clazz_ids = params[:clazz_id] || []
runnable_ids = params[:material_id].split(',')
runnable_type = params[:material_type].classify
assign_summary_data = []
clazz_ids.each do|clazz_id|
already_assigned_material_names = []
newly_assigned_material_names = []
portal_clazz = Portal::Clazz.find(clazz_id)
runnable_ids.each do|runnable_id|
portal_clazz_offerings = portal_clazz.offerings
portal_offering = portal_clazz_offerings.find_by_runnable_id_and_runnable_type(runnable_id,runnable_type)
if portal_offering.nil?
offering = Portal::Offering.find_or_create_by_clazz_id_and_runnable_type_and_runnable_id(portal_clazz.id,runnable_type,runnable_id)
if offering.position == 0
offering.position = portal_clazz.offerings.length
offering.save
end
newly_assigned_material_names << offering.name
else
already_assigned_material_names << portal_offering.name
end
end
assign_summary_data << [portal_clazz.name, newly_assigned_material_names,already_assigned_material_names]
end
if request.xhr?
render :update do |page|
if runnable_ids.length == 1
material_parent = nil
if runnable_type == "Investigation"
material = ::Investigation.find(params[:material_id])
used_in_clazz_count = material.offerings_count
elsif runnable_type == "Activity"
material = ::Activity.find(params[:material_id])
material_parent = material.parent
used_in_clazz_count = (material_parent)? material_parent.offerings_count : material.offerings_count
elsif runnable_type == "ExternalActivity"
material = ::ExternalActivity.find(params[:material_id])
used_in_clazz_count = material.offerings_count
runnable_display_name = material.template_type
end
if(used_in_clazz_count == 0)
class_count_desc = "Not used in any class."
elsif(used_in_clazz_count == 1)
class_count_desc = "Used in 1 class."
else
class_count_desc = "Used in #{used_in_clazz_count} classes."
end
if clazz_ids.count > 0
page << "close_popup()"
page << "getMessagePopup('<div class=\"feedback_message\"><b>#{material.name.gsub("'","\\'")}</b> is assigned to the selected class(es) successfully.</div>')"
page.replace_html "material_clazz_count", class_count_desc
if !material_parent.nil? && runnable_type == "Activity"
used_in_clazz_count = material.offerings_count + material.parent.offerings_count
if(used_in_clazz_count == 0)
class_count_desc = "Not used in any class."
elsif(used_in_clazz_count == 1)
class_count_desc = "Used in 1 class."
else
class_count_desc = "Used in #{used_in_clazz_count} classes."
end
page.replace_html "activity_clazz_count_#{runnable_ids[0]}", class_count_desc
end
if runnable_type == "Investigation"
material.activities.each do|activity|
used_in_clazz_count = activity.offerings_count + material.offerings_count
if(used_in_clazz_count == 0)
class_count_desc = "Not used in any class."
elsif(used_in_clazz_count == 1)
class_count_desc = "Used in 1 class."
else
class_count_desc = "Used in #{used_in_clazz_count} classes."
end
page.replace_html "activity_clazz_count_#{activity.id}", class_count_desc
end
end
#page.replace_html "search_#{runnable_type.downcase}_#{runnable_id}", {:partial => 'result_item', :locals=>{:material=>material}}
else
page << "$('error_message').update('Select at least one class to assign this #{runnable_type}');$('error_message').show()"
end
else
if clazz_ids.count > 0
runnable_ids.each do|runnable_id|
material = ::Activity.find(runnable_id)
used_in_clazz_count = material.offerings_count + material.parent.offerings_count
if(used_in_clazz_count == 0)
class_count_desc = "Not used in any class."
elsif(used_in_clazz_count == 1)
class_count_desc = "Used in 1 class."
else
class_count_desc = "Used in #{used_in_clazz_count} classes."
end
page.replace_html "activity_clazz_count_#{runnable_id}", class_count_desc
end
page.replace_html "clazz_summary_data", {:partial => 'material_assign_summary', :locals=>{:summary_data=>assign_summary_data}}
page << "setPopupHeight()"
else
page << "$('error_message').update('Select at least one class to assign this #{runnable_type}');$('error_message').show()"
end
end
end
end
end
def get_current_material_unassigned_collections
material_type = params[:material_type]
material_ids = params[:material_id]
material_ids = material_ids.split(',')
@collections = MaterialsCollection.includes(:materials_collection_items).all
if material_ids.length == 1 #Check if material to be assigned is a single activity or investigation
@material = [find_material(material_type, params[:material_id])]
@assigned_collections = @collections.select{|c| _collection_has_materials(c, @material) }
else
@material = material_ids.collect{|a| ::Activity.find(a)}
@assigned_collections = []
end
@unassigned_collections = @collections - @assigned_collections
render :partial => 'material_unassigned_collections'
end
def add_material_to_collections
collection_ids = params[:materials_collection_id] || []
runnable_ids = params[:material_id].split(',')
runnable_type = params[:material_type].classify
assign_summary_data = []
collection_ids.each do|collection_id|
already_assigned_material_names = []
newly_assigned_material_names = []
collection = MaterialsCollection.includes(:materials_collection_items).find(collection_id)
runnable_ids.each do|runnable_id|
collection_items = collection.materials_collection_items
item = collection_items.find_by_material_id_and_material_type(runnable_id,runnable_type)
if item.nil?
item = MaterialsCollectionItem.find_or_create_by_materials_collection_id_and_material_type_and_material_id(collection.id,runnable_type,runnable_id)
if item.position.nil?
item.position = collection_items.length
item.save
end
newly_assigned_material_names << collection.name
else
already_assigned_material_names << collection.name
end
end
assign_summary_data << [collection.name, newly_assigned_material_names,already_assigned_material_names]
end
if request.xhr?
render :update do |page|
materials = []
if runnable_ids.length == 1
if runnable_type == "Investigation"
materials.push ::Investigation.find(params[:material_id])
elsif runnable_type == "Activity"
materials.push ::Activity.find(params[:material_id])
elsif runnable_type == "ExternalActivity"
materials.push ::ExternalActivity.find(params[:material_id])
end
else
runnable_ids.each do |id|
materials.push ::Activity.find(id)
end
end
if collection_ids.count > 0
material_names = materials.map {|m| "<b>#{m.name}</b>" }.join(", ").gsub("'","\\'")
page << "close_popup()"
page << "getMessagePopup('<div class=\"feedback_message\">#{material_names} #{'is'.pluralize(runnable_ids.length)} assigned to the selected collection(s) successfully.</div>')"
else
page << "$('error_message').update('Select at least one collection to assign this #{runnable_type}');$('error_message').show()"
end
end
end
end
private
def _collection_has_materials(collection, materials)
items = collection.materials_collection_items.map{|i| [i.material_type, i.material_id] }
material_items = materials.map {|m| [m.class.to_s, m.id] }
has_them_all = (material_items - items).empty? && (material_items & items).length == material_items.length
return has_them_all
end
end
|
class SearchController < ApplicationController
RESULT_SET = 300
def index
@hashtags = params[:tags]
@hashtags = "" if @hashtags.nil?
@twitter ||= Twitter::REST::Client.new do |config|
config.consumer_key = ENV["twitter_consumer_key"]
config.consumer_secret = ENV["twitter_consumer_secret"]
config.access_token = ENV["twitter_access_token"]
config.access_token_secret = ENV["twitter_access_token_secret"]
end
[ "#makerhood" ].each do |forced_keyword|
@hashtags = "#{@hashtags} #{forced_keyword}" unless @hashtags.include?(forced_keyword)
end
# Pick out the main tags
focus_tags = @hashtags.split(" ")
@active_tags = []
focus_tags.each do |t|
t = t.gsub("#", "")
t = Tag.where('lower(name) = ?', t.downcase).first
@active_tags.push t if t
end
@twitter_results = @twitter.search("#{@hashtags} -rt", result_type: "recent").take(50)
@twitter_results.each do |tr|
t = Tweet.find_or_initialize_by(tweet_id: tr.id)
t.data = tr.to_json
tr.hashtags.each do |hashtag|
t.tag_list.add(hashtag.text)
end
t.save!
end
@video_results = Rails.cache.fetch(@hashtags, expires_in: 2.hours) do
videos = Yt::Collections::Videos.new
@video_results = videos.where(q: @hashtags)
end
@twitter_results = Tweet.search(@hashtags).records.to_a
@social_results = @twitter_results# + @video_results
@video_results.each.with_index do |video, i|
@social_results << video
break if i > 10
end
# @social_results.shuffle!
@tags = Tag.all.order(taggings_count: :desc)
end
end
fixed search to AND search for tags
class SearchController < ApplicationController
RESULT_SET = 300
def index
@hashtags = params[:tags]
@hashtags = "" if @hashtags.nil?
@twitter ||= Twitter::REST::Client.new do |config|
config.consumer_key = ENV["twitter_consumer_key"]
config.consumer_secret = ENV["twitter_consumer_secret"]
config.access_token = ENV["twitter_access_token"]
config.access_token_secret = ENV["twitter_access_token_secret"]
end
[ "#makerhood" ].each do |forced_keyword|
@hashtags = "#{@hashtags} #{forced_keyword}" unless @hashtags.include?(forced_keyword)
end
# Pick out the main tags
focus_tags = @hashtags.split(" ")
@active_tags = []
focus_tags.each do |t|
t = t.gsub("#", "")
t = Tag.where('lower(name) = ?', t.downcase).first
@active_tags.push t if t
end
@twitter_results = @twitter.search("#{@hashtags} -rt", result_type: "recent").take(50)
@twitter_results.each do |tr|
t = Tweet.find_or_initialize_by(tweet_id: tr.id)
t.data = tr.to_json
tr.hashtags.each do |hashtag|
t.tag_list.add(hashtag.text)
end
t.save!
end
@video_results = Rails.cache.fetch(@hashtags, expires_in: 2.hours) do
videos = Yt::Collections::Videos.new
@video_results = videos.where(q: @hashtags)
end
@twitter_results = Tweet.search(query: { "query_string": { query: @hashtags.split(" ").join(" AND ") } }).records.to_a
@social_results = @twitter_results# + @video_results
@video_results.each.with_index do |video, i|
@social_results << video
break if i > 10
end
# @social_results.shuffle!
@tags = Tag.all.order(taggings_count: :desc)
end
end
|
class SearchController < CmsController
cms_admin_paths :content,
'Search' => { :action => 'index'}
@@results_per_page = 20
def index
cms_page_path ['Content'], 'Search'
@search = self.content_search_node
if self.update_search && @search.search?
@results, @more = content_search_handler
if @results.length > 0
@showing = (@search.page * @@results_per_page)+1
@showing_end= @results.length + @showing-1
end
end
opensearch_auto_discovery_header
render :action => 'index'
end
protected
def search_handlers
return @search_handlers if @search_handlers
@search_handlers = {
'members' => {
:title => 'members: [member name or email address]',
:subtitle => 'Search members by name or email',
:text => 'members:'
},
'edit' => {
:title => 'edit: [/url/to_page]',
:subtitle => 'Edit a page of the site',
:text => 'edit:'
}
}
@search_handlers.each do |name,hsh|
hsh[:name] = name
hsh[:subtitle] = hsh[:subtitle].t
end
@search_handlers
end
def opensearch_auto_discovery_header
@domain = Domain.find DomainModel.active_domain_id
opensearch_url = url_for :action => 'opensearch'
title = "Backend search for %s" / @domain.name.humanize
@header = "<link rel='search' type='application/opensearchdescription+xml' title='#{vh title}' href='#{vh opensearch_url}' />"
end
public
def autocomplete
search = params[:search]
case search
when /^:$/
@results = search_handlers.values
when /^(\/.*)/
@results = SiteNode.find(:all,:conditions => ['node_path LIKE ? AND node_type="P"', "%#{$1}%" ],:order => "LENGTH(node_path)").map do |node|
{ :title => node.node_path,
:url => node.node_path }
end
when /^([a-zA-Z0-9]+)\:(.*)$/
search_handler = $1
search_terms = $2.strip
# Check if we match a search handler, if not show the handlers
if !search_terms.blank? && handler = search_handlers[search_handler]
if !handler[:class]
@results = self.send("#{handler[:name]}_search_handler",search_terms)
else
@results = handler[:class].send("#{handler[:name]}_search_handler",search_terms)
end
else
@results = search_handlers.values
end
else
@search = self.content_search_node
if self.update_search && @search.search?
@results, @more = content_search_handler
end
end
render :action => 'autocomplete', :layout => false
end
def suggestions
search = params[:search]
case search
when /^:$/
@results = search_handlers.values
when /^(\/.*)/
@results = SiteNode.find(:all,:conditions => ['node_path LIKE ? AND node_type="P"', "%#{$1}%" ],:order => "LENGTH(node_path)").map do |node|
{ :title => node.node_path }
end
when /^([a-zA-Z0-9]+)\:(.*)$/
search_handler = $1
search_terms = $2.strip
# Check if we match a search handler, if not show the handlers
if !search_terms.blank? && handler = search_handlers[search_handler]
if !handler[:class]
@results = self.send("#{handler[:name]}_search_handler",search_terms)
else
@results = handler[:class].send("#{handler[:name]}_search_handler",search_terms)
end
else
@results = search_handlers.values
end
end
suggestions = []
@results.each { |result| suggestions.push result[:title] } if @results
render :json => [search, suggestions]
end
def opensearch
search_url = url_for :action => 'index'
suggest_url = url_for :action => 'suggestions'
icon_url = Configuration.domain_link '/favicon.ico'
@domain = Domain.find DomainModel.active_domain_id
domain_name = @domain.name.humanize
title = '%s Admin Search' / domain_name
description = "Backend search for #{domain_name}"
data = { :title => title, :description => description, :search_url => search_url, :suggest_url => suggest_url,
:icon => {:url => icon_url, :width => 16, :height => 16, :type => 'image/x-icon'}
}
render :partial => 'opensearch', :locals => { :data => data }
end
protected
def members_search_handler(terms)
terms = terms.strip
if terms.include?("@")
users = EndUser.find(:all,:conditions => ['email LIKE ?', "%#{terms}%"],:limit => 10)
elsif terms.split(" ").length > 1
users = EndUser.find(:all,:conditions => [ 'full_name LIKE ?',"%#{terms}%" ], :limit => 10 )
else
users = (EndUser.find(:all,:conditions => [ 'full_name LIKE ?',"%#{terms}%" ],:limit => 5 ) +
EndUser.find(:all,:conditions => ['email LIKE ?', "%#{terms}%"],:limit => 5)).uniq
end
members_url = url_for(:controller => '/members',:action => 'view')
users.map! do |usr|
{ :title => usr.email,
:subtitle => usr.full_name,
:url => members_url + "/" + usr.id.to_s
}
end
end
def edit_search_handler(terms)
language = Configuration.languages[0]
edit_url = url_for(:controller => '/edit', :action => 'page' )
@results = SiteNode.find(:all,:conditions => ['node_path LIKE ? AND node_type="P"', "%#{terms}%" ],:order => "LENGTH(node_path)",:include => :live_revisions).map do |node|
rev = node.active_revisions.detect { |rev| rev.language == language} || node.active_revisions[0]
if(rev)
{
:title => "Edit Page: %s" / node.node_path,
:subtitle => rev.title || node.title.humanize,
:url => edit_url + "/page/#{node.id}"
}
end
end.compact
end
def content_search_handler
@results, @more = @search.backend_search
@results.map! do |result|
admin_url = result[:node].admin_url
if admin_url
edit_title = admin_url.delete(:title)
permission = admin_url.delete(:permission)
else
admin_url = '#'
end
if myself.has_content_permission?(permission)
result[:url] = url_for(admin_url)
result
else
nil
end
end.compact!
@results.pop if @results.length > @search.per_page
[@results, @more]
end
def content_search_node
return @search if @search
@search = ContentNodeSearch.new :per_page => @@results_per_page, :max_per_page => @@results_per_page, :page => 1
end
def searched
return @searched if ! @searched.nil?
@searched = params[:search]
end
def update_search
return false unless self.searched
@search.terms = params[:search]
@search.page = params[:page] if params[:page]
@search.per_page = params[:per_page] if params[:per_page]
@search.content_type_id = params[:content_type_id] if params[:content_type_id]
@search.valid?
end
end
Added better suggestions, goto first result if search is from a handler
class SearchController < CmsController
cms_admin_paths :content,
'Search' => { :action => 'index'}
@@results_per_page = 20
def index
cms_page_path ['Content'], 'Search'
@search = self.content_search_node
if self.update_search && @search.search?
case @search.terms
when /^(\/.*)/
node = SiteNode.find(:first, :conditions => ['node_path = ? AND node_type="P"', "#{$1}" ])
return redirect_to SiteNode.content_admin_url(node.id) if node
when /^([a-zA-Z0-9]+)\:(.*)$/
search_handler = $1
search_terms = $2.strip
if !search_terms.blank? && handler = search_handlers[search_handler]
if !handler[:class]
@results = self.send("#{handler[:name]}_search_handler",search_terms)
else
@results = handler[:class].send("#{handler[:name]}_search_handler",search_terms)
end
return redirect_to @results[0][:url] if @results && @results.length > 0
end
end
@results, @more = content_search_handler
if @results.length > 0
@showing = (@search.page * @@results_per_page)+1
@showing_end= @results.length + @showing-1
end
end
opensearch_auto_discovery_header
render :action => 'index'
end
protected
def search_handlers
return @search_handlers if @search_handlers
@search_handlers = {
'members' => {
:title => 'members: [member name or email address]',
:subtitle => 'Search members by name or email',
:text => 'members:'
},
'edit' => {
:title => 'edit: [/url/to_page]',
:subtitle => 'Edit a page of the site',
:text => 'edit:'
}
}
@search_handlers.each do |name,hsh|
hsh[:name] = name
hsh[:subtitle] = hsh[:subtitle].t
end
@search_handlers
end
def opensearch_auto_discovery_header
@domain = Domain.find DomainModel.active_domain_id
opensearch_url = url_for :action => 'opensearch'
title = "Backend search for %s" / @domain.name.humanize
@header = "<link rel='search' type='application/opensearchdescription+xml' title='#{vh title}' href='#{vh opensearch_url}' />"
end
public
def autocomplete
search = params[:search]
case search
when /^:$/
@results = search_handlers.values
when /^(\/.*)/
@results = SiteNode.find(:all,:conditions => ['node_path LIKE ? AND node_type="P"', "%#{$1}%" ],:order => "LENGTH(node_path)").map do |node|
{ :title => node.node_path,
:url => node.node_path }
end
when /^([a-zA-Z0-9]+)\:(.*)$/
search_handler = $1
search_terms = $2.strip
# Check if we match a search handler, if not show the handlers
if !search_terms.blank? && handler = search_handlers[search_handler]
if !handler[:class]
@results = self.send("#{handler[:name]}_search_handler",search_terms)
else
@results = handler[:class].send("#{handler[:name]}_search_handler",search_terms)
end
else
@results = search_handlers.values
end
else
@search = self.content_search_node
if self.update_search && @search.search?
@results, @more = content_search_handler
end
end
render :action => 'autocomplete', :layout => false
end
def suggestions
search = params[:search]
case search
when /^(\/.*)/
@results = SiteNode.find(:all,:conditions => ['node_path LIKE ? AND node_type="P"', "%#{$1}%" ],:order => "LENGTH(node_path)").map do |node|
{ :title => node.node_path,
:suggestion => node.node_path,
:subtitle => node.title,
:url => SiteNode.content_admin_url(node.id) }
end
when /^([a-zA-Z0-9]+)\:(.*)$/
search_handler = $1
search_terms = $2.strip
# Check if we match a search handler, if not show the handlers
if !search_terms.blank? && handler = search_handlers[search_handler]
if !handler[:class]
@results = self.send("#{handler[:name]}_search_handler",search_terms)
else
@results = handler[:class].send("#{handler[:name]}_search_handler",search_terms)
end
@results.map do |result|
result[:suggestion] = "#{search_handler}:#{result[:title]}"
result
end if @results
end
end
suggestions = []
descriptions = []
urls = []
@results.each do |result|
suggestions.push result[:suggestion]
descriptions.push result[:subtitle]
urls.push result[:url]
end if @results
render :json => [search, suggestions, descriptions, urls]
end
def opensearch
search_url = url_for :action => 'index'
suggest_url = url_for :action => 'suggestions'
icon_url = Configuration.domain_link '/favicon.ico'
@domain = Domain.find DomainModel.active_domain_id
domain_name = @domain.name.humanize
title = '%s Admin Search' / domain_name
description = "Backend search for #{domain_name}"
data = { :title => title, :description => description, :search_url => search_url, :suggest_url => suggest_url,
:icon => {:url => icon_url, :width => 16, :height => 16, :type => 'image/x-icon'}
}
render :partial => 'opensearch', :locals => { :data => data }
end
protected
def members_search_handler(terms)
terms = terms.strip
if terms.include?("@")
users = EndUser.find(:all,:conditions => ['email LIKE ?', "%#{terms}%"],:limit => 10)
elsif terms.split(" ").length > 1
users = EndUser.find(:all,:conditions => [ 'full_name LIKE ?',"%#{terms}%" ], :limit => 10 )
else
users = (EndUser.find(:all,:conditions => [ 'full_name LIKE ?',"%#{terms}%" ],:limit => 5 ) +
EndUser.find(:all,:conditions => ['email LIKE ?', "%#{terms}%"],:limit => 5)).uniq
end
members_url = url_for(:controller => '/members',:action => 'view')
users.map! do |usr|
{ :title => usr.email,
:subtitle => usr.full_name,
:url => members_url + "/" + usr.id.to_s
}
end
end
def edit_search_handler(terms)
language = Configuration.languages[0]
edit_url = url_for(:controller => '/edit', :action => 'page' )
@results = SiteNode.find(:all,:conditions => ['node_path LIKE ? AND node_type="P"', "%#{terms}%" ],:order => "LENGTH(node_path)",:include => :live_revisions).map do |node|
rev = node.active_revisions.detect { |rev| rev.language == language} || node.active_revisions[0]
if(rev)
{
:title => "Edit Page: %s" / node.node_path,
:subtitle => rev.title || node.title.humanize,
:url => edit_url + "/page/#{node.id}"
}
end
end.compact
end
def content_search_handler
@results, @more = @search.backend_search
@results.map! do |result|
admin_url = result[:node].admin_url
if admin_url
edit_title = admin_url.delete(:title)
permission = admin_url.delete(:permission)
else
admin_url = '#'
end
if myself.has_content_permission?(permission)
result[:url] = url_for(admin_url)
result
else
nil
end
end.compact!
@results.pop if @results.length > @search.per_page
[@results, @more]
end
def content_search_node
return @search if @search
@search = ContentNodeSearch.new :per_page => @@results_per_page, :max_per_page => @@results_per_page, :page => 1
end
def searched
return @searched if ! @searched.nil?
@searched = params[:search]
end
def update_search
return false unless self.searched
@search.terms = params[:search]
@search.page = params[:page] if params[:page]
@search.per_page = params[:per_page] if params[:per_page]
@search.content_type_id = params[:content_type_id] if params[:content_type_id]
@search.valid?
end
end
|
class SearchController < ApplicationController
def index
@search = Search.new(search_params)
@trips ||= []
if @search.valid?
found_trips = Trip.search(@search)
@trips = Trip.includes(:points).find(found_trips.map &:id)
else
@search = Search.new
end
end
private
def search_params
params.require(:search).permit(:from_city, :from_lon, :from_lat, :to_city, :to_lon, :to_lat, :date)
end
end
don't reinitialize search when invalid
class SearchController < ApplicationController
def index
@search = Search.new(search_params)
@trips ||= []
if @search.valid?
found_trips = Trip.search(@search)
@trips = Trip.includes(:points).find(found_trips.map &:id)
end
end
private
def search_params
params.require(:search).permit(:from_city, :from_lon, :from_lat, :to_city, :to_lon, :to_lat, :date)
end
end |
# vim: ts=4 sw=4 expandtab
# DONE 1. set analyzers for every language
# TODO 1.a. actually configure the analyzer so that certain words are protected (like allah, don't want to stem that). hopefully an alternate solution is available, so this isn't priority until the steps below are done.
# TODO 2. determine the language of the query (here)
# TODO 3. apply weights to different types of indices e.g. text > tafsir
# TODO 4. break down fields into analyzed and unanalyzed and weigh them
#
# NEW
# TODO 1. determine language
# 2. refactor query accordingly
# 3. refactor code
# 4. refine search, optimize for performance
require 'elasticsearch'
class SearchController < ApplicationController
include LanguageDetection
def query
query = params[:q]
page = [ ( params[:page] or params[:p] or 1 ).to_i, 1 ].max
size = [ [ ( params[:size] or params[:s] or 20 ).to_i, 20 ].max, 40 ].min # sets the max to 40 and min to 20
# Determining query language
# - Determine if Arabic (regex); if not, determine boost using the following...
# a. Use Accept-Language HTTP header
# b. Use country-code to language mapping (determine country code from geolocation)
# c. Use language-code from user application settings (should get at least double priority to anything else)
# d. Fallback to boosting English if nothing was determined from above and the query is pure ascii
# Rails.logger.info "headers #{ ap headers }"
# Rails.logger.info "session #{ ap session }"
# Rails.logger.info "params #{ ap params }"
start_time = Time.now
search_params = Hash.new
most_fields_fields_val = Array.new
if query =~ /^(?:\s*[\p{Arabic}\p{Diacritic}\p{Punct}\p{Digit}]+\s*)+$/
search_params.merge!( {
index: [ 'text-font', 'tafsir' ],
body: {
indices_boost: {
:"text-font" => 4,
:"tafsir" => 1
}
}
} )
most_fields_fields_val = [
'text^5',
'text.lemma^4',
'text.stem^3',
'text.root^1.5',
'text.lemma_clean^3',
'text.stem_clean^2',
'text.ngram^2',
'text.stemmed^2'
]
else
most_fields_fields_val = [ 'text^1.6', 'text.stemmed' ]
# TODO filter for langs that have translations only
search_params.merge!( {
index: [ 'trans*', 'text-font' ],
body: {
indices_boost: @indices_boost
}
} )
end
search_params.merge!( {
type: 'data',
explain: false, # debugging... on or off?
} )
# highlighting
search_params[:body].merge!( {
highlight: {
fields: {
text: {
type: 'fvh',
matched_fields: [ 'text.root', 'text.stem_clean', 'text.lemma_clean', 'text.stemmed', 'text' ],
## NOTE this set of commented options highlights up to the first 100 characters only but returns the whole string
#fragment_size: 100,
#fragment_offset: 0,
#no_match_size: 100,
#number_of_fragments: 1
number_of_fragments: 0
}
},
tags_schema: 'styled',
#force_source: true
},
} )
# query
search_params[:body].merge!( {
query: {
bool: {
must: [ {
## NOTE leaving this in for future reference
# terms: {
# :'ayah.surah_id' => [ 24 ]
# :'ayah.ayah_key' => [ '24_35' ]
# }
#}, {
multi_match: {
type: 'most_fields',
query: query,
fields: most_fields_fields_val,
minimum_should_match: '3<62%'
}
} ]
}
},
} )
# other experimental stuff
search_params[:body].merge!( {
fields: [ 'ayah.ayah_key', 'ayah.ayah_num', 'ayah.surah_id', 'ayah.ayah_index', 'text' ],
_source: [ "text", "ayah.*", "resource.*", "language.*" ],
} )
# aggregations
search_params[:body].merge!( {
aggs: {
by_ayah_key: {
terms: {
field: "ayah.ayah_key",
size: 6236,
order: {
max_score: "desc"
}
},
aggs: {
max_score: {
max: {
script: "_score"
}
}
}
}
},
size: 0
} )
#return search_params
client = Elasticsearch::Client.new # trace: true, log: true;
results = client.search( search_params )
total_hits = results['hits']['total']
buckets = results['aggregations']['by_ayah_key']['buckets']
imin = ( page - 1 ) * size
imax = page * size - 1
buckets_on_page = buckets[ imin .. imax ]
keys = buckets_on_page.map { |h| h[ 'key' ] }
doc_count = buckets_on_page.inject( 0 ) { |doc_count, h| doc_count + h[ 'doc_count' ] }
#return buckets
# restrict to keys on this page
search_params[:body][:query][:bool][:must].unshift( {
terms: {
:'ayah.ayah_key' => keys
}
} )
# limit to the number of docs we know we want
search_params[:body][:size] = doc_count
# get rid of the aggregations
search_params[:body].delete( :aggs )
# pull the new query with hits
results = client.search( search_params ).deep_symbolize_keys
#return results
# override experimental
search_params_text_font = {
index: [ 'text-font' ],
type: 'data',
explain: false,
size: keys.length,
body: {
query: {
ids: {
type: 'data',
values: keys.map { |k| "1_#{k}" }
}
}
}
}
results_text_font = client.search( search_params_text_font ).deep_symbolize_keys
ayah_key_to_font_text = results_text_font[:hits][:hits].map { |h| [ h[:_source][:ayah][:ayah_key], h[:_source][:text] ] }.to_h
ayah_key_to_font_text = {}
ayah_key_hash = {}
by_key = {}
results[:hits][:hits].each do |hit|
_source = hit[:_source]
_score = hit[:_score]
_text = ( hit.key?( :highlight ) && hit[ :highlight ].key?( :text ) && hit[ :highlight ][ :text ].first.length ) ? hit[ :highlight ][ :text ].first : _source[ :text ]
_ayah = _source[:ayah]
by_key[ _ayah[:ayah_key] ] = {
key: _ayah[:ayah_key],
ayah: _ayah[:ayah_num],
surah: _ayah[:surah_id],
index: _ayah[:ayah_index],
score: 0,
match: {
hits: 0,
best: []
}
} if by_key[ _ayah[:ayah_key] ] == nil
#quran = by_key[ _ayah[ 'ayah_key' ] ][:bucket][:quran]
result = by_key[ _ayah[:ayah_key] ]
# TODO: transliteration does not have a resource or language.
#id name slug text lang dir
extension = {
text: _text,
score: _score,
}.merge( _source[:resource] ? {
id: _source[:resource][:resource_id],
name: _source[:resource][:name],
slug: _source[:resource][:slug],
lang: _source[:resource][:language_code],
} : {name: 'Transliteration'} )
.merge( _source[:language] ? {
dir: _source[:language][:direction],
} : {} )
# .merge( { debug: hit } )
if hit[:_index] == 'text-font' && _text.length
extension[:_do_interpolate] = true
end
result[:score] = _score if _score > result[:score]
result[:match][:hits] = result[:match][:hits] + 1
result[:match][:best].push( {}.merge!( extension ) ) # if result[:match][:best].length < 3
end
word_id_hash = {}
word_id_to_highlight = {}
# attribute the "bucket" structure for each ayah result
by_key.values.each do |result|
result[:bucket] = Quran::Ayah.get_ayat( { surah_id: result[:surah], ayah: result[:ayah], content: params[:content], audio: params[:audio] } ).first
if result[:bucket][:content]
resource_id_to_bucket_content_index = {}
result[:bucket][:content].each_with_index do | c, i |
resource_id_to_bucket_content_index[ c[:id].to_i ] = i
end
#
result[:match][:best].each do |b|
id = b[:id].to_i
if index = resource_id_to_bucket_content_index[ id ]
result[:bucket][:content][ index ][:text] = b[:text]
end
end
end
result[:match][:best].each do |h|
if h.delete( :_do_interpolate )
t = h[:text].split( '' )
parsed = { word_ids: [] }
for i in 0 .. t.length - 1
# state logic
# if its in a highlight tag
# if its in the class value
# if its in a word id
# if its a start index
# if its an end index
# if its highlighted
parsed[:a_number] = t[i].match( /\d/ ) ? true : false
parsed[:a_start_index] = false
parsed[:an_end_index] = false
if not parsed[:in_highlight_tag] and t[i] == '<'
parsed[:in_highlight_tag] = true
elsif parsed[:in_highlight_tag] and t[i] == '<'
parsed[:in_highlight_tag] = false
end
if parsed[:in_highlight_tag] and not parsed[:in_class_value] and t[i-1] == '"' and t[i-2] == '='
parsed[:in_class_value] = true
elsif parsed[:in_highlight_tag] and parsed[:in_class_value] and t[i] == '"'
parsed[:in_class_value] = false
end
if parsed[:a_number] and ( i == 0 or ( t[i-1] == ' ' or t[i-1] == '>' ) )
parsed[:in_word_id] = true
parsed[:a_start_index] = true
elsif not parsed[:a_number] and parsed[:in_word_id]
parsed[:in_word_id] = false
end
if parsed[:in_word_id] and ( i == t.length - 1 or ( t[i+1] == ' ' or t[i+1] == '<' ) )
parsed[:an_end_index] = true
end
# control logic
if i == 0
parsed[:current] = { word_id: [], indices: [], highlight: [] }
end
if parsed[:in_class_value]
parsed[:current][:highlight].push( t[i] )
end
if parsed[:in_word_id]
parsed[:current][:word_id].push( t[i] )
if parsed[:a_start_index]
parsed[:current][:indices][0] = i
end
if parsed[:an_end_index]
parsed[:current][:indices][1] = i
parsed[:current][:word_id] = parsed[:current][:word_id].join( '' )
parsed[:current][:highlight] = parsed[:current][:highlight].join( '' )
if not parsed[:current][:highlight].length > 0
parsed[:current].delete( :highlight )
end
if parsed[:current].key?( :highlight )
word_id_to_highlight[ parsed[:current][:word_id].to_i ] = parsed[:current][:highlight] #true
end
parsed[:word_ids].push( parsed[:current] )
parsed[:current] = { word_id: [], indices: [], highlight: [] }
end
end
end
if parsed[:word_ids].length > 0
# init the word_id_hash
result[:bucket][:quran].each do |h|
word_id_hash[ h[:word][:id].to_s.to_sym ] = { text: h[:word][:arabic] } if h[:word][:id]
if word_id_to_highlight.key? h[:word][:id].to_i
h[:highlight] = word_id_to_highlight[ h[:word][:id] ]
end
end
parsed[:word_ids].each do |p|
word_id = p[:word_id] #.delete :word_id
word_id_hash[ word_id.to_s.to_sym ].merge!( p )
end
end
word_id_hash.each do |id,h|
for i in h[:indices][0] .. h[:indices][1]
t[i] = nil
end
t[ h[:indices][0] ] = h[:text]
end
h[:text] = t.join( '' )
end
end
end
return_result = by_key.keys.sort {|a,b| by_key[ b ][ :score ] <=> by_key[ a ][ :score ] } .map { |k| by_key[ k ] }
# HACK: a block of transformation hacks
return_result.map! do |r|
# HACK: move back from '2_255' ayah_key format (was an experimental change b/c of ES acting weird) to '2:255'
r[:key].gsub! /_/, ':'
# HACK: a bit of a hack, or just keeping redundant info tidy? removing redundant keys from the 'bucket' property (I really want to rename that property)
r[:bucket].delete :surah
r[:bucket].delete :ayah
r[:bucket][:quran].map! do |q|
q.delete :ayah_key
q.delete :word if q[:word] and q[:word][:id] == nil # get rid of the word block if its just a bunch of nils
q
end
r[:match][:best] = r[:match][:best][ 0 .. 2 ] # top 3
r
end
delta_time = Time.now - start_time
render json: {
query: params[:q],
hits: return_result.length,
page: page,
size: size,
took: delta_time,
total: buckets.length,
results: return_result
}
end
end
Important search Comment
# vim: ts=4 sw=4 expandtab
# DONE 1. set analyzers for every language
# TODO 1.a. actually configure the analyzer so that certain words are protected (like allah, don't want to stem that). hopefully an alternate solution is available, so this isn't priority until the steps below are done.
# TODO 2. determine the language of the query (here)
# TODO 3. apply weights to different types of indices e.g. text > tafsir
# TODO 4. break down fields into analyzed and unanalyzed and weigh them
#
# NEW
# TODO 1. determine language
# 2. refactor query accordingly
# 3. refactor code
# 4. refine search, optimize for performance
require 'elasticsearch'
class SearchController < ApplicationController
include LanguageDetection
def query
query = params[:q]
page = [ ( params[:page] or params[:p] or 1 ).to_i, 1 ].max
size = [ [ ( params[:size] or params[:s] or 20 ).to_i, 20 ].max, 40 ].min # sets the max to 40 and min to 20
# Determining query language
# - Determine if Arabic (regex); if not, determine boost using the following...
# a. Use Accept-Language HTTP header
# b. Use country-code to language mapping (determine country code from geolocation)
# c. Use language-code from user application settings (should get at least double priority to anything else)
# d. Fallback to boosting English if nothing was determined from above and the query is pure ascii
# Rails.logger.info "headers #{ ap headers }"
# Rails.logger.info "session #{ ap session }"
# Rails.logger.info "params #{ ap params }"
start_time = Time.now
search_params = Hash.new
most_fields_fields_val = Array.new
if query =~ /^(?:\s*[\p{Arabic}\p{Diacritic}\p{Punct}\p{Digit}]+\s*)+$/
search_params.merge!( {
index: [ 'text-font', 'tafsir' ],
body: {
indices_boost: {
:"text-font" => 4,
:"tafsir" => 1
}
}
} )
most_fields_fields_val = [
'text^5',
'text.lemma^4',
'text.stem^3',
'text.root^1.5',
'text.lemma_clean^3',
'text.stem_clean^2',
'text.ngram^2',
'text.stemmed^2'
]
else
most_fields_fields_val = [ 'text^1.6', 'text.stemmed' ]
# TODO filter for langs that have translations only
search_params.merge!( {
index: [ 'trans*', 'text-font' ],
body: {
indices_boost: @indices_boost #coming from language detection
}
} )
end
search_params.merge!( {
type: 'data',
explain: false, # debugging... on or off?
} )
# highlighting
search_params[:body].merge!( {
highlight: {
fields: {
text: {
type: 'fvh',
matched_fields: [ 'text.root', 'text.stem_clean', 'text.lemma_clean', 'text.stemmed', 'text' ],
## NOTE this set of commented options highlights up to the first 100 characters only but returns the whole string
#fragment_size: 100,
#fragment_offset: 0,
#no_match_size: 100,
#number_of_fragments: 1
number_of_fragments: 0
}
},
tags_schema: 'styled',
#force_source: true
},
} )
# query
search_params[:body].merge!( {
query: {
bool: {
must: [ {
## NOTE leaving this in for future reference
# terms: {
# :'ayah.surah_id' => [ 24 ]
# :'ayah.ayah_key' => [ '24_35' ]
# }
#}, {
multi_match: {
type: 'most_fields',
query: query,
fields: most_fields_fields_val,
minimum_should_match: '3<62%'
}
} ]
}
},
} )
# other experimental stuff
search_params[:body].merge!( {
fields: [ 'ayah.ayah_key', 'ayah.ayah_num', 'ayah.surah_id', 'ayah.ayah_index', 'text' ],
_source: [ "text", "ayah.*", "resource.*", "language.*" ],
} )
# aggregations
search_params[:body].merge!( {
aggs: {
by_ayah_key: {
terms: {
field: "ayah.ayah_key",
size: 6236,
order: {
max_score: "desc"
}
},
aggs: {
max_score: {
max: {
script: "_score"
}
}
}
}
},
size: 0
} )
#return search_params
client = Elasticsearch::Client.new # trace: true, log: true;
results = client.search( search_params )
total_hits = results['hits']['total']
buckets = results['aggregations']['by_ayah_key']['buckets']
imin = ( page - 1 ) * size
imax = page * size - 1
buckets_on_page = buckets[ imin .. imax ]
keys = buckets_on_page.map { |h| h[ 'key' ] }
doc_count = buckets_on_page.inject( 0 ) { |doc_count, h| doc_count + h[ 'doc_count' ] }
#return buckets
# restrict to keys on this page
search_params[:body][:query][:bool][:must].unshift( {
terms: {
:'ayah.ayah_key' => keys
}
} )
# limit to the number of docs we know we want
search_params[:body][:size] = doc_count
# get rid of the aggregations
search_params[:body].delete( :aggs )
# pull the new query with hits
results = client.search( search_params ).deep_symbolize_keys
#return results
# override experimental
search_params_text_font = {
index: [ 'text-font' ],
type: 'data',
explain: false,
size: keys.length,
body: {
query: {
ids: {
type: 'data',
values: keys.map { |k| "1_#{k}" }
}
}
}
}
results_text_font = client.search( search_params_text_font ).deep_symbolize_keys
ayah_key_to_font_text = results_text_font[:hits][:hits].map { |h| [ h[:_source][:ayah][:ayah_key], h[:_source][:text] ] }.to_h
ayah_key_to_font_text = {}
ayah_key_hash = {}
by_key = {}
results[:hits][:hits].each do |hit|
_source = hit[:_source]
_score = hit[:_score]
_text = ( hit.key?( :highlight ) && hit[ :highlight ].key?( :text ) && hit[ :highlight ][ :text ].first.length ) ? hit[ :highlight ][ :text ].first : _source[ :text ]
_ayah = _source[:ayah]
by_key[ _ayah[:ayah_key] ] = {
key: _ayah[:ayah_key],
ayah: _ayah[:ayah_num],
surah: _ayah[:surah_id],
index: _ayah[:ayah_index],
score: 0,
match: {
hits: 0,
best: []
}
} if by_key[ _ayah[:ayah_key] ] == nil
#quran = by_key[ _ayah[ 'ayah_key' ] ][:bucket][:quran]
result = by_key[ _ayah[:ayah_key] ]
# TODO: transliteration does not have a resource or language.
#id name slug text lang dir
extension = {
text: _text,
score: _score,
}.merge( _source[:resource] ? {
id: _source[:resource][:resource_id],
name: _source[:resource][:name],
slug: _source[:resource][:slug],
lang: _source[:resource][:language_code],
} : {name: 'Transliteration'} )
.merge( _source[:language] ? {
dir: _source[:language][:direction],
} : {} )
# .merge( { debug: hit } )
if hit[:_index] == 'text-font' && _text.length
extension[:_do_interpolate] = true
end
result[:score] = _score if _score > result[:score]
result[:match][:hits] = result[:match][:hits] + 1
result[:match][:best].push( {}.merge!( extension ) ) # if result[:match][:best].length < 3
end
word_id_hash = {}
word_id_to_highlight = {}
# attribute the "bucket" structure for each ayah result
by_key.values.each do |result|
result[:bucket] = Quran::Ayah.get_ayat( { surah_id: result[:surah], ayah: result[:ayah], content: params[:content], audio: params[:audio] } ).first
if result[:bucket][:content]
resource_id_to_bucket_content_index = {}
result[:bucket][:content].each_with_index do | c, i |
resource_id_to_bucket_content_index[ c[:id].to_i ] = i
end
#
result[:match][:best].each do |b|
id = b[:id].to_i
if index = resource_id_to_bucket_content_index[ id ]
result[:bucket][:content][ index ][:text] = b[:text]
end
end
end
result[:match][:best].each do |h|
if h.delete( :_do_interpolate )
t = h[:text].split( '' )
parsed = { word_ids: [] }
for i in 0 .. t.length - 1
# state logic
# if its in a highlight tag
# if its in the class value
# if its in a word id
# if its a start index
# if its an end index
# if its highlighted
parsed[:a_number] = t[i].match( /\d/ ) ? true : false
parsed[:a_start_index] = false
parsed[:an_end_index] = false
if not parsed[:in_highlight_tag] and t[i] == '<'
parsed[:in_highlight_tag] = true
elsif parsed[:in_highlight_tag] and t[i] == '<'
parsed[:in_highlight_tag] = false
end
if parsed[:in_highlight_tag] and not parsed[:in_class_value] and t[i-1] == '"' and t[i-2] == '='
parsed[:in_class_value] = true
elsif parsed[:in_highlight_tag] and parsed[:in_class_value] and t[i] == '"'
parsed[:in_class_value] = false
end
if parsed[:a_number] and ( i == 0 or ( t[i-1] == ' ' or t[i-1] == '>' ) )
parsed[:in_word_id] = true
parsed[:a_start_index] = true
elsif not parsed[:a_number] and parsed[:in_word_id]
parsed[:in_word_id] = false
end
if parsed[:in_word_id] and ( i == t.length - 1 or ( t[i+1] == ' ' or t[i+1] == '<' ) )
parsed[:an_end_index] = true
end
# control logic
if i == 0
parsed[:current] = { word_id: [], indices: [], highlight: [] }
end
if parsed[:in_class_value]
parsed[:current][:highlight].push( t[i] )
end
if parsed[:in_word_id]
parsed[:current][:word_id].push( t[i] )
if parsed[:a_start_index]
parsed[:current][:indices][0] = i
end
if parsed[:an_end_index]
parsed[:current][:indices][1] = i
parsed[:current][:word_id] = parsed[:current][:word_id].join( '' )
parsed[:current][:highlight] = parsed[:current][:highlight].join( '' )
if not parsed[:current][:highlight].length > 0
parsed[:current].delete( :highlight )
end
if parsed[:current].key?( :highlight )
word_id_to_highlight[ parsed[:current][:word_id].to_i ] = parsed[:current][:highlight] #true
end
parsed[:word_ids].push( parsed[:current] )
parsed[:current] = { word_id: [], indices: [], highlight: [] }
end
end
end
if parsed[:word_ids].length > 0
# init the word_id_hash
result[:bucket][:quran].each do |h|
word_id_hash[ h[:word][:id].to_s.to_sym ] = { text: h[:word][:arabic] } if h[:word][:id]
if word_id_to_highlight.key? h[:word][:id].to_i
h[:highlight] = word_id_to_highlight[ h[:word][:id] ]
end
end
parsed[:word_ids].each do |p|
word_id = p[:word_id] #.delete :word_id
word_id_hash[ word_id.to_s.to_sym ].merge!( p )
end
end
word_id_hash.each do |id,h|
for i in h[:indices][0] .. h[:indices][1]
t[i] = nil
end
t[ h[:indices][0] ] = h[:text]
end
h[:text] = t.join( '' )
end
end
end
return_result = by_key.keys.sort {|a,b| by_key[ b ][ :score ] <=> by_key[ a ][ :score ] } .map { |k| by_key[ k ] }
# HACK: a block of transformation hacks
return_result.map! do |r|
# HACK: move back from '2_255' ayah_key format (was an experimental change b/c of ES acting weird) to '2:255'
r[:key].gsub! /_/, ':'
# HACK: a bit of a hack, or just keeping redundant info tidy? removing redundant keys from the 'bucket' property (I really want to rename that property)
r[:bucket].delete :surah
r[:bucket].delete :ayah
r[:bucket][:quran].map! do |q|
q.delete :ayah_key
q.delete :word if q[:word] and q[:word][:id] == nil # get rid of the word block if its just a bunch of nils
q
end
r[:match][:best] = r[:match][:best][ 0 .. 2 ] # top 3
r
end
delta_time = Time.now - start_time
render json: {
query: params[:q],
hits: return_result.length,
page: page,
size: size,
took: delta_time,
total: buckets.length,
results: return_result
}
end
end
|
class SearchController < ApplicationController
after_action :enable_caching
# before_action :ignore_empty_query, only: [:index, :map] ## FERDI - I commented this out so the page would load
before_action :load_search, only: [:index, :map]
def index
#render partial: 'grid' if request.xhr? ## FERDI - I think we can delete this?
end
def search_results
@results = {
search_term: 'My search',
categories: [
{ id: 0, title: 'All' }, # Pull id from CMS
{ id: 0, title: 'News & Stories' }, # Pull id and title from CMS
{ id: 0, title: 'Resources' } # Pull id and title from CMS
],
current_page: 1,
page_items_start: 1,
page_items_end: 15,
total_items: 45, # Total items for selected category
results: [
{
title: 'Protected area coverage per country/territory by UN Environment Regions',
url: 'http://google.com',
summary: 'This page provides access to national statistics for every country and territory classified under the UN Environment Regions.The regions listed below are based upon UN Environment’s Global Environment Outlook (GEO) process.',
image: 'image url'
},
{
title: 'Protected area coverage per country/territory by UN Environment Regions',
url: 'http://google.com',
summary: 'This page provides access to national statistics for every country and territory classified under the UN Environment Regions.The regions listed below are based upon UN Environment’s Global Environment Outlook (GEO) process.',
image: 'image url'
}
]
}.to_json
render json: @results
end
def map
render :index
end
def autocomplete
@results = Autocompletion.lookup params[:q]
## TODO Ferdi this needs to return // [ { title: String, url: String } ]
# render partial: 'search/autocomplete'
render json: @results
end
def search_areas
#for searching for OECMs or WDPAs
#this one is likely to change as it doesn't have any of the filtering in yet - but i could do with some data to work with
@results = {
filters: [],
results: [
{
geo_type: 'region',
title: I18n.t('global.geo_types.regions'),
total: 10,
areas: [
{
title: 'Asia & Pacific',
url: 'url to page'
}
]
},
{
geo_type: 'country',
title: I18n.t('global.geo_types.countries'),
total: 10,
areas: [
{
areas: 5908,
region: 'America',
title: 'United States of America',
url: 'url to page'
},
{
areas: 508,
regions: 'Europe',
title: 'United Kingdom',
url: 'url to page'
},
{
areas: 508,
regions: 'Europe',
title: 'United Kingdom',
url: 'url to page'
},
{
areas: 508,
regions: 'Europe',
title: 'United Kingdom',
url: 'url to page'
}
]
},
{
geo_type: 'site',
title: I18n.t('global.area_types.wdpa'), ## OR I18n.t('global.area_types.oecm')
total: 30,
areas: [
{
country: 'France',
image: 'url to generated map of PA location',
region: 'Europe',
title: 'Avenc De Fra Rafel',
url: 'url to page'
}
]
}
]
}.to_json
render json: @results
end
def search_areas_pagination
#for specific page of OECMs or WDPAs
#if regions
@results = [
{
title: 'Asia & Pacific',
url: 'url to page'
}
].to_json
#if countries
@results = [
{
areas: 5908,
region: 'America',
title: 'United States of America',
url: 'url to page'
}
]
#if sites
@results = [
{
country: 'France',
image: 'url to generated map of PA location',
region: 'Europe',
title: 'Avenc De Fra Rafel',
url: 'url to page'
}
]
render json: @results
end
private
def ignore_empty_query
@query = params[:q]
redirect_to :root if @query.blank? && filters.empty?
end
def load_search
begin
@search = Search.search(@query, search_options)
rescue => e
Rails.logger.warn("error in search controller: #{e.message}")
@search = nil
end
@main_filter = params[:main]
end
def search_options
options = {filters: filters}
options[:page] = params[:page].to_i if params[:page].present?
options
end
def filters
params.stringify_keys.slice(*Search::ALLOWED_FILTERS)
end
end
Update search controller
class SearchController < ApplicationController
after_action :enable_caching
# before_action :ignore_empty_query, only: [:index, :map] ## FERDI - I commented this out so the page would load
before_action :load_search, only: [:index, :map]
def index
#render partial: 'grid' if request.xhr? ## FERDI - I think we can delete this?
end
def search_results
@results = {
search_term: 'My search',
categories: [
{ id: 0, title: 'All' }, # Pull id from CMS
{ id: 0, title: 'News & Stories' }, # Pull id and title from CMS
{ id: 0, title: 'Resources' } # Pull id and title from CMS
],
current_page: 1,
page_items_start: 1,
page_items_end: 15,
total_items: 45, # Total items for selected category
results: [
{
title: 'Protected area coverage per country/territory by UN Environment Regions',
url: 'http://google.com',
summary: 'This page provides access to national statistics for every country and territory classified under the UN Environment Regions.The regions listed below are based upon UN Environment’s Global Environment Outlook (GEO) process.',
image: 'image url'
},
{
title: 'Protected area coverage per country/territory by UN Environment Regions',
url: 'http://google.com',
summary: 'This page provides access to national statistics for every country and territory classified under the UN Environment Regions.The regions listed below are based upon UN Environment’s Global Environment Outlook (GEO) process.',
image: 'image url'
}
]
}.to_json
render json: @results
end
def map
render :index
end
def autocomplete
@results = Autocompletion.lookup params[:q] ## TODO Ferdi this needs to return // [ { title: String, url: String } ]
# render partial: 'search/autocomplete'
render json: @results
end
def search_areas
#for searching for OECMs or WDPAs
#this one is likely to change as it doesn't have any of the filtering in yet - but i could do with some data to work with
@results = {
filters: [],
results: [
{
geo_type: 'region',
title: I18n.t('global.geo_types.regions'),
total: 10,
areas: [
{
title: 'Asia & Pacific',
url: 'url to page'
}
]
},
{
geo_type: 'country',
title: I18n.t('global.geo_types.countries'),
total: 10,
areas: [
{
areas: 5908,
region: 'America',
title: 'United States of America',
url: 'url to page'
},
{
areas: 508,
regions: 'Europe',
title: 'United Kingdom',
url: 'url to page'
},
{
areas: 508,
regions: 'Europe',
title: 'United Kingdom',
url: 'url to page'
},
{
areas: 508,
regions: 'Europe',
title: 'United Kingdom',
url: 'url to page'
}
]
},
{
geo_type: 'site',
title: I18n.t('global.area_types.wdpa'), ## OR I18n.t('global.area_types.oecm')
total: 30,
areas: [
{
country: 'France',
image: 'url to generated map of PA location',
region: 'Europe',
title: 'Avenc De Fra Rafel',
url: 'url to page'
}
]
}
]
}.to_json
render json: @results
end
def search_areas_pagination
#for specific page of OECMs or WDPAs
#if regions
@results = [
{
title: 'Asia & Pacific',
url: 'url to page'
}
].to_json
#if countries
@results = [
{
areas: 5908,
region: 'America',
title: 'United States of America',
url: 'url to page'
}
]
#if sites
@results = [
{
country: 'France',
image: 'url to generated map of PA location',
region: 'Europe',
title: 'Avenc De Fra Rafel',
url: 'url to page'
}
]
render json: @results
end
private
def ignore_empty_query
@query = params[:q]
redirect_to :root if @query.blank? && filters.empty?
end
def load_search
begin
@search = Search.search(@query, search_options)
rescue => e
Rails.logger.warn("error in search controller: #{e.message}")
@search = nil
end
@main_filter = params[:main]
end
def search_options
options = {filters: filters}
options[:page] = params[:page].to_i if params[:page].present?
options
end
def filters
params.stringify_keys.slice(*Search::ALLOWED_FILTERS)
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.