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 |
|---|---|---|---|---|---|---|---|---|
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/range/overlap_spec.rb | spec/motion-support/core_ext/range/overlap_spec.rb | describe "Range" do
describe "overlaps?" do
it "should overlaps last inclusive" do
(1..5).overlaps?(5..10).should.be.true
end
it "should overlaps last exclusive" do
(1...5).overlaps?(5..10).should.be.false
end
it "should overlaps first inclusive" do
(5..10).overlaps?(1..5).should.be.true
end
it "should overlaps first exclusive" do
(5..10).overlaps?(1...5).should.be.false
end
it "should should compare identical inclusive" do
((1..10) === (1..10)).should.be.true
end
it "should should compare identical exclusive" do
((1...10) === (1...10)).should.be.true
end
it "should should compare other with exlusive end" do
((1..10) === (1...10)).should.be.true
end
it "should overlaps on time" do
time_range_1 = Time.utc(2005, 12, 10, 15, 30)..Time.utc(2005, 12, 10, 17, 30)
time_range_2 = Time.utc(2005, 12, 10, 17, 00)..Time.utc(2005, 12, 10, 18, 00)
time_range_1.overlaps?(time_range_2).should.be.true
end
it "should no overlaps on time" do
time_range_1 = Time.utc(2005, 12, 10, 15, 30)..Time.utc(2005, 12, 10, 17, 30)
time_range_2 = Time.utc(2005, 12, 10, 17, 31)..Time.utc(2005, 12, 10, 18, 00)
time_range_1.overlaps?(time_range_2).should.be.false
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/time/calculation_spec.rb | spec/motion-support/core_ext/time/calculation_spec.rb | describe "Time" do
describe "calculations" do
describe "seconds_since_midnight" do
it "should calculate correctly" do
Time.local(2005,1,1,0,0,1).seconds_since_midnight.should == 1
Time.local(2005,1,1,0,1,0).seconds_since_midnight.should == 60
Time.local(2005,1,1,1,1,0).seconds_since_midnight.should == 3660
Time.local(2005,1,1,23,59,59).seconds_since_midnight.should == 86399
Time.local(2005,1,1,0,1,0,10).seconds_since_midnight.should == 60.00001
end
end
describe "seconds_until_end_of_day" do
it "should calculate correctly" do
Time.local(2005,1,1,23,59,59).seconds_until_end_of_day.should == 0
Time.local(2005,1,1,23,59,58).seconds_until_end_of_day.should == 1
Time.local(2005,1,1,23,58,59).seconds_until_end_of_day.should == 60
Time.local(2005,1,1,22,58,59).seconds_until_end_of_day.should == 3660
Time.local(2005,1,1,0,0,0).seconds_until_end_of_day.should == 86399
end
end
describe "beginning_of_day" do
it "should calculate correctly" do
Time.local(2005,2,4,10,10,10).beginning_of_day.should == Time.local(2005,2,4,0,0,0)
end
end
describe "beginning_of_hour" do
it "should calculate correctly" do
Time.local(2005,2,4,19,30,10).beginning_of_hour.should == Time.local(2005,2,4,19,0,0)
end
end
describe "beginning_of_minute" do
it "should calculate correctly" do
Time.local(2005,2,4,19,30,10).beginning_of_minute.should == Time.local(2005,2,4,19,30,0)
end
end
describe "end_of_day" do
it "should calculate correctly" do
Time.local(2007,8,12,10,10,10).end_of_day.should == Time.local(2007,8,12,23,59,59,Rational(999999999, 1000))
end
end
describe "end_of_hour" do
it "should calculate correctly" do
Time.local(2005,2,4,19,30,10).end_of_hour.should == Time.local(2005,2,4,19,59,59,Rational(999999999, 1000))
end
end
describe "end_of_minute" do
it "should calculate correctly" do
Time.local(2005,2,4,19,30,10).end_of_minute.should == Time.local(2005,2,4,19,30,59,Rational(999999999, 1000))
end
end
describe "last_year" do
it "should calculate correctly" do
Time.local(2005,6,5,10,0,0).last_year.should == Time.local(2004,6,5,10)
end
end
describe "ago" do
it "should calculate correctly" do
Time.local(2005,2,22,10,10,10).ago(1).should == Time.local(2005,2,22,10,10,9)
Time.local(2005,2,22,10,10,10).ago(3600).should == Time.local(2005,2,22,9,10,10)
Time.local(2005,2,22,10,10,10).ago(86400*2).should == Time.local(2005,2,20,10,10,10)
Time.local(2005,2,22,10,10,10).ago(86400*2 + 3600 + 25).should == Time.local(2005,2,20,9,9,45)
end
end
describe "since" do
it "should calculate correctly" do
Time.local(2005,2,22,10,10,10).since(1).should == Time.local(2005,2,22,10,10,11)
Time.local(2005,2,22,10,10,10).since(3600).should == Time.local(2005,2,22,11,10,10)
Time.local(2005,2,22,10,10,10).since(86400*2).should == Time.local(2005,2,24,10,10,10)
Time.local(2005,2,22,10,10,10).since(86400*2 + 3600 + 25).should == Time.local(2005,2,24,11,10,35)
end
end
describe "change" do
it "should calculate correctly" do
Time.local(2005,2,22,15,15,10).change(:year => 2006).should == Time.local(2006,2,22,15,15,10)
Time.local(2005,2,22,15,15,10).change(:month => 6).should == Time.local(2005,6,22,15,15,10)
Time.local(2005,2,22,15,15,10).change(:year => 2012, :month => 9).should == Time.local(2012,9,22,15,15,10)
Time.local(2005,2,22,15,15,10).change(:hour => 16).should == Time.local(2005,2,22,16)
Time.local(2005,2,22,15,15,10).change(:hour => 16, :min => 45).should == Time.local(2005,2,22,16,45)
Time.local(2005,2,22,15,15,10).change(:min => 45).should == Time.local(2005,2,22,15,45)
Time.local(2005,1,2,11,22,33,44).change(:hour => 5).should == Time.local(2005,1,2,5,0,0,0)
Time.local(2005,1,2,11,22,33,44).change(:min => 6).should == Time.local(2005,1,2,11,6,0,0)
Time.local(2005,1,2,11,22,33,44).change(:sec => 7).should == Time.local(2005,1,2,11,22,7,0)
Time.local(2005,1,2,11,22,33,44).change(:usec => 8).should == Time.local(2005,1,2,11,22,33,8)
end
end
describe "advance" do
it "should calculate correctly" do
Time.local(2005,2,28,15,15,10).advance(:years => 1).should == Time.local(2006,2,28,15,15,10)
Time.local(2005,2,28,15,15,10).advance(:months => 4).should == Time.local(2005,6,28,15,15,10)
Time.local(2005,2,28,15,15,10).advance(:weeks => 3).should == Time.local(2005,3,21,15,15,10)
Time.local(2005,2,28,15,15,10).advance(:weeks => 3.5).should == Time.local(2005,3,25,3,15,10)
Time.local(2005,2,28,15,15,10).advance(:days => 5).should == Time.local(2005,3,5,15,15,10)
Time.local(2005,2,28,15,15,10).advance(:days => 5.5).should == Time.local(2005,3,6,3,15,10)
Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 7).should == Time.local(2012,9,28,15,15,10)
Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :days => 5).should == Time.local(2013,10,3,15,15,10)
Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5).should == Time.local(2013,10,17,15,15,10)
Time.local(2005,2,28,15,15,10).advance(:years => -3, :months => -2, :days => -1).should == Time.local(2001,12,27,15,15,10)
Time.local(2004,2,29,15,15,10).advance(:years => 1).should == Time.local(2005,2,28,15,15,10)
Time.local(2005,2,28,15,15,10).advance(:hours => 5).should == Time.local(2005,2,28,20,15,10)
Time.local(2005,2,28,15,15,10).advance(:minutes => 7).should == Time.local(2005,2,28,15,22,10)
Time.local(2005,2,28,15,15,10).advance(:seconds => 9).should == Time.local(2005,2,28,15,15,19)
Time.local(2005,2,28,15,15,10).advance(:hours => 5, :minutes => 7, :seconds => 9).should == Time.local(2005,2,28,20,22,19)
Time.local(2005,2,28,15,15,10).advance(:hours => -5, :minutes => -7, :seconds => -9).should == Time.local(2005,2,28,10,8,1)
Time.local(2005,2,28,15,15,10).advance(:years => 7, :months => 19, :weeks => 2, :days => 5, :hours => 5, :minutes => 7, :seconds => 9).should == Time.local(2013,10,17,20,22,19)
end
it "should advance with nsec" do
t = Time.at(0, Rational(108635108, 1000))
t.advance(:months => 0).should == t
end
end
describe "days_in_month" do
it "should calculate with year" do
Time.days_in_month(1, 2005).should == 31
Time.days_in_month(2, 2005).should == 28
Time.days_in_month(2, 2004).should == 29
Time.days_in_month(2, 2000).should == 29
Time.days_in_month(2, 1900).should == 28
Time.days_in_month(3, 2005).should == 31
Time.days_in_month(4, 2005).should == 30
Time.days_in_month(5, 2005).should == 31
Time.days_in_month(6, 2005).should == 30
Time.days_in_month(7, 2005).should == 31
Time.days_in_month(8, 2005).should == 31
Time.days_in_month(9, 2005).should == 30
Time.days_in_month(10, 2005).should == 31
Time.days_in_month(11, 2005).should == 30
Time.days_in_month(12, 2005).should == 31
end
it "should calculate for february in common year" do
Time.days_in_month(2, 2007).should == 28
end
it "should calculate for february in leap year" do
Time.days_in_month(2, 2008).should == 29
end
end
describe "last_month" do
it "should work on the 31st" do
Time.local(2004, 3, 31).last_month.should == Time.local(2004, 2, 29)
end
end
describe "<=>" do
it "should compare with time" do
(Time.utc(2000) <=> Time.utc(1999, 12, 31, 23, 59, 59, 999)).should == 1
(Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0)).should == 0
(Time.utc(2000) <=> Time.utc(2000, 1, 1, 0, 0, 0, 001)).should == -1
end
end
describe "all_day" do
it "should calculate correctly" do
Time.local(2011,6,7,10,10,10).all_day.should == (Time.local(2011,6,7,0,0,0)..Time.local(2011,6,7,23,59,59,Rational(999999999, 1000)))
end
end
describe "all_week" do
it "should calculate correctly" do
Time.local(2011,6,7,10,10,10).all_week.should == (Time.local(2011,6,6,0,0,0)..Time.local(2011,6,12,23,59,59,Rational(999999999, 1000)))
Time.local(2011,6,7,10,10,10).all_week(:sunday).should == (Time.local(2011,6,5,0,0,0)..Time.local(2011,6,11,23,59,59,Rational(999999999, 1000)))
end
end
describe "all_month" do
it "should calculate correctly" do
Time.local(2011,6,7,10,10,10).all_month.should == (Time.local(2011,6,1,0,0,0)..Time.local(2011,6,30,23,59,59,Rational(999999999, 1000)))
end
end
describe "all_quarter" do
it "should calculate correctly" do
Time.local(2011,6,7,10,10,10).all_quarter.should == (Time.local(2011,4,1,0,0,0)..Time.local(2011,6,30,23,59,59,Rational(999999999, 1000)))
end
end
describe "all_year" do
it "should calculate correctly" do
Time.local(2011,6,7,10,10,10).all_year.should == (Time.local(2011,1,1,0,0,0)..Time.local(2011,12,31,23,59,59,Rational(999999999, 1000)))
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/time/acts_like_spec.rb | spec/motion-support/core_ext/time/acts_like_spec.rb | describe "Time" do
describe "acts_like" do
it "should act like time" do
Time.now.should.acts_like(:time)
end
it "should not act like date" do
Time.now.should.not.acts_like(:date)
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/time/conversion_spec.rb | spec/motion-support/core_ext/time/conversion_spec.rb | describe "Time" do
describe "conversions" do
describe "to_formatted_s" do
before do
@time = Time.utc(2005, 2, 21, 17, 44, 30.12345678901)
end
it "should use default conversion if no parameter is given" do
@time.to_s.should == @time.to_default_s
end
it "should use default conversion if parameter is unknown" do
@time.to_s(:doesnt_exist).should == @time.to_default_s
end
it "should convert to db format" do
@time.to_s(:db).should == "2005-02-21 17:44:30"
end
it "should convert to short format" do
@time.to_s(:short).should == "21 Feb 17:44"
end
it "should convert to time format" do
@time.to_s(:time).should == "17:44"
end
it "should convert to number format" do
@time.to_s(:number).should == "20050221174430"
end
it "should convert to nsec format" do
@time.to_s(:nsec).should == "20050221174430123456789"
end
it "should convert to long format" do
@time.to_s(:long).should == "February 21, 2005 17:44"
end
it "should convert to long_ordinal format" do
@time.to_s(:long_ordinal).should == "February 21st, 2005 17:44"
end
end
describe "custom date format" do
it "should convert to custom format" do
Time::DATE_FORMATS[:custom] = '%Y%m%d%H%M%S'
Time.local(2005, 2, 21, 14, 30, 0).to_s(:custom).should == '20050221143000'
Time::DATE_FORMATS.delete(:custom)
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/object/blank_spec.rb | spec/motion-support/core_ext/object/blank_spec.rb | class EmptyTrue
def empty?() true; end
end
class EmptyFalse
def empty?() false; end
end
BLANK = [ EmptyTrue.new, nil, false, '', ' ', " \n\t \r ", ' ', [], {} ]
NOT = [ EmptyFalse.new, Object.new, true, 0, 1, 'a', [nil], { nil => 0 } ]
describe "blank" do
describe "blank?" do
BLANK.each do |v|
it "should treat #{v.inspect} as blank" do
v.should.be.blank
end
end
NOT.each do |v|
it "should treat #{v.inspect} as NOT blank" do
v.should.not.be.blank
end
end
end
describe "present?" do
BLANK.each do |v|
it "should treat #{v.inspect} as NOT present" do
v.should.not.be.present
end
end
NOT.each do |v|
it "should treat #{v.inspect} as present" do
v.should.be.present
end
end
end
describe "presence" do
BLANK.each do |v|
it "should return nil for #{v.inspect}.presence" do
v.presence.should.be.nil
end
end
NOT.each do |v|
it "should return self for #{v.inspect}.presence" do
v.presence.should == v
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/object/instance_variable_spec.rb | spec/motion-support/core_ext/object/instance_variable_spec.rb | describe "Object" do
before do
@source = Object.new
@source.instance_variable_set(:@bar, 'bar')
@source.instance_variable_set(:@baz, 'baz')
end
describe "instance_variable_names" do
it "should return all instance variable names" do
@source.instance_variable_names.sort.should == %w(@bar @baz)
end
end
describe "instance_values" do
it "should return the values of all instance variables as a hash" do
@source.instance_values.should == {'bar' => 'bar', 'baz' => 'baz'}
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/object/acts_like_spec.rb | spec/motion-support/core_ext/object/acts_like_spec.rb | class DuckFoo
def acts_like_foo?
true
end
end
describe "Object" do
describe "acts_like" do
it "should not act like anything" do
object = Object.new
object.should.not.acts_like(:time)
object.should.not.acts_like(:date)
object.should.not.acts_like(:foo)
end
it "should allow subclasses to act like something" do
object = DuckFoo.new
object.should.acts_like(:foo)
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/object/to_param_spec.rb | spec/motion-support/core_ext/object/to_param_spec.rb | class ArrayToParam < String
def to_param
"#{self}1"
end
end
class HashToParam < String
def to_param
"#{self}-1"
end
end
describe "to_param" do
describe "object" do
it "should delegate to to_s" do
foo = Object.new
def foo.to_s; 'foo' end
foo.to_param.should == 'foo'
end
end
describe "nil" do
it "should return self" do
nil.to_param.should == nil
end
end
describe "true, false" do
it "should return self" do
true.to_param.should == true
false.to_param.should == false
end
end
describe "array" do
it "should convert string array" do
%w().to_param.should == ''
%w(hello world).to_param.should == 'hello/world'
%w(hello 10).to_param.should == 'hello/10'
end
it "should convert number array" do
[10, 20].to_param.should == '10/20'
end
it "should convert custom object array" do
[ArrayToParam.new('custom'), ArrayToParam.new('param')].to_param.should == 'custom1/param1'
end
end
describe "hash" do
it "should convert a string hash" do
{}.to_param.should == ''
{ :hello => "world" }.to_param.should == 'hello=world'
{ "hello" => 10 }.to_param.should == 'hello=10'
{:hello => "world", "say_bye" => true}.to_param.should == 'hello=world&say_bye=true'
end
it "should convert a number hash" do
{10 => 20, 30 => 40, 50 => 60}.to_param.should == '10=20&30=40&50=60'
end
it "should convert an object hash" do
{HashToParam.new('custom') => HashToParam.new('param'), HashToParam.new('custom2') => HashToParam.new('param2')}.to_param.should == 'custom-1=param-1&custom2-1=param2-1'
end
it "should escape keys and values" do
{ 'param 1' => 'A string with / characters & that should be ? escaped' }.to_param.should == 'param+1=A+string+with+%2F+characters+%26+that+should+be+%3F+escaped'
end
it "should order keys in ascending order" do
Hash[*%w(b 1 c 0 a 2)].to_param.should == 'a=2&b=1&c=0'
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/object/try_spec.rb | spec/motion-support/core_ext/object/try_spec.rb | describe "Object" do
before do
@string = "Hello"
end
describe "try" do
it "should return nil for nonexisting method" do
method = :undefined_method
@string.should.not.respond_to method
@string.try(method).should.be.nil
end
it "should return nil for nonexisting method with arguments" do
method = :undefined_method
@string.should.not.respond_to method
@string.try(method, 'llo', 'y').should.be.nil
end
it "should delegate to existing method" do
@string.try(:size).should == 5
end
it "should forward arguments to existing method" do
@string.try(:sub, 'llo', 'y').should == 'Hey'
end
it "should forward block to existing method" do
@string.try(:sub, 'llo') { |match| 'y' }.should == 'Hey'
end
it "should return nil when called on nil even if method is defined on nil" do
nil.try(:to_s).should.be.nil
nil.try(:to_i).should.be.nil
end
it "should work as expected on false" do
false.try(:to_s).should == 'false'
end
it "should pass existing receiver to block" do
@string.try { |s| s.reverse }.should == @string.reverse
end
it "should not pass nil to block" do
ran = false
nil.try { ran = true }
ran.should == false
end
it "should not call private method" do
klass = Class.new do
private
def private_method
'private method'
end
end
klass.new.try(:private_method).should == nil
end
end
describe "try!" do
it "should raise error for nonexisting method" do
method = :undefined_method
@string.should.not.respond_to method
lambda { @string.try!(method) }.should.raise NoMethodError
end
it "should raise error for nonexisting method with arguments" do
method = :undefined_method
@string.should.not.respond_to method
lambda { @string.try!(method, 'llo', 'y') }.should.raise NoMethodError
end
it "should pass existing receiver to block" do
@string.try! { |s| s.reverse }.should == @string.reverse
end
it "should raise error when calling private method" do
klass = Class.new do
private
def private_method
'private method'
end
end
lambda { klass.new.try!(:private_method) }.should.raise NoMethodError
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/object/to_query_spec.rb | spec/motion-support/core_ext/object/to_query_spec.rb | class Should
def equal_query(query)
@object.to_query.split('&').should == query.split('&')
end
end
describe "to_query" do
it "should do a simple converion" do
{ :a => 10 }.should.equal_query 'a=10'
end
it "should escape for CGI" do
{ 'a:b' => 'c d' }.should.equal_query 'a%3Ab=c+d'
end
it "should work with nil parameter value" do
empty = Object.new
def empty.to_param; nil end
{ 'a' => empty }.should.equal_query 'a='
end
it "should do a nested conversion" do
{ :person => Hash[:login, 'seckar', :name, 'Nicholas'] }.should.equal_query 'person%5Blogin%5D=seckar&person%5Bname%5D=Nicholas'
end
it "should do a multiply nested query" do
Hash[:account, {:person => {:id => 20}}, :person, {:id => 10}].should.equal_query 'account%5Bperson%5D%5Bid%5D=20&person%5Bid%5D=10'
end
it "should work with array values" do
{ :person => {:id => [10, 20]} }.should.equal_query 'person%5Bid%5D%5B%5D=10&person%5Bid%5D%5B%5D=20'
end
it "should not sort array values" do
{ :person => {:id => [20, 10]} }.should.equal_query 'person%5Bid%5D%5B%5D=20&person%5Bid%5D%5B%5D=10'
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/object/deep_dup_spec.rb | spec/motion-support/core_ext/object/deep_dup_spec.rb | describe "deep_dup" do
describe "array" do
it "should deep_dup nested array" do
array = [1, [2, 3]]
dup = array.deep_dup
dup[1][2] = 4
array[1][2].should.be.nil
dup[1][2].should == 4
end
it "should deep_dup array with hash inside" do
array = [1, { :a => 2, :b => 3 } ]
dup = array.deep_dup
dup[1][:c] = 4
array[1][:c].should.be.nil
dup[1][:c].should == 4
end
end
describe "hash" do
it "should deep_dup nested hash" do
hash = { :a => { :b => 'b' } }
dup = hash.deep_dup
dup[:a][:c] = 'c'
hash[:a][:c].should.be.nil
dup[:a][:c].should == 'c'
end
it "should deep_dup hash with array inside" do
hash = { :a => [1, 2] }
dup = hash.deep_dup
dup[:a][2] = 'c'
hash[:a][2].should.be.nil
dup[:a][2].should == 'c'
end
it "should deep_dup hash with init value" do
zero_hash = Hash.new 0
hash = { :a => zero_hash }
dup = hash.deep_dup
dup[:a][44].should == 0
end
end
describe "Object" do
it "should deep_dup object" do
object = Object.new
dup = object.deep_dup
dup.instance_variable_set(:@a, 1)
object.should.not.be.instance_variable_defined(:@a)
dup.should.be.instance_variable_defined(:@a)
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/object/inclusion_spec.rb | spec/motion-support/core_ext/object/inclusion_spec.rb | class LifeUniverseAndEverything
def include?(obj)
obj == 42
end
end
describe 'array' do
describe "in?" do
it "should support arrays" do
1.in?([1,2,3]).should == true
0.in?([1,2,3]).should == false
end
it "should support hashes" do
:a.in?({a:1,b:2,c:3}).should == true
1.in?({a:1,b:2,c:3}).should == false
end
it "should support ranges" do
1.in?(1..3).should == true
0.in?(1..3).should == false
end
it "should support strings" do
'a'.in?("apple").should == true
end
it "should support anything that implements `include?`" do
42.in?(LifeUniverseAndEverything.new).should == true
0.in?(LifeUniverseAndEverything.new).should == false
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/object/to_json_spec.rb | spec/motion-support/core_ext/object/to_json_spec.rb | describe ".to_json" do
describe "object" do
it "should serialize attributes" do
foo = Object.new
class << foo
attr_accessor :test
end
foo.test = 'bar'
foo.to_json.should == '{"test":"bar"}'
end
end
describe "nil" do
it "should return null" do
nil.to_json.should == 'null'
end
end
describe "true, false" do
it "should return self as string" do
true.to_json.should == 'true'
false.to_json.should == 'false'
end
end
describe "string" do
it "should escape the required characters" do
'A string with special \ " &'.to_json.should == "\"A string with special \\\\ \\\" \\u0026\""
end
end
describe "numeric" do
it "should return self" do
2.days.to_json.should == 172800
end
end
describe "Time" do
it "should return iso8601" do
Time.new(2015, 12, 25, 1, 2, 3, '-05:00').utc.to_json.should == '"2015-12-25T06:02:03Z"'
end
end
describe "Date" do
it "should return iso8601" do
Date.new(2015, 12, 25).to_json.should == '"2015-12-25"'
end
end
describe "array" do
it "should convert mixed type array" do
input = [true, false, nil, {:foo => :bar}, 'fizz', '', Time.new(2015, 12, 25, 1, 2, 3, '-05:00').utc, Date.new(2015, 12, 25)]
output = '[true,false,null,{"foo":"bar"},"fizz","","2015-12-25T06:02:03Z","2015-12-25"]'
input.to_json.should == output
end
end
describe "hash" do
it "should convert a string hash" do
{}.to_json.should == '{}'
{ :hello => :world }.to_json.should == '{"hello":"world"}'
{ :hello => "world" }.to_json.should == '{"hello":"world"}'
{ "hello" => 10 }.to_json.should == '{"hello":10}'
{ "hello" => { "world" => "hi" } }.to_json.should == '{"hello":{"world":"hi"}}'
{:hello => "world", "say_bye" => true}.to_json.should == '{"hello":"world","say_bye":true}'
end
it "should convert a number hash" do
{10 => 20, 30 => 40, 50 => 60}.to_json.should == '{"10":20,"30":40,"50":60}'
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/object/duplicable_spec.rb | spec/motion-support/core_ext/object/duplicable_spec.rb | describe "duplicable?" do
before do
@raise_dup = [nil, false, true]
@yes = ['1', Object.new, /foo/, [], {}, Time.now, Class.new, Module.new]
@no = []
end
it "should return false for non-duplicable objects" do
(@raise_dup + @no).each do |v|
v.should.not.be.duplicable
end
end
it "should return true for duplicable objects" do
@yes.each do |v|
v.should.be.duplicable
end
end
it "should not raise when dupping duplicable objects" do
(@yes + @no).each do |v|
lambda { v.dup }.should.not.raise
end
end
it "should raise when dupping non-duplicable objects" do
@raise_dup.each do |v|
lambda { v.dup }.should.raise TypeError
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/date_and_time/calculation_spec.rb | spec/motion-support/core_ext/date_and_time/calculation_spec.rb | class Date
def self.for_spec(year, month, day, hour, minute, second, usec)
new(year, month, day)
end
end
class Time
def self.for_spec(year, month, day, hour, minute, second, usec)
local(year, month, day, hour, minute, second, usec)
end
end
[Date, Time].each do |klass|
describe klass do
@klass = klass
def date_or_time(year, month, day, hour, minute, second, usec = nil)
@klass.for_spec(year, month, day, hour, minute, second, usec)
end
def with_bw_default(bw = :monday)
old_bw = Date.beginning_of_week
Date.beginning_of_week = bw
yield
ensure
Date.beginning_of_week = old_bw
end
describe "yesterday" do
it "should be calculated correctly" do
date_or_time(2005,2,22,10,10,10).yesterday.should == date_or_time(2005,2,21,10,10,10)
date_or_time(2005,3,2,10,10,10).yesterday.yesterday.should == date_or_time(2005,2,28,10,10,10)
end
end
describe "tomorrow" do
it "should be calculated correctly" do
date_or_time(2005,2,22,10,10,10).tomorrow.should == date_or_time(2005,2,23,10,10,10)
date_or_time(2005,2,28,10,10,10).tomorrow.tomorrow.should == date_or_time(2005,3,2,10,10,10)
end
end
describe "days_ago" do
it "should be calculated correctly" do
date_or_time(2005,6,5,10,10,10).days_ago(1).should == date_or_time(2005,6,4,10,10,10)
date_or_time(2005,6,5,10,10,10).days_ago(5).should == date_or_time(2005,5,31,10,10,10)
end
end
describe "days_since" do
it "should be calculated correctly" do
date_or_time(2005,6,5,10,10,10).days_since(1).should == date_or_time(2005,6,6,10,10,10)
date_or_time(2004,12,31,10,10,10).days_since(1).should == date_or_time(2005,1,1,10,10,10)
end
end
describe "weeks_ago" do
it "should be calculated correctly" do
date_or_time(2005,6,5,10,10,10).weeks_ago(1).should == date_or_time(2005,5,29,10,10,10)
date_or_time(2005,6,5,10,10,10).weeks_ago(5).should == date_or_time(2005,5,1,10,10,10)
date_or_time(2005,6,5,10,10,10).weeks_ago(6).should == date_or_time(2005,4,24,10,10,10)
date_or_time(2005,6,5,10,10,10).weeks_ago(14).should == date_or_time(2005,2,27,10,10,10)
date_or_time(2005,1,1,10,10,10).weeks_ago(1).should == date_or_time(2004,12,25,10,10,10)
end
end
describe "weeks_since" do
it "should be calculated correctly" do
date_or_time(2005,7,7,10,10,10).weeks_since(1).should == date_or_time(2005,7,14,10,10,10)
date_or_time(2005,7,7,10,10,10).weeks_since(1).should == date_or_time(2005,7,14,10,10,10)
date_or_time(2005,6,27,10,10,10).weeks_since(1).should == date_or_time(2005,7,4,10,10,10)
date_or_time(2004,12,28,10,10,10).weeks_since(1).should == date_or_time(2005,1,4,10,10,10)
end
end
describe "months_ago" do
it "should be calculated correctly" do
date_or_time(2005,6,5,10,10,10).months_ago(1).should == date_or_time(2005,5,5,10,10,10)
date_or_time(2005,6,5,10,10,10).months_ago(7).should == date_or_time(2004,11,5,10,10,10)
date_or_time(2005,6,5,10,10,10).months_ago(6).should == date_or_time(2004,12,5,10,10,10)
date_or_time(2005,6,5,10,10,10).months_ago(12).should == date_or_time(2004,6,5,10,10,10)
date_or_time(2005,6,5,10,10,10).months_ago(24).should == date_or_time(2003,6,5,10,10,10)
end
end
describe "months_since" do
it "should be calculated correctly" do
date_or_time(2005,6,5,10,10,10).months_since(1).should == date_or_time(2005,7,5,10,10,10)
date_or_time(2005,12,5,10,10,10).months_since(1).should == date_or_time(2006,1,5,10,10,10)
date_or_time(2005,6,5,10,10,10).months_since(6).should == date_or_time(2005,12,5,10,10,10)
date_or_time(2005,12,5,10,10,10).months_since(6).should == date_or_time(2006,6,5,10,10,10)
date_or_time(2005,6,5,10,10,10).months_since(7).should == date_or_time(2006,1,5,10,10,10)
date_or_time(2005,6,5,10,10,10).months_since(12).should == date_or_time(2006,6,5,10,10,10)
date_or_time(2005,6,5,10,10,10).months_since(24).should == date_or_time(2007,6,5,10,10,10)
date_or_time(2005,3,31,10,10,10).months_since(1).should == date_or_time(2005,4,30,10,10,10)
date_or_time(2005,1,29,10,10,10).months_since(1).should == date_or_time(2005,2,28,10,10,10)
date_or_time(2005,1,30,10,10,10).months_since(1).should == date_or_time(2005,2,28,10,10,10)
date_or_time(2005,1,31,10,10,10).months_since(1).should == date_or_time(2005,2,28,10,10,10)
end
end
describe "years_ago" do
it "should be calculated correctly" do
date_or_time(2005,6,5,10,10,10).years_ago(1).should == date_or_time(2004,6,5,10,10,10)
date_or_time(2005,6,5,10,10,10).years_ago(7).should == date_or_time(1998,6,5,10,10,10)
# 1 year ago from leap day
date_or_time(2004,2,29,10,10,10).years_ago(1).should == date_or_time(2003,2,28,10,10,10)
end
end
describe "years_since" do
it "should be calculated correctly" do
date_or_time(2005,6,5,10,10,10).years_since(1).should == date_or_time(2006,6,5,10,10,10)
date_or_time(2005,6,5,10,10,10).years_since(7).should == date_or_time(2012,6,5,10,10,10)
# 1 year since leap day
date_or_time(2004,2,29,10,10,10).years_since(1).should == date_or_time(2005,2,28,10,10,10)
end
end
describe "beginning_of_month" do
it "should be calculated correctly" do
date_or_time(2005,2,22,10,10,10).beginning_of_month.should == date_or_time(2005,2,1,0,0,0)
end
end
describe "beginning_of_quarter" do
it "should be calculated correctly" do
date_or_time(2005,2,15,10,10,10).beginning_of_quarter.should == date_or_time(2005,1,1,0,0,0)
date_or_time(2005,1,1,0,0,0).beginning_of_quarter.should == date_or_time(2005,1,1,0,0,0)
date_or_time(2005,12,31,10,10,10).beginning_of_quarter.should == date_or_time(2005,10,1,0,0,0)
date_or_time(2005,6,30,23,59,59).beginning_of_quarter.should == date_or_time(2005,4,1,0,0,0)
end
end
describe "end_of_quarter" do
it "should be calculated correctly" do
date_or_time(2007,2,15,10,10,10).end_of_quarter.should == date_or_time(2007,3,31,23,59,59,Rational(999999999, 1000))
date_or_time(2007,3,31,0,0,0).end_of_quarter.should == date_or_time(2007,3,31,23,59,59,Rational(999999999, 1000))
date_or_time(2007,12,21,10,10,10).end_of_quarter.should == date_or_time(2007,12,31,23,59,59,Rational(999999999, 1000))
date_or_time(2007,4,1,0,0,0).end_of_quarter.should == date_or_time(2007,6,30,23,59,59,Rational(999999999, 1000))
date_or_time(2008,5,31,0,0,0).end_of_quarter.should == date_or_time(2008,6,30,23,59,59,Rational(999999999, 1000))
end
end
describe "beginning_of_year" do
it "should be calculated correctly" do
date_or_time(2005,2,22,10,10,10).beginning_of_year.should == date_or_time(2005,1,1,0,0,0)
end
end
describe "next_week" do
it "should be calculated correctly" do
date_or_time(2005,2,22,15,15,10).next_week.should == date_or_time(2005,2,28,0,0,0)
date_or_time(2005,2,22,15,15,10).next_week(:friday).should == date_or_time(2005,3,4,0,0,0)
date_or_time(2006,10,23,0,0,0).next_week.should == date_or_time(2006,10,30,0,0,0)
date_or_time(2006,10,23,0,0,0).next_week(:wednesday).should == date_or_time(2006,11,1,0,0,0)
end
it "should be calculated correctly with default beginning of week" do
# calling with_bw_default produces LocalJumpError, even though a block is given
begin
old_bw = Date.beginning_of_week
Date.beginning_of_week = :tuesday
date_or_time(2012,3,21,0,0,0).next_week(:wednesday).should == date_or_time(2012,3,28,0,0,0)
date_or_time(2012,3,21,0,0,0).next_week(:saturday).should == date_or_time(2012,3,31,0,0,0)
date_or_time(2012,3,21,0,0,0).next_week(:tuesday).should == date_or_time(2012,3,27,0,0,0)
date_or_time(2012,3,21,0,0,0).next_week(:monday).should == date_or_time(2012,4,02,0,0,0)
ensure
Date.beginning_of_week = old_bw
end
end
end
describe "next_month" do
it "should be calculated correctly" do
date_or_time(2005,8,31,15,15,10).next_month.should == date_or_time(2005,9,30,15,15,10)
end
end
describe "next_quarter" do
it "should be calculated correctly" do
date_or_time(2005,8,31,15,15,10).next_quarter.should == date_or_time(2005,11,30,15,15,10)
end
end
describe "next_year" do
it "should be calculated correctly" do
date_or_time(2005,6,5,10,10,10).next_year.should == date_or_time(2006,6,5,10,10,10)
end
end
describe "prev_week" do
it "should be calculated correctly" do
date_or_time(2005,3,1,15,15,10).prev_week.should == date_or_time(2005,2,21,0,0,0)
date_or_time(2005,3,1,15,15,10).prev_week(:tuesday).should == date_or_time(2005,2,22,0,0,0)
date_or_time(2005,3,1,15,15,10).prev_week(:friday).should == date_or_time(2005,2,25,0,0,0)
date_or_time(2006,11,6,0,0,0).prev_week.should == date_or_time(2006,10,30,0,0,0)
date_or_time(2006,11,23,0,0,0).prev_week(:wednesday).should == date_or_time(2006,11,15,0,0,0)
end
it "should be calculated correctly with default beginning of week" do
begin
old_bw = Date.beginning_of_week
Date.beginning_of_week = :tuesday
date_or_time(2012,3,21,0,0,0).prev_week(:wednesday).should == date_or_time(2012,3,14,0,0,0)
date_or_time(2012,3,21,0,0,0).prev_week(:saturday).should == date_or_time(2012,3,17,0,0,0)
date_or_time(2012,3,21,0,0,0).prev_week(:tuesday).should == date_or_time(2012,3,13,0,0,0)
date_or_time(2012,3,21,0,0,0).prev_week(:monday).should == date_or_time(2012,3,19,0,0,0)
ensure
Date.beginning_of_week = old_bw
end
end
end
describe "prev_month" do
it "should be calculated correctly" do
date_or_time(2004,3,31,10,10,10).prev_month.should == date_or_time(2004,2,29,10,10,10)
end
end
describe "prev_quarter" do
it "should be calculated correctly" do
date_or_time(2004,5,31,10,10,10).prev_quarter.should == date_or_time(2004,2,29,10,10,10)
end
end
describe "prev_year" do
it "should be calculated correctly" do
date_or_time(2005,6,5,10,10,10).prev_year.should == date_or_time(2004,6,5,10,10,10)
end
end
describe "days_to_week_start" do
it "should be calculated correctly" do
date_or_time(2011,11,01,0,0,0).days_to_week_start(:tuesday).should == 0
date_or_time(2011,11,02,0,0,0).days_to_week_start(:tuesday).should == 1
date_or_time(2011,11,03,0,0,0).days_to_week_start(:tuesday).should == 2
date_or_time(2011,11,04,0,0,0).days_to_week_start(:tuesday).should == 3
date_or_time(2011,11,05,0,0,0).days_to_week_start(:tuesday).should == 4
date_or_time(2011,11,06,0,0,0).days_to_week_start(:tuesday).should == 5
date_or_time(2011,11,07,0,0,0).days_to_week_start(:tuesday).should == 6
date_or_time(2011,11,03,0,0,0).days_to_week_start(:monday).should == 3
date_or_time(2011,11,04,0,0,0).days_to_week_start(:tuesday).should == 3
date_or_time(2011,11,05,0,0,0).days_to_week_start(:wednesday).should == 3
date_or_time(2011,11,06,0,0,0).days_to_week_start(:thursday).should == 3
date_or_time(2011,11,07,0,0,0).days_to_week_start(:friday).should == 3
date_or_time(2011,11,8,0,0,0).days_to_week_start(:saturday).should == 3
date_or_time(2011,11,9,0,0,0).days_to_week_start(:sunday).should == 3
end
it "should be calculated correctly with default beginning of week" do
begin
old_bw = Date.beginning_of_week
Date.beginning_of_week = :friday
date_or_time(2012,03,8,0,0,0).days_to_week_start.should == 6
date_or_time(2012,03,7,0,0,0).days_to_week_start.should == 5
date_or_time(2012,03,6,0,0,0).days_to_week_start.should == 4
date_or_time(2012,03,5,0,0,0).days_to_week_start.should == 3
date_or_time(2012,03,4,0,0,0).days_to_week_start.should == 2
date_or_time(2012,03,3,0,0,0).days_to_week_start.should == 1
date_or_time(2012,03,2,0,0,0).days_to_week_start.should == 0
ensure
Date.beginning_of_week = old_bw
end
end
end
describe "beginning_of_week" do
it "should be calculated correctly" do
date_or_time(2005,2,4,10,10,10).beginning_of_week.should == date_or_time(2005,1,31,0,0,0)
date_or_time(2005,11,28,0,0,0).beginning_of_week.should == date_or_time(2005,11,28,0,0,0)
date_or_time(2005,11,29,0,0,0).beginning_of_week.should == date_or_time(2005,11,28,0,0,0)
date_or_time(2005,11,30,0,0,0).beginning_of_week.should == date_or_time(2005,11,28,0,0,0)
date_or_time(2005,12,01,0,0,0).beginning_of_week.should == date_or_time(2005,11,28,0,0,0)
date_or_time(2005,12,02,0,0,0).beginning_of_week.should == date_or_time(2005,11,28,0,0,0)
date_or_time(2005,12,03,0,0,0).beginning_of_week.should == date_or_time(2005,11,28,0,0,0)
date_or_time(2005,12,04,0,0,0).beginning_of_week.should == date_or_time(2005,11,28,0,0,0)
end
end
describe "end_of_week" do
it "should be calculated correctly" do
date_or_time(2007,12,31,10,10,10).end_of_week.should == date_or_time(2008,1,6,23,59,59,Rational(999999999, 1000))
date_or_time(2007,8,27,0,0,0).end_of_week.should == date_or_time(2007,9,2,23,59,59,Rational(999999999, 1000))
date_or_time(2007,8,28,0,0,0).end_of_week.should == date_or_time(2007,9,2,23,59,59,Rational(999999999, 1000))
date_or_time(2007,8,29,0,0,0).end_of_week.should == date_or_time(2007,9,2,23,59,59,Rational(999999999, 1000))
date_or_time(2007,8,30,0,0,0).end_of_week.should == date_or_time(2007,9,2,23,59,59,Rational(999999999, 1000))
date_or_time(2007,8,31,0,0,0).end_of_week.should == date_or_time(2007,9,2,23,59,59,Rational(999999999, 1000))
date_or_time(2007,9,01,0,0,0).end_of_week.should == date_or_time(2007,9,2,23,59,59,Rational(999999999, 1000))
date_or_time(2007,9,02,0,0,0).end_of_week.should == date_or_time(2007,9,2,23,59,59,Rational(999999999, 1000))
end
end
describe "end_of_month" do
it "should be calculated correctly" do
date_or_time(2005,3,20,10,10,10).end_of_month.should == date_or_time(2005,3,31,23,59,59,Rational(999999999, 1000))
date_or_time(2005,2,20,10,10,10).end_of_month.should == date_or_time(2005,2,28,23,59,59,Rational(999999999, 1000))
date_or_time(2005,4,20,10,10,10).end_of_month.should == date_or_time(2005,4,30,23,59,59,Rational(999999999, 1000))
end
end
describe "end_of_year" do
it "should be calculated correctly" do
date_or_time(2007,2,22,10,10,10).end_of_year.should == date_or_time(2007,12,31,23,59,59,Rational(999999999, 1000))
date_or_time(2007,12,31,10,10,10).end_of_year.should == date_or_time(2007,12,31,23,59,59,Rational(999999999, 1000))
end
end
describe "weekdays" do
it "should return monday with default beginning of week" do
begin
old_bw = Date.beginning_of_week
Date.beginning_of_week = :saturday
date_or_time(2012,9,18,0,0,0).monday.should == date_or_time(2012,9,17,0,0,0)
ensure
Date.beginning_of_week = old_bw
end
end
it "should return sunday with default beginning of week" do
begin
old_bw = Date.beginning_of_week
Date.beginning_of_week = :wednesday
date_or_time(2012,9,19,0,0,0).sunday.should == date_or_time(2012,9,23,23,59,59, Rational(999999999, 1000))
ensure
Date.beginning_of_week = old_bw
end
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/array/prepend_and_append_spec.rb | spec/motion-support/core_ext/array/prepend_and_append_spec.rb | describe 'array' do
describe "prepend" do
it "should add an element to the front of the array" do
[1, 2, 3].prepend(0).should == [0, 1, 2, 3]
end
it "should change the array" do
array = [1, 2, 3]
array.prepend(0)
array.should == [0, 1, 2, 3]
end
end
describe "append" do
it "should add an element to the back of the array" do
[1, 2, 3].append(4).should == [1, 2, 3, 4]
end
it "should change the array" do
array = [1, 2, 3]
array.append(4)
array.should == [1, 2, 3, 4]
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/array/conversion_spec.rb | spec/motion-support/core_ext/array/conversion_spec.rb | describe 'array' do
describe "to_sentence" do
it "should convert plain array" do
[].to_sentence.should == ""
['one'].to_sentence.should == "one"
['one', 'two'].to_sentence.should == "one and two"
['one', 'two', 'three'].to_sentence.should == "one, two, and three"
end
it "should convert sentence with words connector" do
['one', 'two', 'three'].to_sentence(:words_connector => ' ').should == "one two, and three"
['one', 'two', 'three'].to_sentence(:words_connector => ' & ').should == "one & two, and three"
['one', 'two', 'three'].to_sentence(:words_connector => nil).should == "onetwo, and three"
end
it "should convert sentence with last word connector" do
['one', 'two', 'three'].to_sentence(:last_word_connector => ', and also ').should == "one, two, and also three"
['one', 'two', 'three'].to_sentence(:last_word_connector => nil).should == "one, twothree"
['one', 'two', 'three'].to_sentence(:last_word_connector => ' ').should == "one, two three"
['one', 'two', 'three'].to_sentence(:last_word_connector => ' and ').should == "one, two and three"
end
it "should convert two-element array" do
['one', 'two'].to_sentence.should == "one and two"
['one', 'two'].to_sentence(:two_words_connector => ' ').should == "one two"
end
it "should convert one-element array" do
['one'].to_sentence.should == "one"
end
it "should create new object" do
elements = ["one"]
elements.to_sentence.object_id.should.not == elements[0].object_id
end
it "should convert non-string element" do
[1].to_sentence.should == '1'
end
it "should not modify given hash" do
options = { words_connector: ' ' }
['one', 'two', 'three'].to_sentence(options).should == "one two, and three"
options.should == { words_connector: ' ' }
end
end
describe "to_s" do
it "should convert to database format" do
collection = [
Class.new { def id() 1 end }.new,
Class.new { def id() 2 end }.new,
Class.new { def id() 3 end }.new
]
[].to_s(:db).should == "null"
collection.to_s(:db).should == "1,2,3"
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/array/wrap_spec.rb | spec/motion-support/core_ext/array/wrap_spec.rb | describe 'array' do
describe "wrap" do
it "should return empty array for nil" do
Array.wrap(nil).should == []
end
it "should return unchanged array for array" do
Array.wrap([1, 2, 3]).should == [1, 2, 3]
end
it "should not flatten multidimensional array" do
Array.wrap([[1], [2], [3]]).should == [[1], [2], [3]]
end
it "should turn simple object into array" do
Array.wrap(0).should == [0]
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/array/grouping_spec.rb | spec/motion-support/core_ext/array/grouping_spec.rb | describe 'array grouping' do
describe "in_groups_of" do
it "should group array and fill rest with nil" do
%w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3).should == [
["1", "2", "3"],
["4", "5", "6"],
["7", "8", "9"],
["10", nil, nil]
]
end
it "should group array and fill with specified filler" do
%w(1 2 3 4 5).in_groups_of(2, 'empty').should == [
["1", "2"],
["3", "4"],
["5", "empty"]
]
end
it "should not fill the last group if turned off" do
%w(1 2 3 4 5).in_groups_of(2, false).should == [
["1", "2"],
["3", "4"],
["5"]
]
end
it "should yield each slice to a block if given" do
result = []
%w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) { |group| result << ['foo'] + group + ['bar'] }
result.should == [
["foo", "1", "2", "3", "bar"],
["foo", "4", "5", "6", "bar"],
["foo", "7", "8", "9", "bar"],
["foo", "10", nil, nil, "bar"]
]
end
end
describe "in_groups" do
it "should group array and fill the rest with nil" do
%w(1 2 3 4 5 6 7 8 9 10).in_groups(3).should == [
["1", "2", "3", "4"],
["5", "6", "7", nil],
["8", "9", "10", nil]
]
end
it "should group array and fill the result with specified filler" do
%w(1 2 3 4 5 6 7 8 9 10).in_groups(3, 'empty').should == [
["1", "2", "3", "4"],
["5", "6", "7", "empty"],
["8", "9", "10", "empty"]
]
end
it "should not fill the last group if turned off" do
%w(1 2 3 4 5 6 7).in_groups(3, false).should == [
["1", "2", "3"],
["4", "5"],
["6", "7"]
]
end
it "should yield each slice to a block if given" do
result = []
%w(1 2 3 4 5 6 7 8 9 10).in_groups(3) { |group| result << ['foo'] + group + ['bar'] }
result.should == [
["foo", "1", "2", "3", "4", "bar"],
["foo", "5", "6", "7", nil, "bar"],
["foo", "8", "9", "10", nil, "bar"]
]
end
end
describe "split" do
it "should split array based on delimiting value" do
[1, 2, 3, 4, 5].split(3).should == [[1, 2], [4, 5]]
end
it "should split array based on block result" do
(1..10).to_a.split { |i| i % 3 == 0 }.should == [[1, 2], [4, 5], [7, 8], [10]]
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/array/access_spec.rb | spec/motion-support/core_ext/array/access_spec.rb | describe 'array access' do
describe "from" do
it "should return the tail of an array from position" do
['a', 'b', 'c', 'd'].from(0).should == ["a", "b", "c", "d"]
['a', 'b', 'c', 'd'].from(2).should == ["c", "d"]
['a', 'b', 'c', 'd'].from(10).should == []
[].from(0).should == []
end
end
describe "to" do
it "should return the head of an array up to position" do
['a', 'b', 'c', 'd'].to(0).should == ["a"]
['a', 'b', 'c', 'd'].to(2).should == ["a", "b", "c"]
['a', 'b', 'c', 'd'].to(10).should == ["a", "b", "c", "d"]
[].to(0).should == []
end
end
describe "second" do
it "should return the second element in an array" do
['a', 'b', 'c', 'd'].second.should == 'b'
end
it "should return nil if there is no second element" do
[].second.should == nil
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/array/extract_options_spec.rb | spec/motion-support/core_ext/array/extract_options_spec.rb | describe 'array options' do
describe "extract_options!" do
it "should extract an options hash from an array" do
[1, 2, :a => :b].extract_options!.should == { :a => :b }
end
it "should return an empty hash if the last element is not a hash" do
[1, 2].extract_options!.should == {}
end
it "should return an empty hash on an empty array" do
[].extract_options!.should == {}
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/class/attribute_spec.rb | spec/motion-support/core_ext/class/attribute_spec.rb | describe "class" do
describe "class_attribute" do
before do
@klass = Class.new
@klass.class_eval { class_attribute :setting }
@sub = Class.new(@klass)
end
it "should default to nil" do
@klass.setting.should.be.nil
@sub.setting.should.be.nil
end
it "should be inheritable" do
@klass.setting = 1
@sub.setting.should == 1
end
it "should be overridable" do
@sub.setting = 1
@klass.setting.should.be.nil
@klass.setting = 2
@sub.setting.should == 1
Class.new(@sub).setting.should == 1
end
it "should define a query method" do
@klass.setting?.should.be.false
@klass.setting = 1
@klass.setting?.should.be.true
end
it "should define an instance reader that delegates to class" do
@klass.new.setting.should.be.nil
@klass.setting = 1
@klass.new.setting.should == 1
end
it "should allow to override per instance" do
object = @klass.new
object.setting = 1
@klass.setting.should == nil
@klass.setting = 2
object.setting.should == 1
end
it "should define query method on instance" do
object = @klass.new
object.setting?.should.be.false
object.setting = 1
object.setting?.should.be.true
end
describe "instance_writer => false" do
it "should not create instance writer" do
object = Class.new { class_attribute :setting, :instance_writer => false }.new
lambda { object.setting = 'boom' }.should.raise NoMethodError
end
end
describe "instance_reader => false" do
it "should not create instance reader" do
object = Class.new { class_attribute :setting, :instance_reader => false }.new
lambda { object.setting }.should.raise NoMethodError
lambda { object.setting? }.should.raise NoMethodError
end
end
describe "instance_accessor => false" do
it "should not create reader or writer" do
object = Class.new { class_attribute :setting, :instance_accessor => false }.new
lambda { object.setting }.should.raise NoMethodError
lambda { object.setting? }.should.raise NoMethodError
lambda { object.setting = 'boom' }.should.raise NoMethodError
end
end
it "should work well with singleton classes" do
object = @klass.new
object.singleton_class.setting = 'foo'
object.setting.should == "foo"
end
it "should return set value through setter" do
val = @klass.send(:setting=, 1)
val.should == 1
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/class/attribute_accessor_spec.rb | spec/motion-support/core_ext/class/attribute_accessor_spec.rb | class CAttrAccessorBase
cattr_accessor :empty_accessor
cattr_accessor :base_accessor, :derived_accessor
end
class CAttrAccessorDerived < CAttrAccessorBase
end
describe "class" do
describe "attribute accessors" do
before do
@class = Class.new
@class.instance_eval do
cattr_accessor :foo
cattr_accessor :bar, :instance_writer => false
cattr_reader :shaq, :instance_reader => false
cattr_accessor :camp, :instance_accessor => false
end
@object = @class.new
end
describe "reader" do
it "should return nil by default" do
@class.foo.should.be.nil
end
end
describe "writer" do
it "should set value" do
@class.foo = :test
@class.foo.should == :test
end
it "should set value through instance writer" do
@object.foo = :bar
@object.foo.should == :bar
end
it "should set instance reader's value through module's writer" do
@class.foo = :test
@object.foo.should == :test
end
it "should set module reader's value through instances's writer" do
@object.foo = :bar
@class.foo.should == :bar
end
end
describe "instance_writer => false" do
it "should not create instance writer" do
@class.should.respond_to :foo
@class.should.respond_to :foo=
@object.should.respond_to :bar
@object.should.not.respond_to :bar=
end
end
describe "instance_reader => false" do
it "should not create instance reader" do
@class.should.respond_to :shaq
@object.should.not.respond_to :shaq
end
end
describe "instance_accessor => false" do
it "should not create reader or writer" do
@class.should.respond_to :camp
@object.should.not.respond_to :camp
@object.should.not.respond_to :camp=
end
end
end
describe "invalid attribute accessors" do
it "should raise NameError when creating an invalid reader" do
lambda do
Class.new do
cattr_reader "invalid attribute name"
end
end.should.raise NameError
end
it "should raise NameError when creating an invalid writer" do
lambda do
Class.new do
cattr_writer "invalid attribute name"
end
end.should.raise NameError
end
end
describe "inheritance" do
it "should be accessible in the base class and the derived class" do
CAttrAccessorBase.respond_to?(:empty_accessor).should == true
CAttrAccessorDerived.respond_to?(:empty_accessor).should == true
end
it "should return nil for an unset accessor in the base class" do
CAttrAccessorBase.empty_accessor.should == nil
end
it "should return nil for an unset accessor in the derived class" do
CAttrAccessorDerived.empty_accessor.should == nil
end
it "should return a value for an accessor set in the base class in the base class" do
CAttrAccessorBase.base_accessor = 10
CAttrAccessorBase.base_accessor.should == 10
end
it "should return a value for an accessor set in the base class in the derived class" do
CAttrAccessorBase.base_accessor = 10
CAttrAccessorDerived.base_accessor.should == 10
end
it "should return a value for the base class if set for the derived class" do
CAttrAccessorDerived.derived_accessor = 20
CAttrAccessorBase.derived_accessor.should == 20
end
it "should return a value for an accessor set in the derived class in the derived class" do
CAttrAccessorDerived.derived_accessor = 20
CAttrAccessorDerived.derived_accessor.should == 20
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/module/attr_internal_spec.rb | spec/motion-support/core_ext/module/attr_internal_spec.rb | describe "module" do
describe "attr_internal" do
before do
@target = Class.new
@instance = @target.new
end
describe "reader" do
it "should define reader" do
lambda { @target.attr_internal_reader :foo }.should.not.raise
end
describe "defined" do
before do
@target.attr_internal_reader :foo
end
it "should not have instance variable at first" do
@instance.instance_variable_defined?('@_foo').should.not.be.true
end
it "should not define writer" do
lambda { @instance.foo = 1 }.should.raise NoMethodError
end
it "should return value of internal reader" do
@instance.instance_variable_set('@_foo', 1)
lambda { @instance.foo.should == 1 }.should.not.raise
end
end
end
describe "writer" do
it "should define writer" do
lambda { @target.attr_internal_writer :foo }.should.not.raise
end
describe "defined" do
before do
@target.attr_internal_writer :foo
end
it "should not have instance variable at first" do
@instance.instance_variable_defined?('@_foo').should.not.be.true
end
it "should set instance variable" do
lambda { @instance.foo = 1 }.should.not.raise
@instance.instance_variable_defined?('@_foo').should.be.true
@instance.instance_variable_get('@_foo').should == 1
end
it "should not define reader" do
lambda { @instance.foo }.should.raise NoMethodError
end
end
end
describe "accessor" do
it "should define accessor" do
lambda { @target.attr_internal :foo }.should.not.raise
end
describe "defined" do
before do
@target.attr_internal :foo
end
it "should not have instance variable at first" do
@instance.instance_variable_defined?('@_foo').should.not.be.true
end
it "should set instance variable" do
lambda { @instance.foo = 1 }.should.not.raise
@instance.instance_variable_defined?('@_foo').should.be.true
@instance.instance_variable_get('@_foo').should == 1
end
it "should read from instance variable" do
@instance.instance_variable_set('@_foo', 1)
lambda { @instance.foo }.should.not.raise
end
end
end
describe "naming format" do
it "should allow custom naming format for instance variable" do
begin
Module.attr_internal_naming_format.should == '@_%s'
lambda { Module.attr_internal_naming_format = '@abc%sdef' }.should.not.raise
@target.attr_internal :foo
@instance.instance_variable_defined?('@_foo').should.be.false
@instance.instance_variable_defined?('@abcfoodef').should.be.false
lambda { @instance.foo = 1 }.should.not.raise
@instance.instance_variable_defined?('@_foo').should.not.be.true
@instance.instance_variable_defined?('@abcfoodef').should.be.true
ensure
Module.attr_internal_naming_format = '@_%s'
end
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/module/aliasing_spec.rb | spec/motion-support/core_ext/module/aliasing_spec.rb | module Aliasing
class File
public
def open(file)
end
def open_with_internet(url)
open_without_internet(url)
end
alias_method_chain :open, :internet
protected
def exist?(file)
end
def exist_with_internet?(url)
exist_without_internet?(url)
end
alias_method_chain :exist?, :internet
private
def remove!(file)
end
def remove_with_internet!(url)
remove_without_internet!(url)
end
alias_method_chain :remove!, :internet
end
class Content
attr_accessor :title, :Data
def initialize
@title, @Data = nil, nil
end
def title?
!title.nil?
end
def Data?
!self.Data.nil?
end
end
class Email < Content
alias_attribute :subject, :title
alias_attribute :body, :Data
end
end
describe "module" do
describe "alias_method_chain" do
it "should define 'without' method" do
Aliasing::File.new.should.respond_to :open_without_internet
end
it "should respond to original method" do
Aliasing::File.new.should.respond_to :open
end
it "should respond to 'with' method" do
Aliasing::File.new.should.respond_to :open_with_internet
end
it "should preserve question punctuation" do
Aliasing::File.new.should.respond_to :exist_without_internet?
end
it "should preserve bang punctuation" do
# Ruby objects don't respond to private methods
Aliasing::File.new.should.not.respond_to :remove_without_internet!
end
it "should keep public methods public" do
Aliasing::File.new.public_methods.should.include :"open_without_internet:"
end
it "should keep protected methods protected" do
Aliasing::File.new.protected_methods.should.include :"exist_without_internet?:"
end
it "should keep private methods private" do
Aliasing::File.new.private_methods.should.include :"remove_without_internet!:"
end
end
describe "alias_attribute" do
before do
@email = Aliasing::Email.new
end
describe "getter" do
it "should exist" do
lambda { @email.subject }.should.not.raise
end
it "should read" do
@email.title = "hello"
@email.subject.should == "hello"
end
it "should read from uppercase method" do
@email.body = "world"
@email.Data.should == "world"
end
end
describe "setter" do
it "should exist" do
lambda { @email.subject = "hello" }.should.not.raise
end
it "should write" do
@email.subject = "hello"
@email.title.should == "hello"
end
it "should write to uppercase method" do
@email.Data = "world"
@email.body.should == "world"
end
end
describe "question method" do
it "should exist" do
lambda { @email.subject? }.should.not.raise
end
it "should return false for nil attribute" do
@email.subject?.should == false
end
it "should return true for non-nil attribute" do
@email.title = "hello"
@email.subject?.should == true
end
it "should return true for non-nil uppercase attribute" do
@email.body = "hello"
@email.Data?.should == true
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/module/remove_method_spec.rb | spec/motion-support/core_ext/module/remove_method_spec.rb | module RemoveMethodSpec
class A
def do_something
return 1
end
end
end
describe "module" do
describe "remove_method" do
it "should remove a method from an object" do
RemoveMethodSpec::A.class_eval {
self.remove_possible_method(:do_something)
}
RemoveMethodSpec::A.new.should.not.respond_to :do_something
end
def test_redefine_method_in_an_object
RemoveMethodSpec::A.class_eval {
self.redefine_method(:do_something) { return 100 }
}
RemoveMethodSpec::A.new.do_something.should == 100
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/module/anonymous_spec.rb | spec/motion-support/core_ext/module/anonymous_spec.rb | describe "module" do
describe "anonymous?" do
it "should return true for an anonymous module" do
Module.new.anonymous?.should == true
end
it "should return true for an anonymous class" do
Class.new.anonymous?.should == true
end
it "should return false for a named module" do
Kernel.anonymous?.should == false
end
it "should return false for a named class" do
Object.anonymous?.should == false
end
it "should return false for module that acquired a name" do
NamedModule = Module.new
NamedModule.anonymous?.should == false
end
it "should return false for module that acquired a name" do
NamedClass = Class.new
NamedClass.anonymous?.should == false
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/module/introspection_spec.rb | spec/motion-support/core_ext/module/introspection_spec.rb | module ModuleIntrospection
module Foo
module Bar
end
end
module Baz
end
end
ModuleIntrospectionAlias = ModuleIntrospection::Foo
describe "module" do
describe "introspection" do
describe "parent_name" do
it "should return nil for top-level module" do
ModuleIntrospection.parent_name.should.be.nil
end
it "should return direct parent for nested module" do
ModuleIntrospection::Foo.parent_name.should == "ModuleIntrospection"
end
it "should return nil for anonymous module" do
Module.new.parent_name.should.be.nil
end
it "should return original parent name for module alias" do
ModuleIntrospectionAlias.parent_name.should == "ModuleIntrospection"
end
end
describe "parent" do
it "should return Object for top-level module" do
ModuleIntrospection.parent.should == Object
end
it "should return direct parent for nested module" do
ModuleIntrospection::Foo.parent.should == ModuleIntrospection
end
it "should return nil for anonymous module" do
Module.new.parent.should == Object
end
it "should return original parent for module alias" do
ModuleIntrospectionAlias.parent.should == ModuleIntrospection
end
end
describe "parents" do
it "should return Object for top-level module" do
ModuleIntrospection.parents.should == [Object]
end
it "should return parents for nested module" do
ModuleIntrospection::Foo::Bar.parents.should == [ModuleIntrospection::Foo, ModuleIntrospection, Object]
end
it "should return original parents for module alias" do
ModuleIntrospectionAlias.parents.should == [ModuleIntrospection, Object]
end
end
describe "local_constants" do
it "should return all direct constants within the module as symbols" do
ModuleIntrospection.local_constants.should.include :Foo
ModuleIntrospection.local_constants.should.include :Baz
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/module/attribute_accessor_spec.rb | spec/motion-support/core_ext/module/attribute_accessor_spec.rb | describe "module" do
describe "attribute accessors" do
before do
m = @module = Module.new
@module.instance_eval do
mattr_accessor :foo
mattr_accessor :bar, :instance_writer => false
mattr_reader :shaq, :instance_reader => false
mattr_accessor :camp, :instance_accessor => false
end
@class = Class.new
@class.instance_eval { include m }
@object = @class.new
end
describe "reader" do
it "should return nil by default" do
@module.foo.should.be.nil
end
end
describe "writer" do
it "should set value" do
@module.foo = :test
@module.foo.should == :test
end
it "should set value through instance writer" do
@object.foo = :bar
@object.foo.should == :bar
end
it "should set instance reader's value through module's writer" do
@module.foo = :test
@object.foo.should == :test
end
it "should set module reader's value through instances's writer" do
@object.foo = :bar
@module.foo.should == :bar
end
end
describe "instance_writer => false" do
it "should not create instance writer" do
@module.should.respond_to :foo
@module.should.respond_to :foo=
@object.should.respond_to :bar
@object.should.not.respond_to :bar=
end
end
describe "instance_reader => false" do
it "should not create instance reader" do
@module.should.respond_to :shaq
@object.should.not.respond_to :shaq
end
end
describe "instance_accessor => false" do
it "should not create reader or writer" do
@module.should.respond_to :camp
@object.should.not.respond_to :camp
@object.should.not.respond_to :camp=
end
end
end
describe "invalid attribute accessors" do
it "should raise NameError when creating an invalid reader" do
lambda do
Class.new do
mattr_reader "invalid attribute name"
end
end.should.raise NameError
end
it "should raise NameError when creating an invalid writer" do
lambda do
Class.new do
mattr_writer "invalid attribute name"
end
end.should.raise NameError
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/module/reachable_spec.rb | spec/motion-support/core_ext/module/reachable_spec.rb | describe "Module" do
describe "reachable?" do
it "should be false for an anonymous module" do
Module.new.should.not.be.reachable
end
it "should be false for an anonymous class" do
Class.new.should.not.be.reachable
end
it "should be true for a named module" do
Kernel.should.be.reachable
end
it "should be true for a named class" do
Object.should.be.reachable
end
it "should be false for a named class whose constant has gone" do
class C; end
c = C
Object.send(:remove_const, :C)
c.should.not.be.reachable
end
it "should be false for a named module whose constant has gone" do
module M; end
m = M
Object.send(:remove_const, :M)
m.should.not.be.reachable
end
it "should be false for a named class whose constant was redefined" do
class C; end
c = C
Object.send(:remove_const, :C)
class C; end
C.should.be.reachable
c.should.not.be.reachable
end
it "should be false for a named module whose constant was redefined" do
module M; end
m = M
Object.send(:remove_const, :M)
module M; end
M.should.be.reachable
m.should.not.be.reachable
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/module/delegation_spec.rb | spec/motion-support/core_ext/module/delegation_spec.rb | module ModuleDelegation
class Delegator
def receive
"result"
end
end
class InstanceVariable
def initialize
@instance_variable = Delegator.new
end
delegate :receive, :to => '@instance_variable'
end
class ClassVariable
def initialize
@@class_variable = Delegator.new
end
delegate :receive, :to => '@@class_variable'
end
class RelativeConstant
Receiver = Delegator.new
delegate :receive, :to => 'Receiver'
end
class AbsoluteConstant
Receiver = Delegator.new
delegate :receive, :to => 'ModuleDelegation::AbsoluteConstant::Receiver'
end
class Method
def method
Delegator.new
end
delegate :receive, :to => :method
end
class MethodChain
def first
self
end
def second
Delegator.new
end
delegate :receive, :to => 'first.second'
end
class ConstantSingleton
class Nested
def self.method
Delegator.new
end
end
delegate :receive, :to => 'Nested.method'
end
class AllowNil
delegate :receive, :to => '@undefined', :allow_nil => true
end
class DisallowNil
delegate :receive, :to => '@undefined'
end
class NonexistentMethod
delegate :receive, :to => :nonexistent_method
end
class Prefix
def method
Delegator.new
end
delegate :receive, :to => :method, :prefix => 'foo'
end
class AutoPrefix
def method
Delegator.new
end
delegate :receive, :to => :method, :prefix => true
end
end
describe "module" do
describe "delegation" do
it "should delegate to instance variable" do
ModuleDelegation::InstanceVariable.new.receive.should == "result"
end
it "should delegate to class variable" do
ModuleDelegation::ClassVariable.new.receive.should == "result"
end
it "should delegate to relative constant" do
ModuleDelegation::RelativeConstant.new.receive.should == "result"
end
it "should delegate to absolute constant" do
ModuleDelegation::AbsoluteConstant.new.receive.should == "result"
end
it "should delegate to method" do
ModuleDelegation::Method.new.receive.should == "result"
end
it "should delegate to method chain" do
ModuleDelegation::MethodChain.new.receive.should == "result"
end
it "should delegate to constant's singleton method" do
ModuleDelegation::ConstantSingleton.new.receive.should == "result"
end
it "should delegate to nil without raising an error when allowed" do
ModuleDelegation::AllowNil.new.receive.should.be.nil
end
it "should raise an error when delegating to nil and not allowed" do
lambda { ModuleDelegation::DisallowNil.new.receive }.should.raise
end
it "should raise an error when delegating to non-existent method" do
lambda { ModuleDelegation::NonexistentMethod.new.receive }.should.raise NoMethodError
end
it "should delegate with prefix" do
ModuleDelegation::Prefix.new.foo_receive.should == "result"
end
it "should delegate to method with automatic prefix" do
ModuleDelegation::AutoPrefix.new.method_receive.should == "result"
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/numeric/conversions_spec.rb | spec/motion-support/core_ext/numeric/conversions_spec.rb | describe "Numeric" do
describe "conversions" do
describe "phone" do
it "should format phone number without area code" do
5551234.to_s(:phone).should == "555-1234"
end
it "should format long number without area code" do
225551212.to_s(:phone).should == "22-555-1212"
8005551212.to_s(:phone).should == "800-555-1212"
end
it "should format phone number with area code" do
8005551212.to_s(:phone, :area_code => true).should == "(800) 555-1212"
end
it "should format phone number with custom delimiter" do
8005551212.to_s(:phone, :delimiter => " ").should == "800 555 1212"
5551212.to_s(:phone, :delimiter => '.').should == "555.1212"
end
it "should append extension to phone number" do
8005551212.to_s(:phone, :area_code => true, :extension => 123).should == "(800) 555-1212 x 123"
end
it "should not append whitespace as extension to the phone number" do
8005551212.to_s(:phone, :extension => " ").should == "800-555-1212"
end
it "should format phone number with country code" do
8005551212.to_s(:phone, :country_code => 1).should == "+1-800-555-1212"
225551212.to_s(:phone, :country_code => 45).should == "+45-22-555-1212"
end
it "should format phone number with country code and empty delimiter" do
8005551212.to_s(:phone, :country_code => 1, :delimiter => '').should == "+18005551212"
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/core_ext/numeric/bytes_spec.rb | spec/motion-support/core_ext/numeric/bytes_spec.rb | describe "Numeric" do
describe "bytes" do
it "should calculate kilobytes" do
1.kilobyte.should == 1024.bytes
3.kilobytes.should == 3072
3.kilobyte.should == 3072
end
it "should calculate megabytes" do
1.megabyte.should == 1024.kilobytes
3.5.megabytes.should == 3584.0.kilobytes
3.megabytes.should == 1024.kilobytes + 2.megabytes
512.megabytes.should == 2.gigabytes / 4
3.megabytes.should == 3145728
3.megabyte.should == 3145728
end
it "should calculate gigabytes" do
3.5.gigabytes.should == 3584.0.megabytes
10.gigabytes.should == 256.megabytes * 20 + 5.gigabytes
3.gigabytes.should == 3221225472
3.gigabyte.should == 3221225472
end
it "should calculate terabytes" do
1.terabyte.should == 1.kilobyte ** 4
3.terabytes.should == 3298534883328
3.terabyte.should == 3298534883328
end
it "should calculate petabytes" do
1.petabyte.should == 1.kilobyte ** 5
3.petabytes.should == 3377699720527872
3.petabyte.should == 3377699720527872
end
it "should calculate exabytes" do
1.exabyte.should == 1.kilobyte ** 6
3.exabytes.should == 3458764513820540928
3.exabyte.should == 3458764513820540928
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/_helpers/constantize_test_cases.rb | spec/motion-support/_helpers/constantize_test_cases.rb | module Ace
module Base
class Case
class Dice
end
end
class Fase < Case
end
end
class Gas
include Base
end
end
class Object
module AddtlGlobalConstants
class Case
class Dice
end
end
end
include AddtlGlobalConstants
end
module ConstantizeTestCases
def run_constantize_tests_on(&block)
yield("Ace::Base::Case").should == Ace::Base::Case
yield("::Ace::Base::Case").should == Ace::Base::Case
yield("Ace::Base::Case::Dice").should == Ace::Base::Case::Dice
yield("Ace::Base::Fase::Dice").should == Ace::Base::Fase::Dice
yield("Ace::Gas::Case").should == Ace::Gas::Case
yield("Ace::Gas::Case::Dice").should == Ace::Gas::Case::Dice
yield("Case::Dice").should == Case::Dice
yield("Object::Case::Dice").should == Case::Dice
yield("ConstantizeTestCases").should == ConstantizeTestCases
yield("::ConstantizeTestCases").should == ConstantizeTestCases
yield("").should == Object
yield("::").should == Object
lambda { block.call("UnknownClass") }.should.raise NameError
lambda { block.call("UnknownClass::Ace") }.should.raise NameError
lambda { block.call("UnknownClass::Ace::Base") }.should.raise NameError
lambda { block.call("An invalid string") }.should.raise NameError
lambda { block.call("InvalidClass\n") }.should.raise NameError
lambda { block.call("Ace::ConstantizeTestCases") }.should.raise NameError
lambda { block.call("Ace::Base::ConstantizeTestCases") }.should.raise NameError
lambda { block.call("Ace::Gas::Base") }.should.raise NameError
lambda { block.call("Ace::Gas::ConstantizeTestCases") }.should.raise NameError
end
def run_safe_constantize_tests_on
yield("Ace::Base::Case").should == Ace::Base::Case
yield("::Ace::Base::Case").should == Ace::Base::Case
yield("Ace::Base::Case::Dice").should == Ace::Base::Case::Dice
yield("Ace::Base::Fase::Dice").should == Ace::Base::Fase::Dice
yield("Ace::Gas::Case").should == Ace::Gas::Case
yield("Ace::Gas::Case::Dice").should == Ace::Gas::Case::Dice
yield("Case::Dice").should == Case::Dice
yield("Object::Case::Dice").should == Case::Dice
yield("ConstantizeTestCases").should == ConstantizeTestCases
yield("::ConstantizeTestCases").should == ConstantizeTestCases
yield("").should == Object
yield("::").should == Object
yield("UnknownClass").should.be.nil
yield("UnknownClass::Ace").should.be.nil
yield("UnknownClass::Ace::Base").should.be.nil
yield("An invalid string").should.be.nil
yield("InvalidClass\n").should.be.nil
yield("blargle").should.be.nil
yield("Ace::ConstantizeTestCases").should.be.nil
yield("Ace::Base::ConstantizeTestCases").should.be.nil
yield("Ace::Gas::Base").should.be.nil
yield("Ace::Gas::ConstantizeTestCases").should.be.nil
yield("#<Class:0x7b8b718b>::Nested_1").should.be.nil
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/spec/motion-support/_helpers/inflector_test_cases.rb | spec/motion-support/_helpers/inflector_test_cases.rb | module InflectorTestCases
SingularToPlural = {
"search" => "searches",
"switch" => "switches",
"fix" => "fixes",
"box" => "boxes",
"process" => "processes",
"address" => "addresses",
"case" => "cases",
"stack" => "stacks",
"wish" => "wishes",
"fish" => "fish",
"jeans" => "jeans",
"funky jeans" => "funky jeans",
"my money" => "my money",
"category" => "categories",
"query" => "queries",
"ability" => "abilities",
"agency" => "agencies",
"movie" => "movies",
"archive" => "archives",
"index" => "indices",
"wife" => "wives",
"safe" => "saves",
"half" => "halves",
"move" => "moves",
"salesperson" => "salespeople",
"person" => "people",
"spokesman" => "spokesmen",
"man" => "men",
"woman" => "women",
"basis" => "bases",
"diagnosis" => "diagnoses",
"diagnosis_a" => "diagnosis_as",
"datum" => "data",
"medium" => "media",
"stadium" => "stadia",
"analysis" => "analyses",
"my_analysis" => "my_analyses",
"node_child" => "node_children",
"child" => "children",
"experience" => "experiences",
"day" => "days",
"comment" => "comments",
"foobar" => "foobars",
"newsletter" => "newsletters",
"old_news" => "old_news",
"news" => "news",
"series" => "series",
"species" => "species",
"quiz" => "quizzes",
"perspective" => "perspectives",
"ox" => "oxen",
"photo" => "photos",
"buffalo" => "buffaloes",
"tomato" => "tomatoes",
"dwarf" => "dwarves",
"elf" => "elves",
"information" => "information",
"equipment" => "equipment",
"bus" => "buses",
"status" => "statuses",
"status_code" => "status_codes",
"mouse" => "mice",
"louse" => "lice",
"house" => "houses",
"octopus" => "octopi",
"virus" => "viri",
"alias" => "aliases",
"portfolio" => "portfolios",
"vertex" => "vertices",
"matrix" => "matrices",
"matrix_fu" => "matrix_fus",
"axis" => "axes",
"taxi" => "taxis", # prevents regression
"testis" => "testes",
"crisis" => "crises",
"rice" => "rice",
"shoe" => "shoes",
"horse" => "horses",
"prize" => "prizes",
"edge" => "edges",
"cow" => "kine",
"database" => "databases",
# regression tests against improper inflection regexes
"|ice" => "|ices",
"|ouse" => "|ouses",
"slice" => "slices",
"police" => "police"
}
CamelToUnderscore = {
"Product" => "product",
"SpecialGuest" => "special_guest",
"ApplicationController" => "application_controller",
"Area51Controller" => "area51_controller"
}
UnderscoreToLowerCamel = {
"product" => "product",
"special_guest" => "specialGuest",
"application_controller" => "applicationController",
"area51_controller" => "area51Controller"
}
SymbolToLowerCamel = {
:product => 'product',
:special_guest => 'specialGuest',
:application_controller => 'applicationController',
:area51_controller => 'area51Controller'
}
CamelToUnderscoreWithoutReverse = {
"HTMLTidy" => "html_tidy",
"HTMLTidyGenerator" => "html_tidy_generator",
"FreeBSD" => "free_bsd",
"HTML" => "html",
}
CamelWithModuleToUnderscoreWithSlash = {
"Admin::Product" => "admin/product",
"Users::Commission::Department" => "users/commission/department",
"UsersSection::CommissionDepartment" => "users_section/commission_department",
}
ClassNameToForeignKeyWithUnderscore = {
"Person" => "person_id",
"MyApplication::Billing::Account" => "account_id"
}
ClassNameToForeignKeyWithoutUnderscore = {
"Person" => "personid",
"MyApplication::Billing::Account" => "accountid"
}
ClassNameToTableName = {
"PrimarySpokesman" => "primary_spokesmen",
"NodeChild" => "node_children"
}
UnderscoreToHuman = {
"employee_salary" => "Employee salary",
"employee_id" => "Employee",
"underground" => "Underground"
}
MixtureToTitleCase = {
'active_record' => 'Active Record',
'ActiveRecord' => 'Active Record',
'action web service' => 'Action Web Service',
'Action Web Service' => 'Action Web Service',
'Action web service' => 'Action Web Service',
'actionwebservice' => 'Actionwebservice',
'Actionwebservice' => 'Actionwebservice',
"david's code" => "David's Code",
"David's code" => "David's Code",
"david's Code" => "David's Code",
"sgt. pepper's" => "Sgt. Pepper's",
"i've just seen a face" => "I've Just Seen A Face",
"maybe you'll be there" => "Maybe You'll Be There",
"¿por qué?" => '¿Por Qué?',
"Fred’s" => "Fred’s",
"Fred`s" => "Fred`s"
}
OrdinalNumbers = {
"-1" => "-1st",
"-2" => "-2nd",
"-3" => "-3rd",
"-4" => "-4th",
"-5" => "-5th",
"-6" => "-6th",
"-7" => "-7th",
"-8" => "-8th",
"-9" => "-9th",
"-10" => "-10th",
"-11" => "-11th",
"-12" => "-12th",
"-13" => "-13th",
"-14" => "-14th",
"-20" => "-20th",
"-21" => "-21st",
"-22" => "-22nd",
"-23" => "-23rd",
"-24" => "-24th",
"-100" => "-100th",
"-101" => "-101st",
"-102" => "-102nd",
"-103" => "-103rd",
"-104" => "-104th",
"-110" => "-110th",
"-111" => "-111th",
"-112" => "-112th",
"-113" => "-113th",
"-1000" => "-1000th",
"-1001" => "-1001st",
"0" => "0th",
"1" => "1st",
"2" => "2nd",
"3" => "3rd",
"4" => "4th",
"5" => "5th",
"6" => "6th",
"7" => "7th",
"8" => "8th",
"9" => "9th",
"10" => "10th",
"11" => "11th",
"12" => "12th",
"13" => "13th",
"14" => "14th",
"20" => "20th",
"21" => "21st",
"22" => "22nd",
"23" => "23rd",
"24" => "24th",
"100" => "100th",
"101" => "101st",
"102" => "102nd",
"103" => "103rd",
"104" => "104th",
"110" => "110th",
"111" => "111th",
"112" => "112th",
"113" => "113th",
"1000" => "1000th",
"1001" => "1001st"
}
UnderscoresToDashes = {
"street" => "street",
"street_address" => "street-address",
"person_street_address" => "person-street-address"
}
Irregularities = {
'person' => 'people',
'man' => 'men',
'child' => 'children',
'sex' => 'sexes',
'move' => 'moves',
'cow' => 'kine',
'zombie' => 'zombies',
'genus' => 'genera'
}
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/examples/Inflector/app/app_delegate.rb | examples/Inflector/app/app_delegate.rb | class AppDelegate
def application(application, didFinishLaunchingWithOptions:launchOptions)
@window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
@window.rootViewController = UINavigationController.alloc.initWithRootViewController(InflectorViewController.alloc.init)
@window.makeKeyAndVisible
true
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/examples/Inflector/app/inflector_view_controller.rb | examples/Inflector/app/inflector_view_controller.rb | class InflectorViewController < Formotion::FormController
def init
initWithForm(build_form)
self.title = "Inflector"
@form.on_submit do |form|
submit(form)
end
self
end
def submit(form)
data = form.render
original = String.new(data[:word])
update_fields(original)
form.row(:word).text_field.resignFirstResponder
end
def set_word(word)
@form.values = { :word => word }
update_fields(word)
end
def update_fields(original)
@form.values = {
:singular => original.singularize,
:plural => original.pluralize,
:camelized => original.camelize,
:lower_camelized => original.camelize(:lower),
:underscored => original.underscore,
:classified => original.classify,
:dasherized => original.dasherize,
:titleized => original.titleize,
:humanized => original.humanize
}
end
private
def build_form
@form ||= Formotion::Form.persist({
sections: [{
rows: [{
title: "Word",
key: :word,
type: :string,
placeholder: "Enter a word",
auto_correction: :no,
auto_capitalization: :none
}, {
title: "Select",
type: :button,
key: :select
}]
}, {
rows: [{
title: "Inflect",
type: :submit
}]
}, {
title: "Inflections",
rows: [{
title: "Singular",
key: :singular,
type: :static
}, {
title: "Plural",
key: :plural,
type: :static
}]
}, {
title: "Transformations",
rows: [{
title: "Camelized",
key: :camelized,
type: :static
}, {
title: "Lower-Camelized",
key: :lower_camelized,
type: :static
}, {
title: "Underscored",
key: :underscored,
type: :static
}, {
title: "Classified",
key: :classified,
type: :static
}, {
title: "Dasherized",
key: :dasherized,
type: :static
}, {
title: "Titleized",
key: :titleized,
type: :static
}, {
title: "Humanized",
key: :humanized,
type: :static
}]
}]
})
@form.row(:select).on_tap do
self.navigationController.pushViewController(WordsViewController.alloc.initWithParent(self), animated:true)
end
@form
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/examples/Inflector/app/words_view_controller.rb | examples/Inflector/app/words_view_controller.rb | class WordsViewController < UITableViewController
WORDS = [
[
"Single words",
%w{
alias
axis
buffalo
bus
cat
child
cow
crisis
dog
house
man
matrix
mouse
move
octopus
ox
parenthesis
person
quiz
series
sex
vertex
zombie
}
], [
"Uncountable words",
%w{
equipment
fish
information
jeans
money
police
rice
series
sheep
species
}
], [
"Programming",
%w{
app_delegate
motion_support
motion_support/inflector
ruby_motion
}
], [
"Acronyms",
%w{
free_bsd
html_api
html_tidy
ui_image
ui_table_view_controller
xml_http_request
}
]
]
def initWithParent(parent)
@parent = parent
self.title = "Select word"
self
end
def numberOfSectionsInTableView(tableView)
WORDS.size
end
def tableView(tableView, titleForHeaderInSection:section)
WORDS[section].first
end
def tableView(tableView, numberOfRowsInSection:section)
WORDS[section].last.size
end
def tableView(tableView, cellForRowAtIndexPath:indexPath)
fresh_cell.tap do |cell|
cell.textLabel.text = WORDS[indexPath.section].last[indexPath.row]
end
end
def tableView(tableView, didSelectRowAtIndexPath:indexPath)
@parent.set_word(WORDS[indexPath.section].last[indexPath.row])
navigationController.popViewControllerAnimated(true)
end
private
def fresh_cell
tableView.dequeueReusableCellWithIdentifier('Cell') ||
UITableViewCell.alloc.initWithStyle(UITableViewCellStyleSubtitle, reuseIdentifier:'Cell')
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/examples/Inflector/app/inflections.rb | examples/Inflector/app/inflections.rb | MotionSupport::Inflector.inflections do |inflect|
inflect.acronym 'HTML'
inflect.acronym 'API'
inflect.acronym 'BSD'
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/examples/Inflector/spec/main_spec.rb | examples/Inflector/spec/main_spec.rb | describe "Application 'Inflector'" do
before do
@app = UIApplication.sharedApplication
end
it "has one window" do
@app.windows.size.should == 1
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support.rb | lib/motion-support.rb | unless defined?(Motion::Project::Config)
raise "This file must be required within a RubyMotion project Rakefile."
end
require 'motion-support/motion_support_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.requires)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/core_ext.rb | lib/motion-support/core_ext.rb | require_relative 'motion_support_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.core_ext_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/inflector.rb | lib/motion-support/inflector.rb | require_relative 'motion_support_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.inflector_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/callbacks.rb | lib/motion-support/callbacks.rb | require_relative 'motion_support_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.callbacks_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/motion_support_files.rb | lib/motion-support/motion_support_files.rb | require_relative 'core_ext/core_ext_files'
module MotionSupport
class << self
def callbacks_files
%w(
_stdlib/array
concern
descendants_tracker
callbacks
core_ext/kernel/singleton_class
).map { |file| self.map_file_to_motion_dir(file) }
end
def concern_files
['concern'].map { |file| self.map_file_to_motion_dir(file) }
end
def core_ext_files
base_files = %w(
core_ext/enumerable
core_ext/array
core_ext/metaclass
core_ext/ns_dictionary
core_ext/ns_string
core_ext/regexp
).map { |file| self.map_file_to_motion_dir(file) }
(array_files + class_files + module_files + integer_files + hash_files +
numeric_files + object_files + range_files + string_files + time_files + base_files).uniq
end
def inflector_files
%w(
inflector/inflections
inflector/methods
inflections
core_ext/string/inflections
core_ext/array/prepend_and_append
).map { |file| self.map_file_to_motion_dir(file) }
end
def requires
base_files = %w(
callbacks
concern
descendants_tracker
duration
hash_with_indifferent_access
inflections
logger
number_helper
version
).map { |file| self.map_file_to_motion_dir(file) }
(callbacks_files + core_ext_files + inflector_files + base_files).uniq
end
def map_file_to_motion_dir(file)
File.expand_path(File.join(File.dirname(__FILE__), "/../../motion", "#{file}.rb"))
end
end
end | ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/concern.rb | lib/motion-support/concern.rb | require_relative 'motion_support_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.concern_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/core_ext/range.rb | lib/motion-support/core_ext/range.rb | require_relative 'core_ext_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.range_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/core_ext/array.rb | lib/motion-support/core_ext/array.rb | require_relative 'core_ext_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.array_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/core_ext/time.rb | lib/motion-support/core_ext/time.rb | require_relative 'core_ext_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.time_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/core_ext/class.rb | lib/motion-support/core_ext/class.rb | require_relative 'core_ext_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.class_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/core_ext/string.rb | lib/motion-support/core_ext/string.rb | require_relative 'core_ext_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.string_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/core_ext/object.rb | lib/motion-support/core_ext/object.rb | require_relative 'core_ext_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.object_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/core_ext/core_ext_files.rb | lib/motion-support/core_ext/core_ext_files.rb | module MotionSupport
class << self
def array_files
%w(
core_ext/array
core_ext/array/wrap
core_ext/array/access
core_ext/array/conversions
core_ext/array/extract_options
core_ext/array/grouping
core_ext/array/prepend_and_append
).map { |file| self.map_core_ext_file_to_motion_dir(file) }
end
def class_files
%w(
core_ext/class/attribute
core_ext/class/attribute_accessors
).map { |file| self.map_core_ext_file_to_motion_dir(file) }
end
def hash_files
%w(
core_ext/ns_dictionary
core_ext/object/to_param
core_ext/hash/deep_merge
core_ext/hash/except
core_ext/hash/indifferent_access
core_ext/hash/keys
core_ext/hash/reverse_merge
core_ext/hash/slice
core_ext/hash/deep_delete_if
hash_with_indifferent_access
core_ext/module/delegation
).map { |file| self.map_core_ext_file_to_motion_dir(file) }
end
def integer_files
%w(
core_ext/integer/multiple
core_ext/integer/inflections
core_ext/integer/time
).map { |file| self.map_core_ext_file_to_motion_dir(file) }
end
def module_files
%w(
core_ext/module/aliasing
core_ext/module/introspection
core_ext/module/anonymous
core_ext/module/reachable
core_ext/module/attribute_accessors
core_ext/module/attr_internal
core_ext/module/delegation
core_ext/module/remove_method
).map { |file| self.map_core_ext_file_to_motion_dir(file) }
end
def numeric_files
%w(
duration
core_ext/numeric/bytes
core_ext/numeric/conversions
core_ext/numeric/time
).map { |file| self.map_core_ext_file_to_motion_dir(file) }
end
def object_files
%w(
_stdlib/cgi
core_ext/object/acts_like
core_ext/object/blank
core_ext/object/deep_dup
core_ext/object/duplicable
core_ext/object/inclusion
core_ext/object/try
core_ext/object/instance_variables
core_ext/object/to_json
core_ext/object/to_param
core_ext/object/to_query
).map { |file| self.map_core_ext_file_to_motion_dir(file) }
end
def range_files
%w(
core_ext/range/include_range
core_ext/range/overlaps
).map { |file| self.map_core_ext_file_to_motion_dir(file) }
end
def string_files
%w(
core_ext/ns_string
core_ext/string/access
core_ext/string/behavior
core_ext/string/exclude
core_ext/string/filters
core_ext/string/indent
core_ext/string/starts_ends_with
core_ext/string/inflections
core_ext/string/strip
core_ext/module/delegation
).map { |file| self.map_core_ext_file_to_motion_dir(file) }
end
def time_files
%w(
_stdlib/date
_stdlib/time
core_ext/time/acts_like
core_ext/time/calculations
core_ext/time/conversions
core_ext/date/acts_like
core_ext/date/calculations
core_ext/date/conversions
core_ext/date_and_time/calculations
core_ext/integer/time
core_ext/numeric/time
core_ext/object/acts_like
duration
).map { |file| self.map_core_ext_file_to_motion_dir(file) }
end
def map_core_ext_file_to_motion_dir(file)
File.expand_path(File.join(File.dirname(__FILE__), "/../../../motion", "#{file}.rb"))
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/core_ext/integer.rb | lib/motion-support/core_ext/integer.rb | require_relative 'core_ext_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.integer_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/core_ext/module.rb | lib/motion-support/core_ext/module.rb | require_relative 'core_ext_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.module_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/core_ext/hash.rb | lib/motion-support/core_ext/hash.rb | require_relative 'core_ext_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.hash_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/lib/motion-support/core_ext/numeric.rb | lib/motion-support/core_ext/numeric.rb | require_relative 'core_ext_files'
Motion::Project::App.setup do |app|
app.files.unshift(MotionSupport.numeric_files)
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/version.rb | motion/version.rb | module MotionSupport
VERSION = "1.2.1"
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/duration.rb | motion/duration.rb | module MotionSupport
# Provides accurate date and time measurements using Date#advance and
# Time#advance, respectively. It mainly supports the methods on Numeric.
#
# 1.month.ago # equivalent to Time.now.advance(months: -1)
class Duration < BasicObject
attr_accessor :value, :parts
def initialize(value, parts) #:nodoc:
@value, @parts = value, parts
end
# Adds another Duration or a Numeric to this Duration. Numeric values
# are treated as seconds.
def +(other)
if Duration === other
Duration.new(value + other.value, @parts + other.parts)
else
Duration.new(value + other, @parts + [[:seconds, other]])
end
end
# Subtracts another Duration or a Numeric from this Duration. Numeric
# values are treated as seconds.
def -(other)
self + (-other)
end
def -@ #:nodoc:
Duration.new(-value, parts.map { |type,number| [type, -number] })
end
def is_a?(klass) #:nodoc:
Duration == klass || value.is_a?(klass)
end
alias :kind_of? :is_a?
# Returns +true+ if +other+ is also a Duration instance with the
# same +value+, or if <tt>other == value</tt>.
def ==(other)
if Duration === other
other.value == value
else
other == value
end
end
def self.===(other) #:nodoc:
other.is_a?(Duration)
rescue ::NoMethodError
false
end
# Calculates a new Time or Date that is as far in the future
# as this Duration represents.
def since(time = ::Time.now)
sum(1, time)
end
alias :from_now :since
# Calculates a new Time or Date that is as far in the past
# as this Duration represents.
def ago(time = ::Time.now)
sum(-1, time)
end
alias :until :ago
def inspect #:nodoc:
consolidated = parts.inject(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }
parts = [:years, :months, :days, :minutes, :seconds].map do |length|
n = consolidated[length]
"#{n} #{n == 1 ? length.to_s.singularize : length.to_s}" if n.nonzero?
end.compact
parts = ["0 seconds"] if parts.empty?
parts.to_sentence
end
def as_json(options = nil) #:nodoc:
to_i
end
protected
def sum(sign, time = ::Time.now) #:nodoc:
parts.inject(time) do |t,(type,number)|
if t.acts_like?(:time) || t.acts_like?(:date)
if type == :seconds
t.since(sign * number)
else
t.advance(type => sign * number)
end
else
raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
end
end
end
private
def method_missing(method, *args, &block) #:nodoc:
value.send(method, *args, &block)
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/logger.rb | motion/logger.rb | module Kernel
def log(*args)
MotionSupport.logger.log(*args)
end
def l(*args)
MotionSupport.logger.log(args.map { |a| a.inspect })
end
end
module MotionSupport
class NullLogger
def log(*args)
end
end
class StdoutLogger
def log(*args)
puts args
end
end
class NetworkLogger
def initialize(host = "localhost", port = 2000)
readStream = Pointer.new(:object)
writeStream = Pointer.new(:object)
CFStreamCreatePairWithSocketToHost(nil, host, port, readStream, writeStream)
@output_stream = writeStream[0]
@output_stream.setDelegate(self)
@output_stream.scheduleInRunLoop(NSRunLoop.currentRunLoop, forMode:NSDefaultRunLoopMode)
@output_stream.open
end
def log(*args)
args.each do |string|
data = NSData.alloc.initWithData("#{string}\n".dataUsingEncoding(NSASCIIStringEncoding))
@output_stream.write(data.bytes, maxLength:data.length)
end
end
end
mattr_writer :logger
def self.logger
@logger ||= StdoutLogger.new
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/callbacks.rb | motion/callbacks.rb | module MotionSupport
# Callbacks are code hooks that are run at key points in an object's lifecycle.
# The typical use case is to have a base class define a set of callbacks
# relevant to the other functionality it supplies, so that subclasses can
# install callbacks that enhance or modify the base functionality without
# needing to override or redefine methods of the base class.
#
# Mixing in this module allows you to define the events in the object's
# lifecycle that will support callbacks (via +ClassMethods.define_callbacks+),
# set the instance methods, procs, or callback objects to be called (via
# +ClassMethods.set_callback+), and run the installed callbacks at the
# appropriate times (via +run_callbacks+).
#
# Three kinds of callbacks are supported: before callbacks, run before a
# certain event; after callbacks, run after the event; and around callbacks,
# blocks that surround the event, triggering it when they yield. Callback code
# can be contained in instance methods, procs or lambdas, or callback objects
# that respond to certain predetermined methods. See +ClassMethods.set_callback+
# for details.
#
# class Record
# include MotionSupport::Callbacks
# define_callbacks :save
#
# def save
# run_callbacks :save do
# puts "- save"
# end
# end
# end
#
# class PersonRecord < Record
# set_callback :save, :before, :saving_message
# def saving_message
# puts "saving..."
# end
#
# set_callback :save, :after do |object|
# puts "saved"
# end
# end
#
# person = PersonRecord.new
# person.save
#
# Output:
# saving...
# - save
# saved
module Callbacks
extend Concern
included do
extend MotionSupport::DescendantsTracker
end
# Runs the callbacks for the given event.
#
# Calls the before and around callbacks in the order they were set, yields
# the block (if given one), and then runs the after callbacks in reverse
# order.
#
# If the callback chain was halted, returns +false+. Otherwise returns the
# result of the block, or +true+ if no block is given.
#
# run_callbacks :save do
# save
# end
def run_callbacks(kind, &block)
runner_name = self.class.__define_callbacks(kind, self)
send(runner_name, &block)
end
private
# A hook invoked everytime a before callback is halted.
# This can be overridden in AS::Callback implementors in order
# to provide better debugging/logging.
def halted_callback_hook(filter)
end
class Callback #:nodoc:#
@@_callback_sequence = 0
attr_accessor :chain, :filter, :kind, :options, :klass, :raw_filter
def initialize(chain, filter, kind, options, klass)
@chain, @kind, @klass = chain, kind, klass
normalize_options!(options)
@raw_filter, @options = filter, options
@filter = _compile_filter(filter)
recompile_options!
end
def clone(chain, klass)
obj = super()
obj.chain = chain
obj.klass = klass
obj.options = @options.dup
obj.options[:if] = @options[:if].dup
obj.options[:unless] = @options[:unless].dup
obj
end
def normalize_options!(options)
options[:if] = Array(options[:if])
options[:unless] = Array(options[:unless])
end
def name
chain.name
end
def next_id
@@_callback_sequence += 1
end
def matches?(_kind, _filter)
@kind == _kind && @raw_filter == _filter
end
def duplicates?(other)
matches?(other.kind, other.raw_filter)
end
def _update_filter(filter_options, new_options)
filter_options[:if].concat(Array(new_options[:unless])) if new_options.key?(:unless)
filter_options[:unless].concat(Array(new_options[:if])) if new_options.key?(:if)
end
def recompile!(_options)
_update_filter(self.options, _options)
recompile_options!
end
# Wraps code with filter
def apply(code)
case @kind
when :before
lambda do |obj, value, halted|
if !halted && @compiled_options.call(obj)
result = @filter.call(obj)
halted = chain.config[:terminator].call(result)
if halted
obj.halted_callback_hook(@raw_filter.inspect)
end
end
code.call(obj, value, halted)
end
when :after
lambda do |obj, value, halted|
value, halted = *(code.call(obj, value, halted))
if (!chain.config[:skip_after_callbacks_if_terminated] || !halted) && @compiled_options.call(obj)
@filter.call(obj)
end
[value, halted]
end
when :around
lambda do |obj, value, halted|
if @compiled_options.call(obj) && !halted
@filter.call(obj) do
value, halted = *(code.call(obj, value, halted))
value
end
else
value, halted = *(code.call(obj, value, halted))
value
end
[value, halted]
end
end
end
private
# Options support the same options as filters themselves (and support
# symbols, string, procs, and objects), so compile a conditional
# expression based on the options.
def recompile_options!
@conditions = [ lambda { |obj| true } ]
unless options[:if].empty?
@conditions << Array(_compile_filter(options[:if]))
end
unless options[:unless].empty?
@conditions << Array(_compile_filter(options[:unless])).map {|f| lambda { |obj| !f.call(obj) } }
end
@compiled_options = lambda { |obj| @conditions.flatten.all? { |c| c.call(obj) } }
end
# Filters support:
#
# Arrays:: Used in conditions. This is used to specify
# multiple conditions. Used internally to
# merge conditions from skip_* filters.
# Symbols:: A method to call.
# Procs:: A proc to call with the object.
# Objects:: An object with a <tt>before_foo</tt> method on it to call.
#
# All of these objects are compiled into methods and handled
# the same after this point:
#
# Arrays:: Merged together into a single filter.
# Symbols:: Already methods.
# Procs:: define_method'ed into methods.
# Objects::
# a method is created that calls the before_foo method
# on the object.
def _compile_filter(filter)
case filter
when Array
lambda { |obj, &block| filter.all? {|f| _compile_filter(f).call(obj, &block) } }
when Symbol, String
lambda { |obj, &block| obj.send filter, &block }
when Proc
filter
else
method_name = "_callback_#{@kind}_#{next_id}"
@klass.send(:define_method, "#{method_name}_object") { filter }
scopes = Array(chain.config[:scope])
method_to_call = scopes.map{ |s| s.is_a?(Symbol) ? send(s) : s }.join("_")
@klass.class_eval do
define_method method_name do |&blk|
send("#{method_name}_object").send(method_to_call, self, &blk)
end
end
lambda { |obj, &block| obj.send method_name, &block }
end
end
end
# An Array with a compile method.
class CallbackChain < Array #:nodoc:#
attr_reader :name, :config
def initialize(name, config)
@name = name
@config = {
:terminator => lambda { |result| false },
:scope => [ :kind ]
}.merge!(config)
end
def compile
lambda do |obj, &block|
value = nil
halted = false
callbacks = lambda do |obj, value, halted|
value = !halted && (block.call if block)
[value, halted]
end
reverse_each do |callback|
callbacks = callback.apply(callbacks)
end
value, halted = *(callbacks.call(obj, value, halted))
value
end
end
def append(*callbacks)
callbacks.each { |c| append_one(c) }
end
def prepend(*callbacks)
callbacks.each { |c| prepend_one(c) }
end
private
def append_one(callback)
remove_duplicates(callback)
push(callback)
end
def prepend_one(callback)
remove_duplicates(callback)
unshift(callback)
end
def remove_duplicates(callback)
delete_if { |c| callback.duplicates?(c) }
end
end
module ClassMethods
# This method defines callback chain method for the given kind
# if it was not yet defined.
# This generated method plays caching role.
def __define_callbacks(kind, object) #:nodoc:
name = __callback_runner_name(kind)
unless object.respond_to?(name, true)
block = object.send("_#{kind}_callbacks").compile
define_method name do |&blk|
block.call(self, &blk)
end
protected name.to_sym
end
name
end
def __reset_runner(symbol)
name = __callback_runner_name(symbol)
undef_method(name) if method_defined?(name)
end
def __callback_runner_name_cache
@__callback_runner_name_cache ||= Hash.new {|cache, kind| cache[kind] = __generate_callback_runner_name(kind) }
end
def __generate_callback_runner_name(kind)
"_run__#{self.name.hash.abs}__#{kind}__callbacks"
end
def __callback_runner_name(kind)
__callback_runner_name_cache[kind]
end
# This is used internally to append, prepend and skip callbacks to the
# CallbackChain.
def __update_callbacks(name, filters = [], block = nil) #:nodoc:
type = [:before, :after, :around].include?(filters.first) ? filters.shift : :before
options = filters.last.is_a?(Hash) ? filters.pop : {}
filters.unshift(block) if block
([self] + MotionSupport::DescendantsTracker.descendants(self)).reverse.each do |target|
chain = target.send("_#{name}_callbacks")
yield target, chain.dup, type, filters, options
target.__reset_runner(name)
end
end
# Install a callback for the given event.
#
# set_callback :save, :before, :before_meth
# set_callback :save, :after, :after_meth, if: :condition
# set_callback :save, :around, ->(r, &block) { stuff; result = block.call; stuff }
#
# The second arguments indicates whether the callback is to be run +:before+,
# +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
# means the first example above can also be written as:
#
# set_callback :save, :before_meth
#
# The callback can specified as a symbol naming an instance method; as a
# proc, lambda, or block; as a string to be instance evaluated; or as an
# object that responds to a certain method determined by the <tt>:scope</tt>
# argument to +define_callback+.
#
# If a proc, lambda, or block is given, its body is evaluated in the context
# of the current object. It can also optionally accept the current object as
# an argument.
#
# Before and around callbacks are called in the order that they are set;
# after callbacks are called in the reverse order.
#
# Around callbacks can access the return value from the event, if it
# wasn't halted, from the +yield+ call.
#
# ===== Options
#
# * <tt>:if</tt> - A symbol naming an instance method or a proc; the
# callback will be called only when it returns a +true+ value.
# * <tt>:unless</tt> - A symbol naming an instance method or a proc; the
# callback will be called only when it returns a +false+ value.
# * <tt>:prepend</tt> - If +true+, the callback will be prepended to the
# existing chain rather than appended.
def set_callback(name, *filter_list, &block)
mapped = nil
__update_callbacks(name, filter_list, block) do |target, chain, type, filters, options|
mapped ||= filters.map do |filter|
Callback.new(chain, filter, type, options.dup, self)
end
options[:prepend] ? chain.prepend(*mapped) : chain.append(*mapped)
target.send("_#{name}_callbacks=", chain)
end
end
# Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or
# <tt>:unless</tt> options may be passed in order to control when the
# callback is skipped.
#
# class Writer < Person
# skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 }
# end
def skip_callback(name, *filter_list, &block)
__update_callbacks(name, filter_list, block) do |target, chain, type, filters, options|
filters.each do |filter|
filter = chain.find {|c| c.matches?(type, filter) }
if filter && options.any?
new_filter = filter.clone(chain, self)
chain.insert(chain.index(filter), new_filter)
new_filter.recompile!(options)
end
chain.delete(filter)
end
target.send("_#{name}_callbacks=", chain)
end
end
# Remove all set callbacks for the given event.
def reset_callbacks(symbol)
callbacks = send("_#{symbol}_callbacks")
MotionSupport::DescendantsTracker.descendants(self).each do |target|
chain = target.send("_#{symbol}_callbacks").dup
callbacks.each { |c| chain.delete(c) }
target.send("_#{symbol}_callbacks=", chain)
target.__reset_runner(symbol)
end
self.send("_#{symbol}_callbacks=", callbacks.dup.clear)
__reset_runner(symbol)
end
# Define sets of events in the object lifecycle that support callbacks.
#
# define_callbacks :validate
# define_callbacks :initialize, :save, :destroy
#
# ===== Options
#
# * <tt>:terminator</tt> - Determines when a before filter will halt the
# callback chain, preventing following callbacks from being called and
# the event from being triggered. This is a string to be eval'ed. The
# result of the callback is available in the +result+ variable.
#
# define_callbacks :validate, terminator: 'result == false'
#
# In this example, if any before validate callbacks returns +false+,
# other callbacks are not executed. Defaults to +false+, meaning no value
# halts the chain.
#
# * <tt>:skip_after_callbacks_if_terminated</tt> - Determines if after
# callbacks should be terminated by the <tt>:terminator</tt> option. By
# default after callbacks executed no matter if callback chain was
# terminated or not. Option makes sense only when <tt>:terminator</tt>
# option is specified.
#
# * <tt>:scope</tt> - Indicates which methods should be executed when an
# object is used as a callback.
#
# class Audit
# def before(caller)
# puts 'Audit: before is called'
# end
#
# def before_save(caller)
# puts 'Audit: before_save is called'
# end
# end
#
# class Account
# include MotionSupport::Callbacks
#
# define_callbacks :save
# set_callback :save, :before, Audit.new
#
# def save
# run_callbacks :save do
# puts 'save in main'
# end
# end
# end
#
# In the above case whenever you save an account the method
# <tt>Audit#before</tt> will be called. On the other hand
#
# define_callbacks :save, scope: [:kind, :name]
#
# would trigger <tt>Audit#before_save</tt> instead. That's constructed
# by calling <tt>#{kind}_#{name}</tt> on the given instance. In this
# case "kind" is "before" and "name" is "save". In this context +:kind+
# and +:name+ have special meanings: +:kind+ refers to the kind of
# callback (before/after/around) and +:name+ refers to the method on
# which callbacks are being defined.
#
# A declaration like
#
# define_callbacks :save, scope: [:name]
#
# would call <tt>Audit#save</tt>.
def define_callbacks(*callbacks)
config = callbacks.last.is_a?(Hash) ? callbacks.pop : {}
callbacks.each do |callback|
class_attribute "_#{callback}_callbacks"
send("_#{callback}_callbacks=", CallbackChain.new(callback, config))
end
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/descendants_tracker.rb | motion/descendants_tracker.rb | module MotionSupport
# This module provides an internal implementation to track descendants
# which is faster than iterating through ObjectSpace.
module DescendantsTracker
@@direct_descendants = {}
class << self
def direct_descendants(klass)
@@direct_descendants[klass] || []
end
def descendants(klass)
arr = []
accumulate_descendants(klass, arr)
arr
end
def clear
@@direct_descendants.clear
end
# This is the only method that is not thread safe, but is only ever called
# during the eager loading phase.
def store_inherited(klass, descendant)
(@@direct_descendants[klass] ||= []) << descendant
end
private
def accumulate_descendants(klass, acc)
if direct_descendants = @@direct_descendants[klass]
acc.concat(direct_descendants)
direct_descendants.each { |direct_descendant| accumulate_descendants(direct_descendant, acc) }
end
end
end
def inherited(base)
DescendantsTracker.store_inherited(self, base)
super
end
def direct_descendants
DescendantsTracker.direct_descendants(self)
end
def descendants
DescendantsTracker.descendants(self)
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/hash_with_indifferent_access.rb | motion/hash_with_indifferent_access.rb | module MotionSupport
# Implements a hash where keys <tt>:foo</tt> and <tt>"foo"</tt> are considered
# to be the same.
#
# rgb = MotionSupport::HashWithIndifferentAccess.new
#
# rgb[:black] = '#000000'
# rgb[:black] # => '#000000'
# rgb['black'] # => '#000000'
#
# rgb['white'] = '#FFFFFF'
# rgb[:white] # => '#FFFFFF'
# rgb['white'] # => '#FFFFFF'
#
# Internally symbols are mapped to strings when used as keys in the entire
# writing interface (calling <tt>[]=</tt>, <tt>merge</tt>, etc). This
# mapping belongs to the public interface. For example, given:
#
# hash = MotionSupport::HashWithIndifferentAccess.new(a: 1)
#
# You are guaranteed that the key is returned as a string:
#
# hash.keys # => ["a"]
#
# Technically other types of keys are accepted:
#
# hash = MotionSupport::HashWithIndifferentAccess.new(a: 1)
# hash[0] = 0
# hash # => {"a"=>1, 0=>0}
#
# but this class is intended for use cases where strings or symbols are the
# expected keys and it is convenient to understand both as the same. For
# example the +params+ hash in Ruby on Rails.
#
# Note that core extensions define <tt>Hash#with_indifferent_access</tt>:
#
# rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access
#
# which may be handy.
class HashWithIndifferentAccess < Hash
# Returns +true+ so that <tt>Array#extract_options!</tt> finds members of
# this class.
def extractable_options?
true
end
def with_indifferent_access
dup
end
def nested_under_indifferent_access
self
end
def initialize(constructor = {})
if constructor.is_a?(Hash)
super()
update(constructor)
else
super(constructor)
end
end
def default(key = nil)
if key.is_a?(Symbol) && include?(key = key.to_s)
self[key]
else
super
end
end
def self.new_from_hash_copying_default(hash)
new(hash).tap do |new_hash|
new_hash.default = hash.default
end
end
def self.[](*args)
new.merge!(Hash[*args])
end
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
alias_method :regular_update, :update unless method_defined?(:regular_update)
# Assigns a new value to the hash:
#
# hash = MotionSupport::HashWithIndifferentAccess.new
# hash[:key] = 'value'
#
# This value can be later fetched using either +:key+ or +'key'+.
def []=(key, value)
regular_writer(convert_key(key), convert_value(value))
end
alias_method :store, :[]=
# Updates the receiver in-place, merging in the hash passed as argument:
#
# hash_1 = MotionSupport::HashWithIndifferentAccess.new
# hash_1[:key] = 'value'
#
# hash_2 = MotionSupport::HashWithIndifferentAccess.new
# hash_2[:key] = 'New Value!'
#
# hash_1.update(hash_2) # => {"key"=>"New Value!"}
#
# The argument can be either an
# <tt>MotionSupport::HashWithIndifferentAccess</tt> or a regular +Hash+.
# In either case the merge respects the semantics of indifferent access.
#
# If the argument is a regular hash with keys +:key+ and +"key"+ only one
# of the values end up in the receiver, but which one is unspecified.
#
# When given a block, the value for duplicated keys will be determined
# by the result of invoking the block with the duplicated key, the value
# in the receiver, and the value in +other_hash+. The rules for duplicated
# keys follow the semantics of indifferent access:
#
# hash_1[:key] = 10
# hash_2['key'] = 12
# hash_1.update(hash_2) { |key, old, new| old + new } # => {"key"=>22}
def update(other_hash)
if other_hash.is_a? HashWithIndifferentAccess
super(other_hash)
else
other_hash.each_pair do |key, value|
if block_given? && key?(key)
value = yield(convert_key(key), self[key], value)
end
regular_writer(convert_key(key), convert_value(value))
end
self
end
end
alias_method :merge!, :update
# Checks the hash for a key matching the argument passed in:
#
# hash = MotionSupport::HashWithIndifferentAccess.new
# hash['key'] = 'value'
# hash.key?(:key) # => true
# hash.key?('key') # => true
def key?(key)
super(convert_key(key))
end
alias_method :include?, :key?
alias_method :has_key?, :key?
alias_method :member?, :key?
# Same as <tt>Hash#fetch</tt> where the key passed as argument can be
# either a string or a symbol:
#
# counters = MotionSupport::HashWithIndifferentAccess.new
# counters[:foo] = 1
#
# counters.fetch('foo') # => 1
# counters.fetch(:bar, 0) # => 0
# counters.fetch(:bar) {|key| 0} # => 0
# counters.fetch(:zoo) # => KeyError: key not found: "zoo"
def fetch(key, *extras)
super(convert_key(key), *extras)
end
# Returns an array of the values at the specified indices:
#
# hash = MotionSupport::HashWithIndifferentAccess.new
# hash[:a] = 'x'
# hash[:b] = 'y'
# hash.values_at('a', 'b') # => ["x", "y"]
def values_at(*indices)
indices.collect {|key| self[convert_key(key)]}
end
# Returns an exact copy of the hash.
def dup
self.class.new(self).tap do |new_hash|
new_hash.default = default
end
end
# This method has the same semantics of +update+, except it does not
# modify the receiver but rather returns a new hash with indifferent
# access with the result of the merge.
def merge(hash, &block)
self.dup.update(hash, &block)
end
# Like +merge+ but the other way around: Merges the receiver into the
# argument and returns a new hash with indifferent access as result:
#
# hash = MotionSupport::HashWithIndifferentAccess.new
# hash['a'] = nil
# hash.reverse_merge(a: 0, b: 1) # => {"a"=>nil, "b"=>1}
def reverse_merge(other_hash)
super(self.class.new_from_hash_copying_default(other_hash))
end
# Same semantics as +reverse_merge+ but modifies the receiver in-place.
def reverse_merge!(other_hash)
replace(reverse_merge( other_hash ))
end
# Replaces the contents of this hash with other_hash.
#
# h = { "a" => 100, "b" => 200 }
# h.replace({ "c" => 300, "d" => 400 }) #=> {"c"=>300, "d"=>400}
def replace(other_hash)
super(self.class.new_from_hash_copying_default(other_hash))
end
# Removes the specified key from the hash.
def delete(key)
super(convert_key(key))
end
def stringify_keys!; self end
def deep_stringify_keys!; self end
def stringify_keys; dup end
def deep_stringify_keys; dup end
undef :symbolize_keys!
undef :deep_symbolize_keys!
def symbolize_keys; to_hash.symbolize_keys end
def deep_symbolize_keys; to_hash.deep_symbolize_keys end
def to_options!; self end
# Convert to a regular hash with string keys.
def to_hash
Hash.new(default).merge!(self)
end
protected
def convert_key(key)
key.kind_of?(Symbol) ? key.to_s : key
end
def convert_value(value)
if value.is_a? Hash
value.nested_under_indifferent_access
elsif value.is_a?(Array)
value = value.dup if value.frozen?
value.map! { |e| convert_value(e) }
else
value
end
end
end
end
HashWithIndifferentAccess = MotionSupport::HashWithIndifferentAccess
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/inflections.rb | motion/inflections.rb | module MotionSupport
Inflector.inflections do |inflect|
inflect.plural(/$/, 's')
inflect.plural(/s$/i, 's')
inflect.plural(/^(ax|test)is$/i, '\1es')
inflect.plural(/(octop|vir)us$/i, '\1i')
inflect.plural(/(octop|vir)i$/i, '\1i')
inflect.plural(/(alias|status)$/i, '\1es')
inflect.plural(/(bu)s$/i, '\1ses')
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
inflect.plural(/([ti])um$/i, '\1a')
inflect.plural(/([ti])a$/i, '\1a')
inflect.plural(/sis$/i, 'ses')
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
inflect.plural(/(hive)$/i, '\1s')
inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
inflect.plural(/^(m|l)ouse$/i, '\1ice')
inflect.plural(/^(m|l)ice$/i, '\1ice')
inflect.plural(/^(ox)$/i, '\1en')
inflect.plural(/^(oxen)$/i, '\1')
inflect.plural(/(quiz)$/i, '\1zes')
inflect.singular(/s$/i, '')
inflect.singular(/(ss)$/i, '\1')
inflect.singular(/(n)ews$/i, '\1ews')
inflect.singular(/([ti])a$/i, '\1um')
inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '\1sis')
inflect.singular(/(^analy)(sis|ses)$/i, '\1sis')
inflect.singular(/([^f])ves$/i, '\1fe')
inflect.singular(/(hive)s$/i, '\1')
inflect.singular(/(tive)s$/i, '\1')
inflect.singular(/([lr])ves$/i, '\1f')
inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
inflect.singular(/(s)eries$/i, '\1eries')
inflect.singular(/(m)ovies$/i, '\1ovie')
inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
inflect.singular(/^(m|l)ice$/i, '\1ouse')
inflect.singular(/(bus)(es)?$/i, '\1')
inflect.singular(/(o)es$/i, '\1')
inflect.singular(/(shoe)s$/i, '\1')
inflect.singular(/(cris|test)(is|es)$/i, '\1is')
inflect.singular(/^(a)x[ie]s$/i, '\1xis')
inflect.singular(/(octop|vir)(us|i)$/i, '\1us')
inflect.singular(/(alias|status)(es)?$/i, '\1')
inflect.singular(/^(ox)en/i, '\1')
inflect.singular(/(vert|ind)ices$/i, '\1ex')
inflect.singular(/(matr)ices$/i, '\1ix')
inflect.singular(/(quiz)zes$/i, '\1')
inflect.singular(/(database)s$/i, '\1')
inflect.irregular('person', 'people')
inflect.irregular('man', 'men')
inflect.irregular('child', 'children')
inflect.irregular('sex', 'sexes')
inflect.irregular('move', 'moves')
inflect.irregular('cow', 'kine')
inflect.irregular('zombie', 'zombies')
inflect.uncountable(%w(equipment information rice money species series fish sheep jeans police))
inflect.acronym('UI')
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/concern.rb | motion/concern.rb | module MotionSupport
# A typical module looks like this:
#
# module M
# def self.included(base)
# base.extend ClassMethods
# base.class_eval do
# scope :disabled, -> { where(disabled: true) }
# end
# end
#
# module ClassMethods
# ...
# end
# end
#
# By using <tt>MotionSupport::Concern</tt> the above module could instead be
# written as:
#
# module M
# extend MotionSupport::Concern
#
# included do
# scope :disabled, -> { where(disabled: true) }
# end
#
# module ClassMethods
# ...
# end
# end
#
# Moreover, it gracefully handles module dependencies. Given a +Foo+ module
# and a +Bar+ module which depends on the former, we would typically write the
# following:
#
# module Foo
# def self.included(base)
# base.class_eval do
# def self.method_injected_by_foo
# ...
# end
# end
# end
# end
#
# module Bar
# def self.included(base)
# base.method_injected_by_foo
# end
# end
#
# class Host
# include Foo # We need to include this dependency for Bar
# include Bar # Bar is the module that Host really needs
# end
#
# But why should +Host+ care about +Bar+'s dependencies, namely +Foo+? We
# could try to hide these from +Host+ directly including +Foo+ in +Bar+:
#
# module Bar
# include Foo
# def self.included(base)
# base.method_injected_by_foo
# end
# end
#
# class Host
# include Bar
# end
#
# Unfortunately this won't work, since when +Foo+ is included, its <tt>base</tt>
# is the +Bar+ module, not the +Host+ class. With <tt>MotionSupport::Concern</tt>,
# module dependencies are properly resolved:
#
# module Foo
# extend MotionSupport::Concern
# included do
# def self.method_injected_by_foo
# ...
# end
# end
# end
#
# module Bar
# extend MotionSupport::Concern
# include Foo
#
# included do
# self.method_injected_by_foo
# end
# end
#
# class Host
# include Bar # works, Bar takes care now of its dependencies
# end
module Concern
def self.extended(base) #:nodoc:
base.instance_variable_set("@_dependencies", [])
end
def append_features(base)
if base.instance_variable_defined?("@_dependencies")
base.instance_variable_get("@_dependencies") << self
return false
else
return false if base < self
@_dependencies.each { |dep| base.send(:include, dep) }
super
base.extend const_get("ClassMethods") if const_defined?("ClassMethods")
base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block")
end
end
def included(base = nil, &block)
if base.nil?
@_included_block = block
else
super
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/number_helper.rb | motion/number_helper.rb | module MotionSupport
module NumberHelper
extend self
# Formats a +number+ into a US phone number (e.g., (555)
# 123-9876). You can customize the format in the +options+ hash.
#
# ==== Options
#
# * <tt>:area_code</tt> - Adds parentheses around the area code.
# * <tt>:delimiter</tt> - Specifies the delimiter to use
# (defaults to "-").
# * <tt>:extension</tt> - Specifies an extension to add to the
# end of the generated number.
# * <tt>:country_code</tt> - Sets the country code for the phone
# number.
# ==== Examples
#
# number_to_phone(5551234) # => 555-1234
# number_to_phone('5551234') # => 555-1234
# number_to_phone(1235551234) # => 123-555-1234
# number_to_phone(1235551234, area_code: true) # => (123) 555-1234
# number_to_phone(1235551234, delimiter: ' ') # => 123 555 1234
# number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555
# number_to_phone(1235551234, country_code: 1) # => +1-123-555-1234
# number_to_phone('123a456') # => 123a456
#
# number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: '.')
# # => +1.123.555.1234 x 1343
def number_to_phone(number, options = {})
return unless number
options = options.symbolize_keys
number = number.to_s.strip
area_code = options[:area_code]
delimiter = options[:delimiter] || "-"
extension = options[:extension]
country_code = options[:country_code]
if area_code
number.gsub!(/(\d{1,3})(\d{3})(\d{4}$)/,"(\\1) \\2#{delimiter}\\3")
else
number.gsub!(/(\d{0,3})(\d{3})(\d{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
number.slice!(0, 1) if number.start_with?(delimiter) && !delimiter.blank?
end
str = ''
str << "+#{country_code}#{delimiter}" unless country_code.blank?
str << number
str << " x #{extension}" unless extension.blank?
str
end
end
end | ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/inflector/methods.rb | motion/inflector/methods.rb | module MotionSupport
# The Inflector transforms words from singular to plural, class names to table
# names, modularized class names to ones without, and class names to foreign
# keys. The default inflections for pluralization, singularization, and
# uncountable words are kept in inflections.rb.
module Inflector
extend self
# Returns the plural form of the word in the string.
#
# 'post'.pluralize # => "posts"
# 'octopus'.pluralize # => "octopi"
# 'sheep'.pluralize # => "sheep"
# 'words'.pluralize # => "words"
# 'CamelOctopus'.pluralize # => "CamelOctopi"
def pluralize(word)
apply_inflections(word, inflections.plurals)
end
# The reverse of +pluralize+, returns the singular form of a word in a
# string.
#
# 'posts'.singularize # => "post"
# 'octopi'.singularize # => "octopus"
# 'sheep'.singularize # => "sheep"
# 'word'.singularize # => "word"
# 'CamelOctopi'.singularize # => "CamelOctopus"
def singularize(word)
apply_inflections(word, inflections.singulars)
end
# By default, +camelize+ converts strings to UpperCamelCase. If the argument
# to +camelize+ is set to <tt>:lower</tt> then +camelize+ produces
# lowerCamelCase.
#
# +camelize+ will also convert '/' to '::' which is useful for converting
# paths to namespaces.
#
# 'active_model'.camelize # => "ActiveModel"
# 'active_model'.camelize(:lower) # => "activeModel"
# 'active_model/errors'.camelize # => "ActiveModel::Errors"
# 'active_model/errors'.camelize(:lower) # => "activeModel::Errors"
#
# As a rule of thumb you can think of +camelize+ as the inverse of
# +underscore+, though there are cases where that does not hold:
#
# 'SSLError'.underscore.camelize # => "SslError"
def camelize(term, uppercase_first_letter = true)
string = term.to_s
if uppercase_first_letter
string = string.sub(/^[a-z\d]*/) { inflections.acronyms[$&] || $&.capitalize }
else
string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
end
string.gsub(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }.gsub('/', '::')
end
# Makes an underscored, lowercase form from the expression in the string.
#
# Changes '::' to '/' to convert namespaces to paths.
#
# 'ActiveModel'.underscore # => "active_model"
# 'ActiveModel::Errors'.underscore # => "active_model/errors"
#
# As a rule of thumb you can think of +underscore+ as the inverse of
# +camelize+, though there are cases where that does not hold:
#
# 'SSLError'.underscore.camelize # => "SslError"
def underscore(camel_cased_word)
word = camel_cased_word.to_s.dup
word.gsub!('::', '/')
word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
word.tr!("-", "_")
word.downcase!
word
end
# Capitalizes the first word and turns underscores into spaces and strips a
# trailing "_id", if any. Like +titleize+, this is meant for creating pretty
# output.
#
# 'employee_salary'.humanize # => "Employee salary"
# 'author_id'.humanize # => "Author"
def humanize(lower_case_and_underscored_word)
result = lower_case_and_underscored_word.to_s.dup
inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
result.gsub!(/_id$/, "")
result.tr!('_', ' ')
result.gsub(/([a-z\d]*)/i) { |match|
"#{inflections.acronyms[match] || match.downcase}"
}.gsub(/^\w/) { $&.upcase }
end
# Capitalizes all the words and replaces some characters in the string to
# create a nicer looking title. +titleize+ is meant for creating pretty
# output. It is not used in the Rails internals.
#
# +titleize+ is also aliased as +titlecase+.
#
# 'man from the boondocks'.titleize # => "Man From The Boondocks"
# 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
# 'TheManWithoutAPast'.titleize # => "The Man Without A Past"
# 'raiders_of_the_lost_ark'.titleize # => "Raiders Of The Lost Ark"
def titleize(word)
humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { $&.capitalize }
end
# Create the name of a table like Rails does for models to table names. This
# method uses the +pluralize+ method on the last word in the string.
#
# 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
# 'egg_and_ham'.tableize # => "egg_and_hams"
# 'fancyCategory'.tableize # => "fancy_categories"
def tableize(class_name)
pluralize(underscore(class_name))
end
# Create a class name from a plural table name like Rails does for table
# names to models. Note that this returns a string and not a Class (To
# convert to an actual class follow +classify+ with +constantize+).
#
# 'egg_and_hams'.classify # => "EggAndHam"
# 'posts'.classify # => "Post"
#
# Singular names are not handled correctly:
#
# 'business'.classify # => "Busines"
def classify(table_name)
# strip out any leading schema name
camelize(singularize(table_name.to_s.sub(/.*\./, '')))
end
# Replaces underscores with dashes in the string.
#
# 'puni_puni'.dasherize # => "puni-puni"
def dasherize(underscored_word)
underscored_word.tr('_', '-')
end
# Removes the module part from the expression in the string.
#
# 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
# 'Inflections'.demodulize # => "Inflections"
#
# See also +deconstantize+.
def demodulize(path)
path = path.to_s
if i = path.rindex('::')
path[(i+2)..-1]
else
path
end
end
# Removes the rightmost segment from the constant expression in the string.
#
# 'Net::HTTP'.deconstantize # => "Net"
# '::Net::HTTP'.deconstantize # => "::Net"
# 'String'.deconstantize # => ""
# '::String'.deconstantize # => ""
# ''.deconstantize # => ""
#
# See also +demodulize+.
def deconstantize(path)
path.to_s[0...(path.rindex('::') || 0)] # implementation based on the one in facets' Module#spacename
end
# Creates a foreign key name from a class name.
# +separate_class_name_and_id_with_underscore+ sets whether
# the method should put '_' between the name and 'id'.
#
# 'Message'.foreign_key # => "message_id"
# 'Message'.foreign_key(false) # => "messageid"
# 'Admin::Post'.foreign_key # => "post_id"
def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
end
# Tries to find a constant with the name specified in the argument string.
#
# 'Module'.constantize # => Module
# 'Test::Unit'.constantize # => Test::Unit
#
# The name is assumed to be the one of a top-level constant, no matter
# whether it starts with "::" or not. No lexical context is taken into
# account:
#
# C = 'outside'
# module M
# C = 'inside'
# C # => 'inside'
# 'C'.constantize # => 'outside', same as ::C
# end
#
# NameError is raised when the name is not in CamelCase or the constant is
# unknown.
def constantize(camel_cased_word)
names = camel_cased_word.split('::')
names.shift if names.empty? || names.first.empty?
names.inject(Object) do |constant, name|
if constant == Object
constant.const_get(name)
else
candidate = constant.const_get(name)
next candidate if constant.const_defined?(name, false)
next candidate unless Object.const_defined?(name)
# Go down the ancestors to check it it's owned
# directly before we reach Object or the end of ancestors.
constant = constant.ancestors.inject do |const, ancestor|
break const if ancestor == Object
break ancestor if ancestor.const_defined?(name, false)
const
end
# owner is in Object, so raise
constant.const_get(name, false)
end
end
end
# Tries to find a constant with the name specified in the argument string.
#
# 'Module'.safe_constantize # => Module
# 'Test::Unit'.safe_constantize # => Test::Unit
#
# The name is assumed to be the one of a top-level constant, no matter
# whether it starts with "::" or not. No lexical context is taken into
# account:
#
# C = 'outside'
# module M
# C = 'inside'
# C # => 'inside'
# 'C'.safe_constantize # => 'outside', same as ::C
# end
#
# +nil+ is returned when the name is not in CamelCase or the constant (or
# part of it) is unknown.
#
# 'blargle'.safe_constantize # => nil
# 'UnknownModule'.safe_constantize # => nil
# 'UnknownModule::Foo::Bar'.safe_constantize # => nil
def safe_constantize(camel_cased_word)
constantize(camel_cased_word)
rescue NameError => e
raise unless e.message =~ /(uninitialized constant|wrong constant name) #{const_regexp(camel_cased_word)}$/ ||
e.name.to_s == camel_cased_word.to_s
rescue ArgumentError => e
raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/
end
# Returns the suffix that should be added to a number to denote the position
# in an ordered sequence such as 1st, 2nd, 3rd, 4th.
#
# ordinal(1) # => "st"
# ordinal(2) # => "nd"
# ordinal(1002) # => "nd"
# ordinal(1003) # => "rd"
# ordinal(-11) # => "th"
# ordinal(-1021) # => "st"
def ordinal(number)
abs_number = number.to_i.abs
if (11..13).include?(abs_number % 100)
"th"
else
case abs_number % 10
when 1; "st"
when 2; "nd"
when 3; "rd"
else "th"
end
end
end
# Turns a number into an ordinal string used to denote the position in an
# ordered sequence such as 1st, 2nd, 3rd, 4th.
#
# ordinalize(1) # => "1st"
# ordinalize(2) # => "2nd"
# ordinalize(1002) # => "1002nd"
# ordinalize(1003) # => "1003rd"
# ordinalize(-11) # => "-11th"
# ordinalize(-1021) # => "-1021st"
def ordinalize(number)
"#{number}#{ordinal(number)}"
end
private
# Mount a regular expression that will match part by part of the constant.
# For instance, Foo::Bar::Baz will generate Foo(::Bar(::Baz)?)?
def const_regexp(camel_cased_word) #:nodoc:
parts = camel_cased_word.split("::")
last = parts.pop
parts.reverse.inject(last) do |acc, part|
part.empty? ? acc : "#{part}(::#{acc})?"
end
end
# Applies inflection rules for +singularize+ and +pluralize+.
#
# apply_inflections('post', inflections.plurals) # => "posts"
# apply_inflections('posts', inflections.singulars) # => "post"
def apply_inflections(word, rules)
result = word.to_s.dup
if word.empty? || inflections.uncountables.include?(result.downcase[/\b\w+\Z/])
result
else
rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
result
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/inflector/inflections.rb | motion/inflector/inflections.rb | module MotionSupport
module Inflector
extend self
# A singleton instance of this class is yielded by Inflector.inflections,
# which can then be used to specify additional inflection rules.
#
# MotionSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1\2en'
# inflect.singular /^(ox)en/i, '\1'
#
# inflect.irregular 'octopus', 'octopi'
#
# inflect.uncountable 'equipment'
# end
#
# New rules are added at the top. So in the example above, the irregular
# rule for octopus will now be the first of the pluralization and
# singularization rules that is runs. This guarantees that your rules run
# before any of the rules that may already have been loaded.
class Inflections
def self.instance
@__instance__ ||= new
end
attr_reader :plurals, :singulars, :uncountables, :humans, :acronyms, :acronym_regex
def initialize
@plurals, @singulars, @uncountables, @humans, @acronyms, @acronym_regex = [], [], [], [], {}, /(?=a)b/
end
# Private, for the test suite.
def initialize_dup(orig) # :nodoc:
%w(plurals singulars uncountables humans acronyms acronym_regex).each do |scope|
instance_variable_set("@#{scope}", orig.send(scope).dup)
end
end
# Specifies a new acronym. An acronym must be specified as it will appear
# in a camelized string. An underscore string that contains the acronym
# will retain the acronym when passed to +camelize+, +humanize+, or
# +titleize+. A camelized string that contains the acronym will maintain
# the acronym when titleized or humanized, and will convert the acronym
# into a non-delimited single lowercase word when passed to +underscore+.
#
# acronym 'HTML'
# titleize 'html' #=> 'HTML'
# camelize 'html' #=> 'HTML'
# underscore 'MyHTML' #=> 'my_html'
#
# The acronym, however, must occur as a delimited unit and not be part of
# another word for conversions to recognize it:
#
# acronym 'HTTP'
# camelize 'my_http_delimited' #=> 'MyHTTPDelimited'
# camelize 'https' #=> 'Https', not 'HTTPs'
# underscore 'HTTPS' #=> 'http_s', not 'https'
#
# acronym 'HTTPS'
# camelize 'https' #=> 'HTTPS'
# underscore 'HTTPS' #=> 'https'
#
# Note: Acronyms that are passed to +pluralize+ will no longer be
# recognized, since the acronym will not occur as a delimited unit in the
# pluralized result. To work around this, you must specify the pluralized
# form as an acronym as well:
#
# acronym 'API'
# camelize(pluralize('api')) #=> 'Apis'
#
# acronym 'APIs'
# camelize(pluralize('api')) #=> 'APIs'
#
# +acronym+ may be used to specify any word that contains an acronym or
# otherwise needs to maintain a non-standard capitalization. The only
# restriction is that the word must begin with a capital letter.
#
# acronym 'RESTful'
# underscore 'RESTful' #=> 'restful'
# underscore 'RESTfulController' #=> 'restful_controller'
# titleize 'RESTfulController' #=> 'RESTful Controller'
# camelize 'restful' #=> 'RESTful'
# camelize 'restful_controller' #=> 'RESTfulController'
#
# acronym 'McDonald'
# underscore 'McDonald' #=> 'mcdonald'
# camelize 'mcdonald' #=> 'McDonald'
def acronym(word)
@acronyms[word.downcase] = word
@acronym_regex = /#{@acronyms.values.join("|")}/
end
# Specifies a new pluralization rule and its replacement. The rule can
# either be a string or a regular expression. The replacement should
# always be a string that may include references to the matched data from
# the rule.
def plural(rule, replacement)
@uncountables.delete(rule) if rule.is_a?(String)
@uncountables.delete(replacement)
@plurals.prepend([rule, replacement])
end
# Specifies a new singularization rule and its replacement. The rule can
# either be a string or a regular expression. The replacement should
# always be a string that may include references to the matched data from
# the rule.
def singular(rule, replacement)
@uncountables.delete(rule) if rule.is_a?(String)
@uncountables.delete(replacement)
@singulars.prepend([rule, replacement])
end
# Specifies a new irregular that applies to both pluralization and
# singularization at the same time. This can only be used for strings, not
# regular expressions. You simply pass the irregular in singular and
# plural form.
#
# irregular 'octopus', 'octopi'
# irregular 'person', 'people'
def irregular(singular, plural)
@uncountables.delete(singular)
@uncountables.delete(plural)
s0 = singular[0]
srest = singular[1..-1]
p0 = plural[0]
prest = plural[1..-1]
if s0.upcase == p0.upcase
plural(/(#{s0})#{srest}$/i, '\1' + prest)
plural(/(#{p0})#{prest}$/i, '\1' + prest)
singular(/(#{s0})#{srest}$/i, '\1' + srest)
singular(/(#{p0})#{prest}$/i, '\1' + srest)
else
plural(/#{s0.upcase}(?i)#{srest}$/, p0.upcase + prest)
plural(/#{s0.downcase}(?i)#{srest}$/, p0.downcase + prest)
plural(/#{p0.upcase}(?i)#{prest}$/, p0.upcase + prest)
plural(/#{p0.downcase}(?i)#{prest}$/, p0.downcase + prest)
singular(/#{s0.upcase}(?i)#{srest}$/, s0.upcase + srest)
singular(/#{s0.downcase}(?i)#{srest}$/, s0.downcase + srest)
singular(/#{p0.upcase}(?i)#{prest}$/, s0.upcase + srest)
singular(/#{p0.downcase}(?i)#{prest}$/, s0.downcase + srest)
end
end
# Add uncountable words that shouldn't be attempted inflected.
#
# uncountable 'money'
# uncountable 'money', 'information'
# uncountable %w( money information rice )
def uncountable(*words)
(@uncountables << words).flatten!
end
# Specifies a humanized form of a string by a regular expression rule or
# by a string mapping. When using a regular expression based replacement,
# the normal humanize formatting is called after the replacement. When a
# string is used, the human form should be specified as desired (example:
# 'The name', not 'the_name').
#
# human /_cnt$/i, '\1_count'
# human 'legacy_col_person_name', 'Name'
def human(rule, replacement)
@humans.prepend([rule, replacement])
end
# Clears the loaded inflections within a given scope (default is
# <tt>:all</tt>). Give the scope as a symbol of the inflection type, the
# options are: <tt>:plurals</tt>, <tt>:singulars</tt>, <tt>:uncountables</tt>,
# <tt>:humans</tt>.
#
# clear :all
# clear :plurals
def clear(scope = :all)
case scope
when :all
@plurals, @singulars, @uncountables, @humans = [], [], [], []
else
instance_variable_set "@#{scope}", []
end
end
end
# Yields a singleton instance of Inflector::Inflections so you can specify
# additional inflector rules.
#
# MotionSupport::Inflector.inflections do |inflect|
# inflect.uncountable 'rails'
# end
def inflections
if block_given?
yield Inflections.instance
else
Inflections.instance
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/_stdlib/array.rb | motion/_stdlib/array.rb | class Array
def reverse_each
return to_enum(:reverse_each) unless block_given?
i = size - 1
while i >= 0
yield self[i]
i -= 1
end
self
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/_stdlib/time.rb | motion/_stdlib/time.rb | class Time
def to_date
Date.new(year, month, day)
end
def to_time
self
end
def ==(other)
other &&
year == other.year &&
month == other.month &&
day == other.day &&
hour == other.hour &&
min == other.min &&
sec == other.sec
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/_stdlib/enumerable.rb | motion/_stdlib/enumerable.rb | module Enumerable
def reverse_each(&block)
return to_enum(:reverse_each) unless block_given?
# There is no other way then to convert to an array first... see 1.9's source.
to_a.reverse_each(&block)
self
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/_stdlib/cgi.rb | motion/_stdlib/cgi.rb | # This is a very small part of the CGI class, borrowed from the Rubinius sources
class CGI
@@accept_charset="UTF-8" unless defined?(@@accept_charset)
# URL-encode a string.
# url_encoded_string = CGI::escape("'Stop!' said Fred")
# # => "%27Stop%21%27+said+Fred"
def CGI::escape(string)
string.gsub(/([^ a-zA-Z0-9_.-]+)/) do
'%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
end.tr(' ', '+')
end
# URL-decode a string with encoding(optional).
# string = CGI::unescape("%27Stop%21%27+said+Fred")
# # => "'Stop!' said Fred"
def CGI::unescape(string,encoding=@@accept_charset)
str=string.tr('+', ' ').force_encoding(Encoding::ASCII_8BIT).gsub(/((?:%[0-9a-fA-F]{2})+)/) do
[$1.delete('%')].pack('H*')
end.force_encoding(encoding)
str.valid_encoding? ? str : str.force_encoding(string.encoding)
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/_stdlib/date.rb | motion/_stdlib/date.rb | class Date
def self.gregorian_leap?(year)
if year % 400 == 0
true
elsif year % 100 == 0 then
false
elsif year % 4 == 0 then
true
else
false
end
end
def initialize(year = nil, month = nil, day = nil)
if year && month && day
@value = Time.utc(year, month, day)
else
@value = Time.now
end
end
def self.today
new
end
def to_s
"#{year}-#{month}-#{day}"
end
def ==(other)
year == other.year &&
month == other.month &&
day == other.day
end
def +(other)
val = @value + other * 3600 * 24
Date.new(val.year, val.month, val.day)
end
def -(other)
if other.is_a?(Date)
(@value - other.instance_variable_get(:@value)) / (3600 * 24)
elsif other.is_a?(Time)
(@value - other)
else
self + (-other)
end
end
def >>(months)
new_year = year + (self.month + months - 1) / 12
new_month = (self.month + months) % 12
new_month = new_month == 0 ? 12 : new_month
new_day = [day, Time.days_in_month(new_month, new_year)].min
Date.new(new_year, new_month, new_day)
end
def <<(months)
return self >> -months
end
[:year, :month, :day, :wday, :<, :<=, :>, :>=, :"<=>", :strftime].each do |method|
define_method method do |*args|
@value.send(method, *args)
end
end
def to_date
self
end
def to_time
@value
end
def succ
self + 1
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/ns_dictionary.rb | motion/core_ext/ns_dictionary.rb | class NSDictionary
def to_hash
Hash.new.tap do |h|
h.replace self
end
end
delegate :symbolize_keys, :symbolize_keys!, :deep_symbolize_keys, :deep_symbolize_keys!,
:stringify_keys, :stringify_keys!, :deep_stringify_keys!, :deep_stringify_keys,
:deep_transform_keys, :deep_transform_keys!,
:with_indifferent_access, :nested_under_indifferent_access, :to => :to_hash
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/array.rb | motion/core_ext/array.rb | class Array
# If any item in the array has the key == `key` true, otherwise false.
# Of good use when writing specs.
def has_hash_key?(key)
self.each do |entity|
return true if entity.has_key? key
end
return false
end
# If any item in the array has the value == `key` true, otherwise false
# Of good use when writing specs.
def has_hash_value?(key)
self.each do |entity|
entity.each_pair{|hash_key, value| return true if value == key}
end
return false
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/enumerable.rb | motion/core_ext/enumerable.rb | module Enumerable
# Iterates through a container, yielding each element and its index to the given block.
def collect_with_index(&block)
index = 0
collect do |value|
block.call(value, index).tap do
index += 1
end
end
end
# Calculates a sum from the elements.
#
# payments.sum { |p| p.price * p.tax_rate }
# payments.sum(&:price)
#
# The latter is a shortcut for:
#
# payments.inject(0) { |sum, p| sum + p.price }
#
# It can also calculate the sum without the use of a block.
#
# [5, 15, 10].sum # => 30
# ['foo', 'bar'].sum # => "foobar"
# [[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
#
# The default sum of an empty list is zero. You can override this default:
#
# [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
def sum(identity = 0, &block)
if block_given?
map(&block).sum(identity)
else
inject { |sum, element| sum + element } || identity
end
end
# Convert an enumerable to a hash.
#
# people.index_by(&:login)
# => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
# people.index_by { |person| "#{person.first_name} #{person.last_name}" }
# => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
def index_by
if block_given?
Hash[map { |elem| [yield(elem), elem] }]
else
to_enum :index_by
end
end
# Returns +true+ if the enumerable has more than 1 element. Functionally
# equivalent to <tt>enum.to_a.size > 1</tt>. Can be called with a block too,
# much like any?, so <tt>people.many? { |p| p.age > 26 }</tt> returns +true+
# if more than one person is over 26.
def many?
cnt = 0
if block_given?
any? do |element|
cnt += 1 if yield element
cnt > 1
end
else
any? { (cnt += 1) > 1 }
end
end
# The negative of the <tt>Enumerable#include?</tt>. Returns +true+ if the
# collection does not include the object.
def exclude?(object)
!include?(object)
end
end
class Range #:nodoc:
# Optimize range sum to use arithmetic progression if a block is not given and
# we have a range of numeric values.
def sum(identity = 0)
if block_given? || !(first.is_a?(Integer) && last.is_a?(Integer))
super
else
actual_last = exclude_end? ? (last - 1) : last
if actual_last >= first
(actual_last - first + 1) * (actual_last + first) / 2
else
identity
end
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/ns_string.rb | motion/core_ext/ns_string.rb | class NSString
def to_s
String.new(self)
end
delegate :at, :blank?, :camelcase, :camelize, :classify, :constantize, :dasherize,
:deconstantize, :demodulize, :exclude?, :first, :foreign_key, :from, :humanize,
:indent, :indent!, :last, :pluralize, :safe_constantize, :singularize,
:squish, :squish!, :strip_heredoc, :tableize, :titlecase, :titleize, :to,
:truncate, :underscore,
:to => :to_s
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/regexp.rb | motion/core_ext/regexp.rb | class Regexp #:nodoc:
def multiline?
options & MULTILINE == MULTILINE
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/metaclass.rb | motion/core_ext/metaclass.rb | class Object
# Returns an object's metaclass.
def metaclass
class << self
self
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/string/indent.rb | motion/core_ext/string/indent.rb | class String
# Same as +indent+, except it indents the receiver in-place.
#
# Returns the indented string, or +nil+ if there was nothing to indent.
def indent!(amount, indent_string=nil, indent_empty_lines=false)
indent_string = indent_string || self[/^[ \t]/] || ' '
re = indent_empty_lines ? /^/ : /^(?!$)/
gsub!(re, indent_string * amount)
end
# Indents the lines in the receiver:
#
# <<EOS.indent(2)
# def some_method
# some_code
# end
# EOS
# # =>
# def some_method
# some_code
# end
#
# The second argument, +indent_string+, specifies which indent string to
# use. The default is +nil+, which tells the method to make a guess by
# peeking at the first indented line, and fallback to a space if there is
# none.
#
# " foo".indent(2) # => " foo"
# "foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
# "foo".indent(2, "\t") # => "\t\tfoo"
#
# While +indent_string+ is typically one space or tab, it may be any string.
#
# The third argument, +indent_empty_lines+, is a flag that says whether
# empty lines should be indented. Default is false.
#
# "foo\n\nbar".indent(2) # => " foo\n\n bar"
# "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
#
def indent(amount, indent_string=nil, indent_empty_lines=false)
dup.tap {|_| _.indent!(amount, indent_string, indent_empty_lines)}
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/string/strip.rb | motion/core_ext/string/strip.rb | class String
# Strips indentation in heredocs.
#
# For example in
#
# if options[:usage]
# puts <<-USAGE.strip_heredoc
# This command does such and such.
#
# Supported options are:
# -h This message
# ...
# USAGE
# end
#
# the user would see the usage message aligned against the left margin.
#
# Technically, it looks for the least indented line in the whole string, and removes
# that amount of leading whitespace.
def strip_heredoc
indent = scan(/^[ \t]*(?=\S)/).min.try(:size) || 0
gsub(/^[ \t]{#{indent}}/, '')
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/string/access.rb | motion/core_ext/string/access.rb | class String
# If you pass a single Fixnum, returns a substring of one character at that
# position. The first character of the string is at position 0, the next at
# position 1, and so on. If a range is supplied, a substring containing
# characters at offsets given by the range is returned. In both cases, if an
# offset is negative, it is counted from the end of the string. Returns nil
# if the initial offset falls outside the string. Returns an empty string if
# the beginning of the range is greater than the end of the string.
#
# str = "hello"
# str.at(0) #=> "h"
# str.at(1..3) #=> "ell"
# str.at(-2) #=> "l"
# str.at(-2..-1) #=> "lo"
# str.at(5) #=> nil
# str.at(5..-1) #=> ""
#
# If a Regexp is given, the matching portion of the string is returned.
# If a String is given, that given string is returned if it occurs in
# the string. In both cases, nil is returned if there is no match.
#
# str = "hello"
# str.at(/lo/) #=> "lo"
# str.at(/ol/) #=> nil
# str.at("lo") #=> "lo"
# str.at("ol") #=> nil
def at(position)
self[position]
end
# Returns a substring from the given position to the end of the string.
# If the position is negative, it is counted from the end of the string.
#
# str = "hello"
# str.from(0) #=> "hello"
# str.from(3) #=> "lo"
# str.from(-2) #=> "lo"
#
# You can mix it with +to+ method and do fun things like:
#
# str = "hello"
# str.from(0).to(-1) #=> "hello"
# str.from(1).to(-2) #=> "ell"
def from(position)
self[position..-1]
end
# Returns a substring from the beginning of the string to the given position.
# If the position is negative, it is counted from the end of the string.
#
# str = "hello"
# str.to(0) #=> "h"
# str.to(3) #=> "hell"
# str.to(-2) #=> "hell"
#
# You can mix it with +from+ method and do fun things like:
#
# str = "hello"
# str.from(0).to(-1) #=> "hello"
# str.from(1).to(-2) #=> "ell"
def to(position)
self[0..position]
end
# Returns the first character. If a limit is supplied, returns a substring
# from the beginning of the string until it reaches the limit value. If the
# given limit is greater than or equal to the string length, returns self.
#
# str = "hello"
# str.first #=> "h"
# str.first(1) #=> "h"
# str.first(2) #=> "he"
# str.first(0) #=> ""
# str.first(6) #=> "hello"
def first(limit = 1)
if limit == 0
''
elsif limit >= size
self
else
to(limit - 1)
end
end
# Returns the last character of the string. If a limit is supplied, returns a substring
# from the end of the string until it reaches the limit value (counting backwards). If
# the given limit is greater than or equal to the string length, returns self.
#
# str = "hello"
# str.last #=> "o"
# str.last(1) #=> "o"
# str.last(2) #=> "lo"
# str.last(0) #=> ""
# str.last(6) #=> "hello"
def last(limit = 1)
if limit == 0
''
elsif limit >= size
self
else
from(-limit)
end
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/string/starts_ends_with.rb | motion/core_ext/string/starts_ends_with.rb | class String
alias_method :starts_with?, :start_with?
alias_method :ends_with?, :end_with?
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/string/inflections.rb | motion/core_ext/string/inflections.rb | # String inflections define new methods on the String class to transform names for different purposes.
# For instance, you can figure out the name of a table from the name of a class.
#
# 'ScaleScore'.tableize # => "scale_scores"
#
class String
# Returns the plural form of the word in the string.
#
# If the optional parameter +count+ is specified,
# the singular form will be returned if <tt>count == 1</tt>.
# For any other value of +count+ the plural will be returned.
#
# 'post'.pluralize # => "posts"
# 'octopus'.pluralize # => "octopi"
# 'sheep'.pluralize # => "sheep"
# 'words'.pluralize # => "words"
# 'the blue mailman'.pluralize # => "the blue mailmen"
# 'CamelOctopus'.pluralize # => "CamelOctopi"
# 'apple'.pluralize(1) # => "apple"
# 'apple'.pluralize(2) # => "apples"
def pluralize(count = nil)
if count == 1
self
else
MotionSupport::Inflector.pluralize(self)
end
end
# The reverse of +pluralize+, returns the singular form of a word in a string.
#
# 'posts'.singularize # => "post"
# 'octopi'.singularize # => "octopus"
# 'sheep'.singularize # => "sheep"
# 'word'.singularize # => "word"
# 'the blue mailmen'.singularize # => "the blue mailman"
# 'CamelOctopi'.singularize # => "CamelOctopus"
def singularize
MotionSupport::Inflector.singularize(self)
end
# +constantize+ tries to find a declared constant with the name specified
# in the string. It raises a NameError when the name is not in CamelCase
# or is not initialized. See MotionSupport::Inflector.constantize
#
# 'Module'.constantize # => Module
# 'Class'.constantize # => Class
# 'blargle'.constantize # => NameError: wrong constant name blargle
def constantize
MotionSupport::Inflector.constantize(self)
end
# +safe_constantize+ tries to find a declared constant with the name specified
# in the string. It returns nil when the name is not in CamelCase
# or is not initialized. See MotionSupport::Inflector.safe_constantize
#
# 'Module'.safe_constantize # => Module
# 'Class'.safe_constantize # => Class
# 'blargle'.safe_constantize # => nil
def safe_constantize
MotionSupport::Inflector.safe_constantize(self)
end
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to camelize
# is set to <tt>:lower</tt> then camelize produces lowerCamelCase.
#
# +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
#
# 'active_record'.camelize # => "ActiveRecord"
# 'active_record'.camelize(:lower) # => "activeRecord"
# 'active_record/errors'.camelize # => "ActiveRecord::Errors"
# 'active_record/errors'.camelize(:lower) # => "activeRecord::Errors"
def camelize(first_letter = :upper)
case first_letter
when :upper
MotionSupport::Inflector.camelize(self, true)
when :lower
MotionSupport::Inflector.camelize(self, false)
end
end
alias_method :camelcase, :camelize
# Capitalizes all the words and replaces some characters in the string to create
# a nicer looking title. +titleize+ is meant for creating pretty output. It is not
# used in the Rails internals.
#
# +titleize+ is also aliased as +titlecase+.
#
# 'man from the boondocks'.titleize # => "Man From The Boondocks"
# 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
def titleize
MotionSupport::Inflector.titleize(self)
end
alias_method :titlecase, :titleize
# The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string.
#
# +underscore+ will also change '::' to '/' to convert namespaces to paths.
#
# 'ActiveModel'.underscore # => "active_model"
# 'ActiveModel::Errors'.underscore # => "active_model/errors"
def underscore
MotionSupport::Inflector.underscore(self)
end
# Replaces underscores with dashes in the string.
#
# 'puni_puni'.dasherize # => "puni-puni"
def dasherize
MotionSupport::Inflector.dasherize(self)
end
# Removes the module part from the constant expression in the string.
#
# 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
# 'Inflections'.demodulize # => "Inflections"
#
# See also +deconstantize+.
def demodulize
MotionSupport::Inflector.demodulize(self)
end
# Removes the rightmost segment from the constant expression in the string.
#
# 'Net::HTTP'.deconstantize # => "Net"
# '::Net::HTTP'.deconstantize # => "::Net"
# 'String'.deconstantize # => ""
# '::String'.deconstantize # => ""
# ''.deconstantize # => ""
#
# See also +demodulize+.
def deconstantize
MotionSupport::Inflector.deconstantize(self)
end
# Creates the name of a table like Rails does for models to table names. This method
# uses the +pluralize+ method on the last word in the string.
#
# 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
# 'egg_and_ham'.tableize # => "egg_and_hams"
# 'fancyCategory'.tableize # => "fancy_categories"
def tableize
MotionSupport::Inflector.tableize(self)
end
# Create a class name from a plural table name like Rails does for table names to models.
# Note that this returns a string and not a class. (To convert to an actual class
# follow +classify+ with +constantize+.)
#
# 'egg_and_hams'.classify # => "EggAndHam"
# 'posts'.classify # => "Post"
#
# Singular names are not handled correctly.
#
# 'business'.classify # => "Busines"
def classify
MotionSupport::Inflector.classify(self)
end
# Capitalizes the first word, turns underscores into spaces, and strips '_id'.
# Like +titleize+, this is meant for creating pretty output.
#
# 'employee_salary'.humanize # => "Employee salary"
# 'author_id'.humanize # => "Author"
def humanize
MotionSupport::Inflector.humanize(self)
end
# Creates a foreign key name from a class name.
# +separate_class_name_and_id_with_underscore+ sets whether
# the method should put '_' between the name and 'id'.
#
# 'Message'.foreign_key # => "message_id"
# 'Message'.foreign_key(false) # => "messageid"
# 'Admin::Post'.foreign_key # => "post_id"
def foreign_key(separate_class_name_and_id_with_underscore = true)
MotionSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/string/filters.rb | motion/core_ext/string/filters.rb | class String
# Returns the string, first removing all whitespace on both ends of
# the string, and then changing remaining consecutive whitespace
# groups into one space each.
#
# Note that it handles both ASCII and Unicode whitespace like mongolian vowel separator (U+180E).
#
# %{ Multi-line
# string }.squish # => "Multi-line string"
# " foo bar \n \t boo".squish # => "foo bar boo"
def squish
dup.squish!
end
# Performs a destructive squish. See String#squish.
def squish!
gsub!(/\A[[:space:]]+/, '')
gsub!(/[[:space:]]+\z/, '')
gsub!(/[[:space:]]+/, ' ')
self
end
# Truncates a given +text+ after a given <tt>length</tt> if +text+ is longer than <tt>length</tt>:
#
# 'Once upon a time in a world far far away'.truncate(27)
# # => "Once upon a time in a wo..."
#
# Pass a string or regexp <tt>:separator</tt> to truncate +text+ at a natural break:
#
# 'Once upon a time in a world far far away'.truncate(27, separator: ' ')
# # => "Once upon a time in a..."
#
# 'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
# # => "Once upon a time in a..."
#
# The last characters will be replaced with the <tt>:omission</tt> string (defaults to "...")
# for a total length not exceeding <tt>length</tt>:
#
# 'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
# # => "And they f... (continued)"
def truncate(truncate_at, options = {})
return dup unless length > truncate_at
options[:omission] ||= '...'
length_with_room_for_omission = truncate_at - options[:omission].length
stop = \
if options[:separator]
rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
else
length_with_room_for_omission
end
self[0...stop] + options[:omission]
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/string/exclude.rb | motion/core_ext/string/exclude.rb | class String
# The inverse of <tt>String#include?</tt>. Returns true if the string
# does not include the other string.
#
# "hello".exclude? "lo" #=> false
# "hello".exclude? "ol" #=> true
# "hello".exclude? ?h #=> false
def exclude?(string)
!include?(string)
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/string/behavior.rb | motion/core_ext/string/behavior.rb | class String
# Enable more predictable duck-typing on String-like classes. See <tt>Object#acts_like?</tt>.
def acts_like_string?
true
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/hash/slice.rb | motion/core_ext/hash/slice.rb | class Hash
# Slice a hash to include only the given keys. This is useful for
# limiting an options hash to valid keys before passing to a method:
#
# def search(criteria = {})
# criteria.assert_valid_keys(:mass, :velocity, :time)
# end
#
# search(options.slice(:mass, :velocity, :time))
#
# If you have an array of keys you want to limit to, you should splat them:
#
# valid_keys = [:mass, :velocity, :time]
# search(options.slice(*valid_keys))
def slice(*keys)
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
keys.each_with_object(self.class.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
end
# Replaces the hash with only the given keys.
# Returns a hash containing the removed key/value pairs.
#
# { a: 1, b: 2, c: 3, d: 4 }.slice!(:a, :b)
# # => {:c=>3, :d=>4}
def slice!(*keys)
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
omit = slice(*self.keys - keys)
hash = slice(*keys)
replace(hash)
omit
end
# Removes and returns the key/value pairs matching the given keys.
#
# { a: 1, b: 2, c: 3, d: 4 }.extract!(:a, :b) # => {:a=>1, :b=>2}
# { a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1}
def extract!(*keys)
keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) }
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/hash/reverse_merge.rb | motion/core_ext/hash/reverse_merge.rb | class Hash
# Merges the caller into +other_hash+. For example,
#
# options = options.reverse_merge(size: 25, velocity: 10)
#
# is equivalent to
#
# options = { size: 25, velocity: 10 }.merge(options)
#
# This is particularly useful for initializing an options hash
# with default values.
def reverse_merge(other_hash)
other_hash.merge(self)
end
# Destructive +reverse_merge+.
def reverse_merge!(other_hash)
# right wins if there is no left
merge!( other_hash ){|key,left,right| left }
end
alias_method :reverse_update, :reverse_merge!
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/hash/keys.rb | motion/core_ext/hash/keys.rb | class Hash
# Return a new hash with all keys converted using the block operation.
#
# hash = { name: 'Rob', age: '28' }
#
# hash.transform_keys{ |key| key.to_s.upcase }
# # => { "NAME" => "Rob", "AGE" => "28" }
def transform_keys
result = {}
each_key do |key|
result[yield(key)] = self[key]
end
result
end
# Destructively convert all keys using the block operations.
# Same as transform_keys but modifies +self+.
def transform_keys!
keys.each do |key|
self[yield(key)] = delete(key)
end
self
end
# Return a new hash with all keys converted to strings.
#
# hash = { name: 'Rob', age: '28' }
#
# hash.stringify_keys
# #=> { "name" => "Rob", "age" => "28" }
def stringify_keys
transform_keys{ |key| key.to_s }
end
# Destructively convert all keys to strings. Same as
# +stringify_keys+, but modifies +self+.
def stringify_keys!
transform_keys!{ |key| key.to_s }
end
# Return a new hash with all keys converted to symbols, as long as
# they respond to +to_sym+.
#
# hash = { 'name' => 'Rob', 'age' => '28' }
#
# hash.symbolize_keys
# #=> { name: "Rob", age: "28" }
def symbolize_keys
transform_keys{ |key| key.to_sym rescue key }
end
alias_method :to_options, :symbolize_keys
# Destructively convert all keys to symbols, as long as they respond
# to +to_sym+. Same as +symbolize_keys+, but modifies +self+.
def symbolize_keys!
transform_keys!{ |key| key.to_sym rescue key }
end
alias_method :to_options!, :symbolize_keys!
# Validate all keys in a hash match <tt>*valid_keys</tt>, raising ArgumentError
# on a mismatch. Note that keys are NOT treated indifferently, meaning if you
# use strings for keys but assert symbols as keys, this will fail.
#
# { name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: years"
# { name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: name"
# { name: 'Rob', age: '28' }.assert_valid_keys(:name, :age) # => passes, raises nothing
def assert_valid_keys(*valid_keys)
valid_keys.flatten!
each_key do |k|
raise ArgumentError.new("Unknown key: #{k}") unless valid_keys.include?(k)
end
end
# Return a new hash with all keys converted by the block operation.
# This includes the keys from the root hash and from all
# nested hashes.
#
# hash = { person: { name: 'Rob', age: '28' } }
#
# hash.deep_transform_keys{ |key| key.to_s.upcase }
# # => { "PERSON" => { "NAME" => "Rob", "AGE" => "28" } }
def deep_transform_keys(&block)
result = {}
each do |key, value|
result[yield(key)] = if value.is_a?(Hash)
value.deep_transform_keys(&block)
elsif value.is_a?(Array)
value.map { |v| v.is_a?(Hash) ? v.deep_transform_keys(&block) : v }
else
value
end
end
result
end
# Destructively convert all keys by using the block operation.
# This includes the keys from the root hash and from all
# nested hashes.
def deep_transform_keys!(&block)
keys.each do |key|
value = delete(key)
self[yield(key)] = if value.is_a?(Hash)
value.deep_transform_keys(&block)
elsif value.is_a?(Array)
value.map { |v| v.is_a?(Hash) ? v.deep_transform_keys(&block) : v }
else
value
end
end
self
end
# Return a new hash with all keys converted to strings.
# This includes the keys from the root hash and from all
# nested hashes.
#
# hash = { person: { name: 'Rob', age: '28' } }
#
# hash.deep_stringify_keys
# # => { "person" => { "name" => "Rob", "age" => "28" } }
def deep_stringify_keys
deep_transform_keys{ |key| key.to_s }
end
# Destructively convert all keys to strings.
# This includes the keys from the root hash and from all
# nested hashes.
def deep_stringify_keys!
deep_transform_keys!{ |key| key.to_s }
end
# Return a new hash with all keys converted to symbols, as long as
# they respond to +to_sym+. This includes the keys from the root hash
# and from all nested hashes.
#
# hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }
#
# hash.deep_symbolize_keys
# # => { person: { name: "Rob", age: "28" } }
def deep_symbolize_keys
deep_transform_keys{ |key| key.to_sym rescue key }
end
# Destructively convert all keys to symbols, as long as they respond
# to +to_sym+. This includes the keys from the root hash and from all
# nested hashes.
def deep_symbolize_keys!
deep_transform_keys!{ |key| key.to_sym rescue key }
end
# Returns a string representation of the receiver suitable for use as a URL
# query string:
#
# {name: 'David', nationality: 'Danish'}.to_param
# # => "name=David&nationality=Danish"
#
# An optional namespace can be passed to enclose the param names:
#
# {name: 'David', nationality: 'Danish'}.to_param('user')
# # => "user[name]=David&user[nationality]=Danish"
#
# The string pairs "key=value" that conform the query string
# are sorted lexicographically in ascending order.
#
# This method is also aliased as +to_query+.
def to_param(namespace = nil)
collect do |key, value|
value.to_query(namespace ? "#{namespace}[#{key}]" : key)
end.sort * '&'
end
alias_method :to_query, :to_param
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/hash/indifferent_access.rb | motion/core_ext/hash/indifferent_access.rb | class Hash
# Returns an <tt>MotionSupport::HashWithIndifferentAccess</tt> out of its receiver:
#
# { a: 1 }.with_indifferent_access['a'] # => 1
def with_indifferent_access
MotionSupport::HashWithIndifferentAccess.new_from_hash_copying_default(self)
end
# Called when object is nested under an object that receives
# #with_indifferent_access. This method will be called on the current object
# by the enclosing object and is aliased to #with_indifferent_access by
# default. Subclasses of Hash may overwrite this method to return +self+ if
# converting to an <tt>MotionSupport::HashWithIndifferentAccess</tt> would not be
# desirable.
#
# b = { b: 1 }
# { a: b }.with_indifferent_access['a'] # calls b.nested_under_indifferent_access
alias nested_under_indifferent_access with_indifferent_access
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/hash/deep_merge.rb | motion/core_ext/hash/deep_merge.rb | class Hash
# Returns a new hash with +self+ and +other_hash+ merged recursively.
#
# h1 = { x: { y: [4,5,6] }, z: [7,8,9] }
# h2 = { x: { y: [7,8,9] }, z: 'xyz' }
#
# h1.deep_merge(h2) #=> {x: {y: [7, 8, 9]}, z: "xyz"}
# h2.deep_merge(h1) #=> {x: {y: [4, 5, 6]}, z: [7, 8, 9]}
# h1.deep_merge(h2) { |key, old, new| Array.wrap(old) + Array.wrap(new) }
# #=> {:x=>{:y=>[4, 5, 6, 7, 8, 9]}, :z=>[7, 8, 9, "xyz"]}
def deep_merge(other_hash, &block)
dup.deep_merge!(other_hash, &block)
end
# Same as +deep_merge+, but modifies +self+.
def deep_merge!(other_hash, &block)
other_hash.each_pair do |k,v|
tv = self[k]
if tv.is_a?(Hash) && v.is_a?(Hash)
self[k] = tv.deep_merge(v, &block)
else
self[k] = block && tv ? block.call(k, tv, v) : v
end
end
self
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/hash/except.rb | motion/core_ext/hash/except.rb | class Hash
# Return a hash that includes everything but the given keys. This is useful for
# limiting a set of parameters to everything but a few known toggles:
#
# @person.update(params[:person].except(:admin))
def except(*keys)
dup.except!(*keys)
end
# Replaces the hash without the given keys.
def except!(*keys)
keys.each { |key| delete(key) }
self
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/hash/deep_delete_if.rb | motion/core_ext/hash/deep_delete_if.rb | class Hash
# Returns a new hash with keys deleted if they match a criteria
# h1 = { x: { y: [ { z: 4, y: 1 }, 5, 6] }, a: { b: 2 } }
#
# h1.deep_delete { |k,v| k == :z } #=> { x: { y: [ { y: 1 }, 5, 6] }, a: { b: 2 } }
# h1.deep_delete { |k,v| k == :y } #=> { x: {}, a: { b: 2 } }
def deep_delete_if(&block)
result = {}
each do |key, value|
next if block.call(key, value)
result[key] = if value.is_a?(Hash)
value.deep_delete_if(&block)
elsif value.is_a?(Array)
value.map { |v| v.is_a?(Hash) ? v.deep_delete_if(&block) : v }
else
value
end
end
result
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/date/conversions.rb | motion/core_ext/date/conversions.rb | class Date
DATE_FORMATS = {
:short => '%e %b',
:long => '%B %e, %Y',
:db => '%Y-%m-%d',
:number => '%Y%m%d',
:long_ordinal => lambda { |date|
day_format = MotionSupport::Inflector.ordinalize(date.day)
date.strftime("%B #{day_format}, %Y") # => "April 25th, 2007"
},
:rfc822 => '%e %b %Y',
:iso8601 => '%Y-%m-%d',
:xmlschema => '%Y-%m-%dT00:00:00Z'
}
def iso8601
strftime DATE_FORMATS[:iso8601]
end
# Convert to a formatted string. See DATE_FORMATS for predefined formats.
#
# This method is aliased to <tt>to_s</tt>.
#
# date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
#
# date.to_formatted_s(:db) # => "2007-11-10"
# date.to_s(:db) # => "2007-11-10"
#
# date.to_formatted_s(:short) # => "10 Nov"
# date.to_formatted_s(:long) # => "November 10, 2007"
# date.to_formatted_s(:long_ordinal) # => "November 10th, 2007"
# date.to_formatted_s(:rfc822) # => "10 Nov 2007"
#
# == Adding your own time formats to to_formatted_s
# You can add your own formats to the Date::DATE_FORMATS hash.
# Use the format name as the hash key and either a strftime string
# or Proc instance that takes a date argument as the value.
#
# # config/initializers/time_formats.rb
# Date::DATE_FORMATS[:month_and_year] = '%B %Y'
# Date::DATE_FORMATS[:short_ordinal] = ->(date) { date.strftime("%B #{date.day.ordinalize}") }
def to_formatted_s(format = :default)
formatter = DATE_FORMATS[format]
return to_default_s unless formatter
return formatter.call(self).to_s if formatter.respond_to?(:call)
strftime(formatter)
end
alias_method :to_default_s, :to_s
alias_method :to_s, :to_formatted_s
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005"
def readable_inspect
strftime('%a, %d %b %Y')
end
alias_method :default_inspect, :inspect
alias_method :inspect, :readable_inspect
def xmlschema
strftime DATE_FORMATS[:xmlschema]
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/date/acts_like.rb | motion/core_ext/date/acts_like.rb | class Date
# Duck-types as a Date-like class. See Object#acts_like?.
def acts_like_date?
true
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/date/calculations.rb | motion/core_ext/date/calculations.rb | class Date
include DateAndTime::Calculations
class << self
attr_accessor :beginning_of_week_default
# Returns the week start (e.g. :monday) for the current request, if this has been set (via Date.beginning_of_week=).
# If <tt>Date.beginning_of_week</tt> has not been set for the current request, returns the week start specified in <tt>config.beginning_of_week</tt>.
# If no config.beginning_of_week was specified, returns :monday.
def beginning_of_week
Thread.current[:beginning_of_week] || beginning_of_week_default || :monday
end
# Sets <tt>Date.beginning_of_week</tt> to a week start (e.g. :monday) for current request/thread.
#
# This method accepts any of the following day symbols:
# :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday
def beginning_of_week=(week_start)
Thread.current[:beginning_of_week] = find_beginning_of_week!(week_start)
end
# Returns week start day symbol (e.g. :monday), or raises an ArgumentError for invalid day symbol.
def find_beginning_of_week!(week_start)
raise ArgumentError, "Invalid beginning of week: #{week_start}" unless ::Date::DAYS_INTO_WEEK.key?(week_start)
week_start
end
# Returns a new Date representing the date 1 day ago (i.e. yesterday's date).
def yesterday
::Date.current.yesterday
end
# Returns a new Date representing the date 1 day after today (i.e. tomorrow's date).
def tomorrow
::Date.current.tomorrow
end
# Alias for Date.today.
def current
::Date.today
end
end
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
# and then subtracts the specified number of seconds.
def ago(seconds)
to_time.since(-seconds)
end
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
# and then adds the specified number of seconds
def since(seconds)
to_time.since(seconds)
end
alias :in :since
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
def beginning_of_day
to_time
end
alias :midnight :beginning_of_day
alias :at_midnight :beginning_of_day
alias :at_beginning_of_day :beginning_of_day
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the end of the day (23:59:59)
def end_of_day
to_time.end_of_day
end
alias :at_end_of_day :end_of_day
def plus_with_duration(other) #:nodoc:
if MotionSupport::Duration === other
other.since(self)
else
plus_without_duration(other)
end
end
alias_method :plus_without_duration, :+
alias_method :+, :plus_with_duration
def minus_with_duration(other) #:nodoc:
if MotionSupport::Duration === other
plus_with_duration(-other)
else
minus_without_duration(other)
end
end
alias_method :minus_without_duration, :-
alias_method :-, :minus_with_duration
# Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with
# any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>.
def advance(options)
options = options.dup
d = self
d = d >> options.delete(:years) * 12 if options[:years]
d = d >> options.delete(:months) if options[:months]
d = d + options.delete(:weeks) * 7 if options[:weeks]
d = d + options.delete(:days) if options[:days]
d
end
# Returns a new Date where one or more of the elements have been changed according to the +options+ parameter.
# The +options+ parameter is a hash with a combination of these keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>.
#
# Date.new(2007, 5, 12).change(day: 1) # => Date.new(2007, 5, 1)
# Date.new(2007, 5, 12).change(year: 2005, month: 1) # => Date.new(2005, 1, 12)
def change(options)
::Date.new(
options.fetch(:year, year),
options.fetch(:month, month),
options.fetch(:day, day)
)
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/integer/time.rb | motion/core_ext/integer/time.rb | class Integer
# Enables the use of time calculations and declarations, like <tt>45.minutes +
# 2.hours + 4.years</tt>.
#
# These methods use Time#advance for precise date calculations when using
# <tt>from_now</tt>, +ago+, etc. as well as adding or subtracting their
# results from a Time object.
#
# # equivalent to Time.now.advance(months: 1)
# 1.month.from_now
#
# # equivalent to Time.now.advance(years: 2)
# 2.years.from_now
#
# # equivalent to Time.now.advance(months: 4, years: 5)
# (4.months + 5.years).from_now
#
# While these methods provide precise calculation when used as in the examples
# above, care should be taken to note that this is not true if the result of
# +months+, +years+, etc is converted before use:
#
# # equivalent to 30.days.to_i.from_now
# 1.month.to_i.from_now
#
# # equivalent to 365.25.days.to_f.from_now
# 1.year.to_f.from_now
#
# In such cases, Ruby's core
# Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
# Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
# date and time arithmetic.
def months
MotionSupport::Duration.new(self * 30.days, [[:months, self]])
end
alias :month :months
def years
MotionSupport::Duration.new(self * 365.25.days, [[:years, self]])
end
alias :year :years
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/integer/inflections.rb | motion/core_ext/integer/inflections.rb | class Integer
# Ordinalize turns a number into an ordinal string used to denote the
# position in an ordered sequence such as 1st, 2nd, 3rd, 4th.
#
# 1.ordinalize # => "1st"
# 2.ordinalize # => "2nd"
# 1002.ordinalize # => "1002nd"
# 1003.ordinalize # => "1003rd"
# -11.ordinalize # => "-11th"
# -1001.ordinalize # => "-1001st"
def ordinalize
MotionSupport::Inflector.ordinalize(self)
end
# Ordinal returns the suffix used to denote the position
# in an ordered sequence such as 1st, 2nd, 3rd, 4th.
#
# 1.ordinal # => "st"
# 2.ordinal # => "nd"
# 1002.ordinal # => "nd"
# 1003.ordinal # => "rd"
# -11.ordinal # => "th"
# -1001.ordinal # => "st"
def ordinal
MotionSupport::Inflector.ordinal(self)
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/integer/multiple.rb | motion/core_ext/integer/multiple.rb | class Integer
# Check whether the integer is evenly divisible by the argument.
#
# 0.multiple_of?(0) #=> true
# 6.multiple_of?(5) #=> false
# 10.multiple_of?(2) #=> true
def multiple_of?(number)
number != 0 ? self % number == 0 : zero?
end
end
| ruby | MIT | f9e04234315327a64db8181e3af2c7b87ba3e13a | 2026-01-04T17:47:41.763315Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.