repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/cname_spec.rb | spec/models/cname_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe CNAME, "when new" do
before(:each) do
@cname = CNAME.new
end
it "should be invalid by default" do
@cname.should_not be_valid
end
it "should require content" do
@cname.should have(2).error_on(:content)
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/macro_spec.rb | spec/models/macro_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe Macro, "when new" do
before(:each) do
@macro = Macro.new
end
it "should require a new" do
@macro.should have(1).error_on(:name)
end
it "should have a unique name" do
m = Factory(:macro)
@macro.name = m.name
@macro.should have(1).error_on(:name)
end
it "should be disabled by default" do
@macro.should_not be_active
end
end
describe Macro, "when applied" do
before(:each) do
@target = Factory(:domain)
@macro = Factory(:macro)
@step_create = Factory(:macro_step_create, :macro => @macro, :name => 'foo')
@step_update = Factory(:macro_step_change, :macro => @macro, :record_type => 'A', :name => 'www', :content => '127.0.0.9')
@step_remove_target = Factory(:macro_step_remove, :macro => @macro, :record_type => 'A', :name => 'mail')
@step_remove_wild = Factory(:macro_step_remove, :macro => @macro, :record_type => 'MX', :name => '*')
@step_update2 = Factory(:macro_step_change, :macro => @macro, :record_type => 'A', :name => 'admin', :content => '127.0.0.10')
end
it "should create new RR's" do
@macro.apply_to( @target )
@target.a_records.map(&:shortname).should include('foo')
end
it "should update existing RR's" do
rr = Factory(:www, :domain => @target)
lambda {
@macro.apply_to( @target )
rr.reload
}.should change( rr, :content )
end
it "should remove targetted RR's" do
rr = Factory(:a, :name => 'mail', :domain => @target)
@macro.apply_to( @target )
lambda { rr.reload }.should raise_error( ActiveRecord::RecordNotFound )
end
it "should remove existing RR's (wild card)" do
Factory(:mx, :domain => @target)
@target.mx_records(true).should_not be_empty
@macro.apply_to( @target )
@target.mx_records(true).should be_empty
end
it "should not create RR's that were supposed to be updated but doesn't exist" do
@macro.apply_to( @target )
@target.reload.a_records.detect { |a| a.name =~ /^admin/ }.should be_nil
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/domain_spec.rb | spec/models/domain_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "New 'untyped'", Domain do
subject { Domain.new }
it "should be NATIVE by default" do
subject.type.should == 'NATIVE'
end
it "should not accept rubbish types" do
subject.type = 'DOMINANCE'
subject.should have(1).error_on(:type)
end
end
describe "New MASTER/NATIVE", Domain do
subject { Domain.new }
it "should require a name" do
subject.should have(1).error_on(:name)
end
it "should not allow duplicate names" do
Factory(:domain)
subject.name = "example.com"
subject.should have(1).error_on(:name)
end
it "should bail out on missing SOA fields" do
subject.should have(1).error_on( :primary_ns )
end
it "should be NATIVE by default" do
subject.type.should eql('NATIVE')
end
it "should not require a MASTER" do
subject.should have(:no).errors_on(:master)
end
end
describe "New SLAVE", Domain do
subject { Domain.new( :type => 'SLAVE' ) }
it "should require a master address" do
subject.should have(1).error_on(:master)
end
it "should require a valid master address" do
subject.master = 'foo'
subject.should have(1).error_on(:master)
subject.master = '127.0.0.1'
subject.should have(:no).errors_on(:master)
end
it "should not bail out on missing SOA fields" do
subject.should have(:no).errors_on( :primary_ns )
end
end
describe Domain, "when loaded" do
before(:each) do
@domain = Factory(:domain)
end
it "should have a name" do
@domain.name.should eql('example.com')
end
it "should have an SOA record" do
@domain.soa_record.should be_a_kind_of( SOA )
end
it "should have NS records" do
ns1 = Factory(:ns, :domain => @domain)
ns2 = Factory(:ns, :domain => @domain)
ns = @domain.ns_records
ns.should be_a_kind_of( Array )
ns.should include( ns1 )
ns.should include( ns2 )
end
it "should have MX records" do
mx_f = Factory(:mx, :domain => @domain)
mx = @domain.mx_records
mx.should be_a_kind_of( Array )
mx.should include( mx_f )
end
it "should have A records" do
a_f = Factory(:a, :domain => @domain)
a = @domain.a_records
a.should be_a_kind_of( Array )
a.should include( a_f )
end
it "should give access to all records excluding the SOA" do
Factory(:a, :domain => @domain)
@domain.records_without_soa.size.should be( @domain.records.size - 1 )
end
it "should not complain about missing SOA fields" do
@domain.should have(:no).errors_on(:primary_ns)
end
end
describe Domain, "scopes" do
let(:quentin) { Factory(:quentin) }
let(:aaron) { Factory(:aaron) }
let(:quentin_domain) { Factory(:domain, :user => quentin) }
let(:aaron_domain) { Factory(:domain, :name => 'example.org', :user => aaron) }
let(:admin) { Factory(:admin) }
it "should show all domains to an admin" do
quentin_domain
aaron_domain
Domain.user( admin ).all.should include(quentin_domain)
Domain.user( admin ).all.should include(aaron_domain)
end
it "should restrict owners" do
quentin_domain
aaron_domain
Domain.user( quentin ).all.should include(quentin_domain)
Domain.user( quentin ).all.should_not include(aaron_domain)
Domain.user( aaron ).all.should_not include(quentin_domain)
Domain.user( aaron ).all.should include(aaron_domain)
end
it "should restrict authentication tokens"
end
describe "NATIVE/MASTER", Domain, "when created" do
it "with additional attributes should create an SOA record" do
domain = Domain.new
domain.name = 'example.org'
domain.primary_ns = 'ns1.example.org'
domain.contact = 'admin@example.org'
domain.refresh = 10800
domain.retry = 7200
domain.expire = 604800
domain.minimum = 10800
domain.save.should be_true
domain.soa_record.should_not be_nil
domain.soa_record.primary_ns.should eql('ns1.example.org')
end
it "with bulk additional attributes should be acceptable" do
domain = Domain.new(
:name => 'example.org',
:primary_ns => 'ns1.example.org',
:contact => 'admin@example.org',
:refresh => 10800,
:retry => 7200,
:expire => 608400,
:minimum => 10800
)
domain.save.should be_true
domain.soa_record.should_not be_nil
domain.soa_record.primary_ns.should eql('ns1.example.org')
end
end
describe "SLAVE", Domain, "when created" do
before(:each) do
@domain = Domain.new( :type => 'SLAVE' )
end
it "should create with SOA requirements or SOA record" do
@domain.name = 'example.org'
@domain.master = '127.0.0.1'
@domain.save.should be_true
@domain.soa_record.should be_nil
end
end
describe Domain, "when deleting" do
it "should delete its records as well" do
domain = Factory(:domain)
expect {
domain.destroy
}.to change(Record, :count).by(-domain.records.size)
end
end
describe Domain, "when searching" do
before(:each) do
@quentin = Factory(:quentin)
Factory(:domain, :user => @quentin)
end
it "should return results for admins" do
Domain.search('exa', 1, Factory(:admin)).should_not be_empty
end
it "should return results for users" do
Domain.search('exa', 1, @quentin).should_not be_empty
end
it "should return unscoped results" do
Domain.search('exa', 1).should_not be_empty
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/mx_spec.rb | spec/models/mx_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe MX, "when new" do
before(:each) do
@mx = MX.new
end
it "should be invalid by default" do
@mx.should_not be_valid
end
it "should require a priority" do
@mx.should have(1).error_on(:prio)
end
it "should only allow positive, numeric priorities, between 0 and 65535 (inclusive)" do
@mx.prio = -10
@mx.should have(1).error_on(:prio)
@mx.prio = 65536
@mx.should have(1).error_on(:prio)
@mx.prio = 'low'
@mx.should have(1).error_on(:prio)
@mx.prio = 10
@mx.should have(:no).errors_on(:prio)
end
it "should require content" do
@mx.should have(2).error_on(:content)
end
it "should not accept IP addresses as content" do
@mx.content = "127.0.0.1"
@mx.should have(1).error_on(:content)
end
it "should not accept spaces in content" do
@mx.content = 'spaced out.com'
@mx.should have(1).error_on(:content)
end
it "should support priorities" do
@mx.supports_prio?.should be_true
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/auth_token_spec.rb | spec/models/auth_token_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe AuthToken, "when new" do
before(:each) do
@auth_token = AuthToken.new
end
it "should be invalid by default" do
@auth_token.should_not be_valid
end
it "should require a domain" do
@auth_token.should have(1).error_on(:domain_id)
end
it "should require a user" do
@auth_token.should have(1).error_on(:user_id)
end
it "should require an auth token" do
@auth_token.token.should_not be_nil
@auth_token.token = nil
@auth_token.should have(1).error_on(:token)
end
it "should require the permissions hash" do
@auth_token.permissions.should_not be_nil
@auth_token.permissions = nil
@auth_token.should have(1).error_on(:permissions)
end
it "should require an expiry time" do
@auth_token.should have(1).error_on(:expires_at)
end
it "should require an expiry time in the future" do
@auth_token.expires_at = 1.hour.ago
@auth_token.should have(1).error_on(:expires_at)
end
end
describe AuthToken, "internals" do
before(:each) do
@domain = Factory(:domain)
@auth_token = AuthToken.new( :domain => @domain )
end
it "should extract the name and RR class from Record objects" do
record = Factory(:a, :domain => @domain)
name, type = @auth_token.send(:get_name_and_type_from_param, record )
name.should eql('example.com')
type.should eql('A')
end
it "should correctly set the name and RR class from string input" do
name, type = @auth_token.send(:get_name_and_type_from_param, 'example.com', 'A' )
name.should eql('example.com')
type.should eql('A')
end
it "should correctly set the name and wildcard RR from string input" do
name, type = @auth_token.send(:get_name_and_type_from_param, 'example.com' )
name.should eql('example.com')
type.should eql('*')
name, type = @auth_token.send(:get_name_and_type_from_param, 'example.com', nil )
name.should eql('example.com')
type.should eql('*')
end
it "should append the domain name to string records missing it" do
name, type = @auth_token.send(:get_name_and_type_from_param, 'mail', nil )
name.should eql('mail.example.com')
type.should eql('*')
end
it 'should take the domain name exactly if given a blank name string' do
name, type = @auth_token.send(:get_name_and_type_from_param, '')
name.should eql('example.com')
type.should eql('*')
end
end
describe AuthToken, "and permissions" do
before(:each) do
@domain = Factory(:domain)
@auth_token = AuthToken.new(
:user => Factory(:admin),
:domain => @domain,
:expires_at => 5.hours.since
)
end
it "should have a default policy of 'deny'" do
@auth_token.policy.should eql(:deny)
end
it "should accept a default policy" do
@auth_token.policy = :allow
@auth_token.policy.should eql(:allow)
end
it "should only accept valid policies" do
lambda {
@auth_token.policy = :allow
@auth_token.policy = :deny
}.should_not raise_error
lambda {
@auth_token.policy = :open_sesame
}.should raise_error
end
it "should deny new RR's by default" do
@auth_token.allow_new_records?.should be_false
end
it "should allow for adding new RR" do
@auth_token.allow_new_records = true
@auth_token.allow_new_records?.should be_true
end
it "should deny removing RR's by default" do
@auth_token.remove_records?.should be_false
end
it "should allow for removing RR's" do
@auth_token.remove_records = true
@auth_token.remove_records?.should be_true
a = Factory(:a, :domain => @domain)
@auth_token.can_remove?( a ).should be_false
@auth_token.can_remove?( 'example.com', 'A' ).should be_false
@auth_token.can_change( a )
@auth_token.can_remove?( a ).should be_true
@auth_token.can_remove?( 'example.com', 'A' ).should be_true
end
it "should allow for setting permissions to edit specific RR's (AR)" do
a = Factory(:a, :domain => @domain)
@auth_token.can_change( a )
@auth_token.can_change?( 'example.com' ).should be_true
@auth_token.can_change?( 'example.com', 'MX' ).should be_false
mx = Factory(:mx, :domain => @domain)
@auth_token.can_change?( a ).should be_true
@auth_token.can_change?( mx ).should be_false
end
it "should allow for setting permissions to edit specific RR's (name)" do
a = Factory(:a, :domain => @domain)
mail = Factory(:a, :name => 'mail', :domain => @domain)
@auth_token.can_change( 'mail.example.com' )
@auth_token.can_change?( 'mail.example.com' ).should be_true
@auth_token.can_change?( mail ).should be_true
@auth_token.can_change?( a ).should be_false
end
it "should allow for protecting certain RR's" do
mail = Factory(:a, :name => 'mail', :domain => @domain)
mx = Factory(:mx, :domain => @domain)
a = Factory(:a, :domain => @domain)
@auth_token.policy = :allow
@auth_token.protect( mail )
@auth_token.protect( mx )
@auth_token.can_change?( a ).should be_true
@auth_token.can_change?( 'example.com', 'A' ).should be_true
@auth_token.can_change?( mx ).should be_false
@auth_token.can_change?( 'example.com', 'MX' ).should be_false
@auth_token.can_change?( mail ).should be_false
end
it "should allow for protecting RR's by type" do
mail = Factory(:a, :name => 'mail', :domain => @domain)
mx = Factory(:mx, :domain => @domain)
@auth_token.policy = :allow
@auth_token.protect_type 'A'
@auth_token.can_change?( mail ).should be_false
@auth_token.can_change?( mx ).should be_true
end
it "should prevent removing RR's by type" do
mx = Factory(:mx, :domain => @domain)
@auth_token.policy = :allow
@auth_token.protect_type 'MX'
@auth_token.can_remove?( mx ).should be_false
end
it "should prevent adding RR's by type" do
@auth_token.policy = :allow
@auth_token.allow_new_records = true
@auth_token.protect_type 'MX'
@auth_token.can_add?( MX.new( :name => '', :domain => @domain ) ).should be_false
end
it "should always protect NS records" do
ns1 = Factory(:ns, :domain => @domain)
ns2 = Factory(:ns, :name => 'ns2', :domain => @domain)
@auth_token.policy = :allow
@auth_token.remove_records = true
@auth_token.can_change( ns1 )
@auth_token.can_change?( ns1 ).should be_false
@auth_token.can_remove?( ns2 ).should be_false
end
it "should always protect SOA records" do
@auth_token.policy = :allow
@auth_token.remove_records = true
@auth_token.can_change( @domain.soa_record )
@auth_token.can_change?( @domain.soa_record ).should be_false
@auth_token.can_remove?( @domain.soa_record ).should be_false
end
it "should provide a list of new RR types allowed" do
@auth_token.new_types.should be_empty
@auth_token.allow_new_records = true
@auth_token.new_types.include?('MX').should be_true
@auth_token.protect_type 'MX'
@auth_token.new_types.include?('MX').should be_false
end
end
describe AuthToken, "and authentication" do
before(:each) do
@domain = Factory(:domain)
@user = Factory(:admin)
@auth_token = Factory(:auth_token, :domain => @domain, :user => @user)
end
it "should authenticate current tokens" do
AuthToken.authenticate( '5zuld3g9dv76yosy' ).should eql( @auth_token )
end
it "should not authenticate expired tokens" do
AuthToken.authenticate( 'invalid' ).should be_nil
end
it "should have an easy way to test if it expired" do
@auth_token.should_not be_expired
@auth_token.expire
@auth_token.expires_at.should <( Time.now )
@auth_token.should be_expired
end
it "should correctly report the 'token' role" do
@auth_token.has_role?('token').should be_true
@auth_token.has_role?('admin').should be_false
end
it "should correctly report permissions (deserialized)" do
a = Factory(:a, :domain => @domain)
@auth_token.can_change?( a ).should be_true
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/loc_spec.rb | spec/models/loc_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe LOC do
it "should have tests"
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/srv_spec.rb | spec/models/srv_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe SRV do
before(:each) do
@srv = SRV.new
end
it "should have tests"
it "should support priorities" do
@srv.supports_prio?.should be_true
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/soa_spec.rb | spec/models/soa_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe SOA, "when new" do
before(:each) do
@soa = SOA.new
end
it "should be invalid by default" do
@soa.should_not be_valid
end
it "should be unique per domain" do
@soa.domain = Factory(:domain)
@soa.should have(1).error_on(:domain_id)
end
it "should require a primary NS" do
@soa.should have(1).error_on(:primary_ns)
end
it "should require a contact" do
@soa.should have(1).error_on(:contact)
end
it "should require a valid email address for the contact" do
@soa.contact = 'test'
@soa.should have(1).error_on(:contact)
@soa.contact = 'test@example'
@soa.should have(1).error_on(:contact)
@soa.contact = 'test@example.com'
@soa.should have(:no).errors_on(:contact)
end
it "should flip the first period in the contact to an @" do
@soa.contact = 'test.example.com'
@soa.contact.should == 'test@example.com'
@soa.contact = 'test@example.com'
@soa.contact.should == 'test@example.com'
end
it "should have an autogenerated serial" do
@soa.serial.should_not be_nil
end
it "should only accept positive integers as serials" do
@soa.serial = -2008040101
@soa.should have(1).error_on(:serial)
@soa.serial = 'ISBN123456789'
@soa.should have(1).error_on(:serial)
@soa.serial = 2008040101
@soa.should have(:no).errors_on(:serial)
end
it "should require a refresh time" do
@soa.should have(1).error_on(:refresh)
end
it "should only accept positive integers as refresh time" do
@soa.refresh = -86400
@soa.should have(1).error_on(:refresh)
@soa.refresh = '12h'
@soa.should have(1).error_on(:refresh)
@soa.refresh = 2008040101
@soa.should have(:no).errors_on(:refresh)
end
it "should require a retry time" do
@soa.should have(1).error_on(:retry)
end
it "should only accept positive integers as retry time" do
@soa.retry = -86400
@soa.should have(1).error_on(:retry)
@soa.retry = '15m'
@soa.should have(1).error_on(:retry)
@soa.retry = 2008040101
@soa.should have(:no).errors_on(:retry)
end
it "should require a expiry time" do
@soa.should have(1).error_on(:expire)
end
it "should only accept positive integers as expiry times" do
@soa.expire = -86400
@soa.should have(1).error_on(:expire)
@soa.expire = '2w'
@soa.should have(1).error_on(:expire)
@soa.expire = 2008040101
@soa.should have(:no).errors_on(:expire)
end
it "should require a minimum time" do
@soa.should have(1).error_on(:minimum)
end
it "should only accept positive integers as minimum times" do
@soa.minimum = -86400
@soa.should have(1).error_on(:minimum)
@soa.minimum = '3h'
@soa.should have(1).error_on(:minimum)
@soa.minimum = 10800
@soa.should have(:no).errors_on(:minimum)
end
it "should not allow a minimum of more than 10800 seconds (RFC2308)" do
@soa.minimum = 84600
@soa.should have(1).error_on(:minimum)
end
end
describe SOA, "when created" do
before(:each) do
@domain = Factory(:domain)
@domain.soa_record.destroy
@soa = SOA.new(
:domain => @domain,
:primary_ns => 'ns1.example.com',
:contact => 'dnsadmin@example.com',
:refresh => 7200,
:retry => 1800,
:expire => 604800,
:minimum => 10800
)
end
it "should have the convenience fields populated before save" do
@soa.primary_ns.should eql('ns1.example.com')
end
it "should create a content field from the convenience fields" do
@soa.save.should be_true
@soa.content.should match(/ns1\.example\.com dnsadmin@example.com \d+ 7200 1800 604800 10800/)
end
end
describe SOA, "and serial numbers" do
before(:each) do
@soa = Factory(:domain).soa_record
end
it "should have an easy way to update (without saving)" do
serial = @soa.serial
serial.should_not be_nil
@soa.update_serial
@soa.serial.should_not be( serial )
@soa.serial.should >( serial )
@soa.reload
@soa.serial.should eql( serial )
end
it "should have an easy way to update (with saving)" do
serial = @soa.serial
serial.should_not be_nil
@soa.update_serial!
@soa.serial.should_not be( serial )
@soa.serial.should >( serial )
@soa.reload
@soa.serial.should_not be( serial )
end
it "should update in sequence for the same day" do
date_segment = Time.now.strftime( "%Y%m%d" )
@soa.serial.to_s.should eql( date_segment + '00' )
10.times { @soa.update_serial! }
@soa.serial.to_s.should eql( date_segment + '10' )
end
end
describe SOA, "when serializing to XML" do
before(:each) do
@soa = Factory(:domain).soa_record
end
it "should make an soa tag" do
@soa.to_xml.should match(/<soa>/)
end
it "should have the custom soa attributes present" do
xml = @soa.to_xml
xml.should match(/<primary\-ns/)
xml.should match(/<contact/)
xml.should match(/<serial/)
xml.should match(/<minimum/)
xml.should match(/<expire/)
xml.should match(/<refresh/)
xml.should match(/<retry/)
end
it "should preserve original #to_xml options" do
xml = @soa.to_xml :skip_instruct => true
xml.should_not match(/<\?xml/)
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/spf_spec.rb | spec/models/spf_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe SPF do
it "should have tests"
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/txt_spec.rb | spec/models/txt_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe TXT, "when new" do
before(:each) do
@txt = TXT.new
end
it "should be invalid by default" do
@txt.should_not be_valid
end
it "should require content" do
@txt.should have(1).error_on(:content)
end
it "should not tamper with content" do
@txt.content = "google.com"
@txt.content.should eql("google.com")
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/aaaa_spec.rb | spec/models/aaaa_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe AAAA, "when new" do
before(:each) do
@aaaa = AAAA.new
end
it "should be invalid by default" do
@aaaa.should_not be_valid
end
it "should only accept IPv6 address as content"
it "should not act as a CNAME" do
@aaaa.content = 'google.com'
@aaaa.should have(1).error_on(:content)
end
it "should accept a valid ipv6 address" do
@aaaa.content = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
@aaaa.should have(:no).error_on(:content)
end
it "should not accept new lines in content" do
@aaaa.content = "2001:0db8:85a3:0000:0000:8a2e:0370:7334\nHELLO WORLD"
@aaaa.should have(1).error_on(:content)
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/zone_template_spec.rb | spec/models/zone_template_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe ZoneTemplate, "when new" do
before(:each) do
@zone_template = ZoneTemplate.new
end
it "should be invalid by default" do
@zone_template.should_not be_valid
end
it "should require a name" do
@zone_template.should have(1).error_on(:name)
end
it "should have a unique name" do
Factory(:zone_template)
@zone_template.name = "East Coast Data Center"
@zone_template.should have(1).error_on(:name)
end
it "should require a TTL" do
@zone_template.ttl = nil
@zone_template.should have(1).error_on(:ttl)
end
it "should not require optional owner" do
@zone_template.should have(:no).errors_on(:user_id)
end
end
describe ZoneTemplate, "when loaded" do
before(:each) do
@zone_template = Factory( :zone_template )
Factory(:template_soa, :zone_template => @zone_template)
end
it "should have record templates" do
@zone_template.record_templates.should_not be_empty
end
it "should provide an easy way to build a zone" do
zone = @zone_template.build('example.org')
zone.should be_a_kind_of( Domain )
zone.should be_valid
end
it "should have a sense of validity" do
@zone_template.has_soa?.should be_true
Factory( :zone_template, :name => 'West Coast Data Center' ).has_soa?.should_not be_true
end
end
describe ZoneTemplate, "with scopes" do
before(:each) do
@quentin = Factory(:quentin)
@zone_template = Factory(:zone_template, :user => @quentin)
@other_template = Factory(:zone_template, :name => 'West Coast Data Center')
end
it "should only return a user's templates if not an admin" do
templates = ZoneTemplate.user(@quentin).all
templates.should_not be_empty
templates.size.should be(1)
templates.each { |z| z.user.should eql( @quentin ) }
end
it "should return all templates if the user is an admin" do
templates = ZoneTemplate.user(Factory(:admin)).all
templates.should_not be_empty
templates.size.should be( ZoneTemplate.count )
end
it "should return only valid records" do
templates = ZoneTemplate.with_soa.all
templates.should be_empty
Factory(:template_soa, :zone_template => @zone_template)
ZoneTemplate.with_soa.all.should_not be_empty
end
end
describe ZoneTemplate, "when used to build a zone" do
before(:each) do
@zone_template = Factory( :zone_template )
Factory(:template_soa, :zone_template => @zone_template)
Factory(:template_ns, :zone_template => @zone_template)
Factory(:template_ns, :content => 'ns2.%ZONE%', :zone_template => @zone_template)
@domain = @zone_template.build( 'example.org' )
end
it "should create a valid new zone" do
@domain.should be_valid
@domain.should be_a_kind_of( Domain )
end
it "should create the correct number of records (from templates)" do
@domain.records.size.should eql( @zone_template.record_templates.size )
end
it "should create a SOA record" do
soa = @domain.soa_record
soa.should_not be_nil
soa.should be_a_kind_of( SOA )
soa.primary_ns.should eql('ns1.example.org')
end
it "should create two NS records" do
ns = @domain.ns_records
ns.should be_a_kind_of( Array )
ns.size.should be(2)
ns.each { |r| r.should be_a_kind_of( NS ) }
end
end
describe ZoneTemplate, "when used to build a zone for a user" do
before(:each) do
@user = Factory(:quentin)
@zone_template = Factory(:zone_template, :user => @quentin)
Factory(:template_soa, :zone_template => @zone_template)
Factory(:template_ns, :zone_template => @zone_template)
Factory(:template_ns, :name => 'ns2.%ZONE%', :zone_template => @zone_template)
Factory(:template_cname, :zone_template => @zone_template)
Factory(:template_cname, :name => 'www.%ZONE%', :zone_template => @zone_template)
@domain = @zone_template.build( 'example.org', @user )
end
it "should create a valid new zone" do
@domain.should be_valid
@domain.should be_a_kind_of( Domain )
end
it "should be owned by the user" do
@domain.user.should be( @user )
end
it "should create the correct number of records (from templates)" do
@domain.records.size.should eql( @zone_template.record_templates.size )
end
it "should create a SOA record" do
soa = @domain.soa_record
soa.should_not be_nil
soa.should be_a_kind_of( SOA )
soa.primary_ns.should eql('ns1.example.org')
end
it "should create two NS records" do
ns = @domain.ns_records
ns.should be_a_kind_of( Array )
ns.size.should be(2)
ns.each { |r| r.should be_a_kind_of( NS ) }
end
it "should create the correct CNAME's from the template" do
cnames = @domain.cname_records
cnames.size.should be(2)
end
end
describe ZoneTemplate, "and finders" do
before(:each) do
zt1 = Factory(:zone_template)
Factory(:template_soa, :zone_template => zt1 )
Factory(:zone_template, :name => 'No SOA')
end
it "should be able to return all templates" do
ZoneTemplate.find(:all).size.should be( ZoneTemplate.count )
end
it "should respect required validations" do
ZoneTemplate.find(:all, :require_soa => true).size.should be( 1 )
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/ns_spec.rb | spec/models/ns_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe NS, "when new" do
before(:each) do
@ns = NS.new
end
it "should be invalid by default" do
@ns.should_not be_valid
end
it "should require content" do
@ns.should have(2).error_on(:content)
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/models/user_spec.rb | spec/models/user_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe User do
it 'suspends user' do
quentin = Factory(:quentin)
quentin.suspend!
quentin.should be_suspended
end
it 'does not authenticate suspended user'
it 'deletes user' do
quentin = Factory(:quentin)
quentin.deleted_at.should be_nil
quentin.delete!
#quentin.deleted_at.should_not be_nil
quentin.should be_deleted
end
it 'does not authenticate deleted users'
describe "being unsuspended" do
before do
@user = Factory(:quentin)
@user.suspend!
end
it 'reverts to active state' do
@user.unsuspend!
@user.should be_active
end
end
protected
def create_user(options = {})
User.create({ :login => 'quire', :email => 'quire@example.com', :password => 'quire', :password_confirmation => 'quire' }.merge(options))
end
end
describe User, "as owner" do
before(:each) do
@user = Factory(:quentin, :auth_tokens => true)
Factory(:domain, :user => @user)
Factory(:zone_template, :user => @user)
end
it "should have domains" do
@user.domains.should_not be_empty
end
it "should have templates" do
@user.zone_templates.should_not be_empty
end
it "should not have auth_tokens" do
@user.auth_tokens?.should be_false
end
end
describe User, "as admin" do
before(:each) do
@admin = Factory(:admin, :auth_tokens => true)
end
it "should not own domains" do
@admin.domains.should be_empty
end
it "should not own zone templates" do
@admin.zone_templates.should be_empty
end
it "should have auth tokens" do
@admin.auth_tokens?.should be_true
end
end
describe User, "and roles" do
it "should have a admin boolean flag" do
Factory( :admin ).admin.should be_true
Factory( :quentin ).admin.should be_false
end
it "should have a way to easily find active owners" do
Factory(:quentin)
candidates = User.active_owners
candidates.each do |user|
user.should be_active
user.should_not be_admin
end
end
end
describe User, "and audits" do
it "should have username persisted in audits when removed" do
admin = Factory(:admin)
Audit.as_user( admin ) do
domain =Factory(:domain)
audit = domain.audits.first
audit.user.should eql( admin )
audit.username.should be_nil
admin.destroy
audit.reload
audit.user.should eql( 'admin' )
audit.username.should eql('admin')
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/macros/edit.html.haml_spec.rb | spec/views/macros/edit.html.haml_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "macros/edit.html.haml" do
context "for new macros" do
before(:each) do
assign(:macro, Macro.new)
render
end
it "should behave accordingly" do
rendered.should have_tag('h1', :content => 'New Macro')
end
end
context "for existing records" do
before(:each) do
@macro = Factory(:macro)
assign(:macro, @macro)
render
end
it "should behave accordingly" do
rendered.should have_tag('h1', :content => 'Update Macro')
end
end
describe "for records with errors" do
before(:each) do
m = Macro.new
m.valid?
assign(:macro, m)
render
end
it "should display the errors" do
rendered.should have_tag('div.errorExplanation')
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/macros/index.html.haml_spec.rb | spec/views/macros/index.html.haml_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "macros/index.html.haml" do
it "should render a list of macros" do
2.times { |i| Factory(:macro, :name => "Macro #{i}") }
assign(:macros, Macro.all)
render
rendered.should have_tag('h1', :content => 'Macros')
render.should have_tag("table a[href^='/macro']")
end
it "should indicate no macros are present" do
assign(:macros, Macro.all)
render
rendered.should have_tag('em', :content => "don't have any macros")
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/macros/show.html.haml_spec.rb | spec/views/macros/show.html.haml_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "macros/show.html.haml" do
before(:each) do
@macro = Factory(:macro)
Factory(:macro_step_create, :macro => @macro)
assign(:macro, @macro)
assign(:macro_step, @macro.macro_steps.new)
render
end
it "should have the name of the macro" do
rendered.should have_tag('h1', :content => @macro.name)
end
it "should have an overview table" do
rendered.should have_tag('table.grid td', :content => "Name")
rendered.should have_tag('table.grid td', :content => "Description")
rendered.should have_tag('table.grid td', :content => "Active")
end
it "should have a list of steps" do
rendered.should have_tag('h1', :content => 'Macro Steps')
rendered.should have_tag('table#steps-table td', :content => "1")
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/domains/apply_macro.html.haml_spec.rb | spec/views/domains/apply_macro.html.haml_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "domains/apply_macro.html.haml" do
before(:each) do
@domain = Factory(:domain)
@macro = Factory(:macro)
assign(:domain, @domain)
assign(:macros, Macro.all)
render
end
it "should have a selection of macros" do
rendered.should have_tag('select[name=macro_id]')
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/domains/new.html.haml_spec.rb | spec/views/domains/new.html.haml_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "domains/new.html.haml" do
before(:each) do
assign(:domain, Domain.new)
view.stubs(:current_user).returns( Factory(:admin) )
end
it "should have a link to create a zone template if no zone templates are present" do
assign(:zone_templates, [])
render
rendered.should have_selector("a[href='#{new_zone_template_path}']")
rendered.should_not have_selector("select[name*=zone_template_id]")
end
it "should have a list of zone templates to select from" do
zt = Factory(:zone_template)
Factory(:template_soa, :zone_template => zt)
render
rendered.should have_selector("select[name*=zone_template_id]")
rendered.should_not have_selector("a[href='#{new_zone_template_path}']")
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/domains/show.html.haml_spec.rb | spec/views/domains/show.html.haml_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "domains/show.html.haml" do
context "for all users" do
before(:each) do
view.stubs(:current_user).returns( Factory(:admin) )
view.stubs(:current_token).returns( nil )
@domain = Factory(:domain)
assign(:domain, @domain)
assign(:users, User.active_owners)
render :template => "/domains/show.html.haml", :layout => "layouts/application"
end
it "should have the domain name in the title and dominant on the page" do
rendered.should have_tag( "title", :content => "example.com" )
rendered.should have_tag( "h1", :content => "example.com" )
end
end
context "for admins and domains without owners" do
before(:each) do
view.stubs(:current_user).returns( Factory(:admin) )
view.stubs(:current_token).returns( nil )
@domain = Factory(:domain)
assign(:domain, @domain)
assign(:users, User.active_owners)
render
end
it "should display the owner" do
rendered.should have_tag( "div#owner-info" )
end
it "should allow changing the SOA" do
rendered.should have_tag( "div#soa-form")
end
it "should have a form for adding new records" do
rendered.should have_tag( "div#record-form-div" )
end
it "should have not have an additional warnings for removing" do
rendered.should_not have_tag('div#warning-message')
rendered.should_not have_tag('a[onclick*=deleteDomain]')
end
end
context "for admins and domains with owners" do
before(:each) do
view.stubs(:current_user).returns( Factory(:admin) )
view.stubs(:current_token).returns( nil )
@domain = Factory(:domain, :user => Factory(:quentin))
assign(:domain, @domain)
assign(:users, User.active_owners)
render
end
it "should offer to remove the domain" do
rendered.should have_tag( "a img[id$=delete-zone]" )
end
it "should have have an additional warnings for removing" do
rendered.should have_tag('div#warning-message')
rendered.should have_tag('a[onclick*=deleteDomain]')
end
end
context "for owners" do
before(:each) do
quentin = Factory(:quentin)
view.stubs(:current_user).returns( quentin )
view.stubs(:current_token).returns( nil )
@domain = Factory(:domain, :user => quentin)
assign(:domain, @domain)
render
end
it "should display the owner" do
rendered.should_not have_tag( "div#ownerinfo" )
end
it "should allow for changing the SOA" do
rendered.should have_tag( "div#soa-form" )
end
it "should have a form for adding new records" do
rendered.should have_tag( "div#record-form-div" )
end
it "should offer to remove the domain" do
rendered.should have_tag( "a img[id$=delete-zone]" )
end
it "should have not have an additional warnings for removing" do
rendered.should_not have_tag('div#warning-message')
rendered.should_not have_tag('a[onclick*=deleteDomain]')
end
end
context "for SLAVE domains" do
before(:each) do
view.stubs(:current_user).returns( Factory(:admin) )
view.stubs(:current_token).returns( nil )
@domain = Factory(:domain, :type => 'SLAVE', :master => '127.0.0.1')
assign(:domain, @domain)
assign(:users, User.active_owners)
render
end
it "should show the master address" do
rendered.should have_tag('#domain-name td', :content => "Master server")
rendered.should have_tag('#domain-name td', :content => @domain.master)
end
it "should not allow for changing the SOA" do
rendered.should_not have_tag( "div#soa-form" )
end
it "should not have a form for adding new records" do
rendered.should_not have_tag( "div#record-form-div" )
end
it "should offer to remove the domain" do
rendered.should have_tag( "a img[id$=delete-zone]" )
end
end
context "for token users" do
before(:each) do
@admin = Factory(:admin)
@domain = Factory(:domain)
assign(:domain, @domain)
view.stubs(:current_token).returns( Factory(:auth_token, :user => @admin, :domain => @domain) )
view.stubs(:current_user).returns( nil )
end
it "should not offer to remove the domain" do
render
rendered.should_not have_tag( "a img[id$=delete-zone]" )
end
it "should not offer to edit the SOA" do
render
rendered.should_not have_tag( "a[onclick^=showSOAEdit]")
rendered.should_not have_tag( "div#soa-form" )
end
it "should only allow new record if permitted (FALSE)" do
render
rendered.should_not have_tag( "div#record-form-div" )
end
it "should only allow new records if permitted (TRUE)" do
token = AuthToken.new(
:domain => @domain
)
token.allow_new_records=( true )
view.stubs(:current_token).returns( token )
render
rendered.should have_tag( "div#record-form-div" )
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/domains/_record.html.haml_spec.rb | spec/views/domains/_record.html.haml_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "domains/_record" do
context "for a user" do
before(:each) do
view.stubs(:current_user).returns( Factory(:admin) )
domain = Factory(:domain)
@record = Factory(:ns, :domain => domain)
render :partial => 'domains/record', :object => @record
end
it "should have a marker row (used by AJAX)" do
rendered.should have_tag("tr#marker_ns_#{@record.id}")
end
it "should have a row with the record details" do
rendered.should have_tag("tr#show_ns_#{@record.id} > td", :content => "") # shortname
rendered.should have_tag("tr#show_ns_#{@record.id} > td", :content => "") # ttl
rendered.should have_tag("tr#show_ns_#{@record.id} > td", :content => "NS") # shortname
rendered.should have_tag("tr#show_ns_#{@record.id} > td", :content => "") # prio
rendered.should have_tag("tr#show_ns_#{@record.id} > td", :content => "ns1.example.com")
end
it "should have a row for editing record details" do
rendered.should have_tag("tr#edit_ns_#{@record.id} > td[colspan='7'] > form")
end
it "should have links to edit/remove the record" do
rendered.should have_tag("a[onclick^=editRecord]")
rendered.should have_tag("a > img[src*=database_delete]")
end
end
context "for a SLAVE domain" do
before(:each) do
view.stubs(:current_user).returns( Factory(:admin) )
domain = Factory(:domain, :type => 'SLAVE', :master => '127.0.0.1')
@record = domain.a_records.create( :name => 'foo', :content => '127.0.0.1' )
render :partial => 'domains/record', :object => @record
end
it "should not have tooltips ready" do
rendered.should_not have_tag("div#record-template-edit-#{@record.id}")
rendered.should_not have_tag("div#record-template-delete-#{@record.id}")
end
it "should have a row with the record details" do
rendered.should have_tag("tr#show_a_#{@record.id} > td", :content => "") # shortname
rendered.should have_tag("tr#show_a_#{@record.id} > td", :content => "") # ttl
rendered.should have_tag("tr#show_a_#{@record.id} > td", :content => "A")
rendered.should have_tag("tr#show_a_#{@record.id} > td", :content => "") # prio
rendered.should have_tag("tr#show_a_#{@record.id} > td", :content => "foo")
end
it "should not have a row for editing record details" do
rendered.should_not have_tag("tr#edit_ns_#{@record.id} > td[colspan='7'] > form")
end
it "should not have links to edit/remove the record" do
rendered.should_not have_tag("a[onclick^=editRecord]")
rendered.should_not have_tag("a > img[src*=database_delete]")
end
end
context "for a token" do
before(:each) do
@domain = Factory(:domain)
view.stubs(:current_user).returns( nil )
view.stubs(:current_token).returns( Factory(:auth_token, :domain => @domain, :user => Factory(:admin)) )
end
it "should not allow editing NS records" do
record = Factory(:ns, :domain => @domain)
render :partial => 'domains/record', :object => record
rendered.should_not have_tag("a[onclick^=editRecord]")
rendered.should_not have_tag("tr#edit_ns_#{record.id}")
end
it "should not allow removing NS records" do
record = Factory(:ns, :domain => @domain)
render :partial => 'domains/record', :object => record
rendered.should_not have_tag("a > img[src*=database_delete]")
end
it "should allow edit records that aren't protected" do
record = Factory(:a, :domain => @domain)
render :partial => 'domains/record', :object => record
rendered.should have_tag("a[onclick^=editRecord]")
rendered.should_not have_tag("a > img[src*=database_delete]")
rendered.should have_tag("tr#edit_a_#{record.id}")
end
it "should allow removing records if permitted" do
record = Factory(:a, :domain => @domain)
token = AuthToken.new(
:domain => @domain
)
token.remove_records=( true )
token.can_change( record )
view.stubs(:current_token).returns( token )
render :partial => 'domains/record', :object => record
rendered.should have_tag("a > img[src*=database_delete]")
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/templates/new.html.haml_spec.rb | spec/views/templates/new.html.haml_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "templates/new.html.haml" do
context "and new templates" do
before(:each) do
assign(:zone_template, ZoneTemplate.new)
end
it "should have a list of users if provided" do
Factory(:quentin)
render
rendered.should have_tag('select#zone_template_user_id')
end
it "should render without a list of users" do
render
rendered.should_not have_tag('select#zone_template_user_id')
end
it "should render with a missing list of users (nil)" do
render
rendered.should_not have_tag('select#zone_template_user_id')
end
it "should show the correct title" do
render
rendered.should have_tag('h1.underline', :content => 'New Zone Template')
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/templates/edit.html.haml_spec.rb | spec/views/templates/edit.html.haml_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "templates/edit.html.haml" do
context "and existing templates" do
before(:each) do
@zone_template = Factory(:zone_template)
assign(:zone_template, @zone_template)
end
it "should show the correct title" do
render
rendered.should have_tag('h1.underline', :content => 'Update Zone Template')
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/templates/show.html.haml_spec.rb | spec/views/templates/show.html.haml_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "templates/show.html.haml" do
context "for complete templates" do
before(:each) do
@zone_template = Factory(:zone_template)
Factory(:template_soa, :zone_template => @zone_template)
assign(:zone_template, @zone_template)
assign(:record_template, RecordTemplate.new( :record_type => 'A' ))
render
end
it "should have the template name" do
rendered.should have_tag('h1', :content => @zone_template.name)
end
it "should have a table with template overview" do
rendered.should have_selector('table.grid td', :content => 'Name')
rendered.should have_selector('table.grid td', :content => 'TTL')
end
it "should have the record templates" do
rendered.should have_selector('h1', :content => 'Record templates')
rendered.should have_selector('table#record-table')
end
it "should not have an SOA warning" do
violated "ZoneTemplate does not have SOA" unless @zone_template.has_soa?
rendered.should_not have_selector('div#soa-warning')
end
end
context "for partial templates" do
before(:each) do
@zone_template = Factory(:zone_template)
assign(:zone_template, @zone_template)
assign(:record_template, RecordTemplate.new( :record_type => 'A' ))
render
end
it "should have an SOA warning" do
rendered.should have_tag('div#soa-warning')
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/audits/domain.html.haml_spec.rb | spec/views/audits/domain.html.haml_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "audits/domain.html.haml" do
context "and domain audits" do
before(:each) do
@domain = Factory(:domain)
end
it "should handle no audit entries on the domain" do
@domain.expects(:audits).returns( [] )
assign(:domain, @domain)
render
rendered.should have_tag("em", :content => "No revisions found for the domain")
end
it "should handle audit entries on the domain" do
audit = Audit.new(
:auditable => @domain,
:created_at => Time.now,
:version => 1,
:audited_changes => {},
:action => 'create',
:username => 'admin'
)
@domain.expects(:audits).at_most(2).returns( [ audit ] )
assign(:domain, @domain)
render
rendered.should have_tag("ul > li > a", :content => "1 create by")
end
end
context "and resource record audits" do
before(:each) do
Audit.as_user( 'admin' ) do
@domain = Factory(:domain)
end
end
it "should handle no audit entries" do
@domain.expects(:associated_audits).at_most(2).returns( [] )
assign(:domain, @domain)
render
rendered.should have_tag("em", :content => "No revisions found for any resource records of the domain")
end
it "should handle audit entries" do
assign(:domain, @domain)
render
rendered.should have_tag("ul > li > a", :content => "1 create by admin")
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/search/results.html.haml_spec.rb | spec/views/search/results.html.haml_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "search/results.html.haml" do
before(:each) do
@admin = Factory(:admin)
view.stubs(:current_user).returns(@admin)
view.stubs(:current_token).returns(nil)
end
it "should handle no results" do
assign(:results, [])
render
rendered.should have_tag("strong", :content => "No domains found")
end
it "should handle results within the pagination limit" do
1.upto(4) do |i|
zone = Domain.new
zone.id = i
zone.name = "zone-#{i}.com"
zone.save( :validate => false ).should be_true
end
assign(:results, Domain.search( 'zone', 1, @admin ))
render
rendered.should have_tag("table a", :content => "zone-1.com")
end
it "should handle results with pagination and scoping" do
1.upto(100) do |i|
zone = Domain.new
zone.id = i
zone.name = "domain-#{i}.com"
zone.save( :validate => false ).should be_true
end
assign(:results, Domain.search( 'domain', 1, @admin ))
render
rendered.should have_tag("table a", :content => "domain-1.com")
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/macro_steps/update.js.rjs_spec.rb | spec/views/macro_steps/update.js.rjs_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "macro_steps/update.js.rjs" do
before(:each) do
assigns[:macro] = @macro = Factory(:macro)
assigns[:macro_step] = @macro_step = Factory(:macro_step_create, :macro => @macro)
end
describe "for valid updates" do
before(:each) do
render "macro_steps/update.js.rjs"
end
xit "should display a notice" do
response.should include_text(%{showflash("info"})
end
xit "should update the steps table" do
response.should have_rjs(:remove, "show_macro_step_#{@macro_step.id}")
response.should have_rjs(:remove, "edit_macro_step_#{@macro_step.id}")
response.should have_rjs(:replace, "marker_macro_step_#{@macro_step.id}")
end
end
describe "for invalid updates" do
before(:each) do
assigns[:macro_step].content = ''
assigns[:macro_step].valid?
render "macro_steps/update.js.rjs"
end
xit "should display an error" do
response.should have_rjs(:replace_html, "error_macro_step_#{@macro_step.id}")
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/spec/views/macro_steps/create.js.rjs_spec.rb | spec/views/macro_steps/create.js.rjs_spec.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'spec_helper'
describe "macro_steps/create.js.rjs" do
describe "for failed records" do
before(:each) do
assigns[:macro] = Factory.build(:macro)
assigns[:macro_step] = MacroStep.new
assigns[:macro_step].valid?
render('macro_steps/create.js.rjs')
end
xit "should insert errors into the page" do
response.should have_rjs(:replace_html, 'record-form-error')
end
xit "should have a error flash" do
response.should include_text(%{showflash("error"})
end
end
describe "for successful records" do
before(:each) do
assigns[:macro] = Factory(:macro)
assigns[:macro_step] = Factory(:macro_step_create, :macro => assigns[:macro])
render('macro_steps/create.js.rjs')
end
xit "should display a notice flash" do
response.should include_text(%{showflash("info"} )
end
xit "should insert the steps into the table" do
response.should have_rjs(:insert, :bottom, 'steps-table')
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/scoped_finders.rb | lib/scoped_finders.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
module ScopedFinders
def self.included( base ) #:nodoc:
base.extend( ClassMethods )
end
module ClassMethods
def scope_user
extend SingletonMethods
class << self
alias_method_chain :find, :scope
alias_method_chain :paginate, :scope
end
end
end
module SingletonMethods
# Convenient scoped finder method that restricts lookups to the specified
# :user. If the user has an admin role, the scoping is discarded totally,
# since an admin _is a admin_.
#
# Example:
#
# Domain.find(:all) # Normal behavior
# Domain.find(:all, :user => user_instance) # Will scope lookups to the user
#
def find_with_scope( *args )
options = args.extract_options!
user = options.delete( :user )
unless user.nil? || user.has_role?( 'admin' )
with_scope( :find => { :conditions => [ 'user_id = ?', user.id ] } ) do
find_without_scope( *args << options )
end
else
find_without_scope( *args << options )
end
end
# Paginated find with scope. See #find.
def paginate_with_scope( *args, &block )
options = args.pop
user = options.delete( :user )
unless user.nil? || user.has_role?( 'admin' )
with_scope( :find => { :conditions => [ 'user_id = ?', user.id ] } ) do
paginate_without_scope( *args << options, &block )
end
else
paginate_without_scope( *args << options, &block )
end
end
# For our lookup purposes
def search( params, page, user = nil )
paginate :per_page => 5, :page => page,
:conditions => ['name LIKE ?', "%#{params.chomp}%"],
:user => user
end
end
end
ActiveRecord::Base.send( :include, ScopedFinders )
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/model_serialization_with_warnings.rb | lib/model_serialization_with_warnings.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
# Complement the functionality provided by the 'validation_scopes' plugin.
# We rely on the 'validation_scope :warning' construct to define validations
# that don't block model persistence. But the plugin doesn't add the warnings
# to the serialized forms (json & xml) of the resources where the validation
# scopes are defined.
#
# This model provides a half-baked solution to this. It overrides the 'as_json'
# and 'as_xml' methods, adding a 'warnings' property when appropriate.
module ModelSerializationWithWarnings
extend ActiveSupport::Concern
included do
def as_json(options = nil)
self.warnings.any? ? super.merge!('warnings' => self.warnings.as_json) : super
end
def to_xml(options = {})
self.warnings.any? ? super(:methods => [:warnings]) : super
end
def becomes(klass)
became = super(klass)
became.instance_variable_set("@warnings", @warnings)
became
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/domain_ownership.rb | lib/domain_ownership.rb | require 'singleton'
module DomainOwnership
class API
include Singleton
def initialize
end
def has_permission?(name, user, action = @permissions_action)
false
end
def users_permissions_info(user)
{:sub_components => [["sub_component_name_1", "sub_component_id_1"],["sub_component_name_n", "sub_component_id_n"]]}
end
def get_sub_components_from_user(user)
[["sub_component_name_1", "sub_component_id_1"],["sub_component_name_n", "sub_component_id_n"]]
end
# ARTEMIA
def patch_domain_ownership_info(id, name, sub_component, classifier)
end
def post_domain_ownership_info(name, sub_component_id, classifier, user)
end
def get_domain_ownership_info(name)
{ sub_component: "sub_component", sub_component_id: "sub_component_id", id: "id" }
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/zonefile.rb | lib/zonefile.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
# = Ruby Zonefile - Parse and manipulate DNS Zone Files.
#
# == Description
# This class can read, manipulate and create DNS zone files. It supports A, AAAA, MX, NS, SOA,
# TXT, CNAME, PTR and SRV records. The data can be accessed by the instance method of the same
# name. All except SOA return an array of hashes containing the named data. SOA directly returns the
# hash since there can only be one SOA information.
#
# The following hash keys are returned per record type:
#
# * SOA
# - :ttl, :primary_ns, :contact, :serial, :refresh, :retry, :expire, :minimum
# * A
# - :name, :ttl, :class, :content
# * MX
# - :name, :ttl, :class, :prio, :content
# * NS
# - :name, :ttl, :class, :content
# * CNAME
# - :name, :ttl, :class, :content
# * TXT
# - :name, :ttl, :class, :text
# * A4 (AAAA)
# - :name, :ttl, :class, :content
# * PTR
# - :name, :ttl, :class, :content
# * SRV
# - :name, :ttl, :class, :prio, :weight, :port, :content
#
# == Examples
#
# === Read a Zonefile
#
# zf = Zonefile.from_file('/path/to/zonefile.db')
#
# # Display MX-Records
# zf.mx.each do |mx_record|
# puts "Mail Exchagne with priority: #{mx_record[:prio]} --> #{mx_record[:content]}"
# end
#
# # Show SOA TTL
# puts "Record Time To Live: #{zf.soa[:ttl]}"
#
# # Show A-Records
# zf.a.each do |a_record|
# puts "#{a_record[:name]} --> #{a_record[:content]}"
# end
#
#
# ==== Manipulate a Zonefile
#
# zf = Zonefile.from_file('/path/to/zonefile.db')
#
# # Change TTL and add an A-Record
#
# zf.soa[:ttl] = '123123' # Change the SOA ttl
# zf.a << { :class => 'IN', :name => 'www', :content => '192.168.100.1', :ttl => 3600 } # add A-Record
#
# # Setting PTR records (deleting existing ones)
#
# zf.ptr = [ { :class => 'IN', :name=>'1.100.168.192.in-addr.arpa', :content => 'my.host.com' },
# { :class => 'IN', :name=>'2.100.168.192.in-addr.arpa', :content => 'me.host.com' } ]
#
# # Increase Serial Number
# zf.new_serial
#
# # Print new zonefile
# puts "New Zonefile: \n#{zf.output}"
#
# == Author
#
# Martin Boese, based on Simon Flack Perl library DNS::ZoneParse
#
# GloboDns record types:
#
# [ 0] "A",
# [ 1] "AAAA",
# [ 2] "CERT",
# [ 3] "CNAME",
# [ 4] "DLV",
# [ 5] "DNSKEY",
# [ 6] "DS",
# [ 7] "IPSECKEY",
# [ 8] "KEY",
# [ 9] "KX",
# [10] "LOC",
# [11] "MX",
# [12] "ns",
# [13] "NSEC",
# [14] "NSEC3",
# [15] "NSEC3PARAM",
# [16] "PTR",
# [17] "RRSIG",
# [18] "SIG",
# [19] "SOA",
# [20] "SPF",
# [21] "SRV",
# [22] "TA",
# [23] "TKEY",
# [24] "TSIG",
# [25] "TXT"
require 'pathname'
class Zonefile
RECORDS = %w{ mx a aaaa ns cname txt ptr srv soa }
attr :records
attr :all_records
attr :soa
attr :data
# global $ORIGIN option
attr :origin
# global $TTL option
attr :ttl
def method_missing(m, *args)
mname = m.to_s.sub("=","")
return super unless RECORDS.include?(mname)
if m.to_s[-1].chr == '=' then
@records[mname.intern] = args.first
@records[mname.intern]
else
@records[m]
end
end
# Compact a zonefile content - removes empty lines, comments,
# converts tabs into spaces etc...
def self.simplify(zf)
zf.gsub(/("(""|[^"])*")|;.*$/, '\1') # strip comments (unless the ; is inside quotes)
.gsub(/\r/, '') # strip carriage return characters
.gsub(/\n+\s*\n+/, "\n") # strip blank lines
.gsub(/(\(.*?\))/m) { # join content split into multiple lines using parentheses
$1.gsub(/\s+/, ' ')
}.strip # remove trailing whitespace
end
# create a new zonefile object by passing the content of the zonefile
def initialize(zonefile = '', file_name = nil, origin = nil, chroot_dir = nil, options_dir = nil)
@data = zonefile
@filename = file_name
@origin = origin || (file_name ? file_name.split('/').last : '')
@chroot_dir = chroot_dir
@options_dir = options_dir
@all_records = []
@records = {}
@soa = {}
RECORDS.each { |r| @records[r.intern] = [] }
parse
end
# True if no records (except sao) is defined in this file
def empty?
RECORDS.each do |r|
return false unless @records[r.intern].empty?
end
true
end
# Create a new object by reading the content of a file
def self.from_file(file_name, origin = nil, chroot_dir = nil, options_dir = nil)
Zonefile.new(File.read(file_name), file_name.split('/').last, origin, chroot_dir, options_dir)
end
def add_record(type, data = {})
type_sym = type.downcase.to_sym
type_str = type.upcase
data[:name] = @all_records.last[:name] if (data[:name].nil? || data[:name].strip == '') && @all_records.last
@records[type_sym] << data if @records.has_key?(type_sym)
@all_records << data.merge({:type => type_str})
end
# Generates a new serial number in the format of YYYYMMDDII if possible
def new_serial
base = "%04d%02d%02d" % [Time.now.year, Time.now.month, Time.now.day ]
if ((@soa[:serial].to_i / 100) > base.to_i) then
ns = @soa[:serial].to_i + 1
@soa[:serial] = ns.to_s
return ns.to_s
end
ii = 0
while (("#{base}%02d" % ii).to_i <= @soa[:serial].to_i) do
ii += 1
end
@soa[:serial] = "#{base}%02d" % ii
end
def parse_line(line)
valid_name = /[\@a-z_\-\.0-9\*]+/i
valid_ip6 = /[\@a-z_\-\.0-9\*:]+/i
rr_class = /\b(?:IN|HS|CH)\b/i
rr_type = /\b(?:NS|A|CNAME)\b/i
rr_ttl = /(?:\d+[wdhms]?)+/i
ttl_cls = /(?:(#{rr_ttl})\s+)?(?:(#{rr_class})\s+)?/
if line =~ /^\$ORIGIN\s*(#{valid_name})/ix
@origin = $1
elsif line =~ /\$TTL\s+(#{rr_ttl})/i
@ttl = $1
elsif line =~ /\$INCLUDE\s+("[\w\. \/_\-]+"|[\w\.\/_\-]+)\s+("[\.\w_]+"|[\.\w_]+)?/i
old_origin = @origin
filename = $1
@origin = $2 if $2
final_path = Pathname.new(filename).absolute? ? File.join(@chroot_dir || '', filename) : File.join(@chroot_dir || '', @options_dir || '', filename)
File.exists?(final_path) or raise RuntimeError.new("[Zonefile][ERROR] unable to find included file \"#{final_path}\"")
content = File::read(final_path)
Zonefile.simplify(content).each_line do |line|
parse_line(line)
end
@origin = old_origin
elsif line =~ /^(#{valid_name})? \s*
#{ttl_cls}
(#{rr_type}) \s+
(#{valid_name})
/ix
add_record($4, :name => $1, :ttl => $2, :class => $3, :content => $5)
elsif line =~ /^(#{valid_name})? \s*
#{ttl_cls}
AAAA \s+
(#{valid_ip6})
/x
add_record('aaaa', :name => $1, :ttl => $2, :class => $3, :content => $4)
elsif line =~ /^(#{valid_name})? \s*
#{ttl_cls}
MX \s+
(\d+) \s+
(#{valid_name})
/ix
add_record('mx', :name => $1, :ttl => $2, :class => $3, :prio => $4.to_i, :content => $5)
elsif line=~/^(#{valid_name})? \s*
#{ttl_cls}
SRV \s+
(\d+) \s+
(\d+) \s+
(\d+) \s+
(#{valid_name})
/ix
add_record('srv', :name => $1, :ttl => $2, :class => $3, :prio => $4, :weight => $5, :port => $6, :content => $7)
elsif line =~ /^(#{valid_name}) \s+
#{ttl_cls}
SOA \s+
(#{valid_name}) \s+
(#{valid_name}) \s*
\(?\s*
(#{rr_ttl}) \s+
(#{rr_ttl}) \s+
(#{rr_ttl}) \s+
(#{rr_ttl}) \s+
(#{rr_ttl}) \s*
\)?
/ix
@soa[:type] = 'SOA'
@soa[:name] = $1
@soa[:ttl] = $2 || ''
@soa[:class] = $3
@soa[:primary_ns] = $4
@soa[:contact] = $5
@soa[:serial] = $6
@soa[:refresh] = $7
@soa[:retry] = $8
@soa[:expire] = $9
@soa[:minimum] = $10
@all_records << @soa
elsif line=~ /^(#{valid_name})? \s*
#{ttl_cls}
PTR \s+
(#{valid_name})
/ix
add_record('ptr', :name => $1, :class => $3, :ttl => $2, :content => $4)
elsif line =~ /^(#{valid_name})? \s* #{ttl_cls} ([A-Z0-9]+) \s+ (.*)$/ix
# add_record('txt', :name => $1, :ttl => $2, :class => $3, :text => $4.strip)
add_record($4, :name => $1, :ttl => $2, :class => $3, :content => $5)
else
STDERR.puts "[WARNING][Zonefile.parse][#{@filename}/#{@origin}] unparseable line: \"#{line}\""
end
end
def parse
Zonefile.simplify(@data).each_line do |line|
parse_line(line)
end
end
# Build a new nicely formatted Zonefile
def output
out =<<-ENDH
;
; Database file #{@filename || 'unknown'} for #{@origin || 'unknown'} zone.
; Zone version: #{self.soa[:serial]}
;
#{self.soa[:name]} #{self.soa[:ttl]} IN SOA #{self.soa[:primary]} #{self.soa[:contact]} (
#{self.soa[:serial]} ; serial number
#{self.soa[:refresh]} ; refresh
#{self.soa[:retry]} ; retry
#{self.soa[:expire]} ; expire
#{self.soa[:minimum]} ; minimum TTL
)
#{@origin ? "$ORIGIN #{@origin}" : ''}
#{@ttl ? "$TTL #{@ttl}" : ''}
; Zone NS Records
ENDH
self.ns.each do |ns|
out << "#{ns[:name]} #{ns[:ttl]} #{ns[:class]} NS #{ns[:content]}\n"
end
out << "\n; Zone MX Records\n" unless self.mx.empty?
self.mx.each do |mx|
out << "#{mx[:name]} #{mx[:ttl]} #{mx[:class]} MX #{mx[:prio]} #{mx[:content]}\n"
end
out << "\n; Zone A Records\n" unless self.a.empty?
self.a.each do |a|
out << "#{a[:name]} #{a[:ttl]} #{a[:class]} A #{a[:content]}\n"
end
out << "\n; Zone CNAME Records\n" unless self.cname.empty?
self.cname.each do |cn|
out << "#{cn[:name]} #{cn[:ttl]} #{cn[:class]} CNAME #{cn[:content]}\n"
end
out << "\n; Zone AAAA Records\n" unless self.aaaa.empty?
self.aaaa.each do |a4|
out << "#{a4[:name]} #{a4[:ttl]} #{a4[:class]} AAAA #{a4[:content]}\n"
end
out << "\n; Zone TXT Records\n" unless self.txt.empty?
self.txt.each do |tx|
out << "#{tx[:name]} #{tx[:ttl]} #{tx[:class]} TXT #{tx[:text]}\n"
end
out << "\n; Zone SRV Records\n" unless self.srv.empty?
self.srv.each do |srv|
out << "#{srv[:name]} #{srv[:ttl]} #{srv[:class]} SRV #{srv[:prio]} #{srv[:weight]} #{srv[:port]} #{srv[:content]}\n"
end
out << "\n; Zone PTR Records\n" unless self.ptr.empty?
self.ptr.each do |ptr|
out << "#{ptr[:name]} #{ptr[:ttl]} #{ptr[:class]} PTR #{ptr[:content]}\n"
end
out
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/ip_address_validator.rb | lib/ip_address_validator.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
class IpAddressValidator < ActiveModel::EachValidator
include RecordPatterns
def validate_each( record, attribute, value )
return if record.generate?
record.errors[ attribute ] << I18n.t(:message_attribute_must_be_ip) unless valid?( value )
end
def valid?( ip )
begin
ip = IPAddr.new ip
if options[:ipv6]
return ip.ipv6?
else
return ip.ipv4?
end
rescue Exception => e
false
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/record_patterns.rb | lib/record_patterns.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
module RecordPatterns
IPV4 = '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
IPV6 = '(([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:)'
def fqdn?( value )
value =~ /\A\S+\Z/
end
def hostname?( value )
value =~ /^(?![0-9]+$)(?!-)[_\-.a-zA-Z0-9-]{,63}(?<!-)$/
end
def ip?( value )
ipv4?( value ) || ipv6?( value )
end
def ipv4?( value )
value =~ /\A#{IPV4}\z/
end
def reverse_ipv4_fragment?( value )
value =~ /\A(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){0,3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\z/
end
def ipv6?( value )
value =~ /\A#{IPV6}\z/
end
def reverse_ipv6_fragment?( value )
value =~ /\A(?:(?:[a-fA-F0-9])\.){1,31}(?:[a-fA-F0-9])\z/
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/hijacker.rb | lib/hijacker.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
# Hijacker class
#
# This class is used by RoleRequirementTestHelper to temporarily hijack a controller action for testing
#
# It can be used for other tests as well.
#
# You can contract the author with questions
# Tim C. Harper - irb(main):001:0> ( 'tim_see_harperATgmail._see_om'.gsub('_see_', 'c').gsub('AT', '@') )
#
#
# Example usage:
# hijacker = Hijacker.new(ListingsController)
# hijacker.hijack_instance_method("index", "render :text => 'hello world!'" )
# get :index # will return "hello world"
# hijacker.restore # put things back the way you found it
class Hijacker
def initialize(klass)
@target_klass = klass
@method_stores = {}
end
def hijack_class_method(method_name, eval_string = nil, arg_names = [], &block)
hijack_method(class_self_instance, method_name, eval_string, arg_names, &block )
end
def hijack_instance_method(method_name, eval_string = nil, arg_names = [], &block)
hijack_method(@target_klass, method_name, eval_string, arg_names, &block )
end
# restore all
def restore
@method_stores.each_pair{|klass, method_stores|
method_stores.reverse_each{ |method_name, method|
klass.send :undef_method, method_name
klass.send :define_method, method_name, method if method
}
}
@method_stores.clear
true
rescue
false
end
protected
def class_self_instance
@target_klass.send :eval, "class << self; self; end;"
end
def hijack_method(klass, method_name, eval_string = nil, arg_names = [], &block)
method_name = method_name.to_s
# You have got love ruby! What other language allows you to pillage and plunder a class like this?
(@method_stores[klass]||=[]) << [
method_name,
klass.instance_methods.include?(method_name) && klass.instance_method(method_name)
]
klass.send :undef_method, method_name
if Symbol === eval_string
klass.send :define_method, method_name, klass.instance_methods(eval_string)
elsif String === eval_string
klass.class_eval <<-EOF
def #{method_name}(#{arg_names * ','})
#{eval_string}
end
EOF
elsif block_given?
klass.send :define_method, method_name, block
end
true
rescue
false
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/hostname_validator.rb | lib/hostname_validator.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
class HostnameValidator < ActiveModel::EachValidator
include RecordPatterns
def validate_each( record, attribute, value )
record.errors[ attribute ] << I18n.t(:message_attribute_must_be_hostname) unless fqdn?( value ) && !ip?( value )
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/globo_dns/exporter.rb | lib/globo_dns/exporter.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require File.expand_path('../../../config/environment', __FILE__)
module GloboDns
class RevertableError < ::RuntimeError; end
class Exporter
include GloboDns::Config
include GloboDns::Util
include SyslogHelper
attr_reader :logger
CONFIG_START_TAG = '### BEGIN GloboDns ###'
CONFIG_END_TAG = '### END GloboDns ###'
GIT_AUTHOR = 'DNS API <dnsapi@example.com>'
CHECKCONF_STANDARD_MESSAGES = [
/^zone .*?: loaded serial\s+\d+\n/
]
def initialize
@logger = GloboDns::StringIOLogger.new(Rails.logger)
@something_exported = false
@default_view = View.default
end
def export_all(master_named_conf_content, slaves_named_conf_contents, options = {})
@views_enabled = (defined? GloboDns::Config::ENABLE_VIEW and GloboDns::Config::ENABLE_VIEW)
@logger ||= GloboDns::StringIOLogger.new(options.delete(:logger) || Rails.logger)
lock_tables = options.delete(:lock_tables)
if (options[:use_master_named_conf_for_slave])
slaves_named_conf_contents = [master_named_conf_content] * slaves_named_conf_contents.size
end
@views=View.all.collect(&:name)
Domain.connection.execute("LOCK TABLE #{View.table_name} READ, #{Domain.table_name} READ, #{Record.table_name} READ, #{Audited::Adapters::ActiveRecord::Audit.table_name} READ") unless (lock_tables == false)
export_master(master_named_conf_content, options)
if SLAVE_ENABLED?
Bind::Slaves.each_with_index do |slave, index|
# only exports if the slave hosts is defined.
export_slave(slaves_named_conf_contents[index], options.merge!(index: index)) if slave_enabled?(slave)
end
end
syslog_info('export successful')
Notifier.export_successful(@logger.string).deliver_now if @something_exported
rescue Exception => e
@logger.error(e.to_s + e.backtrace.join("\n"))
syslog_error('export failed')
Notifier.export_failed("#{e}\n\n#{@logger.string}\n\nBacktrace:\n#{e.backtrace.join("\n")}").deliver_now
raise e
ensure
Domain.connection.execute('UNLOCK TABLES') unless (lock_tables == false)
end
def export_master(named_conf_content, options = {})
bind_server_data = {
:user => Bind::Master::USER,
:host => Bind::Master::HOST,
:chroot_dir => Bind::Master::CHROOT_DIR,
:zones_dir => Bind::Master::ZONES_DIR,
:named_conf_file => Bind::Master::NAMED_CONF_FILE
}
export(named_conf_content, Bind::Master::EXPORT_CHROOT_DIR, bind_server_data, _slave = false, options.merge(:label => 'master'))
end
def export_slave(named_conf_content, options = {})
index = options[:index] || 0
bind_server_data = {
:user => Bind::Slaves[index]::USER,
:host => Bind::Slaves[index]::HOST,
:chroot_dir => Bind::Slaves[index]::CHROOT_DIR,
:zones_dir => Bind::Slaves[index]::ZONES_DIR,
:named_conf_file => Bind::Slaves[index]::NAMED_CONF_FILE
}
export(named_conf_content, Bind::Slaves[index]::EXPORT_CHROOT_DIR, bind_server_data, _slave = true, options.merge(:label => "slave#{index+1}", :index => index))
end
def export(named_conf_content, chroot_dir, bind_server_data, slave, options = {})
@options = options
@logger ||= @options[:logger] || Rails.logger
@slave = slave
zones_root_dir = bind_server_data[:zones_dir] or raise ArgumentError.new('missing "bind_server_data.zones_dir" attr')
named_conf_file = bind_server_data[:named_conf_file] or raise ArgumentError.new('missing "bind_server_data.named_conf_file" attr')
if @options[:use_tmp_dir].nil? || @options[:use_tmp_dir]
@options[:use_tmp_dir] = true
end
# get last commit timestamp and the export/current timestamp
Dir.chdir(File.join(chroot_dir, zones_root_dir))
if @options[:all] == true
# ignore the current git content and export all records
@last_commit_date = Time.at(0)
@last_commit_date_destroyed = last_export_timestamp
else
if slave
@last_commit_date = Dir.chdir(File.join(chroot_dir, zones_root_dir)) do
Time.at(exec('git last commit date', GloboDns::Config::Binaries::GIT, 'log', '-1', '--format=%at').to_i)
end
else
@last_commit_date = last_export_timestamp
end
end
@export_timestamp = Time.now.round
#@touch_timestamp = @export_timestamp + 1 # we add 1 second to avoid minor subsecond discrepancies
# when comparing each file's mtime with the @export_times
#Remove destroyed domains
removed_zones = remove_destroyed_domains(File.join(chroot_dir, zones_root_dir), slave)
if @options[:use_tmp_dir]
tmp_dir = Dir.mktmpdir
@logger.info "[GloboDns::Exporter] tmp dir: #{tmp_dir}"
File.chmod(02770, tmp_dir)
FileUtils.chown(nil, BIND_GROUP, tmp_dir, verbose: true)
File.umask(0007)
# recursivelly copy the current configuration to the tmp dir
exec('rsync chroot', 'rsync', '-v', '-a', '--exclude', 'session.key', '--exclude', '.git/', File.join(chroot_dir, '.'), tmp_dir)
else
tmp_dir = chroot_dir
end
# export main configuration file
named_conf_content = self.class.load_named_conf(chroot_dir, named_conf_file) if named_conf_content.blank?
export_named_conf(named_conf_content, tmp_dir, zones_root_dir, named_conf_file)
new_zones = []
if @views_enabled
conf_files_names = [ZONES_FILE, SLAVES_FILE, FORWARDS_FILE, REVERSE_FILE]
# make sure zones|slaves|forwards|reverse.conf are empty when BIND is using views
conf_files_names.each do |conf_file_name|
conf_file = File.join(tmp_dir, zones_root_dir, conf_file_name)
File.open(conf_file, 'w') do |file|
file.puts ''
end
end
# export all views
abs_zones_root_dir = File.join(tmp_dir, zones_root_dir)
abs_views_dir = File.join(tmp_dir, zones_root_dir, '/views')
abs_views_file = File.join(abs_zones_root_dir, VIEWS_FILE)
File.exist?(abs_views_dir) || FileUtils.mkdir(abs_views_dir)
File.open(abs_views_file, 'w') do |file|
View.all.each do |view|
file.puts view.to_bind9_conf(zones_root_dir, '', @slave) unless view.default?
if @slave == true
export_domain_group(tmp_dir, zones_root_dir, view.zones_file, view.zones_dir, [] , true , options.merge(view: view, type: ""))
export_domain_group(tmp_dir, zones_root_dir, view.reverse_file, view.reverse_dir, [] , true , options.merge(view: view, type: ""))
export_domain_group(tmp_dir, zones_root_dir, view.slaves_file, view.slaves_dir, view.domains_master_or_reverse_or_slave, view.updated_since?(@last_commit_date), options.merge(view: view, type: "zones-slave-reverse"))
export_domain_group(tmp_dir, zones_root_dir, view.forwards_file, view.forwards_dir, view.domains.forward_export_to_ns(( options[:index].nil? ? 0 : options[:index] + 1 )) , true , options.merge(view: view, type: "forwards"))
else
new_zones_noreverse = export_domain_group(tmp_dir , zones_root_dir , view.zones_file , view.zones_dir , view.domains.master , view.updated_since?(@last_commit_date), options.merge(:view => view, :type => "zones"))
new_zones_reverse = export_domain_group(tmp_dir , zones_root_dir , view.reverse_file , view.reverse_dir , view.domains._reverse , view.updated_since?(@last_commit_date), options.merge(:view => view, :type => "reverse"))
if not new_zones_noreverse.empty? and not new_zones_reverse.empty?
# If there is a new zone in non-reverse or reverse, I need update ,.everything.
# If both have only changes, may I reload only changed zones
new_zones += new_zones_noreverse + new_zones_reverse
end
export_domain_group(tmp_dir , zones_root_dir , view.slaves_file , view.slaves_dir , view.domains.slave , view.updated_since?(@last_commit_date), options.merge(:view => view, :type => "slave"))
export_domain_group(tmp_dir , zones_root_dir , view.forwards_file , view.forwards_dir , view.domains.forward_export_to_ns(( options[:index].nil? ? 0 : options[:index] + 1 )) , view.updated_since?(@last_commit_date), options.merge(:view => view, :type => "forwards"))
end
end
file.puts @default_view.to_bind9_conf(zones_root_dir, '', @slave) # write default view at the end
end
# new_zones?
else
# remove views folder
views_dir = File.join(tmp_dir, zones_root_dir, '/views')
views_file = File.join(tmp_dir, zones_root_dir, VIEWS_FILE)
FileUtils.rm_rf(views_dir) if File.directory? views_dir
unless View.all.empty?
# make sure views.conf is empty when BIND is not using views
File.open(views_file, 'w') do |file|
file.puts ''
end
end
# export each view-less domain group to a separate file
if @slave == true
export_domain_group(tmp_dir, zones_root_dir, ZONES_FILE, ZONES_DIR, [], true, options)
export_domain_group(tmp_dir, zones_root_dir, REVERSE_FILE, REVERSE_DIR, [], true, options)
export_domain_group(tmp_dir, zones_root_dir, SLAVES_FILE, SLAVES_DIR, Domain.noview.master_or_reverse_or_slave, false, options)
export_domain_group(tmp_dir, zones_root_dir, FORWARDS_FILE, FORWARDS_DIR, Domain.noview.forward_export_to_ns(( options[:index].nil? ? 0 : options[:index] + 1 )), false, options)
else
new_zones_noreverse = export_domain_group(tmp_dir, zones_root_dir, ZONES_FILE, ZONES_DIR, Domain.noview.master)
new_zones_reverse = export_domain_group(tmp_dir, zones_root_dir, REVERSE_FILE, REVERSE_DIR, Domain.noview._reverse)
if not new_zones_noreverse.empty? and not new_zones_reverse.empty?
# If there is a new zone in non-reverse or reverse, I need update everything.
# If both have only changes, may I reload only changed zones
new_zones += new_zones_noreverse + new_zones_reverse
end
export_domain_group(tmp_dir, zones_root_dir, SLAVES_FILE, SLAVES_DIR, Domain.noview.slave)
export_domain_group(tmp_dir, zones_root_dir, FORWARDS_FILE, FORWARDS_DIR, Domain.noview.forward_export_to_ns(( options[:index].nil? ? 0 : options[:index] + 1 )))
end
end
# remove files that older than the export timestamp; these are the
# zonefiles from domains that have been removed from the database
# (otherwise they'd have been regenerated or 'touched')
remove_untouched_zonefiles(File.join(tmp_dir, zones_root_dir, ZONES_DIR), @export_timestamp)
remove_untouched_zonefiles(File.join(tmp_dir, zones_root_dir, REVERSE_DIR), @export_timestamp)
remove_untouched_zonefiles(File.join(tmp_dir, zones_root_dir, SLAVES_DIR), @export_timestamp, true)
# validate configuration with 'named-checkconf'
run_checkconf(tmp_dir, named_conf_file)
check_zones_being_exported(tmp_dir, named_conf_file) unless @slave
# sync generated files on the tmp dir to the local chroot repository
if @options[:use_tmp_dir]
sync_repository_and_commit(tmp_dir, chroot_dir, zones_root_dir, named_conf_file, bind_server_data)
else
commit_repository(tmp_dir, chroot_dir, zones_root_dir, named_conf_file, bind_server_data)
end
updated_zones = removed_zones.empty? ? new_zones : []
# sync files in chroot repository to remote dir on the actual BIND server
sync_remote_bind_and_reload(chroot_dir, zones_root_dir, named_conf_file, bind_server_data, updated_zones)
@something_exported = true
rescue ExitStatusError => err
if err.message == "Nothing to be exported!"
@logger.info "[GloboDns::Exporter][INFO] #{err.message}"
else
raise err
end
rescue Exception => e
if @revert_operation_data && @options[:reset_repository_on_failure] != false
@logger.error(e.to_s + e.backtrace.join("\n"))
revert_operation()
end
raise e
ensure
if !tmp_dir.nil? && @options[:use_tmp_dir] && !@options[:keep_tmp_dir]
FileUtils.remove_entry_secure tmp_dir
end
Domain.connection.execute('UNLOCK TABLES') if @options[:lock_tables]
end
def self.load_named_conf(chroot_dir, named_conf_file)
File.read(File.join(chroot_dir, named_conf_file)).sub(/\n*#{GloboDns::Exporter::CONFIG_START_TAG}.*#{GloboDns::Exporter::CONFIG_END_TAG}\n*/m, "\n")
end
private
def export_named_conf(content, chroot_dir, zones_root_dir, named_conf_file)
content.gsub!("\r\n", "\n")
content.sub!(/\A[\s\n]+/, '')
content.sub!(/[\s\n]*\Z/, "\n")
content.sub!(/\n*#{GloboDns::Exporter::CONFIG_START_TAG}.*#{GloboDns::Exporter::CONFIG_END_TAG}\n*/m, "\n")
abs_zones_root_dir = File.join(chroot_dir, zones_root_dir)
abs_named_conf_file = File.join(abs_zones_root_dir, File.basename(named_conf_file))
File.open(abs_named_conf_file, 'w') do |file|
file.puts content
file.puts
file.puts CONFIG_START_TAG
file.puts '# this block is auto generated; do not edit'
file.puts "include \"#{File.join(zones_root_dir, GloboDns::Config::VIEWS_FILE)}\";"
file.puts "include \"#{File.join(zones_root_dir, GloboDns::Config::ZONES_FILE)}\";\n"
file.puts "include \"#{File.join(zones_root_dir, GloboDns::Config::SLAVES_FILE)}\";\n"
file.puts "include \"#{File.join(zones_root_dir, GloboDns::Config::FORWARDS_FILE)}\";\n"
file.puts "include \"#{File.join(zones_root_dir, GloboDns::Config::REVERSE_FILE)}\";\n"
file.puts CONFIG_END_TAG
end
#File.utime(@touch_timestamp, @touch_timestamp, abs_named_conf_file)
end
def export_views(chroot_dir, zones_root_dir, options = {})
abs_zones_root_dir = File.join(chroot_dir, zones_root_dir)
abs_views_dir = File.join(chroot_dir, zones_root_dir, '/views')
abs_views_file = File.join(abs_zones_root_dir, VIEWS_FILE)
File.exist?(abs_views_dir) or FileUtils.mkdir(abs_views_dir)
File.open(abs_views_file, 'w') do |file|
View.all.each do |view|
file.puts view.to_bind9_conf(zones_root_dir, '', @slave) unless view.default?
if @slave == true
# chroot_dir , zones_root_dir , file_name , dir_name , domains , export_all_domains
export_domain_group(chroot_dir , zones_root_dir , view.zones_file , view.zones_dir , [] , true , options.merge(:view => view, :type => ""))
export_domain_group(chroot_dir , zones_root_dir , view.reverse_file , view.reverse_dir , [] , true , options.merge(:view => view, :type => ""))
export_domain_group(chroot_dir , zones_root_dir , view.slaves_file , view.slaves_dir , view.domains_master_or_reverse_or_slave , view.updated_since?(@last_commit_date) , options.merge(:view => view, :type => "zones-slave-reverse"))
export_domain_group(chroot_dir , zones_root_dir , view.forwards_file , view.forwards_dir , view.domains.forward_export_to_ns(( options[:index].nil? ? 0 : options[:index] + 1 )) , true , options.merge(:view => view, :type => "forwards"))
# export_domain_group(chroot_dir , zones_root_dir , view.slaves_file , view.slaves_dir , view.domains.master_or_reverse_or_slave , view.updated_since?(@last_commit_date) , options)
# export_domain_group(chroot_dir , zones_root_dir , view.forwards_file , view.forwards_dir , view.domains.forward_export_to_ns(( options[:index].nil? ? 0 : options[:index] + 1 )) , true , options)
else
# chroot_dir , zones_root_dir , file_name , dir_name , domains , export_all_domains
export_domain_group(chroot_dir , zones_root_dir , view.zones_file , view.zones_dir , view.domains.master , view.updated_since?(@last_commit_date), options.merge(:view => view, :type => "zones"))
export_domain_group(chroot_dir , zones_root_dir , view.reverse_file , view.reverse_dir , view.domains._reverse , view.updated_since?(@last_commit_date), options.merge(:view => view, :type => "reverse"))
export_domain_group(chroot_dir , zones_root_dir , view.slaves_file , view.slaves_dir , view.domains.slave , view.updated_since?(@last_commit_date), options.merge(:view => view, :type => "slave"))
export_domain_group(chroot_dir , zones_root_dir , view.forwards_file , view.forwards_dir , view.domains.forward_export_to_ns(( options[:index].nil? ? 0 : options[:index] + 1 )) , view.updated_since?(@last_commit_date), options.merge(:view => view, :type => "forwards"))
end
end
file.puts @default_view.to_bind9_conf(zones_root_dir) # write default view at the end
end
#File.utime(@touch_timestamp, @touch_timestamp, abs_views_file)
end
def other_views_zones(domains)
# if a default zone is changed, force update of same name zones from other views
if @views_enabled
ids = domains.pluck(:id)
domains.where(view: @default_view).each do |d|
ids.push(Domain.where(name:d.name).pluck(:id))
end
ids.uniq
Domain.where(id:ids)
else
domains
end
end
def write_zone_conf(zones_root_dir, export_all_domains, abs_zones_root_dir, output_file, domains, options)
File.open(output_file, 'w') do |file|
# dump zonefile of updated domains
updated_domains = export_all_domains ? domains : other_views_zones(domains.updated_since(@last_commit_date))
updated_domains.each do |domain|
unless !(options[:view] == @default_view) and @slave or domain.forward? # Slaves and forwards don't replicate the zone-files. # other views use the zone conf of the default view
update_serial = (options[:view] == domain.view)
@logger.debug "[DEBUG] writing zonefile for domain #{domain.name} (last updated: #{domain.updated_at}; repo: #{@last_commit_date}; created_at: #{domain.created_at}) (domain.updated?: #{domain.updated_since?(@last_commit_date)}; domain.records.updated_since-count: #{domain.records.updated_since(@last_commit_date).count})"
# create subdir for this domain, if it doesn't exist yet.
abs_zonefile_dir = File.join(abs_zones_root_dir, domain.zonefile_dir)
File.exist?(abs_zonefile_dir) || FileUtils.mkdir_p(abs_zonefile_dir)
# Create/Update the zonefile itself
abs_zonefile_path = File.join(abs_zones_root_dir, domain.zonefile_path)
domain.to_zonefile(abs_zonefile_path, update_serial) unless domain.slave?
#File.utime(@touch_timestamp, @touch_timestamp, File.join(abs_zonefile_path)) unless domain.slave? || domain.forward?
end
end
domains.each do |domain|
if @slave || domain.slave? && !domain.forward?
domain = domain.clone
domain.view = options[:view] if options[:view] && options[:view] != @default_view
domain.slave!
abs_zonefile_dir = File::join(abs_zones_root_dir, domain.zonefile_dir)
File.exist?(abs_zonefile_dir) || FileUtils.mkdir_p(abs_zonefile_dir)
abs_zonefile_path = File.join(abs_zones_root_dir, domain.zonefile_path)
File.exist?(abs_zonefile_path) || File.open(abs_zonefile_path,'w')
if @slave && domain.master.nil?
masters_external_ip = (GloboDns::Config::Bind::Slaves[options[:index]]::MASTERS_EXTERNAL_IP == true) if defined? GloboDns::Config::Bind::Slaves[options[:index]]::MASTERS_EXTERNAL_IP
if masters_external_ip
domain.master = GloboDns::Config::Bind::Master::IPADDR_EXTERNAL
else
domain.master = Bind::Master::IPADDR
end
domain.master += " port #{Bind::Master::PORT}" if defined?(Bind::Master::PORT)
domain.master += " key #{domain.query_key_name}" if domain.query_key_name
end
end
file.puts domain.to_bind9_conf(zones_root_dir, '')
end
end
end
def export_domain_group(chroot_dir, zones_root_dir, file_name, dir_name, domains, export_all_domains = false, options = {})
# abs stands for absolute
abs_zones_root_dir = File.join(chroot_dir, zones_root_dir)
abs_file_name = File.join(abs_zones_root_dir, file_name)
abs_dir_name = File.join(abs_zones_root_dir, dir_name)
array_new_zones = []
n_zones = []
# @logger.debug "Export domain group chroot_dir=#{chroot_dir} zones_root_dir=#{zones_root_dir} file_name=#{file_name} dir_name=#{dir_name} export_all_domains=#{export_all_domains}"
File.exist?(abs_dir_name) or FileUtils.mkdir(abs_dir_name)
# write <view>_<type>_default.conf (basically the default_<type>.conf excluding the zones that exist in this view)
if options[:view] && !options[:view].default?
abs_default_file_name = File.join(abs_dir_name+"-default.conf")
case options[:type]
when "zones"
default_domains = @default_view.domains.master.not_in_view(options[:view])
when "slave"
default_domains = @default_view.domains.slave.not_in_view(options[:view])
when "forwards"
default_domains = @default_view.domains.forward.not_in_view(options[:view])
when "reverse"
default_domains = @default_view.domains.reverse.not_in_view(options[:view])
when "zones-slave-reverse"
default_domains = @default_view.domains.master_or_reverse_or_slave.not_in_view(options[:view])
end
write_zone_conf(zones_root_dir, export_all_domains, abs_zones_root_dir, abs_default_file_name, default_domains, options) unless (@slave and not (options[:type] == "zones-slave-reverse" or options[:type] == "forwards")) # if options[:zones]
end
# write <view>_<type>.conf (the zones that exist in this view)
File.open(abs_file_name, 'w') do |file|
# dump zonefile of updated domains
updated_domains = export_all_domains ? domains : domains.updated_since(@last_commit_date)
updated_domains.each do |domain|
n_zones << domain unless export_all_domains && @slave
unless @slave || domain.forward? # Slaves and forwards don't replicate the zone-files.
@logger.debug "[DEBUG] writing zonefile for domain #{domain.name} (last updated: #{domain.updated_at}; repo: #{@last_commit_date}; created_at: #{domain.created_at}) (domain.updated?: #{domain.updated_since?(@last_commit_date)}; domain.records.updated_since-count: #{domain.records.updated_since(@last_commit_date).count})"
# create subdir for this domain, if it doesn't exist yet.
abs_zonefile_dir = File::join(abs_zones_root_dir, domain.zonefile_dir)
File.exist?(abs_zonefile_dir) or FileUtils.mkdir_p(abs_zonefile_dir)
# Create/Update the zonefile itself
abs_zonefile_path = File.join(abs_zones_root_dir, domain.zonefile_path)
domain.to_zonefile(abs_zonefile_path) unless domain.slave?
#File.utime(@touch_timestamp, @touch_timestamp, File.join(abs_zonefile_path)) unless domain.slave? || domain.forward?
end
end
#If one zone is new, we need a full reload to bind.
n_zones.each do |z|
if z.created_at > @last_commit_date
array_new_zones = []
break
else
array_new_zones << "#{z.name}"
end
end
# write entries to index file (<domain_type>.conf).
domains = domains.not_in_view(@default_view) if @slave and !domains.empty? and options[:view] and !options[:view].default?
domains.each do |domain|
if @slave or domain.slave? and not domain.forward?
domain.view = options[:view] if options[:view]
domain = domain.clone
domain.slave!
abs_zonefile_dir = File.join(abs_zones_root_dir, domain.zonefile_dir)
File.exist?(abs_zonefile_dir) || FileUtils.mkdir_p(abs_zonefile_dir)
abs_zonefile_path = File.join(abs_zones_root_dir, domain.zonefile_path)
File.exist?(abs_zonefile_path) || File.open(abs_zonefile_path, 'w')
if @slave && domain.master.nil?
masters_external_ip = (GloboDns::Config::Bind::Slaves[options[:index]]::MASTERS_EXTERNAL_IP == true) if defined? GloboDns::Config::Bind::Slaves[options[:index]]::MASTERS_EXTERNAL_IP
if masters_external_ip
domain.master = GloboDns::Config::Bind::Master::IPADDR_EXTERNAL
else
domain.master = Bind::Master::IPADDR
end
domain.master += " port #{Bind::Master::PORT}" if defined?(Bind::Master::PORT)
domain.master += " key #{domain.query_key_name}" if domain.query_key_name
end
end
file.puts domain.to_bind9_conf(zones_root_dir, '')
end
end
#File.utime(@touch_timestamp, @touch_timestamp, abs_dir_name)
#File.utime(@touch_timestamp, @touch_timestamp, abs_file_name)
return array_new_zones
end
def remove_untouched_zonefiles(dir, export_timestamp, slave = false)
if slave
patern = File.join(dir, 'dbs.*')
else
patern = File.join(dir, 'db.*')
end
Dir.glob(patern).each do |file|
if File.mtime(file) < export_timestamp
@logger.debug "[DEBUG] removing untouched zonefile \"#{file}\" (mtime (#{File.mtime(file)}) < export ts (#{export_timestamp}))"
FileUtils.rm(file)
end
end
end
def run_checkconf(chroot_dir, named_conf_file)
output = exec_as_root('named-checkconf', Binaries::CHECKCONF, '-z', '-t', chroot_dir, named_conf_file)
clean_checkconf_output(output)
rescue ExitStatusError => e
raise ExitStatusError.new(clean_checkconf_output(e.message))
end
def sync_repository_and_commit(tmp_dir, chroot_dir, zones_root_dir, named_conf_file, bind_server_data)
abs_tmp_zones_root_dir = File.join(tmp_dir, zones_root_dir, '')
abs_repository_zones_dir = File.join(chroot_dir, zones_root_dir, '')
# set 'bind' as group of the tmp_dir, add rwx permission to group
FileUtils.chown_R(nil, BIND_GROUP, abs_tmp_zones_root_dir)
exec('chmod_R', 'chmod', '-R', 'g+u', abs_tmp_zones_root_dir) # ruby doesn't accept symbolic mode on chmod
#--- change to the directory with the local copy of the zone files
Dir.chdir(abs_repository_zones_dir)
#--- save data required to revert the respository to the current version
orig_head=get_head_commit('original')
label = @options[:label]
@revert_operation_data ||= {}
@revert_operation_data[label] = {
bind_server_data: bind_server_data,
chroot_dir: chroot_dir,
revert_server: false, # Only true after sync_remote
revision: orig_head,
zones_root_dir: zones_root_dir
}
#--- sync to Bind9's data dir
if @slave
rsync_output = exec('local rsync',
Binaries::RSYNC,
'--checksum',
'--archive',
'--delete',
'--verbose',
# '--omit-dir-times',
'--group',
'--perms',
# "--include=#{NAMED_CONF_FILE}",
"--include=#{File.basename(named_conf_file)}",
"--include=#{VIEWS_FILE}",
"--include=*#{ZONES_FILE}",
"--include=*#{SLAVES_FILE}",
"--include=*#{FORWARDS_FILE}",
"--include=*#{REVERSE_FILE}",
"--include=*#{VIEWS_DIR}/***",
"--include=*#{ZONES_DIR}/***",
"--include=*#{SLAVES_DIR}/***",
"--include=*#{FORWARDS_DIR}/***",
"--include=*#{REVERSE_DIR}/***",
'--exclude=*',
abs_tmp_zones_root_dir,
abs_repository_zones_dir)
else
rsync_output = exec('local rsync',
Binaries::RSYNC,
'--checksum',
'--archive',
'--delete',
'--verbose',
# '--omit-dir-times',
'--group',
'--perms',
# "--include=#{NAMED_CONF_FILE}",
"--include=#{File.basename(named_conf_file)}",
"--include=#{VIEWS_FILE}",
"--include=*#{ZONES_FILE}",
"--include=*#{SLAVES_FILE}",
"--include=*#{FORWARDS_FILE}",
"--include=*#{REVERSE_FILE}",
"--include=*#{VIEWS_DIR}/***",
"--include=*#{ZONES_DIR}/***",
"--include=*#{SLAVES_DIR}/***",
"--include=*#{FORWARDS_DIR}/***",
"--include=*#{REVERSE_DIR}/***",
'--exclude=*',
abs_tmp_zones_root_dir,
abs_repository_zones_dir)
end
@logger.debug "[GloboDns::Exporter][DEBUG] rsync:\n#{rsync_output}"
#--- add all changed files to git's index
# exec_as_bind('git add', Binaries::GIT, 'add', '-A')
exec('git add', Binaries::GIT, 'add', '-A')
#--- check status output; if there are no changes, just return
git_status_output = exec('git status', Binaries::GIT, 'status')
if git_status_output =~ /nothing to commit \(working directory clean\)/ or git_status_output =~ /On branch master\nnothing to commit, working directory clean/
raise ExitStatusError, "Nothing to be exported!"
end
#--- commit the changes
# commit_output = exec_as_bind('git commit', Binaries::GIT, 'commit', "--author=#{GIT_AUTHOR}", "--date=#{@export_timestamp}", '-m', '"[GloboDns::exporter]"')
commit_output = exec('git commit', Binaries::GIT, 'commit', "--author=#{GIT_AUTHOR}", "--date=#{@export_timestamp}", '-m', '"[GloboDns::exporter]"')
@logger.info "[GloboDns::Exporter][INFO] changes committed:\n#{commit_output}"
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | true |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/globo_dns/resolver.rb | lib/globo_dns/resolver.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
module GloboDns
class Resolver
include GloboDns::Config
include GloboDns::Util
DEFAULT_PORT = 53
def initialize(host, port)
@host = host
@port = port
end
MASTER = GloboDns::Resolver.new(Bind::Master::IPADDR, (Bind::Master::PORT rescue DEFAULT_PORT).to_i)
SLAVES = Bind::Slaves.map do |slave|
GloboDns::Resolver.new(slave::IPADDR, (slave::PORT rescue DEFAULT_PORT).to_i)
end
def resolve(record)
name = Record::fqdn(record.name, record.domain.name)
key_name = record.domain.try(:query_key_name)
key_value = record.domain.try(:query_key)
args = [Binaries::DIG, '@'+@host, '-p', @port.to_s, '-t', record.type]
args += ['-y', "#{key_name}:#{key_value}"] if key_name && key_value
args += [name, '+norecurse', '+noauthority', '+time=1'] # , '+short']
exec!('dig', *args)
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/globo_dns/string_io_logger.rb | lib/globo_dns/string_io_logger.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
module GloboDns
# class StringIOLogger < ActiveSupport::TaggedLogging
class StringIOLogger
def initialize(logger)
@logger = ActiveSupport::TaggedLogging.new(logger)
@sio = StringIO.new('', 'w')
@sio_logger = Logger.new(@sio)
@console_logger = Logger.new(STDOUT)
end
def add(severity, message = nil, progname = nil, &block)
message = (block_given? ? block.call : progname) if message.nil?
@sio_logger.add(severity, "#{message}", progname)
@logger.add(severity, "#{message}", progname)
end
def string
@sio.string
end
def error(*args)
rv = @logger.error(*args)
add(Logger::Severity::ERROR,*args,'globodns')
rv
end
def warn(*args)
rv = @logger.warn(*args)
add(Logger::Severity::WARN,*args,'globodns')
rv
end
def info(*args)
rv = @logger.info(*args)
add(Logger::Severity::INFO,*args,'globodns')
rv
end
def debug(*args)
rv = @logger.debug(*args)
# add(Logger::Severity::DEBUG,*args,'globodns')
rv
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/globo_dns/config.rb | lib/globo_dns/config.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require File.expand_path('../../../config/environment', __FILE__)
module GloboDns
module Config
def self.load(yaml_string)
template = ERB.new(yaml_string)
yml = YAML::load(template.result)
set_constants(yml[Rails.env])
end
def self.load_from_file(file = Rails.root.join('config', 'globodns.yml'))
self.load(IO::read(file))
end
def SLAVE_ENABLED?
if Bind.constants.include?(:Slaves)
@slave_enabled ||= Bind::Slaves.any? {|slave| !slave::HOST.nil? and slave::HOST != '' rescue false}
else
@slave_enabled = false
end
end
def slave_enabled? slave
!slave::HOST.nil? and slave::HOST != '' rescue false
end
def get_nameservers
ns = Bind::Slaves.collect{|slave| slave::HOST}
ns.unshift(Bind::Master::HOST)
Hash[(0...ns.size).zip ns]
end
protected
def self.set_constants(hash, module_ = self)
hash.each do |key, value|
if value.is_a?(Hash)
new_module = module_.const_set(key.camelize, Module.new)
self.set_constants(value, new_module)
elsif value.is_a? Array
deep = false;
module_.const_set(key.camelize, value)
value.each_with_index do |item, index|
if item.is_a?(Hash)
deep = true
value[index] = Module.new
self.set_constants item, value[index]
end
end
if !deep
# Shouldn't create deep modules,
# remove the camelized key
module_.send :remove_const, key.camelize
# and sets a normal key
module_.const_set(key.upcase, value)
end
else
module_.const_set(key.upcase, value)
end
end
true
end
end # Config
end # GloboDns
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/globo_dns/importer.rb | lib/globo_dns/importer.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require File.expand_path('../importer/util', __FILE__)
module GloboDns
class Importer
include GloboDns::Config
include GloboDns::Util
include SyslogHelper
attr_reader :logger
def import(options = {})
import_timestamp = Time.now
master_chroot_dir = options.delete(:master_chroot_dir) || Bind::Master::CHROOT_DIR
master_named_conf_path = options.delete(:master_named_conf_file) || Bind::Master::NAMED_CONF_FILE
slaves_chroot_dirs = options.delete(:slave_chroot_dir) || Bind::Slaves.map { |slave| slave::CHROOT_DIR }
slaves_named_conf_paths = options.delete(:slave_named_conf_file) || Bind::Slaves.map { |slave| slave::NAMED_CONF_FILE }
@logger = GloboDns::StringIOLogger.new(options.delete(:logger) || Rails.logger)
@logger.level = Logger::DEBUG if options[:debug]
slaves_canonical_named_conf = []
if options[:remote]
master_tmp_dir = Dir.mktmpdir
logger.debug "syncing master chroot dir to \"#{master_tmp_dir}\""
puts "#{Bind::Master::USER}@#{Bind::Master::HOST}:#{File.join(master_chroot_dir, '')}"
exec('rsync remote master',
Binaries::RSYNC,
'--archive',
'--no-owner',
'--no-group',
'--no-perms',
'--verbose',
'--exclude=session.key',
"#{Bind::Master::USER}@#{Bind::Master::HOST}:#{File.join(master_chroot_dir, '')}",
master_tmp_dir)
master_chroot_dir = master_tmp_dir
if SLAVE_ENABLED?
Bind::Slaves.each_with_index do |slave, index|
slave_tmp_dir = Dir.mktmpdir
logger.debug "syncing slave chroot dir to \"#{slave_tmp_dir}\""
exec('rsync remote slave',
Binaries::RSYNC,
'--archive',
'--no-owner',
'--no-group',
'--no-perms',
'--verbose',
'--exclude=session.key',
"#{slave::USER}@#{slave::HOST}:#{File.join(slaves_chroot_dirs[index], '')}",
slave_tmp_dir)
slaves_chroot_dirs[index] = slave_tmp_dir
end
end
end
named_conf_path = File.join(master_chroot_dir, master_named_conf_path)
File.exists?(named_conf_path) or raise "master BIND configuration file not found (\"#{named_conf_path}\")"
# test zone files
exec_as_root('named-checkconf', Binaries::CHECKCONF, '-z', '-t', master_chroot_dir, master_named_conf_path)
# generate canonical representation of the configuration file
master_canonical_named_conf = exec_as_root('named-checkconf', Binaries::CHECKCONF, '-p', '-t', master_chroot_dir, master_named_conf_path)
if SLAVE_ENABLED?
Bind::Slaves.each_with_index do |slave, index|
named_conf_path = File.join(slaves_chroot_dirs[index], slaves_named_conf_paths[index])
File.exists?(named_conf_path) or raise "slave #{index+1} BIND configuration file not found (\"#{named_conf_path}\")"
# test zone files
exec_as_root('named-checkconf', Binaries::CHECKCONF, '-z', '-t', slaves_chroot_dirs[index], slaves_named_conf_paths[index]) if slave::HOST
# generate canonical representation of the configuration file
slaves_canonical_named_conf << exec_as_root('named-checkconf', Binaries::CHECKCONF, '-p', '-t', slaves_chroot_dirs[index], slaves_named_conf_paths[index]) if slave::HOST
end #each
end #if
if options[:debug]
# write canonical representation to a tmp file, for debugging purposes
File.open('/tmp/globodns.canonical.master.named.conf.' + ('%x' % (rand * 999999)), 'w') do |file|
file.write(master_canonical_named_conf)
logger.debug "canonical master BIND configuration written to \"#{file.path}\""
end
if SLAVE_ENABLED?
Bind::Slaves.each_with_index do |slave, index|
File.open("/tmp/globodns.canonical.slave-#{index+1}.named.conf." + ('%x' % (rand * 999999)), 'w') do |file|
file.write(slaves_canonical_named_conf[index])
logger.debug "canonical slave BIND configuration for slave #{index+1} written to \"#{file.path}\""
end
end
end
end
# load grammar
Citrus.load(File.expand_path('../importer/named_conf.citrus', __FILE__))
# process slave first, cache the filtered config and free the parsed
# tree to free some memory
if SLAVE_ENABLED?
slaves_configs = []
slaves_rndc_keys = []
Bind::Slaves.each_with_index do |slave, index|
slave_root = nil
begin
slave_root = NamedConf.parse(slaves_canonical_named_conf[index])
rescue Citrus::ParseError => e
raise RuntimeError.new("[ERROR] unable to parse canonical slave BIND configuration for slave #{index+1} (line #{e.line_number}, column #{e.line_offset}: #{e.line})")
end
slaves_configs << slave_root.config
slaves_rndc_keys << slave_root.rndc_key
slave_root = nil
if options[:debug]
File.open("/tmp/globodns.filtered.slave-#{index+1}.named.conf." + ('%x' % (rand * 999999)), 'w') do |file|
file.write(slave_root.config)
logger.debug "filtered slave BIND configuration for slave #{index+1} written to \"#{file.path}\""
end
end
end
end
# now, process the master file
master_root = nil
begin
master_root = NamedConf.parse(master_canonical_named_conf)
rescue Citrus::ParseError => e
raise RuntimeError.new("[ERROR] unable to parse canonical master BIND configuration #{master_canonical_named_conf} (line #{e.line_number}, column #{e.line_offset}: #{e.line})")
end
master_config = master_root.config
master_rndc_key = master_root.rndc_key
if options[:debug]
# write filtered/parsed representation to a tmp file, for debugging purposes
File.open('/tmp/globodns.filtered.master.named.conf.' + ('%x' % (rand * 999999)), 'w') do |file|
file.write(master_config)
logger.debug "filtered master BIND configuration written to \"#{file.path}\""
end
end
# disable auditing on all affected models
View.disable_auditing
Domain.disable_auditing
Record.disable_auditing
# save the 'View's and 'Domain's found by the parser to the DB
# ActiveRecord::Base.connection.execute "TRUNCATE `#{View.table_name}`"
# ActiveRecord::Base.connection.execute "TRUNCATE `#{Domain.table_name}`"
# ActiveRecord::Base.connection.execute "TRUNCATE `#{Record.table_name}`"
Record.delete_all
Domain.delete_all
View.delete_all
# find 'common/shared' domains
domain_views = Hash.new
master_root.views.each do |view|
view.domains.each do |domain|
domain_views[domain.import_key] ||= Array.new
domain_views[domain.import_key] << view.name
end
end
common_domains = domain_views.select { |domain_key, views|
views.size == master_root.views.size
}
# save each view and its respective domains
master_root.views.each do |view|
logger.info "saving view: #{view.model.inspect}"
unless view.model.save
logger.error("unable to save view #{view.name}: #{view.model.errors.full_messages}")
next
end
while domain = view.domains.shift
domain.chroot_dir = master_chroot_dir
domain.bind_dir = master_root.bind_dir
domain.logger = logger
domain_views = common_domains[domain.import_key]
unless domain.model && domain.model.soa_record
logger.error "unable to build DB model from zone statement: #{domain.to_str}"
next
end
if domain_views == false
next
elsif domain_views.is_a?(Array)
common_domains[domain.import_key] = false
else
domain.model.view_id = view.model.id
end
# Look for a sibling, and merge replicated records.
domain.model.set_sibling()
logger.info " saving domain: #{domain.model.inspect} (soa: #{domain.model.soa_record.inspect})"
domain.model.save or logger.error("unable to save domain #{domain.model.name}: #{domain.model.errors.full_messages} (soa: #{domain.model.soa_record.errors.full_messages})")
domain.reset_model
end
end
# save domains outside any views
logger.info "viewless domains:"
while domain = master_root.domains.shift
domain.chroot_dir = master_chroot_dir
domain.bind_dir = master_root.bind_dir
domain.logger = logger
unless domain.model && domain.model.soa_record
logger.error "unable to build DB model from zone statement: #{domain.to_str}"
next
end
logger.info " saving domain: #{domain.model.inspect} (soa: #{domain.model.soa_record.inspect})"
domain.model.save or logger.error("unable to save domain #{domain.model.name}: #{domain.model.errors.full_messages} (soa: #{domain.model.soa_record.errors.full_messages})")
domain.reset_model
end
# generate rdnc.conf files
if master_rndc_key
write_rndc_conf(Bind::Master::EXPORT_CHROOT_DIR, master_rndc_key, Bind::Master::IPADDR, Bind::Master::RNDC_PORT)
else
logger.warn "no rndc key found in master's named.conf"
FileUtils.rm(File.join(Bind::Master::EXPORT_CHROOT_DIR, RNDC_CONFIG_FILE))
end
if SLAVE_ENABLED?
Bind::Slaves.each_with_index do |slave, index|
if slaves_rndc_keys[index]
write_rndc_conf(slave::EXPORT_CHROOT_DIR, slaves_rndc_keys[index], slave::IPADDR, slave::RNDC_PORT)
else
logger.warn "no rndc key found in slave's named.conf for slave #{index+1}"
FileUtils.rm(File.join(slave::EXPORT_CHROOT_DIR, RNDC_CONFIG_FILE))
end
end
end
# finally, regenerate/export the updated database
if options[:export]
GloboDns::Exporter.new.export_all(master_config, slaves_configs,
:all => true,
:keep_tmp_dir => true,
:abort_on_rndc_failure => false,
:logger => logger)
else
save_config(master_config, Bind::Master::EXPORT_CHROOT_DIR, Bind::Master::ZONES_DIR, Bind::Master::NAMED_CONF_FILE, import_timestamp)
Bind::Slaves.each_with_index do |slave, index|
save_config(slaves_configs[index], slave::EXPORT_CHROOT_DIR, slave::ZONES_DIR, slave::NAMED_CONF_FILE, import_timestamp) if SLAVE_ENABLED?
end
end
syslog_info('import successful')
Notifier.import_successful(@logger.string).deliver
rescue Exception => e
syslog_error 'import failed'
Notifier.import_failed("#{e}\n\n#{@logger.string}\n\nBacktrace:\n#{e.backtrace.join("\n")}").deliver
raise e
# ensure
# FileUtils.remove_entry_secure master_tmp_dir unless master_tmp_dir.nil? || @options[:keep_tmp_dir] == true
# FileUtils.remove_entry_secure slave_tmp_dir unless slave_tmp_dir.nil? || @options[:keep_tmp_dir] == true
end
def write_rndc_conf(chroot_dir, key_str, bind_host, bind_port)
File.open(File.join(chroot_dir, RNDC_CONFIG_FILE), 'w') do |file|
file.puts key_str
file.puts ""
file.puts "options {"
file.puts " default-key \"#{RNDC_KEY_NAME}\";"
file.puts " default-server #{bind_host};"
file.puts " default-port #{bind_port};" if bind_port
file.puts "};"
end
end
# saves *and commits the changes to git*
def save_config(content, chroot_dir, zones_dir, named_conf_file, timestamp)
Dir.chdir(File.join(chroot_dir, zones_dir)) do
File.open(File.basename(named_conf_file), 'w') do |file|
file.write(content)
file.puts GloboDns::Exporter::CONFIG_START_TAG
file.puts "# imported on #{timestamp}"
file.puts GloboDns::Exporter::CONFIG_END_TAG
end
exec('git add', Binaries::GIT, 'add', '.')
commit_output = exec('git commit', Binaries::GIT, 'commit', "--author=#{GIT_AUTHOR}", "--date=#{timestamp}", '-am', '"[GloboDns::importer]"')
logger.info "import changes committed:\n#{commit_output}"
end
end
end # class Importer
end # module GloboDns
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/globo_dns/tester.rb | lib/globo_dns/tester.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require File.expand_path('../../../config/environment', __FILE__)
module GloboDns
class Tester < ActiveSupport::TestCase
include GloboDns::Config
include GloboDns::Util
def initialize(*args)
options = args.first.is_a?(Hash) ? args.shift : Hash.new
@logger = options.delete(:logger) || Rails.logger
super(args)
end
def teardown
# nothing to do
end
def setup
# parse diff output and save records to be tested
Dir.chdir(File.join(Bind::Master::CHROOT_DIR, BIND_CONFIG_DIR))
log_output = exec('git log', Binaries::GIT, '--no-pager', 'log', '--stat', '-p', '-1')
# Rails.logger.debug "[GloboDns::Tester::git] git log -1:\n#{log_output}"
@added_domains, @removed_domains, @modified_domains = Hash.new, Hash.new, Hash.new
added_domain, removed_domain = Array.new, Array.new
log_output.each_line do |line|
if line =~ /^\+\+\+ \/dev\/null$/
added_domain = nil
elsif line =~ /^\+\+\+ b\/(?:#{ZONES_DIR}|#{REVERSE_DIR})\/db\.(.*)$/
added_domain = $1
elsif line =~ /^\-\-\- \/dev\/null$/
removed_domain = nil
elsif line =~ /^\-\-\- a\/(?:#{ZONES_DIR}|#{REVERSE_DIR})\/db\.(.*)$/
removed_domain = $1
elsif line =~ /^([\+\-])([\S]+)\s*(\d+)?\s+IN\s+([A-Z]+)\s*(\d+)?\s+(.*)$/
domain, domain_list = if added_domain == removed_domain
[added_domain, @modified_domains]
elsif added_domain.nil? && !removed_domain.nil?
[removed_domain, @removed_domains]
elsif !added_domain.nil? && removed_domain.nil?
[added_domain, @added_domains]
else
raise "[ERROR] invalid domain operation"
end
domain_list[domain] ||= Array.new
domain_list[domain] << {:domain => domain, :op => $1, :name => $2, :ttl => $3, :type => $4, :prio => $5, :content => $6}
end
end
true
end
def run_all
setup
self.public_methods.grep(/test_/).each do |method_name|
m = self.method(method_name)
m.call if m.parameters.empty?
end
end
def test_added_domains
@added_domains.each do |domain, records|
@logger.info "[GloboDns::Tester::added] \"#{domain}\""
test_added_domain(domain, records)
@logger.info "[GloboDns::Tester::added] \"#{domain}\": ok"
end
true
end
def test_removed_domains
@removed_domains.each do |domain, records|
@logger.info "[GloboDns::Tester::removed] \"#{domain}\""
test_removed_domain(domain, records)
@logger.info "[GloboDns::Tester::removed] \"#{domain}\": ok"
end
true
end
def test_modified_domains
@modified_domains.each do |domain, records|
@logger.info "[GloboDns::Tester::modified] \"#{domain}\""
test_modified_domain(domain, records)
@logger.info "[GloboDns::Tester::modified] \"#{domain}\": ok"
end
true
end
private
def test_added_domain(domain, records)
log_test 'added', 'domain' do
db_domain = Domain.where('name' => domain).first
refute_nil db_domain
end
records.each do |record|
test_record(record, domain, 'added')
end
end
def test_removed_domain(domain, records)
log_test 'removed', 'domain' do
db_domain = Domain.where('name' => domain).first
assert_nil db_domain
end
records.each do |record|
test_record(record, domain, 'removed')
end
end
def test_modified_domain(domain, records)
log_test 'modified', 'domain' do
db_domain = Domain.where('name' => domain).first
refute_nil db_domain
end
tested_records = Hash.new
records.each do |record|
next unless record[:op] == '+'
test_record(record, domain, 'modified')
tested_records[Record::fqdn(record[:name], domain) + ':' + record[:type]] = true
end
records.each do |record|
next unless record[:op] == '-' && !tested_records.include?(Record::fqdn(record[:name], domain) + ':' + record[:type])
test_record(record, domain, 'modified')
end
end
def test_record(record, domain, category_label = '')
log_test category_label, "record: #{record[:name]}/#{record[:type]}" do
db_records = Record.joins(:domain).
where("#{Domain.table_name}.name" => domain).
where("#{Record.table_name}.name" => possible_record_names(record[:name], domain)).
where("#{Record.table_name}.type" => record[:type]).
all
resources = resolver.getresources(Record::fqdn(record[:name], domain), Record::resolv_resource_class(record[:type]))
match_resolve_resources_against_db_records(resources, db_records)
end
end
def test_added_record(record, domain, category_label = '')
log_test category_label, "record: #{record[:name]}/#{record[:type]}" do
db_records = Record.joins(:domain).
where("#{Domain.table_name}.name" => domain).
where("#{Record.table_name}.name" => possible_record_names(record[:name], domain)).
where("#{Record.table_name}.type" => record[:type]).
all
refute db_records.empty?
resources = resolver.getresources(Record::fqdn(record[:name], domain), Record::resolv_resource_class(record[:type]))
refute resources.empty?, "no resources found (domain: #{domain}, name: #{record[:name]}, type: #{record[:type]})"
match_resolve_resources_against_db_records(resources, db_records)
end
end
def test_removed_record(record, domain, category_label = '')
log_test category_label, "record: #{record[:name]}/#{record[:type]}" do
db_records = Record.joins(:domain).
where("#{Domain.table_name}.name" => domain).
where("#{Record.table_name}.name" => possible_record_names(record[:name], domain)).
where("#{Record.table_name}.type" => record[:type]).
all
assert db_records.empty?
assert_raises Resolv::ResolvError do resolver.getresource(Record::fqdn(record[:name], domain), Record::resolv_resource_class(record[:type])) end
end
end
def log_test(category, name)
string = "[GloboDns::Tester#{category ? '::' + category : ''}] #{name}:"
yield
string += " ok"
rescue
string += " failed"
ensure
@logger.info string
end
def possible_record_names(name, domain)
fqdn_name = Record::fqdn(name, domain)
fqdn_domain = domain + '.' if domain[-1] != '.'
names = Array.new
names << name
names << fqdn_name if name[-1] != '.'
names << fqdn_domain if name == '@'
names << '@' if fqdn_name == fqdn_domain
names
end
def match_resolve_resources_against_db_records(resources, db_records)
# trivial first check: matching sizes
assert resources.size == db_records.size, "resources and db_records sizes do not match (#{resources.size} = #{db_records.size})"
resources.each do |resource|
# the db_records array should only be empty after the last loop iteration
refute db_records.empty?, "db_records.empty? prematurely (on resource #{resource.inspect})"
# no db_record was found that matches the give resource
refute_nil db_records.reject! { |db_record| db_record.match_resolv_resource(resource) }, "resource #{resource.inspect} found no match"
end
# after the loop is finished, the db_records array should be empty; if it's not,
# it means that one or more resources were not found
assert db_records.empty?, "db_records not empty? #{db_records.inspect}"
end
end # Tester
end # GloboDns
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/globo_dns/util.rb | lib/globo_dns/util.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
module GloboDns
module Util
class ExitStatusError < ::RuntimeError; end
def self.logger=(value)
@@logger = value
end
def self.logger
@@logger ||= Rails.logger
end
# similar to 'Kernel::system', but captures the STDOUT using IO::popen and
# raises and exception if the return code is not '0' (success)
def self.exec(command_id, *args)
output = nil
self.logger.info "[GloboDns::Util::exec] #{args.join(' ')}"
IO::popen(args + [:err => [:child, :out]]) do |io|
output = io.read
end
$?.exitstatus == 0 or raise ExitStatusError.new("[ERROR] '#{command_id}' failed: #{$?} (#{output})")
output
end
# same as 'exec', but don't raise an exception if the exit status is not 0
def self.exec!(command_id, *args)
output = nil
self.logger.info "[GloboDns::Util::exec!] #{args.join(' ')}"
IO::popen(args + [:err => [:child, :out]]) do |io|
output = io.read
end
output
rescue Exception => e
"#{output}\n#{e}\n#{e.backtrace}"
end
def self.exec_as_bind(command_id, *args)
args.unshift(GloboDns::Config::Binaries::SUDO, '-u', GloboDns::Config::BIND_USER)
exec(command_id, *args)
end
def self.exec_as_root(command_id, *args)
args.unshift(GloboDns::Config::Binaries::SUDO)
exec(command_id, *args)
end
def self.last_export_timestamp
Dir.chdir(File.join(GloboDns::Config::Bind::Master::EXPORT_CHROOT_DIR, GloboDns::Config::Bind::Master::ZONES_DIR)) do
Time.at(exec('git last commit date', GloboDns::Config::Binaries::GIT, 'log', '-1', '--format=%at').to_i)
end
end
def self.included(base)
base.send(:include, InstanceMethods)
end
module InstanceMethods
def exec(command_id, *args)
GloboDns::Util::exec(command_id, *args)
end
def exec!(command_id, *args)
GloboDns::Util::exec!(command_id, *args)
end
def exec_as_bind(command_id, *args)
GloboDns::Util::exec_as_bind(command_id, *args)
end
def exec_as_root(command_id, *args)
GloboDns::Util::exec_as_root(command_id, *args)
end
def last_export_timestamp
GloboDns::Util::last_export_timestamp
end
end
end # Util
end # GloboDns
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/globo_dns/importer/named_conf_parser.rb | lib/globo_dns/importer/named_conf_parser.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
# Autogenerated from a Treetop grammar. Edits may be lost.
require File.expand_path('../../../../config/environment', __FILE__)
require File.expand_path('../util', __FILE__)
module NamedConf
include Treetop::Runtime
def root
@root ||= :file
end
module File0
def space1
elements[0]
end
def top_level_directive
elements[1]
end
def space2
elements[2]
end
end
module File1
attr_accessor :chroot_dir
def named_conf
view_keys = views.collect(&:key_name)
str = ''
elements.each do |element|
next unless element.respond_to?(:top_level_directive)
top_level = element.top_level_directive
# skip zones and views
next if is_rule?(top_level, 'zone') ||
is_rule?(top_level, 'view') ||
is_rule?(top_level, 'key') && top_level.respond_to?(:key_name) && view_keys.include?(top_level.key_name.to_s)
str << top_level.text_value << "\n\n"
end
str
end
def views
@views ||= get_views_recursively
end
def domains
@domains ||= get_domains_recursively
end
def directory_option
@directory_option ||= get_directory_option_recursively
end
private
def is_rule?(node, rule_name)
node.extension_modules.include?("NamedConf::#{rule_name.camelize}0".constantize)
end
def get_views_recursively(node = self, views = Array.new)
views << node.view if node.respond_to?(:view)
node.elements.each do |child|
get_views_recursively(child, views) unless child.terminal?
end
views
end
def get_domains_recursively(node = self, domains = Array.new)
node.respond_to?(:view) and return domains
node.respond_to?(:domain) and domains << node.domain
node.elements.each do |child|
get_domains_recursively(child, domains) unless child.terminal?
end
domains
end
def get_directory_option_recursively(node = self)
top_level = elements.find{|e| e.respond_to?(:top_level_directive) && is_rule?(e.top_level_directive, 'options')}
top_level and top_level.top_level_directive.options_statements.elements.find{|e| e.respond_to?(:directory_option)}.try(:directory_option)
end
end
def _nt_file
start_index = index
if node_cache[:file].has_key?(index)
cached = node_cache[:file][index]
if cached
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
@index = cached.interval.end
end
return cached
end
s0, i0 = [], index
loop do
i1, s1 = index, []
r2 = _nt_space
s1 << r2
if r2
r3 = _nt_top_level_directive
s1 << r3
if r3
r4 = _nt_space
s1 << r4
end
end
if s1.last
r1 = instantiate_node(SyntaxNode,input, i1...index, s1)
r1.extend(File0)
else
@index = i1
r1 = nil
end
if r1
s0 << r1
else
break
end
end
if s0.empty?
@index = i0
r0 = nil
else
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
r0.extend(File1)
end
node_cache[:file][start_index] = r0
r0
end
module TopLevelDirective0
end
def _nt_top_level_directive
start_index = index
if node_cache[:top_level_directive].has_key?(index)
cached = node_cache[:top_level_directive][index]
if cached
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
@index = cached.interval.end
end
return cached
end
i0 = index
r1 = _nt_acl
if r1
r0 = r1
r0.extend(TopLevelDirective0)
else
r2 = _nt_controls
if r2
r0 = r2
r0.extend(TopLevelDirective0)
else
r3 = _nt_include_
if r3
r0 = r3
r0.extend(TopLevelDirective0)
else
r4 = _nt_key
if r4
r0 = r4
r0.extend(TopLevelDirective0)
else
r5 = _nt_logging
if r5
r0 = r5
r0.extend(TopLevelDirective0)
else
r6 = _nt_lwres
if r6
r0 = r6
r0.extend(TopLevelDirective0)
else
r7 = _nt_masters
if r7
r0 = r7
r0.extend(TopLevelDirective0)
else
r8 = _nt_options
if r8
r0 = r8
r0.extend(TopLevelDirective0)
else
r9 = _nt_server
if r9
r0 = r9
r0.extend(TopLevelDirective0)
else
r10 = _nt_statistics_channels
if r10
r0 = r10
r0.extend(TopLevelDirective0)
else
r11 = _nt_trusted_keys
if r11
r0 = r11
r0.extend(TopLevelDirective0)
else
r12 = _nt_managed_keys
if r12
r0 = r12
r0.extend(TopLevelDirective0)
else
r13 = _nt_view
if r13
r0 = r13
r0.extend(TopLevelDirective0)
else
r14 = _nt_zone
if r14
r0 = r14
r0.extend(TopLevelDirective0)
else
@index = i0
r0 = nil
end
end
end
end
end
end
end
end
end
end
end
end
end
end
node_cache[:top_level_directive][start_index] = r0
r0
end
module Acl0
def space1
elements[1]
end
def acl_name
elements[2]
end
def space2
elements[3]
end
def space3
elements[5]
end
def acl_statements
elements[6]
end
def space4
elements[7]
end
def space5
elements[9]
end
end
module Acl1
end
def _nt_acl
start_index = index
if node_cache[:acl].has_key?(index)
cached = node_cache[:acl][index]
if cached
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
@index = cached.interval.end
end
return cached
end
i0, s0 = index, []
if has_terminal?('acl', false, index)
r1 = instantiate_node(SyntaxNode,input, index...(index + 3))
@index += 3
else
terminal_parse_failure('acl')
r1 = nil
end
s0 << r1
if r1
r2 = _nt_space
s0 << r2
if r2
r3 = _nt_acl_name
s0 << r3
if r3
r4 = _nt_space
s0 << r4
if r4
if has_terminal?('{', false, index)
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('{')
r5 = nil
end
s0 << r5
if r5
r6 = _nt_space
s0 << r6
if r6
r7 = _nt_acl_statements
s0 << r7
if r7
r8 = _nt_space
s0 << r8
if r8
if has_terminal?('}', false, index)
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('}')
r9 = nil
end
s0 << r9
if r9
r10 = _nt_space
s0 << r10
if r10
if has_terminal?(';', false, index)
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure(';')
r11 = nil
end
s0 << r11
end
end
end
end
end
end
end
end
end
end
if s0.last
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
r0.extend(Acl0)
r0.extend(Acl1)
else
@index = i0
r0 = nil
end
node_cache[:acl][start_index] = r0
r0
end
module Controls0
def space1
elements[1]
end
def space2
elements[3]
end
def controls_statements
elements[4]
end
def space3
elements[5]
end
def space4
elements[7]
end
end
module Controls1
end
def _nt_controls
start_index = index
if node_cache[:controls].has_key?(index)
cached = node_cache[:controls][index]
if cached
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
@index = cached.interval.end
end
return cached
end
i0, s0 = index, []
if has_terminal?('controls', false, index)
r1 = instantiate_node(SyntaxNode,input, index...(index + 8))
@index += 8
else
terminal_parse_failure('controls')
r1 = nil
end
s0 << r1
if r1
r2 = _nt_space
s0 << r2
if r2
if has_terminal?('{', false, index)
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('{')
r3 = nil
end
s0 << r3
if r3
r4 = _nt_space
s0 << r4
if r4
r5 = _nt_controls_statements
s0 << r5
if r5
r6 = _nt_space
s0 << r6
if r6
if has_terminal?('}', false, index)
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('}')
r7 = nil
end
s0 << r7
if r7
r8 = _nt_space
s0 << r8
if r8
if has_terminal?(';', false, index)
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure(';')
r9 = nil
end
s0 << r9
end
end
end
end
end
end
end
end
if s0.last
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
r0.extend(Controls0)
r0.extend(Controls1)
else
@index = i0
r0 = nil
end
node_cache[:controls][start_index] = r0
r0
end
module Include_0
def space1
elements[1]
end
def filename
elements[2]
end
def space2
elements[3]
end
end
def _nt_include_
start_index = index
if node_cache[:include_].has_key?(index)
cached = node_cache[:include_][index]
if cached
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
@index = cached.interval.end
end
return cached
end
i0, s0 = index, []
if has_terminal?('include', false, index)
r1 = instantiate_node(SyntaxNode,input, index...(index + 7))
@index += 7
else
terminal_parse_failure('include')
r1 = nil
end
s0 << r1
if r1
r2 = _nt_space
s0 << r2
if r2
r3 = _nt_filename
s0 << r3
if r3
r4 = _nt_space
s0 << r4
if r4
if has_terminal?(';', false, index)
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure(';')
r5 = nil
end
s0 << r5
end
end
end
end
if s0.last
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
r0.extend(Include_0)
else
@index = i0
r0 = nil
end
node_cache[:include_][start_index] = r0
r0
end
module Key0
def space1
elements[1]
end
def key_name
elements[2]
end
def space2
elements[3]
end
def space3
elements[5]
end
def key_statements
elements[6]
end
def space4
elements[7]
end
def space5
elements[9]
end
end
module Key1
end
def _nt_key
start_index = index
if node_cache[:key].has_key?(index)
cached = node_cache[:key][index]
if cached
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
@index = cached.interval.end
end
return cached
end
i0, s0 = index, []
if has_terminal?('key', false, index)
r1 = instantiate_node(SyntaxNode,input, index...(index + 3))
@index += 3
else
terminal_parse_failure('key')
r1 = nil
end
s0 << r1
if r1
r2 = _nt_space
s0 << r2
if r2
r3 = _nt_key_name
s0 << r3
if r3
r4 = _nt_space
s0 << r4
if r4
if has_terminal?('{', false, index)
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('{')
r5 = nil
end
s0 << r5
if r5
r6 = _nt_space
s0 << r6
if r6
r7 = _nt_key_statements
s0 << r7
if r7
r8 = _nt_space
s0 << r8
if r8
if has_terminal?('}', false, index)
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('}')
r9 = nil
end
s0 << r9
if r9
r10 = _nt_space
s0 << r10
if r10
if has_terminal?(';', false, index)
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure(';')
r11 = nil
end
s0 << r11
end
end
end
end
end
end
end
end
end
end
if s0.last
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
r0.extend(Key0)
r0.extend(Key1)
else
@index = i0
r0 = nil
end
node_cache[:key][start_index] = r0
r0
end
module Logging0
def space1
elements[1]
end
def space2
elements[3]
end
def logging_statements
elements[4]
end
def space3
elements[5]
end
def space4
elements[7]
end
end
module Logging1
end
def _nt_logging
start_index = index
if node_cache[:logging].has_key?(index)
cached = node_cache[:logging][index]
if cached
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
@index = cached.interval.end
end
return cached
end
i0, s0 = index, []
if has_terminal?('logging', false, index)
r1 = instantiate_node(SyntaxNode,input, index...(index + 7))
@index += 7
else
terminal_parse_failure('logging')
r1 = nil
end
s0 << r1
if r1
r2 = _nt_space
s0 << r2
if r2
if has_terminal?('{', false, index)
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('{')
r3 = nil
end
s0 << r3
if r3
r4 = _nt_space
s0 << r4
if r4
r5 = _nt_logging_statements
s0 << r5
if r5
r6 = _nt_space
s0 << r6
if r6
if has_terminal?('}', false, index)
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('}')
r7 = nil
end
s0 << r7
if r7
r8 = _nt_space
s0 << r8
if r8
if has_terminal?(';', false, index)
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure(';')
r9 = nil
end
s0 << r9
end
end
end
end
end
end
end
end
if s0.last
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
r0.extend(Logging0)
r0.extend(Logging1)
else
@index = i0
r0 = nil
end
node_cache[:logging][start_index] = r0
r0
end
module Lwres0
def space1
elements[1]
end
def space2
elements[3]
end
def lwres_statements
elements[4]
end
def space3
elements[5]
end
def space4
elements[7]
end
end
module Lwres1
end
def _nt_lwres
start_index = index
if node_cache[:lwres].has_key?(index)
cached = node_cache[:lwres][index]
if cached
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
@index = cached.interval.end
end
return cached
end
i0, s0 = index, []
if has_terminal?('lwres', false, index)
r1 = instantiate_node(SyntaxNode,input, index...(index + 5))
@index += 5
else
terminal_parse_failure('lwres')
r1 = nil
end
s0 << r1
if r1
r2 = _nt_space
s0 << r2
if r2
if has_terminal?('{', false, index)
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('{')
r3 = nil
end
s0 << r3
if r3
r4 = _nt_space
s0 << r4
if r4
r5 = _nt_lwres_statements
s0 << r5
if r5
r6 = _nt_space
s0 << r6
if r6
if has_terminal?('}', false, index)
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('}')
r7 = nil
end
s0 << r7
if r7
r8 = _nt_space
s0 << r8
if r8
if has_terminal?(';', false, index)
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure(';')
r9 = nil
end
s0 << r9
end
end
end
end
end
end
end
end
if s0.last
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
r0.extend(Lwres0)
r0.extend(Lwres1)
else
@index = i0
r0 = nil
end
node_cache[:lwres][start_index] = r0
r0
end
module Masters0
def space1
elements[1]
end
def masters_name
elements[2]
end
def space2
elements[3]
end
def space3
elements[5]
end
def masters_statements
elements[6]
end
def space4
elements[7]
end
def space5
elements[9]
end
end
module Masters1
end
def _nt_masters
start_index = index
if node_cache[:masters].has_key?(index)
cached = node_cache[:masters][index]
if cached
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
@index = cached.interval.end
end
return cached
end
i0, s0 = index, []
if has_terminal?('masters', false, index)
r1 = instantiate_node(SyntaxNode,input, index...(index + 7))
@index += 7
else
terminal_parse_failure('masters')
r1 = nil
end
s0 << r1
if r1
r2 = _nt_space
s0 << r2
if r2
r3 = _nt_masters_name
s0 << r3
if r3
r4 = _nt_space
s0 << r4
if r4
if has_terminal?('{', false, index)
r5 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('{')
r5 = nil
end
s0 << r5
if r5
r6 = _nt_space
s0 << r6
if r6
r7 = _nt_masters_statements
s0 << r7
if r7
r8 = _nt_space
s0 << r8
if r8
if has_terminal?('}', false, index)
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('}')
r9 = nil
end
s0 << r9
if r9
r10 = _nt_space
s0 << r10
if r10
if has_terminal?(';', false, index)
r11 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure(';')
r11 = nil
end
s0 << r11
end
end
end
end
end
end
end
end
end
end
if s0.last
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
r0.extend(Masters0)
r0.extend(Masters1)
else
@index = i0
r0 = nil
end
node_cache[:masters][start_index] = r0
r0
end
module Options0
def space1
elements[1]
end
def space2
elements[3]
end
def options_statements
elements[4]
end
def space3
elements[5]
end
def space4
elements[7]
end
end
module Options1
end
def _nt_options
start_index = index
if node_cache[:options].has_key?(index)
cached = node_cache[:options][index]
if cached
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
@index = cached.interval.end
end
return cached
end
i0, s0 = index, []
if has_terminal?('options', false, index)
r1 = instantiate_node(SyntaxNode,input, index...(index + 7))
@index += 7
else
terminal_parse_failure('options')
r1 = nil
end
s0 << r1
if r1
r2 = _nt_space
s0 << r2
if r2
if has_terminal?('{', false, index)
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('{')
r3 = nil
end
s0 << r3
if r3
r4 = _nt_space
s0 << r4
if r4
r5 = _nt_options_statements
s0 << r5
if r5
r6 = _nt_space
s0 << r6
if r6
if has_terminal?('}', false, index)
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('}')
r7 = nil
end
s0 << r7
if r7
r8 = _nt_space
s0 << r8
if r8
if has_terminal?(';', false, index)
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure(';')
r9 = nil
end
s0 << r9
end
end
end
end
end
end
end
end
if s0.last
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
r0.extend(Options0)
r0.extend(Options1)
else
@index = i0
r0 = nil
end
node_cache[:options][start_index] = r0
r0
end
module Server0
def ipaddr_prefix_length
elements[1]
end
end
module Server1
def space1
elements[1]
end
def server_ipaddr
elements[2]
end
def space2
elements[4]
end
def space3
elements[6]
end
def server_statements
elements[7]
end
def space4
elements[8]
end
def space5
elements[10]
end
end
module Server2
end
def _nt_server
start_index = index
if node_cache[:server].has_key?(index)
cached = node_cache[:server][index]
if cached
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
@index = cached.interval.end
end
return cached
end
i0, s0 = index, []
if has_terminal?('server', false, index)
r1 = instantiate_node(SyntaxNode,input, index...(index + 6))
@index += 6
else
terminal_parse_failure('server')
r1 = nil
end
s0 << r1
if r1
r2 = _nt_space
s0 << r2
if r2
r3 = _nt_server_ipaddr
s0 << r3
if r3
i5, s5 = index, []
if has_terminal?('/', false, index)
r6 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('/')
r6 = nil
end
s5 << r6
if r6
r7 = _nt_ipaddr_prefix_length
s5 << r7
end
if s5.last
r5 = instantiate_node(SyntaxNode,input, i5...index, s5)
r5.extend(Server0)
else
@index = i5
r5 = nil
end
if r5
r4 = r5
else
r4 = instantiate_node(SyntaxNode,input, index...index)
end
s0 << r4
if r4
r8 = _nt_space
s0 << r8
if r8
if has_terminal?('{', false, index)
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('{')
r9 = nil
end
s0 << r9
if r9
r10 = _nt_space
s0 << r10
if r10
r11 = _nt_server_statements
s0 << r11
if r11
r12 = _nt_space
s0 << r12
if r12
if has_terminal?('}', false, index)
r13 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('}')
r13 = nil
end
s0 << r13
if r13
r14 = _nt_space
s0 << r14
if r14
if has_terminal?(';', false, index)
r15 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure(';')
r15 = nil
end
s0 << r15
end
end
end
end
end
end
end
end
end
end
end
if s0.last
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
r0.extend(Server1)
r0.extend(Server2)
else
@index = i0
r0 = nil
end
node_cache[:server][start_index] = r0
r0
end
module StatisticsChannels0
def space1
elements[1]
end
def space2
elements[3]
end
def statistics_channels_statements
elements[4]
end
def space3
elements[5]
end
def space4
elements[7]
end
end
module StatisticsChannels1
end
def _nt_statistics_channels
start_index = index
if node_cache[:statistics_channels].has_key?(index)
cached = node_cache[:statistics_channels][index]
if cached
cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
@index = cached.interval.end
end
return cached
end
i0, s0 = index, []
if has_terminal?('statistics-channels', false, index)
r1 = instantiate_node(SyntaxNode,input, index...(index + 19))
@index += 19
else
terminal_parse_failure('statistics-channels')
r1 = nil
end
s0 << r1
if r1
r2 = _nt_space
s0 << r2
if r2
if has_terminal?('{', false, index)
r3 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('{')
r3 = nil
end
s0 << r3
if r3
r4 = _nt_space
s0 << r4
if r4
r5 = _nt_statistics_channels_statements
s0 << r5
if r5
r6 = _nt_space
s0 << r6
if r6
if has_terminal?('}', false, index)
r7 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure('}')
r7 = nil
end
s0 << r7
if r7
r8 = _nt_space
s0 << r8
if r8
if has_terminal?(';', false, index)
r9 = instantiate_node(SyntaxNode,input, index...(index + 1))
@index += 1
else
terminal_parse_failure(';')
r9 = nil
end
s0 << r9
end
end
end
end
end
end
end
end
if s0.last
r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
r0.extend(StatisticsChannels0)
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | true |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/lib/globo_dns/importer/util.rb | lib/globo_dns/importer/util.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
String.class_eval do
def strip_quotes
self.sub(/^['"]?(.*?)['"]?$/, '\1')
end
end
Citrus::Match.class_eval do
def delete_from(parent)
captures.clear
matches.clear
puts "indeed! parent.matches includes it!" if parent.matches.include?(self)
parent.matches.delete(self)
parent.captures.each do |key, value|
puts "indeed! parent.captures[#{key}] is it!" if value.object_id == self.object_id
parent.captures[key] = value = nil if value.object_id == self.object_id
puts "indeed! parent.captures[#{key}] includes it!" if value.is_a?(Array) && value.include?(self)
parent.captures[key].delete(self) if value.is_a?(Array) && value.include?(self)
end
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/application.rb | config/application.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module GloboDns
class Application < Rails::Application
# Set if the application uses OmniAuth or not
config.omniauth = false
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
config.autoload_paths += %W( #{config.root}/lib )
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
# config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
config.assets.paths << Rails.root.join('vendor', 'assets', 'fonts')
config.assets.precompile << /\.(?:svg|eot|woff|ttf)$/
# application version
version_file_name = File.expand_path('../../REVISION', __FILE__)
puts "Reading version on #{version_file_name}"
if File.exists? version_file_name
config.app_version = File.read(version_file_name).strip
else
config.app_version = 'DEVELOPMENT'
end
puts "Application version is '#{config.app_version}'"
# Version of your assets, change this if you want to expire all your assets
config.assets.version = config.app_version
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/environment.rb | config/environment.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
# Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
GloboDns::Application.initialize!
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/routes.rb | config/routes.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
GloboDns::Application.routes.draw do
get 'access_denied/new'
get 'access_denied/create'
get "access_denied" => "access_denied#show", as: :access_denied
if GloboDns::Application.config.omniauth
devise_for :users, :controllers => { :omniauth_callbacks => 'omniauth_callbacks'}
resources :views
resources :users
devise_scope :users do
match 'users/sign_in' => 'access_denied#show', via: [:get, :post]
# get 'auth/sign_in' => redirect('users/auth/oauthprovider'), :as => :new_user_session
get 'auth/sign_out', :to => 'application#logout', :as => :destroy_user_session
end
else
devise_for :users, :controllers => { :sessions => 'sessions' }
resources :views
resources :users
# devise_scope :user do
resource :user do
get 'update_password' => 'users#update_password', :as => 'update_password'
put 'update_password/save' => 'users#save_password_update', :as => 'save_password_update'
end
end
resources :domains do
get 'update_domain_owner', :on => :member
resources :records, :shallow => true do
get 'update_domain_owner', :on => :member
get 'resolve', :on => :member
get 'verify_owner', :on => :member
end
end
resources :domain_templates do
resources :record_templates, :shallow => true
end
scope 'bind9', :as => 'bind9', :controller => 'bind9' do
get '', :action => 'index'
get 'config', :action => 'configuration'
post 'export'
post 'schedule_export'
end
match '/audits(/:action(/:id))' => 'audits#index', :as => :audits, :via => :get
root :to => 'dashboard#index'
get 'healthcheck' => lambda { |env| [200, {"Content-Type" => "text/plain"}, ["WORKING"]] }
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/unicorn.rb | config/unicorn.rb | # Sample verbose configuration file for Unicorn (not Rack)
#
# This configuration file documents many features of Unicorn
# that may not be needed for some applications. See
# http://unicorn.bogomips.org/examples/unicorn.conf.minimal.rb
# for a much simpler configuration file.
#
# See http://unicorn.bogomips.org/Unicorn/Configurator.html for complete
# documentation.
# Use at least one worker per core if you're on a dedicated server,
# more will usually help for _short_ waits on databases/caches.
worker_processes 4
# Since Unicorn is never exposed to outside clients, it does not need to
# run on the standard HTTP port (80), there is no reason to start Unicorn
# as root unless it's from system init scripts.
# If running the master process as root and the workers as an unprivileged
# user, do this to switch euid/egid in the workers (also chowns logs):
# user "unprivileged_user", "unprivileged_group"
# Help ensure your application will always spawn in the symlinked
# "current" directory that Capistrano sets up.
# working_directory "/path/to/app/current" # available in 0.94.0+
# listen on both a Unix domain socket and a TCP port,
# we use a shorter backlog for quicker failover when busy
# listen "/path/to/.unicorn.sock", :backlog => 64
listen 3000, :tcp_nopush => true
# nuke workers after 30 seconds instead of 60 seconds (the default)
timeout 600
# feel free to point this anywhere accessible on the filesystem
# pid "/path/to/app/shared/pids/unicorn.pid"
# By default, the Unicorn logger will write to stderr.
# Additionally, ome applications/frameworks log to stderr or stdout,
# so prevent them from going to /dev/null when daemonized here:
# stderr_path "log/unicorn.stderr.log"
# stdout_path "log/unicorn.stdout.log"
# combine Ruby 2.0.0dev or REE with "preload_app true" for memory savings
# http://rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
preload_app true
GC.respond_to?(:copy_on_write_friendly=) and
GC.copy_on_write_friendly = true
# Enable this flag to have unicorn test client connections by writing the
# beginning of the HTTP headers before calling the application. This
# prevents calling the application for connections that have disconnected
# while queued. This is only guaranteed to detect clients on the same
# host unicorn runs on, and unlikely to detect disconnects even on a
# fast LAN.
check_client_connection false
# local variable to guard against running a hook multiple times
run_once = true
before_fork do |server, worker|
# the following is highly recomended for Rails + "preload_app true"
# as there's no need for the master process to hold a connection
defined?(ActiveRecord::Base) and
ActiveRecord::Base.connection.disconnect!
# Occasionally, it may be necessary to run non-idempotent code in the
# master before forking. Keep in mind the above disconnect! example
# is idempotent and does not need a guard.
if run_once
# do_something_once_here ...
run_once = false # prevent from firing again
end
# The following is only recommended for memory/DB-constrained
# installations. It is not needed if your system can house
# twice as many worker_processes as you have configured.
#
# # This allows a new master process to incrementally
# # phase out the old master process with SIGTTOU to avoid a
# # thundering herd (especially in the "preload_app false" case)
# # when doing a transparent upgrade. The last worker spawned
# # will then kill off the old master process with a SIGQUIT.
# old_pid = "#{server.config[:pid]}.oldbin"
# if old_pid != server.pid
# begin
# sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
# Process.kill(sig, File.read(old_pid).to_i)
# rescue Errno::ENOENT, Errno::ESRCH
# end
# end
#
# Throttle the master from forking too quickly by sleeping. Due
# to the implementation of standard Unix signal handlers, this
# helps (but does not completely) prevent identical, repeated signals
# from being lost when the receiving process is busy.
# sleep 1
end
after_fork do |server, worker|
# per-process listener ports for debugging/admin/migrations
# addr = "127.0.0.1:#{9293 + worker.nr}"
# server.listen(addr, :tries => -1, :delay => 5, :tcp_nopush => true)
# the following is *required* for Rails + "preload_app true",
defined?(ActiveRecord::Base) and
ActiveRecord::Base.establish_connection
# if preload_app is true, then you may also want to check and
# restart any other shared sockets/descriptors such as Memcached,
# and Redis. TokyoCabinet file handles are safe to reuse
# between any number of forked children (assuming your kernel
# correctly implements pread()/pwrite() system calls)
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/boot.rb | config/boot.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'rubygems'
# Set up gems listed in the Gemfile.
gemfile = File.expand_path('../../Gemfile', __FILE__)
begin
ENV['BUNDLE_GEMFILE'] = gemfile
require 'bundler'
Bundler.setup
rescue Bundler::GemNotFound => e
STDERR.puts e.message
STDERR.puts "Try running `bundle install`."
exit!
end if File.exist?(gemfile)
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/initializers/syslogger.rb | config/initializers/syslogger.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
Rails.class_eval do
def self.syslogger
@logger ||= Syslogger.new('globodns', Syslog::LOG_PID | Syslog::LOG_CONS, Syslog::LOG_LOCAL0)
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/initializers/session_store.rb | config/initializers/session_store.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
# Be sure to restart your server when you modify this file.
GloboDns::Application.config.session_store :cookie_store, :key => '_globodns_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# GlobDns::Application.config.session_store :active_record_store
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/initializers/devise.rb | config/initializers/devise.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# omni_auth = true
omni_auth = false
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class with default "from" parameter.
config.mailer_sender = "globodns@example.com"
# Configure the class responsible to send e-mails.
# config.mailer = "Devise::Mailer"
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
config.authentication_keys = [ :email ] if omni_auth
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
config.params_authenticatable = true unless GloboDns::Application.config.omniauth
# Tell if authentication through HTTP Basic Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:token]` will
# enable it only for token authentication.
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. "Application" by default.
# config.http_authentication_realm = "Application"
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# :http_auth and :token_auth by adding those symbols to the array below.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing :skip => :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
config.pepper = "800d3e9a2d7e489579b8407eefd17820c7a9c38af7387154ae2ba77b9462e3c7570620a7d9f383385bc55f33af522f1161182de340a0c78eed60dae4c8700b83"
config.secret_key = '72cebbf8a3326292f993bcee6584399f5237b2e459056b1c715d4716bf8932ba2cad9c75f66a6d70cff426218f2e70bcb6c6148720c59ea9ac8a3592dfb92623'
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming his account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming his account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming his account.
# config.allow_unconfirmed_access_for = 2.days
# If true, requires any email changes to be confirmed (exctly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed new email is stored in
# unconfirmed email column, and copied to email column on successful confirmation.
# config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# If true, uses the password salt as remember token. This should be turned
# to false if you are not using database authenticatable.
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.cookie_options = {}
# ==> Configuration for :validatable
# Range for password length. Default is 6..128.
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# an one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^@]+@[^@]+\z/ unless GloboDns::Application.config.omniauth
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper)
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable
# Defines name of the authentication token params key
# config.token_authentication_key = :auth_token
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Configure sign_out behavior.
# Sign_out action can be scoped (i.e. /users/sign_out affects only :user scope).
# The default is true, which means any logout action will sign out all active scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ["*/*", :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :some_external_strategy
# end
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/auth'
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/initializers/new_rails_defaults.rb | config/initializers/new_rails_defaults.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
# Be sure to restart your server when you modify this file.
# These settings change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.
if defined?(ActiveRecord)
# Include Active Record class name as root for JSON serialized output.
ActiveRecord::Base.include_root_in_json = true
# Store the full class name (including module namespace) in STI type column.
ActiveRecord::Base.store_full_sti_class = true
end
# Use ISO 8601 format for JSON serialized times and dates.
ActiveSupport.use_standard_json_time_format = true
# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
# if you're including raw json in an HTML page.
ActiveSupport.escape_html_entities_in_json = false
# Disable SQL logging
ActiveRecord::Base.logger.level = Logger::INFO
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/initializers/omniauth.rb | config/initializers/omniauth.rb | # OmniAuth.config.logger = Rails.logger
# Rails.application.config.middleware.use OmniAuth::Builder do
# provider :oauth_provider,
# Rails.application.secrets.oauth_provider_client_id,
# Rails.application.secrets.oauth_provider_client_secret,
# {provider_ignores_state: true, environment: Rails.env}
# end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/initializers/inflections.rb | config/initializers/inflections.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/initializers/globodns.rb | config/initializers/globodns.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
require 'globo_dns/config'
GloboDns::Config::load_from_file(Rails.root.join('config', 'globodns.yml'))
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/initializers/define_enum.rb | config/initializers/define_enum.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
ActiveRecord::Base.class_eval do
def self.define_enum(attribute, symbols, values = nil)
define_method((attribute.to_s + '_str').to_sym) { self.class.const_get(attribute.to_s.pluralize.upcase.to_sym)[self.send(attribute)] }
values ||= symbols.collect{|symbol| symbol.to_s[0]}
symbols.zip(values).inject(Hash.new) do |hash, (enum_sym, enum_value)|
enum_str = enum_sym.to_s
value = enum_value
hash[value] = enum_str
const_set(enum_sym, value)
define_method(enum_str.downcase + '?') { self.send(attribute) == value }
define_method(enum_str.downcase + '!') { self.send((attribute.to_s + '=').to_sym, value) }
hash
end.freeze
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/initializers/override_active_record_becomes.rb | config/initializers/override_active_record_becomes.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
# see https://github.com/rails/rails/pull/3023
ActiveRecord::Base.class_eval do
# Returns an instance of the specified +klass+ with the attributes of the
# current record. This is mostly useful in relation to single-table
# inheritance structures where you want a subclass to appear as the
# superclass. This can be used along with record identification in
# Action Pack to allow, say, <tt>Client < Company</tt> to do something
# like render <tt>:partial => @client.becomes(Company)</tt> to render that
# instance using the companies/company partial instead of clients/client.
#
# Note: The new instance will share a link to the same attributes as the original class.
# So any change to the attributes in either instance will affect the other.
def becomes(klass)
became = klass.new
became.instance_variable_set("@attributes", @attributes)
became.instance_variable_set("@attributes_cache", @attributes_cache)
became.instance_variable_set("@new_record", new_record?)
became.instance_variable_set("@destroyed", destroyed?)
became.instance_variable_set("@errors", errors)
became
end
# Wrapper around +becomes+ that also changes the instance's sti column value.
# This is especially useful if you want to persist the changed class in your
# database.
#
# Note: The old instance's sti column value will be changed too, as both objects
# share the same set of attributes.
def becomes!(klass)
became = becomes(klass)
became.send("#{klass.inheritance_column}=", klass.sti_name) unless self.class.descends_from_active_record?
became
end
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/initializers/backtrace_silencers.rb | config/initializers/backtrace_silencers.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
# Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/initializers/mime_types.rb | config/initializers/mime_types.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/initializers/secret_token.rb | config/initializers/secret_token.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
# Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
GloboDns::Application.config.secret_token = ENV["SECRET_KEY_BASE"]
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/environments/test.rb | config/environments/test.rb | ertando configu# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
GloboDns::Application.configure do
# Settings specified here will take precedence over those in config/environment.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# config.eager_load required for Devise version 3.5.6
config.eager_load = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Use a different logger for distributed setups
config.logger = Syslogger.new('globodns', Syslog::LOG_PID | Syslog::LOG_CONS, Syslog::LOG_LOCAL0)
# See everything in the log (default is :info)
config.logger.level = Logger::DEBUG
config.log_level = :debug
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_files = false # used on Rails 5.0
config.static_cache_control = "public, max-age=3600"
# Allow pass debug_assets=true as a query parameter to load pages with unpackaged assets
config.assets.allow_debugging = true
# Default host for testing mail
config.action_mailer.default_url_options = { :host => "example.com" }
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/environments/cucumber.rb | config/environments/cucumber.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
config.cache_classes = true # This must be true for Cucumber to operate correctly!
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
config.gem "cucumber", :lib => false, :version => ">=0.3.11" unless File.directory?(File.join(Rails.root, 'vendor/plugins/cucumber'))
config.gem "webrat", :lib => false, :version => ">=0.4.4" unless File.directory?(File.join(Rails.root, 'vendor/plugins/webrat'))
config.gem "rspec", :lib => false, :version => ">=1.2.6" unless File.directory?(File.join(Rails.root, 'vendor/plugins/rspec'))
config.gem "rspec-rails", :lib => 'spec/rails', :version => ">=1.2.6" unless File.directory?(File.join(Rails.root, 'vendor/plugins/rspec-rails'))
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/environments/development.rb | config/environments/development.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
GloboDns::Application.configure do
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
config.eager_load = false
config.logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
# See everything in the log (default is :info)
config.logger.level = Logger::DEBUG
config.log_level = :debug
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
# Localhost default for devise
config.action_mailer.default_url_options = { :host => 'localhost' }
config.autoload_paths += %W(#{config.root}/lib)
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
globocom/GloboDNS | https://github.com/globocom/GloboDNS/blob/d745871945c76cd26a8c926873b59690ef1ea5a7/config/environments/production.rb | config/environments/production.rb | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
GloboDns::Application.configure do
# 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
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
# Specifies the header that your server uses for sending files
config.action_dispatch.x_sendfile_header = "X-Sendfile"
config.time_zone = 'Brasilia'
config.active_record.default_timezone = :local
# 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
# Use a different logger for distributed setups
app_config = YAML::load_file Rails.root.join("config", "globodns.yml")
app_name = app_config[Rails.env]['appname'] || "globodns"
config.logger = Syslogger.new(app_name, Syslog::LOG_PID | Syslog::LOG_CONS, Syslog::LOG_LOCAL3)
# See everything in the log (default is :info)
config.logger.level = Logger::DEBUG
config.log_level = :debug
# 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_files = true # used on Rails 5.0
# 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
# 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
# Compress JavaScript and CSS
config.assets.compress = true
# Don't fallback to assets pipeline
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
end
| ruby | Apache-2.0 | d745871945c76cd26a8c926873b59690ef1ea5a7 | 2026-01-04T17:43:23.539268Z | false |
jqr/php-serialize | https://github.com/jqr/php-serialize/blob/68c0b6f9a20c07d7498d3bce62a37f1e240eddfe/benchmark.rb | benchmark.rb | $:.push(File.dirname(__FILE__) + '/lib')
require 'php_serialize'
require 'benchmark'
TIMES = 10000
value1 = {[1, 2, 5] * 10 => {'b' * 40 => [1, 2, 'Hello world' * 200, {'c' => 33}]}}
value2 = {'125' * 10 => {'b' * 40 => [1, 2, 'Hello world' * 200, {'c' => 33}]}}
php1 = PHP.serialize(value1)
php2 = PHP.serialize_session(value2)
if value1 != PHP.unserialize(php1) || value2 != PHP.unserialize(php2)
raise "serializer broken"
end
Benchmark.bmbm do |x|
x.report("regular") do
TIMES.times do
PHP.unserialize(php1)
end
end
x.report("session") do
TIMES.times do
PHP.unserialize(php2)
end
end
end | ruby | MIT | 68c0b6f9a20c07d7498d3bce62a37f1e240eddfe | 2026-01-04T17:48:15.410864Z | false |
jqr/php-serialize | https://github.com/jqr/php-serialize/blob/68c0b6f9a20c07d7498d3bce62a37f1e240eddfe/test/php_serialize_test.rb | test/php_serialize_test.rb | #!/usr/local/bin/ruby
# encoding: utf-8
require 'test/unit'
$:.unshift File.join(File.dirname(__FILE__), 'lib')
require 'php_serialize'
TestStruct = Struct.new(:name, :value)
class TestClass
attr_accessor :name
attr_accessor :value
def initialize(name = nil, value = nil)
@name = name
@value = value
end
def to_assoc
[['name', @name], ['value', @value]]
end
def ==(other)
other.class == self.class and other.name == @name and other.value == @value
end
end
ClassMap = {
TestStruct.name.capitalize.intern => TestStruct,
TestClass.name.capitalize.intern => TestClass
}
class TestPhpSerialize < Test::Unit::TestCase
def self.test(ruby, php, opts = {})
if opts[:name]
name = opts[:name]
else
name = ruby.to_s
end
define_method("test_#{name}".intern) do
assert_nothing_thrown do
serialized = PHP.serialize(ruby)
assert_equal php, serialized
unserialized = PHP.unserialize(serialized, ClassMap)
case ruby
when Symbol
assert_equal ruby.to_s, unserialized
else
assert_equal ruby, unserialized
end
end
end
end
test nil, 'N;'
test false, 'b:0;'
test true, 'b:1;'
test 42, 'i:42;'
test(-42, 'i:-42;')
test 2147483647, "i:2147483647;", :name => 'Max Fixnum'
test(-2147483648, "i:-2147483648;", :name => 'Min Fixnum')
test 4.2, 'd:4.2;'
test 'test', 's:4:"test";'
test :test, 's:4:"test";', :name => 'Symbol'
test "\"\n\t\"", "s:4:\"\"\n\t\"\";", :name => 'Complex string'
test [nil, true, false, 42, 4.2, 'test'], 'a:6:{i:0;N;i:1;b:1;i:2;b:0;i:3;i:42;i:4;d:4.2;i:5;s:4:"test";}',
:name => 'Array'
test({'foo' => 'bar', 4 => [5,4,3,2]}, 'a:2:{s:3:"foo";s:3:"bar";i:4;a:4:{i:0;i:5;i:1;i:4;i:2;i:3;i:3;i:2;}}', :name => 'Hash')
test TestStruct.new("Foo", 65), 'O:10:"teststruct":2:{s:4:"name";s:3:"Foo";s:5:"value";i:65;}',
:name => 'Struct'
test TestClass.new("Foo", 65), 'O:9:"testclass":2:{s:4:"name";s:3:"Foo";s:5:"value";i:65;}',
:name => 'Class'
# PHP counts multibyte string, not string length
def test_multibyte_string
assert_equal "s:6:\"öäü\";", PHP.serialize("öäü")
assert_equal PHP.unserialize("s:6:\"öäü\";"), "öäü"
end
# Verify assoc is passed down calls.
# Slightly awkward because hashes don't guarantee order.
def test_assoc
assert_nothing_raised do
ruby = {'foo' => ['bar','baz'], 'hash' => {'hash' => 'smoke'}}
ruby_assoc = [['foo', ['bar','baz']], ['hash', [['hash','smoke']]]]
phps = [
'a:2:{s:4:"hash";a:1:{s:4:"hash";s:5:"smoke";}s:3:"foo";a:2:{i:0;s:3:"bar";i:1;s:3:"baz";}}',
'a:2:{s:3:"foo";a:2:{i:0;s:3:"bar";i:1;s:3:"baz";}s:4:"hash";a:1:{s:4:"hash";s:5:"smoke";}}'
]
serialized = PHP.serialize(ruby, true)
assert phps.include?(serialized)
unserialized = PHP.unserialize(serialized, true)
assert_equal ruby_assoc.sort, unserialized.sort
end
end
# Multibyte version.
# Verify assoc is passed down calls.
# Slightly awkward because hashes don't guarantee order.
def test_assoc_multibyte
assert_nothing_raised do
ruby = {'ああ' => ['öäü','漢字'], 'hash' => {'おはよう' => 'smoke'}}
ruby_assoc = [['ああ', ['öäü','漢字']], ['hash', [['おはよう','smoke']]]]
phps = [
'a:2:{s:6:"ああ";a:2:{i:0;s:6:"öäü";i:1;s:6:"漢字";}s:4:"hash";a:1:{s:12:"おはよう";s:5:"smoke";}}',
'a:2:{s:4:"hash";a:1:{s:12:"おはよう";s:5:"smoke";}s:6:"ああ";a:2:{i:0;s:6:"öäü";i:1;s:6:"漢字";}}'
]
serialized = PHP.serialize(ruby, true)
assert phps.include?(serialized)
unserialized = PHP.unserialize(serialized, true)
assert_equal ruby_assoc.sort, unserialized.sort
end
end
def test_sessions
assert_nothing_raised do
ruby = {'session_id' => 42, 'user_data' => {'uid' => 666}}
phps = [
'session_id|i:42;user_data|a:1:{s:3:"uid";i:666;}',
'user_data|a:1:{s:3:"uid";i:666;}session_id|i:42;'
]
unserialized = PHP.unserialize(phps.first)
assert_equal ruby, unserialized
serialized = PHP.serialize_session(ruby)
assert phps.include?(serialized)
end
end
def test_new_struct_creation
assert_nothing_raised do
phps = 'O:8:"stdClass":2:{s:3:"url";s:17:"/legacy/index.php";s:8:"dateTime";s:19:"2012-10-24 22:29:13";}'
PHP.unserialize(phps)
end
end
def test_encoding_kept
s = String.new('s:3:"abc";', encoding: "ISO-8859-1")
assert_equal "ISO-8859-1", s.encoding.name
PHP.unserialize(s)
assert_equal "ISO-8859-1", s.encoding.name
end
end
| ruby | MIT | 68c0b6f9a20c07d7498d3bce62a37f1e240eddfe | 2026-01-04T17:48:15.410864Z | false |
jqr/php-serialize | https://github.com/jqr/php-serialize/blob/68c0b6f9a20c07d7498d3bce62a37f1e240eddfe/lib/php-serialize.rb | lib/php-serialize.rb | # Bunlder auto requires the gemname, so we redirect to the right file.
require "php_serialize"
| ruby | MIT | 68c0b6f9a20c07d7498d3bce62a37f1e240eddfe | 2026-01-04T17:48:15.410864Z | false |
jqr/php-serialize | https://github.com/jqr/php-serialize/blob/68c0b6f9a20c07d7498d3bce62a37f1e240eddfe/lib/php_serialize.rb | lib/php_serialize.rb | # frozen_string_literal: true
require 'stringio'
module PHP
class StringIOReader < StringIO
# Reads data from the buffer until +char+ is found. The
# returned string will include +char+.
def read_until(char)
val, cpos = '', pos
if idx = string.index(char, cpos)
val = read(idx - cpos + 1)
end
val
end
end
# Returns a string representing the argument in a form PHP.unserialize
# and PHP's unserialize() should both be able to load.
#
# string = PHP.serialize(mixed var[, bool assoc])
#
# Array, Hash, Fixnum, Float, True/FalseClass, NilClass, String and Struct
# are supported; as are objects which support the to_assoc method, which
# returns an array of the form [['attr_name', 'value']..]. Anything else
# will raise a TypeError.
#
# If 'assoc' is specified, Array's who's first element is a two value
# array will be assumed to be an associative array, and will be serialized
# as a PHP associative array rather than a multidimensional array.
def PHP.serialize(var, assoc = false) # {{{
s = String.new
case var
when Array
s << "a:#{var.size}:{"
if assoc and var.first.is_a?(Array) and var.first.size == 2
var.each { |k,v|
s << PHP.serialize(k, assoc) << PHP.serialize(v, assoc)
}
else
var.each_with_index { |v,i|
s << "i:#{i};#{PHP.serialize(v, assoc)}"
}
end
s << '}'
when Hash
s << "a:#{var.size}:{"
var.each do |k,v|
s << "#{PHP.serialize(k, assoc)}#{PHP.serialize(v, assoc)}"
end
s << '}'
when Struct
# encode as Object with same name
s << "O:#{var.class.to_s.bytesize}:\"#{var.class.to_s.downcase}\":#{var.members.length}:{"
var.members.each do |member|
s << "#{PHP.serialize(member, assoc)}#{PHP.serialize(var[member], assoc)}"
end
s << '}'
when String, Symbol
s << "s:#{var.to_s.bytesize}:\"#{var.to_s}\";"
when Integer
s << "i:#{var};"
when Float
s << "d:#{var};"
when NilClass
s << 'N;'
when FalseClass, TrueClass
s << "b:#{var ? 1 : 0};"
else
if var.respond_to?(:to_assoc)
v = var.to_assoc
# encode as Object with same name
s << "O:#{var.class.to_s.bytesize}:\"#{var.class.to_s.downcase}\":#{v.length}:{"
v.each do |k,v|
s << "#{PHP.serialize(k.to_s, assoc)}#{PHP.serialize(v, assoc)}"
end
s << '}'
else
raise TypeError, "Unable to serialize type #{var.class}"
end
end
s
end # }}}
# Like PHP.serialize, but only accepts a Hash or associative Array as the root
# type. The results are returned in PHP session format.
#
# string = PHP.serialize_session(mixed var[, bool assoc])
def PHP.serialize_session(var, assoc = false) # {{{
s = String.new
case var
when Hash
var.each do |key,value|
if key.to_s.include?('|')
raise IndexError, "Top level names may not contain pipes"
end
s << "#{key}|#{PHP.serialize(value, assoc)}"
end
when Array
var.each do |x|
case x
when Array
if x.size == 2
s << "#{x[0]}|#{PHP.serialize(x[1])}"
else
raise TypeError, "Array is not associative"
end
end
end
else
raise TypeError, "Unable to serialize sessions with top level types other than Hash and associative Array"
end
s
end # }}}
# Returns an object containing the reconstituted data from serialized.
#
# mixed = PHP.unserialize(string serialized, [hash classmap, [bool assoc]])
#
# If a PHP array (associative; like an ordered hash) is encountered, it
# scans the keys; if they're all incrementing integers counting from 0,
# it's unserialized as an Array, otherwise it's unserialized as a Hash.
# Note: this will lose ordering. To avoid this, specify assoc=true,
# and it will be unserialized as an associative array: [[key,value],...]
#
# If a serialized object is encountered, the hash 'classmap' is searched for
# the class name (as a symbol). Since PHP classnames are not case-preserving,
# this *must* be a .capitalize()d representation. The value is expected
# to be the class itself; i.e. something you could call .new on.
#
# If it's not found in 'classmap', the current constant namespace is searched,
# and failing that, a new Struct(classname) is generated, with the arguments
# for .new specified in the same order PHP provided; since PHP uses hashes
# to represent attributes, this should be the same order they're specified
# in PHP, but this is untested.
#
# each serialized attribute is sent to the new object using the respective
# {attribute}=() method; you'll get a NameError if the method doesn't exist.
#
# Array, Hash, Fixnum, Float, True/FalseClass, NilClass and String should
# be returned identically (i.e. foo == PHP.unserialize(PHP.serialize(foo))
# for these types); Struct should be too, provided it's in the namespace
# Module.const_get within unserialize() can see, or you gave it the same
# name in the Struct.new(<structname>), otherwise you should provide it in
# classmap.
#
# Note: StringIO is required for unserialize(); it's loaded as needed
def PHP.unserialize(string, classmap = nil, assoc = false) # {{{
if classmap == true or classmap == false
assoc = classmap
classmap = {}
end
classmap ||= {}
ret = nil
original_encoding = string.encoding
string = StringIOReader.new(string.dup.force_encoding('BINARY'))
while string.string[string.pos, 32] =~ /^(\w+)\|/ # session_name|serialized_data
ret ||= {}
string.pos += $&.size
ret[$1] = PHP.do_unserialize(string, classmap, assoc, original_encoding)
end
ret || PHP.do_unserialize(string, classmap, assoc, original_encoding)
end
private
def PHP.do_unserialize(string, classmap, assoc, original_encoding)
val = nil
# determine a type
type = string.read(2)[0,1]
case type
when 'a' # associative array, a:length:{[index][value]...}
count = string.read_until('{').to_i
val = Array.new
count.times do |i|
val << [do_unserialize(string, classmap, assoc, original_encoding), do_unserialize(string, classmap, assoc, original_encoding)]
end
string.read(1) # skip the ending }
# now, we have an associative array, let's clean it up a bit...
# arrays have all numeric indexes, in order; otherwise we assume a hash
array = true
i = 0
val.each do |key,_|
if key != i # wrong index -> assume hash
array = false
break
end
i += 1
end
val = val.map { |tuple|
tuple.map { |it|
it.kind_of?(String) ? it.force_encoding(original_encoding) : it
}
}
if array
val.map! {|_,value| value }
elsif !assoc
val = Hash[val]
end
when 'O' # object, O:length:"class":length:{[attribute][value]...}
# class name (lowercase in PHP, grr)
len = string.read_until(':').to_i + 3 # quotes, seperator
klass = string.read(len)[1...-2].capitalize.intern # read it, kill useless quotes
# read the attributes
attrs = []
len = string.read_until('{').to_i
len.times do
attr = (do_unserialize(string, classmap, assoc, original_encoding))
attrs << [attr.intern, (attr << '=').intern, do_unserialize(string, classmap, assoc, original_encoding)]
end
string.read(1)
val = nil
# See if we need to map to a particular object
if classmap.has_key?(klass)
val = classmap[klass].new
elsif Struct.const_defined?(klass) # Nope; see if there's a Struct
classmap[klass] = val = Struct.const_get(klass)
val = val.new
else # Nope; see if there's a Constant
begin
classmap[klass] = val = Module.const_get(klass)
val = val.new
rescue NameError # Nope; make a new Struct
classmap[klass] = val = Struct.new(klass.to_s, *attrs.collect { |v| v[0].to_s })
val = val.new
end
end
attrs.each do |attr,attrassign,v|
val.__send__(attrassign, v)
end
when 's' # string, s:length:"data";
len = string.read_until(':').to_i + 3 # quotes, separator
val = string.read(len)[1...-2].force_encoding(original_encoding) # read it, kill useless quotes
when 'i' # integer, i:123
val = string.read_until(';').to_i
when 'd' # double (float), d:1.23
val = string.read_until(';').to_f
when 'N' # NULL, N;
val = nil
when 'b' # bool, b:0 or 1
val = string.read(2)[0] == '1'
else
raise TypeError, "Unable to unserialize type '#{type}'"
end
val
end # }}}
end
| ruby | MIT | 68c0b6f9a20c07d7498d3bce62a37f1e240eddfe | 2026-01-04T17:48:15.410864Z | false |
jqr/php-serialize | https://github.com/jqr/php-serialize/blob/68c0b6f9a20c07d7498d3bce62a37f1e240eddfe/lib/php/serialize/version.rb | lib/php/serialize/version.rb | module PHP
module Serialize
VERSION = "1.4.1"
end
end
| ruby | MIT | 68c0b6f9a20c07d7498d3bce62a37f1e240eddfe | 2026-01-04T17:48:15.410864Z | false |
rubaidh/google_analytics | https://github.com/rubaidh/google_analytics/blob/d834044d84a8954bf58d57663523b25c2a8cbbc6/init.rb | init.rb | require File.dirname(__FILE__) + "/rails/init" | ruby | MIT | d834044d84a8954bf58d57663523b25c2a8cbbc6 | 2026-01-04T17:48:05.438336Z | false |
rubaidh/google_analytics | https://github.com/rubaidh/google_analytics/blob/d834044d84a8954bf58d57663523b25c2a8cbbc6/rails/init.rb | rails/init.rb | require 'rubaidh/google_analytics'
require 'rubaidh/view_helpers'
ActionController::Base.send :include, Rubaidh::GoogleAnalyticsMixin
ActionController::Base.send :after_filter, :add_google_analytics_code
ActionView::Base.send :include, Rubaidh::GoogleAnalyticsViewHelper | ruby | MIT | d834044d84a8954bf58d57663523b25c2a8cbbc6 | 2026-01-04T17:48:05.438336Z | false |
rubaidh/google_analytics | https://github.com/rubaidh/google_analytics/blob/d834044d84a8954bf58d57663523b25c2a8cbbc6/test/google_analytics_test.rb | test/google_analytics_test.rb | require File.dirname(__FILE__) + '/test_helper.rb'
require 'test/unit'
require 'rubygems'
require 'mocha'
RAILS_ENV = 'test'
class TestMixin
class MockRequest
attr_accessor :format
end
class MockResponse
attr_accessor :body
end
include Rubaidh::GoogleAnalyticsMixin
attr_accessor :request, :response
def initialize
self.request = MockRequest.new
self.response = MockResponse.new
end
# override the mixin's method
def google_analytics_code
"Google Code"
end
end
class GoogleAnalyticsTest < Test::Unit::TestCase
def setup
@ga = Rubaidh::GoogleAnalytics.new
@ga.tracker_id = "the tracker id"
end
def test_createable
assert_not_nil(@ga)
end
def test_domain_name_defaults_to_nil
assert_nil(@ga.domain_name)
end
def test_legacy_mode_defaults_to_false
assert_equal(false, @ga.legacy_mode)
end
def test_default_analytics_url
assert_equal("http://www.google-analytics.com/urchin.js", @ga.analytics_url)
end
def test_default_analytics_ssl_url
assert_equal('https://ssl.google-analytics.com/urchin.js', @ga.analytics_ssl_url)
end
def test_default_environments
assert_equal(false, @ga.environments.include?('test'))
assert_equal(false, @ga.environments.include?('development'))
assert_equal(true, @ga.environments.include?('production'))
end
def test_default_formats
assert_equal(false, @ga.formats.include?(:xml))
assert_equal(true, @ga.formats.include?(:html))
end
def test_defer_load_defaults_to_true
assert_equal(true, @ga.defer_load)
end
def test_local_javascript_defaults_to_false
assert_equal(false, @ga.local_javascript)
end
# test self.enabled
def test_enabled_requires_tracker_id
Rubaidh::GoogleAnalytics.stubs(:tracker_id).returns(nil)
assert_raise(Rubaidh::GoogleAnalyticsConfigurationError) { Rubaidh::GoogleAnalytics.enabled?(:html) }
end
def test_enabled_requires_analytics_url
Rubaidh::GoogleAnalytics.stubs(:analytics_url).returns(nil)
assert_raise(Rubaidh::GoogleAnalyticsConfigurationError) { Rubaidh::GoogleAnalytics.enabled?(:html) }
end
def test_enabled_returns_false_if_current_environment_not_enabled
Rubaidh::GoogleAnalytics.stubs(:environments).returns(['production'])
assert_equal(false, Rubaidh::GoogleAnalytics.enabled?(:html))
end
def test_enabled_with_default_format
Rubaidh::GoogleAnalytics.stubs(:environments).returns(['test'])
assert_equal(true, Rubaidh::GoogleAnalytics.enabled?(:html))
end
def test_enabled_with_not_included_format
Rubaidh::GoogleAnalytics.stubs(:environments).returns(['test'])
assert_equal(false, Rubaidh::GoogleAnalytics.enabled?(:xml))
end
def test_enabled_with_added_format
Rubaidh::GoogleAnalytics.stubs(:environments).returns(['test'])
Rubaidh::GoogleAnalytics.stubs(:formats).returns([:xml])
assert_equal(true, Rubaidh::GoogleAnalytics.enabled?(:xml))
end
# test request_tracker_id
def test_request_tracker_id_without_override
Rubaidh::GoogleAnalytics.stubs(:tracker_id).returns("1234")
assert_equal("1234", Rubaidh::GoogleAnalytics.request_tracker_id)
end
def test_request_tracker_id_with_override
Rubaidh::GoogleAnalytics.stubs(:tracker_id).returns("1234")
Rubaidh::GoogleAnalytics.override_tracker_id = "4567"
assert_equal("4567", Rubaidh::GoogleAnalytics.request_tracker_id)
end
def test_request_tracker_id_resets_override
Rubaidh::GoogleAnalytics.override_tracker_id = "4567"
Rubaidh::GoogleAnalytics.stubs(:tracker_id).returns("1234")
foo = Rubaidh::GoogleAnalytics.request_tracker_id
assert_nil(Rubaidh::GoogleAnalytics.override_tracker_id)
end
# test request_tracked_path
def test_request_tracked_path_without_override
assert_equal('', Rubaidh::GoogleAnalytics.request_tracked_path)
end
def test_request_tracked_path_with_override
Rubaidh::GoogleAnalytics.override_trackpageview = "/my/path"
assert_equal("'/my/path'", Rubaidh::GoogleAnalytics.request_tracked_path)
end
def test_request_tracked_path_resets_override
Rubaidh::GoogleAnalytics.override_trackpageview = "/my/path"
foo = Rubaidh::GoogleAnalytics.request_tracked_path
assert_nil(Rubaidh::GoogleAnalytics.override_trackpageview)
end
# Test the before_filter method does what we expect by subsituting the body tags and inserting
# some google code for us automagically.
def test_add_google_analytics_code
# setup our test mixin
mixin = TestMixin.new
# bog standard body tag
Rubaidh::GoogleAnalytics.defer_load = false
mixin.response.body = "<body><p>some text</p></body>"
mixin.add_google_analytics_code
assert_equal mixin.response.body, '<body>Google Code<p>some text</p></body>'
Rubaidh::GoogleAnalytics.defer_load = true
mixin.response.body = "<body><p>some text</p></body>"
mixin.add_google_analytics_code
assert_equal mixin.response.body, '<body><p>some text</p>Google Code</body>'
# body tag upper cased (ignoring this is semantically incorrect)
Rubaidh::GoogleAnalytics.defer_load = false
mixin.response.body = "<BODY><p>some text</p></BODY>"
mixin.add_google_analytics_code
assert_equal mixin.response.body, '<BODY>Google Code<p>some text</p></BODY>'
Rubaidh::GoogleAnalytics.defer_load = true
mixin.response.body = "<BODY><p>some text</p></BODY>"
mixin.add_google_analytics_code
assert_equal mixin.response.body, '<BODY><p>some text</p>Google Code</body>'
# body tag has additional attributes
Rubaidh::GoogleAnalytics.defer_load = false
mixin.response.body = '<body style="background-color:red"><p>some text</p></body>'
mixin.add_google_analytics_code
assert_equal mixin.response.body, '<body style="background-color:red">Google Code<p>some text</p></body>'
Rubaidh::GoogleAnalytics.defer_load = true
mixin.response.body = '<body style="background-color:red"><p>some text</p></body>'
mixin.add_google_analytics_code
assert_equal mixin.response.body, '<body style="background-color:red"><p>some text</p>Google Code</body>'
end
end
| ruby | MIT | d834044d84a8954bf58d57663523b25c2a8cbbc6 | 2026-01-04T17:48:05.438336Z | false |
rubaidh/google_analytics | https://github.com/rubaidh/google_analytics/blob/d834044d84a8954bf58d57663523b25c2a8cbbc6/test/test_helper.rb | test/test_helper.rb | ENV['RAILS_ENV'] = 'test'
require 'rubygems'
require 'test/unit'
require File.expand_path(File.dirname(__FILE__) + '/../lib/rubaidh/google_analytics.rb')
require File.expand_path(File.dirname(__FILE__) + '/../lib/rubaidh/view_helpers.rb')
| ruby | MIT | d834044d84a8954bf58d57663523b25c2a8cbbc6 | 2026-01-04T17:48:05.438336Z | false |
rubaidh/google_analytics | https://github.com/rubaidh/google_analytics/blob/d834044d84a8954bf58d57663523b25c2a8cbbc6/test/view_helpers_test.rb | test/view_helpers_test.rb | require File.dirname(__FILE__) + '/test_helper.rb'
include Rubaidh::GoogleAnalyticsViewHelper
include ActionView::Helpers::UrlHelper
include ActionView::Helpers::TagHelper
class ViewHelpersTest < Test::Unit::TestCase
def setup
Rubaidh::GoogleAnalytics.defer_load = false
end
def test_link_to_tracked_should_return_a_tracked_link
assert_equal "<a href=\"http://www.example.com\" onclick=\"javascript:pageTracker._trackPageview('/sites/linked');\">Link</a>", link_to_tracked('Link', '/sites/linked', "http://www.example.com" )
end
def test_link_to_tracked_with_legacy_should_return_a_tracked_link
Rubaidh::GoogleAnalytics.legacy_mode = true
assert_equal "<a href=\"http://www.example.com\" onclick=\"javascript:urchinTracker('/sites/linked');\">Link</a>", link_to_tracked('Link', '/sites/linked', "http://www.example.com" )
end
def test_link_to_tracked_should_error_if_defer_load
Rubaidh::GoogleAnalytics.defer_load = true
assert_raise(Rubaidh::AnalyticsError) { link_to_tracked('Link', '/sites/linked', "http://www.example.com" ) }
end
def test_link_to_tracked_if_with_true_should_return_a_tracked_link
assert_equal "<a href=\"http://www.example.com\" onclick=\"javascript:pageTracker._trackPageview('/sites/linked');\">Link</a>", link_to_tracked_if(true, 'Link', '/sites/linked', "http://www.example.com" )
end
def test_link_to_tracked_if_with_false_should_return_unlinked_text
assert_equal "Link", link_to_tracked_if(false, 'Link', '/sites/linked', "http://www.example.com" )
end
def test_link_to_tracked_if_should_error_if_defer_load
Rubaidh::GoogleAnalytics.defer_load = true
assert_raise(Rubaidh::AnalyticsError) { link_to_tracked_if(false, 'Link', '/sites/linked', "http://www.example.com" ) }
end
def test_link_to_tracked_unless_with_false_should_return_a_tracked_link
assert_equal "<a href=\"http://www.example.com\" onclick=\"javascript:pageTracker._trackPageview('/sites/linked');\">Link</a>", link_to_tracked_unless(false, 'Link', '/sites/linked', "http://www.example.com" )
end
def test_link_to_tracked_unless_with_true_should_return_unlinked_text
assert_equal "Link", link_to_tracked_unless(true, 'Link', '/sites/linked', "http://www.example.com" )
end
def test_link_to_tracked_unless_should_error_if_defer_load
Rubaidh::GoogleAnalytics.defer_load = true
assert_raise(Rubaidh::AnalyticsError) { link_to_tracked_unless(false, 'Link', '/sites/linked', "http://www.example.com" ) }
end
def test_link_to_tracked_unless_current
#postponed
end
end
| ruby | MIT | d834044d84a8954bf58d57663523b25c2a8cbbc6 | 2026-01-04T17:48:05.438336Z | false |
rubaidh/google_analytics | https://github.com/rubaidh/google_analytics/blob/d834044d84a8954bf58d57663523b25c2a8cbbc6/lib/rubaidh.rb | lib/rubaidh.rb | module Rubaidh #:nodoc:
end
| ruby | MIT | d834044d84a8954bf58d57663523b25c2a8cbbc6 | 2026-01-04T17:48:05.438336Z | false |
rubaidh/google_analytics | https://github.com/rubaidh/google_analytics/blob/d834044d84a8954bf58d57663523b25c2a8cbbc6/lib/rubaidh/view_helpers.rb | lib/rubaidh/view_helpers.rb | module Rubaidh
# Collection of methods similar to the ones in ActionView::Helpers::UrlHelper,
# with the addition of outbound link tracking. See the Google Analytics help
# at http://www.google.com/support/googleanalytics/bin/answer.py?answer=55527
# for more information on outbound link tracking.
module GoogleAnalyticsViewHelper
# Creates a link tag of the given +name+ using a URL created by the set of +options+,
# with outbound link tracking under +track_path+ in Google Analytics. The +html_options+
# will accept a hash of attributes for the link tag.
def link_to_tracked(name, track_path = "/", options = {}, html_options = {})
raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true
html_options.merge!({:onclick => tracking_call(track_path)})
link_to name, options, html_options
end
# Creates a link tag of the given +name+ using a URL created by the set of +options+
# if +condition+ is true, with outbound link tracking under +track_path+ in Google Analytics.
# The +html_options+ will accept a hash of attributes for the link tag.
def link_to_tracked_if(condition, name, track_path = "/", options = {}, html_options = {}, &block)
raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true
html_options.merge!({:onclick => tracking_call(track_path)})
link_to_unless !condition, name, options, html_options, &block
end
# Creates a link tag of the given +name+ using a URL created by the set of +options+
# unless +condition+ is true, with outbound link tracking under +track_path+ in Google Analytics.
# The +html_options+ will accept a hash of attributes for the link tag.
def link_to_tracked_unless(condition, name, track_path = "/", options = {}, html_options = {}, &block)
raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true
html_options.merge!({:onclick => tracking_call(track_path)})
link_to_unless condition, name, options, html_options, &block
end
# Creates a link tag of the given +name+ using a URL created by the set of +options+
# unless the current request URI is the same as the link's, with outbound link tracking
# under +track_path+ in Google Analytics. If the request URI is the same as the link
# URI, only the name is returned, or the block is yielded, if one exists.
# The +html_options+ will accept a hash of attributes for the link tag.
def link_to_tracked_unless_current(name, track_path = "/", options = {}, html_options = {}, &block)
raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true
html_options.merge!({:onclick =>tracking_call(track_path)})
link_to_unless current_page?(options), name, options, html_options, &block
end
private
def tracking_call(track_path)
if GoogleAnalytics.legacy_mode
"javascript:urchinTracker('#{track_path}');"
else
"javascript:pageTracker._trackPageview('#{track_path}');"
end
end
end
# Error raised by tracking methods if Rubaidh::GoogleAnalytics.defer_load is not configured
# properly to enable tracking.
class AnalyticsError < StandardError
attr_reader :message
def initialize(message)
@message = message
end
end
end
| ruby | MIT | d834044d84a8954bf58d57663523b25c2a8cbbc6 | 2026-01-04T17:48:05.438336Z | false |
rubaidh/google_analytics | https://github.com/rubaidh/google_analytics/blob/d834044d84a8954bf58d57663523b25c2a8cbbc6/lib/rubaidh/google_analytics.rb | lib/rubaidh/google_analytics.rb | require 'active_support'
require 'action_pack'
require 'action_view'
module Rubaidh # :nodoc:
# This module gets mixed in to ActionController::Base
module GoogleAnalyticsMixin
# The javascript code to enable Google Analytics on the current page.
# Normally you won't need to call this directly; the +add_google_analytics_code+
# after filter will insert it for you.
def google_analytics_code
GoogleAnalytics.google_analytics_code(request.ssl?) if GoogleAnalytics.enabled?(request.format)
end
# An after_filter to automatically add the analytics code.
# If you intend to use the link_to_tracked view helpers, you need to set Rubaidh::GoogleAnalytics.defer_load = false
# to load the code at the top of the page
# (see http://www.google.com/support/googleanalytics/bin/answer.py?answer=55527&topic=11006)
def add_google_analytics_code
if GoogleAnalytics.defer_load
response.body.sub! /<\/[bB][oO][dD][yY]>/, "#{google_analytics_code}</body>" if response.body.respond_to?(:sub!)
else
response.body.sub! /(<[bB][oO][dD][yY][^>]*>)/, "\\1#{google_analytics_code}" if response.body.respond_to?(:sub!)
end
end
end
class GoogleAnalyticsConfigurationError < StandardError; end
# The core functionality to connect a Rails application
# to a Google Analytics installation.
class GoogleAnalytics
@@tracker_id = nil
##
# :singleton-method:
# Specify the Google Analytics ID for this web site. This can be found
# as the value of +_getTracker+ if you are using the new (ga.js) tracking
# code, or the value of +_uacct+ if you are using the old (urchin.js)
# tracking code.
cattr_accessor :tracker_id
@@domain_name = nil
##
# :singleton-method:
# Specify a different domain name from the default. You'll want to use
# this if you have several subdomains that you want to combine into
# one report. See the Google Analytics documentation for more
# information.
cattr_accessor :domain_name
@@legacy_mode = false
##
# :singleton-method:
# Specify whether the legacy Google Analytics code should be used. By
# default, the new Google Analytics code is used.
cattr_accessor :legacy_mode
@@analytics_url = 'http://www.google-analytics.com/urchin.js'
##
# :singleton-method:
# The URL that analytics information is sent to. This defaults to the
# standard Google Analytics URL, and you're unlikely to need to change it.
# This has no effect unless you're in legacy mode.
cattr_accessor :analytics_url
@@analytics_ssl_url = 'https://ssl.google-analytics.com/urchin.js'
##
# :singleton-method:
# The URL that analytics information is sent to when using SSL. This defaults to the
# standard Google Analytics URL, and you're unlikely to need to change it.
# This has no effect unless you're in legacy mode.
cattr_accessor :analytics_ssl_url
@@environments = ['production']
##
# :singleton-method:
# The environments in which to enable the Google Analytics code. Defaults
# to 'production' only. Supply an array of environment names to change this.
cattr_accessor :environments
@@formats = [:html, :all]
##
# :singleton-method:
# The request formats where tracking code should be added. Defaults to +[:html, :all]+. The entry for
# +:all+ is necessary to make Google recognize that tracking is installed on a
# site; it is not the same as responding to all requests. Supply an array
# of formats to change this.
cattr_accessor :formats
@@defer_load = true
##
# :singleton-method:
# Set this to true (the default) if you want to load the Analytics javascript at
# the bottom of page. Set this to false if you want to load the Analytics
# javascript at the top of the page. The page will render faster if you set this to
# true, but that will break the linking functions in Rubaidh::GoogleAnalyticsViewHelper.
cattr_accessor :defer_load
@@local_javascript = false
##
# :singleton-method:
# Set this to true to use a local copy of the ga.js (or urchin.js) file.
# This gives you the added benefit of serving the JS directly from your
# server, which in case of a big geographical difference between your server
# and Google's can speed things up for your visitors. Use the
# 'google_analytics:update' rake task to update the local JS copies.
cattr_accessor :local_javascript
##
# :singleton-method:
# Set this to override the initialized domain name for a single render. Useful
# when you're serving to multiple hosts from a single codebase. Typically you'd
# set up a before filter in the appropriate controller:
# before_filter :override_domain_name
# def override_domain_name
# Rubaidh::GoogleAnalytics.override_domain_name = 'foo.com'
# end
cattr_accessor :override_domain_name
##
# :singleton-method:
# Set this to override the initialized tracker ID for a single render. Useful
# when you're serving to multiple hosts from a single codebase. Typically you'd
# set up a before filter in the appropriate controller:
# before_filter :override_tracker_id
# def override_tracker_id
# Rubaidh::GoogleAnalytics.override_tracker_id = 'UA-123456-7'
# end
cattr_accessor :override_tracker_id
##
# :singleton-method:
# Set this to override the automatically generated path to the page in the
# Google Analytics reports for a single render. Typically you'd set this up on an
# action-by-action basis:
# def show
# Rubaidh::GoogleAnalytics.override_trackpageview = "path_to_report"
# ...
cattr_accessor :override_trackpageview
# Return true if the Google Analytics system is enabled and configured
# correctly for the specified format
def self.enabled?(format)
raise Rubaidh::GoogleAnalyticsConfigurationError if tracker_id.blank? || analytics_url.blank?
environments.include?(RAILS_ENV) && formats.include?(format.to_sym)
end
# Construct the javascript code to be inserted on the calling page. The +ssl+
# parameter can be used to force the SSL version of the code in legacy mode only.
def self.google_analytics_code(ssl = false)
return legacy_google_analytics_code(ssl) if legacy_mode
extra_code = domain_name.blank? ? nil : "pageTracker._setDomainName(\"#{domain_name}\");"
if !override_domain_name.blank?
extra_code = "pageTracker._setDomainName(\"#{override_domain_name}\");"
self.override_domain_name = nil
end
code = if local_javascript
<<-HTML
<script src="#{LocalAssetTagHelper.new.javascript_path( 'ga.js' )}" type="text/javascript">
</script>
HTML
else
<<-HTML
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
HTML
end
code << <<-HTML
<script type="text/javascript">
<!--//--><![CDATA[//><!--
try {
var pageTracker = _gat._getTracker('#{request_tracker_id}');
#{extra_code}
pageTracker._initData();
pageTracker._trackPageview(#{request_tracked_path});
} catch(err) {}
//--><!]]>
</script>
HTML
end
# Construct the legacy version of the Google Analytics code. The +ssl+
# parameter specifies whether or not to return the SSL version of the code.
def self.legacy_google_analytics_code(ssl = false)
extra_code = domain_name.blank? ? nil : "_udn = \"#{domain_name}\";"
if !override_domain_name.blank?
extra_code = "_udn = \"#{override_domain_name}\";"
self.override_domain_name = nil
end
url = legacy_analytics_js_url(ssl)
code = <<-HTML
<script src="#{url}" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "#{request_tracker_id}";
#{extra_code}
urchinTracker(#{request_tracked_path});
</script>
HTML
end
# Generate the correct URL for the legacy Analytics JS file
def self.legacy_analytics_js_url(ssl = false)
if local_javascript
LocalAssetTagHelper.new.javascript_path( 'urchin.js' )
else
ssl ? analytics_ssl_url : analytics_url
end
end
# Determine the tracker ID for this request
def self.request_tracker_id
use_tracker_id = override_tracker_id.blank? ? tracker_id : override_tracker_id
self.override_tracker_id = nil
use_tracker_id
end
# Determine the path to report for this request
def self.request_tracked_path
use_tracked_path = override_trackpageview.blank? ? '' : "'#{override_trackpageview}'"
self.override_trackpageview = nil
use_tracked_path
end
end
class LocalAssetTagHelper # :nodoc:
# For helping with local javascripts
include ActionView::Helpers::AssetTagHelper
end
end
| ruby | MIT | d834044d84a8954bf58d57663523b25c2a8cbbc6 | 2026-01-04T17:48:05.438336Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/benchmarks/speed_profile.rb | benchmarks/speed_profile.rb | require 'benchmark/ips'
require 'strings'
text = "Ignorance is the parent of fear."
Benchmark.ips do |x|
x.report('wrap') do
Strings::Wrap.wrap(text, 10)
end
x.report('truncate') do
Strings::Truncate.truncate(text, 10)
end
x.compare!
end
# (2017-12-09)
#
# Calculating -------------------------------------
# wrap 186 i/100ms
# truncate 295 i/100ms
# -------------------------------------------------
# wrap 1917.2 (±2.2%) i/s - 9672 in 5.047297s
# truncate 3020.6 (±3.0%) i/s - 15340 in 5.083516s
#
# Comparison:
# truncate: 3020.6 i/s
# wrap: 1917.2 i/s - 1.58x slower
#
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
if ENV["COVERAGE"] == "true"
require "simplecov"
require "coveralls"
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
])
SimpleCov.start do
command_name "spec"
add_filter "spec"
end
end
require "bundler/setup"
require "strings"
module Helpers
def unindent(text)
text.gsub(/^[ \t]*/, "").chomp
end
end
RSpec.configure do |config|
config.include(Helpers)
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/truncate_spec.rb | spec/unit/truncate_spec.rb | # frozen_string_literal: true
RSpec.describe Strings, "#truncate" do
it "truncates text" do
text = "ラドクリフ、マラソン五輪代表に1万m出場にも含み"
expect(Strings.truncate(text, 12)).to eq("ラドクリフ…")
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/fold_spec.rb | spec/unit/fold_spec.rb | # fronzen_string_literal: true
RSpec.describe Strings, "#fold" do
it "folds a multiline text into a single line" do
expect(Strings.fold("\tfoo \r\n\n\n bar")).to eq(" foo bar")
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/sanitize_spec.rb | spec/unit/sanitize_spec.rb | # frozen_string_literal: true
RSpec.describe Strings, "#sanitize" do
it "removes ansi codes" do
expect(Strings.sanitize("\e[33mfoo\e[0m")).to eq("foo")
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/wrap_spec.rb | spec/unit/wrap_spec.rb | # frozen_string_literal: true
RSpec.describe Strings, "#wrap" do
it "wraps text" do
text = "ラドクリフ、マラソン五輪代表に1万m出場にも含み"
expect(Strings.wrap(text, 8)).to eql([
"ラドクリ",
"フ、マラ",
"ソン五輪",
"代表に1",
"万m出場",
"にも含み"
].join("\n"))
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/pad_spec.rb | spec/unit/pad_spec.rb | # frozen_string_literal: true
RSpec.describe Strings, "#pad" do
it "pads text" do
text = "ラドクリフ、マラソン五輪代表に1万m出場にも含み"
expect(Strings.pad(text, [1,1,1,1])).to eql([
" ",
" ラドクリフ、マラソン五輪代表に1万m出場にも含み ",
" "
].join("\n"))
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/align_spec.rb | spec/unit/align_spec.rb | # frozen_string_literal: true
RSpec.describe Strings, "#align" do
it "aligns text" do
text = "the madness of men"
expect(Strings.align(text, 22, direction: :center)).to eq(" the madness of men ")
end
it "aligns text to left" do
text = "the madness of men"
expect(Strings.align_left(text, 22)).to eq("the madness of men ")
end
it "aligns text to right" do
text = "the madness of men"
expect(Strings.align_right(text, 22)).to eq(" the madness of men")
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/extensions_spec.rb | spec/unit/extensions_spec.rb | # frozen_string_literal: true
require "strings/extensions"
using Strings::Extensions
RSpec.describe Strings::Extensions do
let(:text) { "the madness of men" }
it "aligns a line in the center" do
expect(text.align(22, direction: :center)).to eq(" the madness of men ")
end
it "aligns a line to the left" do
expect(text.align_left(22)).to eq("the madness of men ")
end
it "aligns a line to the right" do
expect(text.align_right(22)).to eq(" the madness of men")
end
it "checks for ansi" do
expect("\e[33mfoo\e[0m".ansi?).to eq(true)
end
it "removes ansi codes" do
expect("\e[33mfoo\e[0m".sanitize).to eq("foo")
end
it "folds a line" do
expect("foo\n\nbar\n".fold).to eq("foo bar ")
end
it "pads a line" do
expect(text.pad(1)).to eq([
" " * (text.size + 2),
" #{text} ",
" " * (text.size + 2),
].join("\n"))
end
it "pads a line" do
expect(text.pad(1)).to eq([
" " * (text.size + 2),
" #{text} ",
" " * (text.size + 2),
].join("\n"))
end
it "pads a line with custom fill" do
expect(text.pad(1, fill: "*")).to eq([
"*" * (text.size + 2),
"*#{text}*",
"*" * (text.size + 2),
].join("\n"))
end
it "truncates a line" do
text = "the madness of men"
expect(text.truncate(10)).to eq("the madn…")
end
it "truncates a line with a custom trailing" do
text = "the madness of men"
expect(text.truncate(10, trailing: "...")).to eq("the ma...")
end
it "truncates into words with a custom trailing" do
text = "the madness of men"
expect(text.truncate(16, trailing: "...", separator: " ")).to eq("the madness...")
end
it "wraps a line" do
expect("foobar1".wrap(3)).to eq("foo\nbar\n1")
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/ansi_spec.rb | spec/unit/ansi_spec.rb | # frozen_string_literal: true
RSpec.describe Strings, "#ansi?" do
it "checks if string has any ansi codes" do
expect(Strings.ansi?("\e[33mfoo\e[0m")).to eq(true)
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/fold/fold_spec.rb | spec/unit/fold/fold_spec.rb | # unicode: utf-8
# frozen_string_literals: true
RSpec.describe Strings, "#fold" do
{
" \n" => " ",
"\n " => " ",
"\n" => " ",
"\n\n\n" => " ",
" \n " => " ",
" \n \n \n" => " "
}.each do |actual, expected|
it "removes newline '#{actual.gsub(/\n/, '\\n')}' to '#{expected}'" do
expect(Strings::Fold.fold(actual)).to eq(expected)
end
end
{
" \r\n" => " ",
"\r\n " => " ",
"\r\n" => " ",
" \r\n " => " ",
}.each do |actual, expected|
it "squashes '#{actual.gsub(/\r\n/, '\\r\\n')}' to '#{expected}'" do
expect(Strings::Fold.fold(actual, "\r\n")).to eq(expected)
end
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/padder/parse_spec.rb | spec/unit/padder/parse_spec.rb | # frozen_string_literal:true
RSpec.describe Strings::Padder, "#parse" do
it "parses nil" do
instance = Strings::Padder.parse(nil)
expect(instance.padding).to eq([])
end
it "parses self" do
value = Strings::Padder.new([])
instance = Strings::Padder.parse(value)
expect(instance.padding).to eq([])
end
it "parses digit" do
instance = Strings::Padder.parse(5)
expect(instance.padding).to eq([5,5,5,5])
end
it "parses 2-element array" do
instance = Strings::Padder.parse([2,3])
expect(instance.padding).to eq([2,3,2,3])
end
it "parses 4-element array" do
instance = Strings::Padder.parse([1,2,3,4])
expect(instance.padding).to eq([1,2,3,4])
end
it "fails to parse unknown value" do
expect {
Strings::Padder.parse(:unknown)
}.to raise_error(Strings::Padder::ParseError)
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/pad/pad_spec.rb | spec/unit/pad/pad_spec.rb | # frozen_string_literal: true
RSpec.describe Strings::Pad, "#pad" do
it "pads content with padding as a single value" do
text = "Ignorance is the parent of fear."
expect(Strings::Pad.pad(text, 1)).to eq([
" ",
" Ignorance is the parent of fear. ",
" ",
].join("\n"))
end
it "pads content with specific padding as an array" do
text = "Ignorance is the parent of fear."
expect(Strings::Pad.pad(text, [1,1,1,1])).to eq([
" ",
" Ignorance is the parent of fear. ",
" ",
].join("\n"))
end
it "pads with custom character" do
text = "Ignorance is the parent of fear."
expect(Strings::Pad.pad(text, [1, 2], fill: "*")).to eq([
"************************************",
"**Ignorance is the parent of fear.**",
"************************************",
].join("\n"))
end
it "pads unicode content" do
text = "ラドクリフ、マラソン"
expect(Strings::Pad.pad(text, [1,1,1,1])).to eq([
" ",
" ラドクリフ、マラソン ",
" "
].join("\n"))
end
it "pads multiline content" do
text = "It is the easiest thing\nin the world for a man\nto look as if he had \na great secret in him."
expect(Strings::Pad.pad(text, [1,2])).to eq([
" ",
" It is the easiest thing ",
" in the world for a man ",
" to look as if he had ",
" a great secret in him. ",
" ",
].join("\n"))
end
it "pads ANSI codes inside content" do
text = "It is \e[35mthe easiest\e[0m thing\nin the \e[34mworld\e[0m for a man\nto look as if he had \na great \e[33msecret\e[0m in him."
expect(Strings::Pad.pad(text, [1,1,1,1])).to eq([
" ",
" It is \e[35mthe easiest\e[0m thing ",
" in the \e[34mworld\e[0m for a man ",
" to look as if he had ",
" a great \e[33msecret\e[0m in him. ",
" ",
].join("\n"))
end
it "handles \r\n line separator" do
text = "Closes #360\r\n\r\nCloses !217"
expect(Strings::Pad.pad(text, [1,1,1,1])).to eq([
" ",
" Closes #360 ",
" ",
" Closes !217 ",
" "
].join("\r\n"))
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/wrap/insert_ansi_spec.rb | spec/unit/wrap/insert_ansi_spec.rb | # frozen_string_literal: true
RSpec.describe "#insert_ansi" do
it "doesn't do anything when empty stack" do
text = "Ignorance is the parent of fear."
val = Strings::Wrap.insert_ansi(text, [])
expect(val).to eq(text)
end
it "inserts ANSI strings in a single line" do
text = "Ignorance is the parent of fear."
stack = [["\e[32;44m", 0], ["\e[0m", text.size]]
val = Strings::Wrap.insert_ansi(text, stack)
expect(val).to eq("\e[32;44mIgnorance is the parent of fear.\e[0m")
expect(stack).to eq([])
end
it "inserts ANSI strings with missing reset in a single line" do
text = "Ignorance is the parent of fear."
stack = [["\e[32;44m", 0]]
val = Strings::Wrap.insert_ansi(text, stack)
expect(val).to eq("\e[32;44mIgnorance is the parent of fear.\e[0m")
expect(stack).to eq([["\e[32;44m", 0]])
end
it "inserts 3 ansi strings in a single line" do
text = "Ignorance is the parent of fear."
stack = [
["\e[32m", 0], ["\e[0m", 9],
["\e[33m", 13], ["\e[0m", 16],
["\e[34m", 27], ["\e[0m", 31]
]
val = Strings::Wrap.insert_ansi(text, stack)
expect(val).to eq("\e[32mIgnorance\e[0m is \e[33mthe\e[0m parent of \e[34mfear\e[0m.")
expect(stack).to eq([])
end
it "inserts nested ANSI strings in a single line" do
text = "Ignorance is the parent of fear."
stack = [["\e[32m", 10], ["\e[33m", 17], ["\e[0m", 23], ["\e[0m", 26]]
val = Strings::Wrap.insert_ansi(text, stack)
expect(val).to eq("Ignorance \e[32mis the \e[33mparent\e[0m of\e[0m fear.")
expect(stack).to eq([])
end
it "removes matching pairs of ANSI codes only" do
text = "one"
stack = [["\e[32m", 0], ["\e[0m", 3], ["\e[33m", 3]]
val = Strings::Wrap.insert_ansi(text, stack)
expect(val).to eq("\e[32mone\e[0m")
expect(stack).to eq([["\e[33m", 3]])
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/wrap/wrap_spec.rb | spec/unit/wrap/wrap_spec.rb | # frozen_string_literal: true
RSpec.describe Strings::Wrap, ".wrap" do
context "when unicode" do
let(:text) { "ラドクリフ、マラソン五輪代表に1万m出場にも含み" }
it "doesn't wrap at zero length" do
expect(Strings::Wrap.wrap(text, 0)).to eq(text)
end
it "doesn't wrap at nil length" do
expect(Strings::Wrap.wrap(text, nil)).to eq(text)
end
it "doesn't wrap at length exceeding content length" do
expect(Strings::Wrap.wrap(text, 100)).to eq(text)
end
it "wraps minimal width" do
str = "#?%"
val = Strings::Wrap.wrap(str, 1)
expect(val).to eq([
"#",
"?",
"%"
].join("\n"))
end
it "wraps correctly unbreakable words" do
expect(Strings::Wrap.wrap("foobar1", 3)).to eq([
"foo",
"bar",
"1"
].join("\n"))
end
it "wraps preserving newline characters" do
expect(Strings::Wrap.wrap("foo\n\n\nbar\r\n\r\nbaz\n", 3)).to eq([
"foo",
"\n\n\n",
"bar",
"\r\n\r\n",
"baz\n"
].join)
end
it "preserves multiple line breaks " do
text = "some \r\n\n\n\nunbreakable\n\n\n\n \r\r\rcontent \t"
expect(Strings::Wrap.wrap(text, 5)).to eq([
"some \r\n\n\n",
"unbre",
"akabl",
"e\n\n\n",
" ",
"\r\r\rcont",
"ent \t"
].join("\n"))
end
it "preserves newlines" do
text = "It is not down\n on any map;\n true places never are."
expect(Strings::Wrap.wrap(text, 10)).to eq([
"It is not ",
"down",
" on any ",
"map;",
" true ",
"places ",
"never are."
].join("\n"))
end
it "wraps ascii text" do
text = "for there is no folly of the beast of the earth which is not infinitely outdone by the madness of men "
expect(Strings::Wrap.wrap(text, 16)).to eq([
"for there is no ",
"folly of the ",
"beast of the ",
"earth which is ",
"not infinitely ",
"outdone by the ",
"madness of men "
].join("\n"))
end
it "wraps at 8 characters" do
expect(Strings::Wrap.wrap(text, 8)).to eq([
"ラドクリ",
"フ、マラ",
"ソン五輪",
"代表に1",
"万m出場",
"にも含み"
].join("\n"))
end
it "preserves whitespace" do
text = " As for me, I am tormented with an everlasting itch for things remote. "
expect(Strings::Wrap.wrap(text, 10)).to eq([
" As for ",
"me, I ",
"am ",
"tormented ",
"with an ",
"e",
"verlasting",
" itch ",
"for ",
"things ",
"remote. "
].join("\n"))
end
end
context "when long text" do
it "wraps long text at 45 characters" do
text =
"What of it, if some old hunks of a sea-captain orders me to get a broom and sweep down the decks? What does that indignity amount to, weighed, I mean, in the scales of the New Testament? Do you think the archangel Gabriel thinks anything the less of me, because I promptly and respectfully obey that old hunks in that particular instance? Who ain't a slave? Tell me that. Well, then, however the old sea-captains may order me about--however they may thump and punch me about, I have the satisfaction of knowing that it is all right;"
expect(Strings::Wrap.wrap(text, 45)).to eq unindent <<-EOS
What of it, if some old hunks of a \nsea-captain orders me to get a broom and \n sweep down the decks? What does that \nindignity amount to, weighed, I mean, in the \n scales of the New Testament? Do you think \nthe archangel Gabriel thinks anything the \nless of me, because I promptly and \nrespectfully obey that old hunks in that \nparticular instance? Who ain't a slave? Tell \nme that. Well, then, however the old \nsea-captains may order me about--however \nthey may thump and punch me about, I have \nthe satisfaction of knowing that it is all \nright;
EOS
end
end
context "with newlines" do
it "preserves newlines for both prefix and postfix" do
text = "\n\nラドクリフ、マラソン五輪代表に1万m出場にも含み\n\n\n"
expect(Strings::Wrap.wrap(text, 10)).to eq([
"\n\nラドクリフ\n",
"、マラソン\n",
"五輪代表に\n",
"1万m出場に\n",
"も含み\n\n\n"
].join)
end
it "handles \r\n line separator" do
text = "Closes #360\r\n\r\nCloses !217"
expect(Strings::Wrap.wrap(text, 15)).to eq(text)
end
end
context "with ANSI codes" do
it "wraps ANSI chars" do
text = "\e[32;44mIgnorance is the parent of fear.\e[0m"
expect(Strings::Wrap.wrap(text, 14)).to eq([
"\e[32;44mIgnorance is \e[0m",
"\e[32;44mthe parent of \e[0m",
"\e[32;44mfear.\e[0m",
].join("\n"))
end
it "wraps ANSI in the middle of text" do
text = "Ignorance is the \e[32mparent\e[0m of fear."
expect(Strings::Wrap.wrap(text, 14)).to eq([
"Ignorance is ",
"the \e[32mparent\e[0m of ",
"fear.",
].join("\n"))
end
it "wraps multline ANSI codes" do
text = "\e32;44mMulti\nLine\nContent.\e[0m"
expect(Strings::Wrap.wrap(text, 14)).to eq([
"\e32;44mMulti\e[0m",
"\e32;44mLine\e[0m",
"\e32;44mContent.\e[0m",
].join("\n"))
end
it "wraps multiple ANSI codes in a single line" do
text = "Talk \e[32mnot\e[0m to me of \e[33mblasphemy\e[0m, man; I'd \e[35mstrike the sun\e[0m if it insulted me."
expect(Strings::Wrap.wrap(text, 30)).to eq([
"Talk \e[32mnot\e[0m to me of \e[33mblasphemy\e[0m, ",
"man; I'd \e[35mstrike the sun\e[0m if it ",
"insulted me."
].join("\n"))
end
it "applies ANSI codes when below wrap width" do
str = "\e[32mone\e[0m\e[33mtwo\e[0m"
val = Strings::Wrap.wrap(str, 6)
expect(val).to eq("\e[32mone\e[0m\e[33mtwo\e[0m")
end
xit "splits ANSI codes matching wrap width with space between codes" do
str = "\e[32mone\e[0m \e[33mtwo\e[0m"
val = Strings::Wrap.wrap(str, 3)
expect(val).to eq("\e[32mone\e[0m\n\e[33mtwo\e[0m")
end
xit "splits ANSI codes matching wrap width" do
str = "\e[32mone\e[0m\e[33mtwo\e[0m"
val = Strings::Wrap.wrap(str, 3)
expect(val).to eq("\e[32mone\e[0m\n\e[33mtwo\e[0m")
end
xit "wraps deeply nested ANSI codes correctly" do
str = "\e[32mone\e[33mtwo\e[0m\e[0m"
val = Strings::Wrap.wrap(str, 3)
expect(val).to eq([
"\e[32mone\e[0m",
"\e[33mtwo\e[0m",
].join("\n"))
end
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/truncate/truncate_spec.rb | spec/unit/truncate/truncate_spec.rb | # frozen_string_literal: true
RSpec.describe Strings::Truncate, "#truncate" do
let(:text) { "ラドクリフ、マラソン五輪代表に1万m出場にも含み" }
it "doesn't change text for 0 length" do
expect(Strings::Truncate.truncate(text, 0)).to eq(text)
end
it "doensn't change text for nil length" do
expect(Strings::Truncate.truncate(text, nil)).to eq(text)
end
it "truncate length of 1 results in just the trailing character" do
expect(Strings::Truncate.truncate(text, 1)).to eq(Strings::Truncate::DEFAULT_TRAILING)
end
it "doesn't change text for equal length" do
truncation = Strings::Truncate.truncate(text, text.length * 2)
expect(truncation).to eq(text)
end
it "truncates text and displays omission" do
trailing = "…"
expect(Strings::Truncate.truncate(text, 12)).to eq("ラドクリフ#{trailing}")
end
it "estimates total width correctly " do
text = "太丸ゴシック体"
trailing = "…"
expect(Strings::Truncate.truncate(text, 8)).to eq("太丸ゴ#{trailing}")
end
it "doesn't truncate text when length exceeds content" do
expect(Strings::Truncate.truncate(text, 100)).to eq(text)
end
it "doesn't truncate whole words" do
text = "I know not all that may be coming, but be it what it will, I'll go to it laughing."
trailing = "…"
truncation = Strings::Truncate.truncate(text, separator: " ")
expect(truncation).to eq("I know not all that may be#{trailing}")
end
it "truncates text with string separator" do
trailing = "…"
truncation = Strings::Truncate.truncate(text, 12, separator: "")
expect(truncation).to eq("ラドクリフ#{trailing}")
end
it "truncates text with regex separator" do
trailing = "…"
truncation = Strings::Truncate.truncate(text, 12, separator: /\s/)
expect(truncation).to eq("ラドクリフ#{trailing}")
end
it "truncates text with custom trailing" do
trailing = "... (see more)"
truncation = Strings::Truncate.truncate(text, 20, trailing: trailing)
expect(truncation).to eq("ラド#{trailing}")
end
it "correctly truncates with ANSI characters" do
text = "I try \e[34mall things\e[0m, I achieve what I can"
truncation = Strings::Truncate.truncate(text, 18)
expect(truncation).to eq("I try \e[34mall things\e[0m…")
end
it "finishes on word boundary" do
text = "for there is no folly of the beast of the earth"
truncation = Strings::Truncate.truncate(text, 20, separator: " ")
expect(truncation).to eq("for there is no…")
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/align/align_left_spec.rb | spec/unit/align/align_left_spec.rb | # frozen_string_literal: true
RSpec.describe Strings::Align, "#align_left" do
it "aligns line to left" do
text = "the madness of men"
expect(Strings::Align.align_left(text, 22)).to eq("the madness of men ")
end
it "fills empty" do
expect(Strings::Align.align_left("", 22)).to eq(" ")
end
it "left justifies string with unicode characters" do
text = "こんにちは"
expect(Strings::Align.align(text, 20, direction: :left)).to eq("こんにちは ")
end
it "left justifies string with ansi codes" do
text = "\e[32mthe madness of men\e[0m"
expect(Strings::Align.align(text, 22, direction: :left)).to eq("\e[32mthe madness of men\e[0m ")
end
it "aligns multiline text to left" do
text = "for there is no folly of the beast\nof the earth which\nis not infinitely\noutdone by the madness of men"
expect(Strings::Align.align_left(text, 40)).to eq([
"for there is no folly of the beast \n",
"of the earth which \n",
"is not infinitely \n",
"outdone by the madness of men "
].join)
end
it "left justifies multiline utf text" do
text = "ラドクリフ\n、マラソン五輪\n代表に1万m出\n場にも含み"
expect(Strings::Align.align_left(text, 20)).to eq([
"ラドクリフ \n",
"、マラソン五輪 \n",
"代表に1万m出 \n",
"場にも含み "
].join)
end
it "left justifies ansi text" do
text = "for \e[35mthere\e[0m is no folly of the beast\nof the \e[33mearth\e0m which\nis \e[34mnot infinitely\e[0m\n\e[33moutdone\e[0m by the madness of men"
expect(Strings::Align.align_left(text, 40)).to eq([
"for \e[35mthere\e[0m is no folly of the beast \n",
"of the \e[33mearth\e0m which \n",
"is \e[34mnot infinitely\e[0m \n",
"\e[33moutdone\e[0m by the madness of men "
].join)
end
it "left justifies multiline text with fill of '*'" do
text = "for there is no folly of the beast\nof the earth which\nis not infinitely\noutdone by the madness of men"
expect(Strings::Align.align_left(text, 40, fill: "*")).to eq([
"for there is no folly of the beast******\n",
"of the earth which**********************\n",
"is not infinitely***********************\n",
"outdone by the madness of men***********"
].join)
end
it "handles \r\n line separator" do
text = "Closes #360\r\n\r\nCloses !217"
expect(Strings::Align.align_left(text, 27)).to eq([
"Closes #360 ",
" ",
"Closes !217 "
].join("\r\n"))
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/align/align_right_spec.rb | spec/unit/align/align_right_spec.rb | # frozen_string_literal: true
RSpec.describe Strings::Align, "#align_right" do
it "aligns line to right" do
text = "the madness of men"
expect(Strings::Align.align_right(text, 22)).to eq(" the madness of men")
end
it "fills empty" do
expect(Strings::Align.align_right("", 22)).to eq(" ")
end
it "aligns string to the right with unicode characters" do
text = "こんにちは"
expect(Strings::Align.align(text, 20, direction: :right)).to eq(" こんにちは")
end
it "aligns string to the right with ansi codees" do
text = "\e[32mthe madness of men\e[0m"
expect(Strings::Align.align(text, 22, direction: :right)).to eq(" \e[32mthe madness of men\e[0m")
end
it "aligns multiline text to the right" do
text = "for there is no folly of the beast\n of the earth which\n is not infinitely\n outdone by the madness of men"
expect(Strings::Align.align_right(text, 40)).to eq([
" for there is no folly of the beast\n",
" of the earth which\n",
" is not infinitely\n",
" outdone by the madness of men"
].join)
end
it "aligns multiline text to right with unicode characters" do
text = "ラドクリフ\n、マラソン五輪\n代表に1万m出\n場にも含み"
expect(Strings::Align.align_right(text, 20)).to eq([
" ラドクリフ\n",
" 、マラソン五輪\n",
" 代表に1万m出\n",
" 場にも含み"
].join)
end
it "right justfies ansi text" do
text = "for \e[35mthere\e[0m is no folly of the beast\nof the \e[33mearth\e0m which\nis \e[34mnot infinitely\e[0m\n\e[33moutdone\e[0m by the madness of men"
expect(Strings::Align.align_right(text, 40)).to eq([
" for \e[35mthere\e[0m is no folly of the beast\n",
" of the \e[33mearth\e0m which\n",
" is \e[34mnot infinitely\e[0m\n",
" \e[33moutdone\e[0m by the madness of men"
].join)
end
it "right justifies multiline text with fill of '*'" do
text = "for there is no folly of the beast\nof the earth which\nis not infinitely\noutdone by the madness of men"
expect(Strings::Align.align_right(text, 40, fill: '*')).to eq([
"******for there is no folly of the beast\n",
"**********************of the earth which\n",
"***********************is not infinitely\n",
"***********outdone by the madness of men"
].join)
end
it "handles \r\n line separator" do
text = "Closes #360\r\n\r\nCloses !217"
expect(Strings::Align.align_right(text, 27)).to eq([
" Closes #360",
" ",
" Closes !217"
].join("\r\n"))
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/spec/unit/align/align_spec.rb | spec/unit/align/align_spec.rb | # frozen_string_literal: true
RSpec.describe Strings::Align, "#align" do
it "doesn't align unrecognized direction" do
text = "the madness of men"
expect {
Strings::Align.align(text, 22, direction: :unknown)
}.to raise_error(ArgumentError, /Unknown alignment/)
end
it "fills empty" do
expect(Strings::Align.align("", 22, direction: :center)).to eq(" ")
end
it "centers line" do
text = "the madness of men"
expect(Strings::Align.align_center(text, 22)).to eq(" the madness of men ")
end
it "centers unicode characters" do
text = "こんにちは"
expect(Strings::Align.align_center(text, 20)).to eq(" こんにちは ")
end
it "centers string with ansi codes" do
text = "\e[32mthe madness of men\e[0m"
expect(Strings::Align.align_center(text, 22)).to eq(" \e[32mthe madness of men\e[0m ")
end
it "centers multiline text" do
text = "for there is no folly of the beast\nof the earth which\nis not infinitely\noutdone by the madness of men"
expect(Strings::Align.align_center(text, 40)).to eq([
" for there is no folly of the beast \n",
" of the earth which \n",
" is not infinitely \n",
" outdone by the madness of men "
].join)
end
it "centers multiline text with exact width" do
text = "the madness \nof men"
expect(Strings::Align.align_center(text, 12)).to eq([
"the madness \n",
" of men "
].join)
end
it "centers multiline unicode text" do
text = "ラドクリフ\n、マラソン五輪\n代表に1万m出\n場にも含み"
expect(Strings::Align.align_center(text, 20)).to eq([
" ラドクリフ \n",
" 、マラソン五輪 \n",
" 代表に1万m出 \n",
" 場にも含み "
].join)
end
it "centers text with ansi codes" do
text = "for \e[35mthere\e[0m is no folly of the beast\nof the \e[33mearth\e0m which\nis \e[34mnot infinitely\e[0m\n\e[33moutdone\e[0m by the madness of men"
expect(Strings::Align.align_center(text, 40)).to eq([
" for \e[35mthere\e[0m is no folly of the beast \n",
" of the \e[33mearth\e0m which \n",
" is \e[34mnot infinitely\e[0m \n",
" \e[33moutdone\e[0m by the madness of men "
].join)
end
it "centers multiline text with fill character '*'" do
text = "for there is no folly of the beast\nof the earth which\nis not infinitely\noutdone by the madness of men"
expect(Strings::Align.align(text, 40, direction: :center, fill: '*')).to eq([
"***for there is no folly of the beast***\n",
"***********of the earth which***********\n",
"***********is not infinitely************\n",
"*****outdone by the madness of men******"
].join)
end
it "handles \r\n line separator" do
text = "Closes #360\r\n\r\nCloses !217"
expect(Strings::Align.align(text, 27)).to eq([
"Closes #360 ",
" ",
"Closes !217 "
].join("\r\n"))
end
it "handles \r\n line separator and centers" do
text = "Closes #360\r\n\r\nCloses !217"
expect(Strings::Align.align_center(text, 27)).to eq([
" Closes #360 ",
" ",
" Closes !217 "
].join("\r\n"))
end
end
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/lib/strings.rb | lib/strings.rb | # frozen_string_literal: true
require "strings-ansi"
require_relative "strings/align"
require_relative "strings/fold"
require_relative "strings/pad"
require_relative "strings/truncate"
require_relative "strings/wrap"
require_relative "strings/version"
module Strings
# Align text within the width.
#
# @see Strings::Align#align
#
# @api public
def align(*args, **kws)
Align.align(*args, **kws)
end
module_function :align
# Align text left within the width.
#
# @see Strings::Align#align_left
#
# @api public
def align_left(*args)
Align.align_left(*args)
end
module_function :align_left
# Align text with the width.
#
# @see Strings::Align#align
#
# @api public
def align_center(*args)
Align.align_center(*args)
end
module_function :align_center
# Align text with the width.
#
# @see Strings::Align#align
#
# @api public
def align_right(*args)
Align.align_right(*args)
end
module_function :align_right
# Check if string contains ANSI codes
#
# @see Strings::ANSI#ansi?
#
# @api public
def ansi?(string)
ANSI.ansi?(string)
end
module_function :ansi?
# Remove any line break characters from the text
#
# @see Strings::Fold#fold
#
# @api public
def fold(*args)
Fold.fold(*args)
end
module_function :fold
# Apply padding to multiline text with ANSI codes
#
# @see Strings::Pad#pad
#
# @api public
def pad(*args)
Pad.pad(*args)
end
module_function :pad
# Remove ANSI codes from the string
#
# @see Strings::ANSI#sanitize
#
# @api public
def sanitize(string)
ANSI.sanitize(string)
end
module_function :sanitize
# Truncate a text at a given length
#
# @see Strings::Truncate#truncate
#
# @api public
def truncate(*args)
Truncate.truncate(*args)
end
module_function :truncate
# Wrap a text into lines at wrap length
#
# @see Strings::Wrap#wrap
#
# @api public
def wrap(*args)
Wrap.wrap(*args)
end
module_function :wrap
end # Strings
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
piotrmurach/strings | https://github.com/piotrmurach/strings/blob/30854c1544d0ae020e2c00ef3b33f0240f47a921/lib/strings/align.rb | lib/strings/align.rb | # frozen_string_literal: true
require "strings-ansi"
require "unicode/display_width"
module Strings
# Responsible for text alignment
module Align
NEWLINE = "\n"
SPACE = " "
LINE_BREAK = %r{\r\n|\r|\n}.freeze
# Aligns text within the width.
#
# If the text is greater than the width then unmodified
# string is returned.
#
# @param [String] text
# the text to align lines of
# @param [Integer] width
# the maximum width to align to
#
# @example
# text = "the madness of men"
#
# Strings::Align.align(text, 22, direction: :left)
# # => "the madness of men "
#
# Strings::Align.align(text, 22, direction: :center)
# # => " the madness of men "
#
# Strings::Align(text, 22, direction: :right)
# # => " the madness of men"
#
# Strings::Align.align(text, 22, direction: :center, fill: "*")
# # => "***the madness of men***"
#
# @api public
def align(text, width, direction: :left, **options)
return text if width.nil?
method = to_alignment(direction)
send(method, text, width, **options)
end
module_function :align
# Convert direction to method name
#
# @api private
def to_alignment(direction)
case direction.to_sym
when :left then :align_left
when :right then :align_right
when :center then :align_center
else
raise ArgumentError, "Unknown alignment `#{direction}`."
end
end
module_function :to_alignment
# Aligns text to the left at given length
#
# @return [String]
#
# @api public
def align_left(text, width, fill: SPACE, separator: nil)
return if width.nil?
sep = separator || text[LINE_BREAK] || NEWLINE
each_line(text, sep) do |line|
width_diff = width - display_width(line)
if width_diff > 0
line + fill * width_diff
else
line
end
end
end
module_function :align_left
# Centers text within the width
#
# @return [String]
#
# @api public
def align_center(text, width, fill: SPACE, separator: nil)
return text if width.nil?
sep = separator || text[LINE_BREAK] || NEWLINE
each_line(text, sep) do |line|
width_diff = width - display_width(line)
if width_diff > 0
right_count = (width_diff.to_f / 2).ceil
left_count = width_diff - right_count
[fill * left_count, line, fill * right_count].join
else
line
end
end
end
module_function :align_center
# Aligns text to the right at given length
#
# @return [String]
#
# @api public
def align_right(text, width, fill: SPACE, separator: nil)
return text if width.nil?
sep = separator || text[LINE_BREAK] || NEWLINE
each_line(text, sep) do |line|
width_diff = width - display_width(line)
if width_diff > 0
fill * width_diff + line
else
line
end
end
end
module_function :align_right
# Enumerate text line by line
#
# @param [String] text
#
# @return [String]
#
# @api private
def each_line(text, separator)
lines = text.split(separator)
return yield(text) if text.empty?
lines.reduce([]) do |aligned, line|
aligned << yield(line)
end.join(separator)
end
module_function :each_line
# Visible width of a string
#
# @api private
def display_width(string)
Unicode::DisplayWidth.of(Strings::ANSI.sanitize(string))
end
module_function :display_width
end # Align
end # Strings
| ruby | MIT | 30854c1544d0ae020e2c00ef3b33f0240f47a921 | 2026-01-04T17:48:15.474368Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.