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 |
|---|---|---|---|---|---|---|---|---|
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/letsencrypt/verify_service.rb | lib/letsencrypt/verify_service.rb | # frozen_string_literal: true
module LetsEncrypt
# Process the verification of the domain
class VerifyService
STATUS_PENDING = 'pending'
STATUS_VALID = 'valid'
attr_reader :checker
def initialize(config: LetsEncrypt.config)
@checker = StatusChecker.new(
max_attempts: config.max_attempts,
interval: config.retry_interval
)
end
def execute(certificate, order)
ActiveSupport::Notifications.instrument('letsencrypt.verify', domain: certificate.domain) do
verify(certificate, order)
end
end
private
def verify(certificate, order)
challenge = order.authorizations.first.http
certificate.challenge!(challenge.filename, challenge.file_content)
challenge.request_validation
checker.execute do
challenge.reload
challenge.status != STATUS_PENDING
end
assert(challenge)
end
def assert(challenge)
return if challenge.status == STATUS_VALID
raise LetsEncrypt::InvalidStatus, "Status not valid (was: #{challenge.status})"
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/letsencrypt/redis.rb | lib/letsencrypt/redis.rb | # frozen_string_literal: true
module LetsEncrypt
# :nodoc:
class Redis
class << self
def connection
@connection ||= ::Redis.new(url: LetsEncrypt.config.redis_url)
end
# Save certificate into redis.
def save(cert)
return unless cert.key.present? && cert.bundle.present?
LetsEncrypt.logger.info "Save #{cert.domain}'s certificate (bundle) to redis"
connection.set "#{cert.domain}.key", cert.key
connection.set "#{cert.domain}.crt", cert.bundle
end
# Delete certificate from redis.
def delete(cert)
return unless cert.key.present? && cert.certificate.present?
LetsEncrypt.logger.info "Delete #{cert.domain}'s certificate from redis"
connection.del "#{cert.domain}.key"
connection.del "#{cert.domain}.crt"
end
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/letsencrypt/errors.rb | lib/letsencrypt/errors.rb | # frozen_string_literal: true
module LetsEncrypt
class Error < StandardError; end
class MaxCheckExceeded < Error; end
class InvalidStatus < Error; end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/letsencrypt/railtie.rb | lib/letsencrypt/railtie.rb | # frozen_string_literal: true
module LetsEncrypt
class Railtie < ::Rails::Railtie
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/letsencrypt/configuration.rb | lib/letsencrypt/configuration.rb | # frozen_string_literal: true
module LetsEncrypt
# :nodoc:
class Configuration
include ActiveSupport::Configurable
config_accessor :acme_directory
config_accessor :use_staging do
!Rails.env.production?
end
config_accessor :private_key_path
config_accessor :use_env_key do
false
end
config_accessor :save_to_redis
config_accessor :redis_url
config_accessor :certificate_model do
'LetsEncrypt::Certificate'
end
config_accessor :max_attempts do
30
end
config_accessor :retry_interval do
1
end
# Returns true if enabled `save_to_redis` feature
def use_redis?
save_to_redis == true
end
# Returns true if under development mode.
def use_staging?
use_staging
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/letsencrypt/renew_service.rb | lib/letsencrypt/renew_service.rb | # frozen_string_literal: true
module LetsEncrypt
# The renew service to create or renew the certificate
class RenewService
attr_reader :acme_client, :config
def initialize(acme_client: LetsEncrypt.client, config: LetsEncrypt.config)
@acme_client = acme_client
@config = config
end
def execute(certificate)
ActiveSupport::Notifications.instrument('letsencrypt.renew', domain: certificate.domain) do
order = acme_client.new_order(identifiers: [certificate.domain])
verify_service = VerifyService.new(config:)
verify_service.execute(certificate, order)
issue_service = IssueService.new(config:)
issue_service.execute(certificate, order)
end
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/letsencrypt/engine.rb | lib/letsencrypt/engine.rb | # frozen_string_literal: true
module LetsEncrypt
# :nodoc:
class Engine < ::Rails::Engine
isolate_namespace LetsEncrypt
engine_name :letsencrypt
config.generators.test_framework :rspec
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/lib/letsencrypt/issue_service.rb | lib/letsencrypt/issue_service.rb | # frozen_string_literal: true
module LetsEncrypt
# The issue service to download the certificate
class IssueService
attr_reader :checker
STATUS_PROCESSING = 'processing'
def initialize(config: LetsEncrypt.config)
@checker = StatusChecker.new(
max_attempts: config.max_attempts,
interval: config.retry_interval
)
end
def execute(certificate, order)
ActiveSupport::Notifications.instrument('letsencrypt.issue', domain: certificate.domain) do
issue(certificate, order)
end
end
private
def issue(certificate, order)
csr = build_csr(certificate)
order.finalize(csr:)
checker.execute do
order.reload
order.status != STATUS_PROCESSING
end
fullchain = order.certificate.split("\n\n")
cert = OpenSSL::X509::Certificate.new(fullchain.shift)
certificate.refresh!(cert, fullchain)
end
def build_csr(certificate)
Acme::Client::CertificateRequest.new(
private_key: OpenSSL::PKey::RSA.new(certificate.key),
subject: {
common_name: certificate.domain
}
)
end
end
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
elct9620/rails-letsencrypt | https://github.com/elct9620/rails-letsencrypt/blob/ff544157f89112d81573dfa1151dea6d97c88c28/config/routes.rb | config/routes.rb | # frozen_string_literal: true
LetsEncrypt::Engine.routes.draw do
get '/acme-challenge/:verification_path', to: 'verifications#show'
end
| ruby | MIT | ff544157f89112d81573dfa1151dea6d97c88c28 | 2026-01-04T17:47:41.292155Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/spec/spec_helper.rb | spec/spec_helper.rb | require 'simplecov'
require 'scrutinizer/ocular'
require "scrutinizer/ocular/formatter"
require "codeclimate-test-reporter"
require "sidekiq/testing"
require 'textris/delay/active_job/missing'
require 'textris/delay/sidekiq/missing'
CodeClimate::TestReporter.configuration.logger = Logger.new("/dev/null")
if Scrutinizer::Ocular.should_run? ||
CodeClimate::TestReporter.run? ||
ENV["COVERAGE"]
formatters = [SimpleCov::Formatter::HTMLFormatter]
if Scrutinizer::Ocular.should_run?
formatters << Scrutinizer::Ocular::UploadingFormatter
end
if CodeClimate::TestReporter.run?
formatters << CodeClimate::TestReporter::Formatter
end
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[*formatters]
CodeClimate::TestReporter.configuration.logger = nil
SimpleCov.start do
add_filter "/lib/textris.rb"
add_filter "/spec/"
add_filter "vendor"
end
end
require_relative '../lib/textris'
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/spec/textris/message_spec.rb | spec/textris/message_spec.rb | describe Textris::Message do
let(:message) do
Textris::Message.new(
:content => 'X',
:from => 'X',
:to => '+48 111 222 333')
end
describe '#initialize' do
describe 'parsing :from' do
it 'parses "name <phone>" syntax properly' do
message = Textris::Message.new(
:content => 'X',
:from => 'Mr Jones <+48 111 222 333> ',
:to => '+48 111 222 333')
expect(message.from_name).to eq('Mr Jones')
expect(message.from_phone).to eq('48111222333')
end
it 'parses phone only properly' do
message = Textris::Message.new(
:content => 'X',
:from => '+48 111 222 333',
:to => '+48 111 222 444')
expect(message.from_name).to be_nil
expect(message.from_phone).to eq('48111222333')
end
it 'parses name only properly' do
message = Textris::Message.new(
:content => 'X',
:from => 'Mr Jones',
:to => '+48 111 222 444')
expect(message.from_name).to eq('Mr Jones')
expect(message.from_phone).to be_nil
end
it 'parses short codes properly' do
message = Textris::Message.new(
:content => 'X',
:from => '894546',
:to => '+48 111 222 444')
expect(message.from_name).to be_nil
expect(message.from_phone).to eq('894546')
end
it 'parses short codes and names properly' do
message = Textris::Message.new(
:content => 'X',
:from => 'Mr Jones <894546> ',
:to => '+48 111 222 444')
expect(message.from_name).to eq('Mr Jones')
expect(message.from_phone).to eq('894546')
end
it 'parses alphameric IDs and names properly' do
message = Textris::Message.new(
:content => 'X',
:from => 'Mr Jones <Company> ',
:to => '+48 111 222 444')
expect(message.from_name).to eq('Mr Jones')
expect(message.from_phone).to eq('Company')
end
end
describe 'parsing :twilio_messaging_service_sid' do
it 'stores the sid' do
message = Textris::Message.new(
content: 'X',
twilio_messaging_service_sid: 'MG9752274e9e519418a7406176694466fa',
to: '+48 111 222 444')
expect(message.twilio_messaging_service_sid)
.to eq('MG9752274e9e519418a7406176694466fa')
end
end
describe 'parsing :to' do
it 'normalizes phone numbers' do
message = Textris::Message.new(
:content => 'X',
:from => 'X',
:to => '+48 111 222 333')
expect(message.to).to eq(['48111222333'])
end
it 'returns array for singular strings' do
message = Textris::Message.new(
:content => 'X',
:from => 'X',
:to => '+48 111 222 333')
expect(message.to).to be_a(Array)
end
it 'takes arrays of strings' do
message = Textris::Message.new(
:content => 'X',
:from => 'X',
:to => ['+48 111 222 333', '+48 444 555 666'])
expect(message.to).to eq(['48111222333', '48444555666'])
end
it 'filters out unplausible phone numbers' do
message = Textris::Message.new(
:content => 'X',
:from => 'X',
:to => ['+48 111 222 333', 'wrong'])
expect(message.to).to eq(['48111222333'])
end
end
describe 'parsing :content' do
it 'preserves newlines and duplicated whitespace' do
message = Textris::Message.new(
:content => "a\nb. \n\n c",
:from => 'X',
:to => '+48 111 222 333')
expect(message.content).to eq("a\nb. \n\n c")
end
it 'preserves leading whitespace, but strips trailing whitespace' do
message = Textris::Message.new(
:content => " a b. c ",
:from => 'X',
:to => '+48 111 222 333')
expect(message.content).to eq(" a b. c")
end
end
it 'raises if :to not provided' do
expect do
Textris::Message.new(
:content => 'X',
:from => 'X',
:to => nil)
end.to raise_error(ArgumentError)
end
it 'raises if :content not provided' do
expect do
Textris::Message.new(
:content => nil,
:from => 'X',
:to => '+48 111 222 333')
end.to raise_error(ArgumentError)
end
end
describe '#texter' do
it 'returns raw texter class for :raw => true' do
message = Textris::Message.new(
:texter => String,
:content => 'X',
:from => 'X',
:to => '+48 111 222 333')
expect(message.texter(:raw => true)).to eq String
end
it 'returns texter class without modules and texter suffix' do
module SampleModule
class SomeSampleTexter; end
end
message = Textris::Message.new(
:texter => SampleModule::SomeSampleTexter,
:content => 'X',
:from => 'X',
:to => '+48 111 222 333')
expect(message.texter).to eq 'SomeSample'
end
end
describe '#content' do
before do
class Textris::Base::RenderingController
def initialize(*args)
end
end
class RenderingTexter < Textris::Base
def action_with_template
text :to => '48 600 700 800'
end
end
end
it 'lazily renders content' do
renderer = RenderingTexter.new(:action_with_template, [])
message = Textris::Message.new(
:renderer => renderer,
:from => 'X',
:to => '+48 111 222 333')
expect { message.content }.to raise_error(ActionView::MissingTemplate)
end
end
describe '#deliver' do
before do
class XDelivery < Textris::Delivery::Base
def deliver(to); end
end
class YDelivery < Textris::Delivery::Base
def deliver(to); end
end
end
it 'invokes delivery classes properly' do
expect(Textris::Delivery).to receive(:get) { [XDelivery, YDelivery] }
message = Textris::Message.new(
:content => 'X',
:from => 'X',
:to => '+48 111 222 333')
expect_any_instance_of(XDelivery).to receive(:deliver_to_all)
expect_any_instance_of(YDelivery).to receive(:deliver_to_all)
message.deliver
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/spec/textris/delivery_spec.rb | spec/textris/delivery_spec.rb | describe Textris::Delivery do
describe '#get' do
before do
Object.send(:remove_const, :Rails) if defined?(Rails)
class FakeEnv
def initialize(options = {})
self.name = 'development'
end
def name=(value)
@development = false
@test = false
@production = false
case value.to_s
when 'development'
@development = true
when 'test'
@test = true
when 'production'
@production = true
end
end
def development?
@development
end
def test?
@test
end
def production?
@production
end
end
Rails = OpenStruct.new(
:application => OpenStruct.new(
:config => OpenStruct.new(
:textris_delivery_method => ['mail', 'test']
)
),
:env => FakeEnv.new(
:test? => false
)
)
end
after do
Object.send(:remove_const, :Rails) if defined?(Rails)
end
it 'maps delivery methods from Rails config to delivery classes' do
expect(Textris::Delivery.get).to eq([
Textris::Delivery::Mail,
Textris::Delivery::Test])
end
it 'returns an array even for single delivery method' do
Rails.application.config.textris_delivery_method = 'mail'
expect(Textris::Delivery.get).to eq([
Textris::Delivery::Mail])
end
it 'defaults to "log" method in development environment' do
Rails.application.config.textris_delivery_method = nil
Rails.env.name = 'development'
expect(Textris::Delivery.get).to eq([
Textris::Delivery::Log])
end
it 'defaults to "test" method in test enviroment' do
Rails.application.config.textris_delivery_method = nil
Rails.env.name = 'test'
expect(Textris::Delivery.get).to eq([
Textris::Delivery::Test])
end
it 'defaults to "mail" method in production enviroment' do
Rails.application.config.textris_delivery_method = nil
Rails.env.name = 'production'
expect(Textris::Delivery.get).to eq([
Textris::Delivery::Mail])
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/spec/textris/base_spec.rb | spec/textris/base_spec.rb | describe Textris::Base do
describe '#default' do
it 'sets defaults' do
some_texter = Class.new(Textris::Base)
expect do
some_texter.instance_eval do
default :from => "Me"
end
end.not_to raise_error
defaults = some_texter.instance_variable_get('@defaults')[:from]
expect(some_texter.instance_variable_get('@defaults')).to have_key(:from)
end
it 'keeps separate defaults for each descendant' do
some_texter = Class.new(Textris::Base)
other_texter = Class.new(Textris::Base)
deep_texter = Class.new(some_texter)
some_texter.instance_eval do
default :from => "Me"
end
other_texter.instance_eval do
default :to => "123"
end
deep_texter.instance_eval do
default :from => "Us", :to => "456"
end
defaults = some_texter.instance_variable_get('@defaults')
expect(defaults).to have_key(:from)
expect(defaults).not_to have_key(:to)
defaults = other_texter.instance_variable_get('@defaults')
expect(defaults).not_to have_key(:from)
expect(defaults).to have_key(:to)
defaults = deep_texter.instance_variable_get('@defaults')
expect(defaults[:from]).to eq 'Us'
expect(defaults[:to]).to eq '456'
end
it "inherits defaults from parent class" do
parent = Class.new(Textris::Base)
parent.instance_eval do
default :from => "Me"
end
child = Class.new(parent)
expect(child.with_defaults({})).to eq({ :from => "Me" })
end
it "overrides defaults from parent class" do
parent = Class.new(Textris::Base)
parent.instance_eval do
default :from => "Me"
end
child = Class.new(parent)
child.instance_eval do
default :from => "Not me", :to => "Me"
end
expect(child.with_defaults({})).to eq({ :from => "Not me", :to => "Me" })
end
end
describe '#with_defaults' do
it 'merges back defaults' do
some_texter = Class.new(Textris::Base)
some_texter.instance_eval do
default :from => "Me"
end
options = some_texter.with_defaults(:to => '123')
expect(options[:from]).to eq 'Me'
expect(options[:to]).to eq '123'
end
end
describe '#deliveries' do
it 'maps to Textris::Delivery::Test.deliveries' do
allow(Textris::Delivery::Test).to receive_messages(:deliveries => ['x'])
expect(Textris::Base.deliveries).to eq (['x'])
end
end
describe '#text' do
before do
class MyTexter < Textris::Base
def action_with_inline_body
text :to => '48 600 700 800', :body => 'asd'
end
def action_with_template
text :to => '48 600 700 800'
end
def set_instance_variable(key, value)
end
end
end
it 'renders inline content when :body provided' do
MyTexter.action_with_inline_body
end
it 'defers template rendering when :body not provided' do
render_options = {}
expect_any_instance_of(MyTexter).not_to receive(:render)
MyTexter.action_with_template
end
end
describe '#my_action' do
before do
class MyTexter < Textris::Base
def my_action(p)
p[:calls] += 1
end
end
end
it 'calls actions on newly created instances' do
call_info = { :calls => 0 }
MyTexter.my_action(call_info)
expect(call_info[:calls]).to eq(1)
end
it 'raises no method error on undefined actions' do
expect { MyTexter.fake_action }.to raise_error NoMethodError
end
it 'responds to defined actions' do
expect(MyTexter.respond_to?(:my_action)).to eq true
end
it 'does not respond to undefined actions' do
expect(MyTexter.respond_to?(:fake_action)).to eq false
end
end
describe Textris::Base::RenderingController do
before do
class Textris::Base::RenderingController
def initialize(*args)
end
end
class ActionMailer::Base
def self.default_url_options
'x'
end
end
end
it 'maps default_url_options to ActionMailer configuration' do
rendering_controller = Textris::Base::RenderingController.new
expect(rendering_controller.default_url_options).to eq 'x'
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/spec/textris/phone_formatter_spec.rb | spec/textris/phone_formatter_spec.rb | describe Textris::PhoneFormatter do
it 'should recognise a 4 digit short code' do
expect(described_class.format("4437")).to eq('4437')
expect(described_class.is_a_short_code?("4437")).to eq(true)
end
it 'should recognise a 5 digit short code' do
expect(described_class.format("44397")).to eq('44397')
expect(described_class.is_a_short_code?("44397")).to eq(true)
end
it 'should recognise a 6 digit short code' do
expect(described_class.format("443975")).to eq('443975')
expect(described_class.is_a_short_code?("443975")).to eq(true)
end
it 'treat strings containing at least 1 letter as alphamerics' do
['a', '1a', '21a', '321a', '4321a', '54321a', '654321a', '7654321a', '87654321a', '987654321a', '0987654321a'].each do |alphameric|
expect(described_class.format(alphameric)).to eq(alphameric)
expect(described_class.is_alphameric?(alphameric)).to eq(true)
end
end
it 'prepends phone number with +' do
expect(described_class.format('48123456789')).to eq('+48123456789')
expect(described_class.is_a_phone_number?('48123456789')).to eq(true)
end
it 'does not prepend phone number with + if it already is prepended' do
expect(described_class.format('+48123456789')).to eq('+48123456789')
expect(described_class.is_a_phone_number?('+48123456789')).to eq(true)
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/spec/textris/delivery/mail_spec.rb | spec/textris/delivery/mail_spec.rb | describe Textris::Delivery::Mail do
let(:message) do
Textris::Message.new(
:from => 'Mr Jones <+48 555 666 777>',
:to => ['+48 600 700 800', '+48 100 200 300'],
:content => 'Some text',
:texter => 'Namespace::MyCuteTexter',
:action => 'my_action',
:media_urls => ['http://example.com/hilarious.gif', 'http://example.org/serious.gif'])
end
let(:delivery) { Textris::Delivery::Mail.new(message) }
before do
Object.send(:remove_const, :Rails) if defined?(Rails)
module MyAppName
class Application < OpenStruct; end
end
Rails = OpenStruct.new(
:application => MyAppName::Application.new(
:config => OpenStruct.new
),
:env => 'test'
)
class FakeMail
def self.deliveries
@deliveries || []
end
def self.deliver(message)
@deliveries ||= []
@deliveries.push(message)
end
def initialize(message)
@message = message
end
def deliver
self.class.deliver(@message)
end
end
allow(Textris::Delivery::Mail::Mailer
).to receive(:notify) do |from, to, subject, body|
FakeMail.new(
:from => from,
:to => to,
:subject => subject,
:body => body)
end
end
after do
Object.send(:remove_const, :Rails) if defined?(Rails)
end
it 'responds to :deliver_to_all' do
expect(delivery).to respond_to(:deliver_to_all)
end
it 'invokes ActionMailer for each recipient' do
expect(Textris::Delivery::Mail::Mailer).to receive(:notify)
delivery.deliver_to_all
expect(FakeMail.deliveries.count).to eq 2
end
it 'reads templates from configuration' do
Rails.application.config = OpenStruct.new(
:textris_mail_from_template => 'a',
:textris_mail_to_template => 'b',
:textris_mail_subject_template => 'c',
:textris_mail_body_template => 'd')
delivery.deliver_to_all
expect(FakeMail.deliveries.last).to eq(
:from => 'a',
:to => 'b',
:subject => 'c',
:body => 'd')
end
it 'defines default templates' do
Rails.application.config = OpenStruct.new
delivery.deliver_to_all
expect(FakeMail.deliveries.last[:from]).to be_present
expect(FakeMail.deliveries.last[:to]).to be_present
expect(FakeMail.deliveries.last[:subject]).to be_present
expect(FakeMail.deliveries.last[:body]).to be_present
end
it 'applies all template interpolations properly' do
interpolations = %w{app env texter action from_name
from_phone to_phone content media_urls}
Rails.application.config = OpenStruct.new(
:textris_mail_to_template => interpolations.map { |i| "%{#{i}}" }.join('-'))
delivery.deliver_to_all
expect(FakeMail.deliveries.last[:to].split('-')).to eq([
'MyAppName', 'test', 'MyCute', 'my_action', 'Mr Jones', '48555666777', '48100200300', 'Some text', 'http://example.com/hilarious.gif, http://example.org/serious.gif'])
end
it 'applies all template interpolation modifiers properly' do
interpolations = %w{app:d texter:dhx action:h from_phone:p}
Rails.application.config = OpenStruct.new(
:textris_mail_to_template => interpolations.map { |i| "%{#{i}}" }.join('--'))
delivery.deliver_to_all
expect(FakeMail.deliveries.last[:to].split('--')).to eq([
'my-app-name', 'My cute', 'My action', '+48 55 566 67 77'])
end
context 'with incomplete message' do
let(:message) do
Textris::Message.new(
:to => ['+48 600 700 800', '+48 100 200 300'],
:content => 'Some text')
end
it 'applies all template interpolations properly when values missing' do
interpolations = %w{app env texter action from_name
from_phone to_phone content}
Rails.env = nil
Rails.application = OpenStruct.new
Rails.application.config = OpenStruct.new(
:textris_mail_to_template => interpolations.map { |i| "%{#{i}}" }.join('-'))
delivery.deliver_to_all
expect(FakeMail.deliveries.last[:to].split('-')).to eq([
'unknown', 'unknown', 'unknown', 'unknown', 'unknown', 'unknown', '48100200300', 'Some text'])
end
end
context 'when sending using twilio messaging service sid' do
let(:message) do
Textris::Message.new(
:to => ['+48 600 700 800', '+48 100 200 300'],
:content => 'Some text',
:twilio_messaging_service_sid => 'NG9752274e9e519418a7406176694466fb')
end
it 'uses the sid in from instead of name and phone' do
delivery.deliver_to_all
expect(FakeMail.deliveries.last[:from])
.to eq('NG9752274e9e519418a7406176694466fb@test.my-app-name.com')
end
end
end
describe Textris::Delivery::Mail::Mailer do
describe '#notify' do
it 'invokes mail with given from, to subject and body' do
mailer = Textris::Delivery::Mail::Mailer
expect_any_instance_of(mailer).to receive(:mail).with(
:from => "a", :to => "b" , :subject => "c", :body => "d")
message = mailer.notify('a', 'b', 'c', 'd')
if message.respond_to?(:deliver_now)
message.deliver_now
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/spec/textris/delivery/nexmo_spec.rb | spec/textris/delivery/nexmo_spec.rb | describe Textris::Delivery::Nexmo do
let(:message) do
Textris::Message.new(
:to => ['+48 600 700 800', '+48 100 200 300'],
:content => 'Some text',
:from => 'Alpha ID')
end
let(:delivery) { Textris::Delivery::Nexmo.new(message) }
before do
module Nexmo
class Client
def send_message(params)
params
end
end
end
end
it 'responds to :deliver_to_all' do
expect(delivery).to respond_to(:deliver_to_all)
end
it 'invokes Nexmo::Client#send_message twice for each recipient' do
expect_any_instance_of(Nexmo::Client).to receive(:send_message).twice do |context, msg|
expect(msg).to have_key(:from)
expect(msg).to have_key(:to)
expect(msg).to have_key(:text)
end
delivery.deliver_to_all
end
describe '#deliver' do
subject { delivery.deliver('48600700800') }
context 'when from_phone is nil' do
it 'will use from_name' do
expect(subject[:from]).to eq 'Alpha ID'
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/spec/textris/delivery/twilio_spec.rb | spec/textris/delivery/twilio_spec.rb | describe Textris::Delivery::Twilio do
before do
class MessageArray
@created = []
class << self
attr_reader :created
end
def create(message)
self.class.created.push(message)
end
end
module Twilio
module REST
class Client
attr_reader :messages
def initialize
@messages = MessageArray.new
end
end
end
end
end
describe "sending multiple messages" do
let(:message) do
Textris::Message.new(
:to => ['+48 600 700 800', '+48 100 200 300'],
:content => 'Some text')
end
let(:delivery) { Textris::Delivery::Twilio.new(message) }
it 'responds to :deliver_to_all' do
expect(delivery).to respond_to(:deliver_to_all)
end
it 'invokes Twilio REST client for each recipient' do
expect_any_instance_of(MessageArray).to receive(:create).twice do |context, msg|
expect(msg).to have_key(:to)
expect(msg).to have_key(:body)
expect(msg).not_to have_key(:media_url)
expect(msg[:body]).to eq(message.content)
end
delivery.deliver_to_all
end
end
describe "sending media messages" do
let(:message) do
Textris::Message.new(
:to => ['+48 600 700 800', '+48 100 200 300'],
:content => 'Some text',
:media_urls => [
'http://example.com/boo.gif',
'http://example.com/yay.gif'])
end
let(:delivery) { Textris::Delivery::Twilio.new(message) }
it 'invokes Twilio REST client for each recipient' do
expect_any_instance_of(MessageArray).to receive(:create).twice do |context, msg|
expect(msg).to have_key(:media_url)
expect(msg[:media_url]).to eq(message.media_urls)
end
delivery.deliver_to_all
end
end
describe 'sending a message using messaging service sid' do
let(:message) do
Textris::Message.new(
to: '+48 600 700 800',
content: 'Some text',
twilio_messaging_service_sid: 'MG9752274e9e519418a7406176694466fa')
end
let(:delivery) { Textris::Delivery::Twilio.new(message) }
it 'uses the sid instead of from for the message' do
delivery.deliver('+11234567890')
expect(MessageArray.created.last[:from]).to be_nil
expect(MessageArray.created.last[:messaging_service_sid])
.to eq('MG9752274e9e519418a7406176694466fa')
end
end
describe "sending from short codes" do
it 'prepends regular phone numbers code with a +' do
number = '48 600 700 800'
message = Textris::Message.new(
:from => number,
:content => 'Some text',
:to => '+48 100 200 300'
)
delivery = Textris::Delivery::Twilio.new(message)
expect_any_instance_of(MessageArray).to receive(:create).once do |context, msg|
expect(msg).to have_key(:from)
expect(msg[:from]).to eq("+#{number.gsub(/\s/, '')}")
end
delivery.deliver_to_all
end
it 'doesn\'t prepend a 6 digit short code with a +' do
number = '894546'
message = Textris::Message.new(
:from => number,
:content => 'Some text',
:to => '+48 100 200 300'
)
delivery = Textris::Delivery::Twilio.new(message)
expect_any_instance_of(MessageArray).to receive(:create).once do |context, msg|
expect(msg).to have_key(:from)
expect(msg[:from]).to eq(number)
end
delivery.deliver_to_all
end
it 'doesn\'t prepend a 5 digit short code with a +' do
number = '44397'
message = Textris::Message.new(
:from => number,
:content => 'Some text',
:to => '+48 100 200 300'
)
delivery = Textris::Delivery::Twilio.new(message)
expect_any_instance_of(MessageArray).to receive(:create).once do |context, msg|
expect(msg).to have_key(:from)
expect(msg[:from]).to eq(number)
end
delivery.deliver_to_all
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/spec/textris/delivery/log_spec.rb | spec/textris/delivery/log_spec.rb | describe Textris::Delivery::Log do
let(:message) do
Textris::Message.new(
:from => 'Mr Jones <+48 555 666 777>',
:to => ['+48 600 700 800', '48100200300'],
:content => 'Some text')
end
let(:delivery) { Textris::Delivery::Log.new(message) }
let(:logger) { FakeLogger.new }
before do
class FakeLogger
def log(kind = :all)
@log[kind.to_s] || ""
end
def method_missing(name, *args)
if Textris::Delivery::Log::AVAILABLE_LOG_LEVELS.include?(name.to_s)
@log ||= {}
@log[name.to_s] ||= ""
@log[name.to_s] += args[0] + "\n"
@log["all"] ||= ""
@log["all"] += args[0] + "\n"
end
end
end
Object.send(:remove_const, :Rails) if defined?(Rails)
Rails = OpenStruct.new(
:logger => logger,
:application => OpenStruct.new(
:config => OpenStruct.new
)
)
end
after do
Object.send(:remove_const, :Rails) if defined?(Rails)
end
it 'responds to :deliver_to_all' do
expect(delivery).to respond_to(:deliver_to_all)
end
it 'prints proper delivery information to log' do
delivery.deliver_to_all
expect(logger.log(:info)).to include "Sent text to +48 600 700 800"
expect(logger.log(:info)).to include "Sent text to +48 10 020 03 00"
expect(logger.log(:debug)).to include "Date: "
expect(logger.log(:debug)).to include "To: +48 600 700 800, +48 600 700 800"
expect(logger.log(:debug)).to include "Texter: UnknownTexter#unknown_action"
expect(logger.log(:debug)).to include "From: Mr Jones <+48 55 566 67 77>"
expect(logger.log(:debug)).to include "Content: Some text"
end
it 'applies configured log level' do
Rails.application.config.textris_log_level = :unknown
delivery.deliver_to_all
expect(logger.log(:info)).to be_blank
expect(logger.log(:debug)).to be_blank
expect(logger.log(:unknown)).not_to be_blank
end
it 'throws error if configured log level is wrong' do
Rails.application.config.textris_log_level = :wronglevel
expect do
delivery.deliver_to_all
end.to raise_error(ArgumentError)
end
context "message with from name and no from phone" do
let(:message) do
Textris::Message.new(
:from => 'Mr Jones',
:to => ['+48 600 700 800', '48100200300'],
:content => 'Some text')
end
it 'prints proper delivery information to log' do
delivery.deliver_to_all
expect(logger.log).to include "From: Mr Jones"
end
end
context "message with from phone and no from name" do
let(:message) do
Textris::Message.new(
:from => '+48 55 566 67 77',
:to => ['+48 600 700 800', '48100200300'],
:content => 'Some text')
end
it 'prints proper delivery information to log' do
delivery.deliver_to_all
expect(logger.log).to include "From: +48 55 566 67 77"
end
end
context "message with no from" do
let(:message) do
Textris::Message.new(
:to => ['+48 600 700 800', '48100200300'],
:content => 'Some text')
end
it 'prints proper delivery information to log' do
delivery.deliver_to_all
expect(logger.log).to include "From: unknown"
end
end
context "message with twilio messaging service sid" do
let(:message) do
Textris::Message.new(
:twilio_messaging_service_sid => 'MG9752274e9e519418a7406176694466fa',
:to => ['+48 600 700 800', '48100200300'],
:content => 'Some text')
end
it 'prints proper delivery information to log' do
delivery.deliver_to_all
expect(logger.log).to include "From: MG9752274e9e519418a7406176694466fa"
end
end
context "message with texter and action" do
let(:message) do
Textris::Message.new(
:texter => "MyClass",
:action => "my_action",
:to => ['+48 600 700 800', '48100200300'],
:content => 'Some text')
end
it 'prints proper delivery information to log' do
delivery.deliver_to_all
expect(logger.log).to include "Texter: MyClass#my_action"
end
end
context "message with media urls" do
let(:message) do
Textris::Message.new(
:from => 'Mr Jones <+48 555 666 777>',
:to => ['+48 600 700 800', '48100200300'],
:content => 'Some text',
:media_urls => [
"http://example.com/hilarious.gif",
"http://example.org/serious.gif"])
end
it 'prints all the media URLs' do
delivery.deliver_to_all
expect(logger.log).to include "Media URLs: http://example.com/hilarious.gif"
expect(logger.log).to include " http://example.org/serious.gif"
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/spec/textris/delivery/test_spec.rb | spec/textris/delivery/test_spec.rb | describe Textris::Delivery::Test do
let(:message) do
Textris::Message.new(
:to => ['+48 600 700 800', '+48 100 200 300'],
:content => 'Some text',
:media_urls => ["http://example.com/hilarious.gif"])
end
let(:delivery) { Textris::Delivery::Test.new(message) }
it 'responds to :deliver_to_all' do
expect(delivery).to respond_to(:deliver_to_all)
end
it 'adds proper deliveries to deliveries array' do
delivery.deliver_to_all
expect(Textris::Delivery::Test.deliveries.count).to eq 2
last_message = Textris::Delivery::Test.deliveries.last
expect(last_message).to be_present
expect(last_message.content).to eq message.content
expect(last_message.from_name).to eq message.from_name
expect(last_message.from_phone).to eq message.from_phone
expect(last_message.texter).to eq message.texter
expect(last_message.action).to eq message.action
expect(last_message.to[0]).to eq message.to[1]
expect(last_message.media_urls[0]).to eq message.media_urls[0]
end
it 'allows clearing messages array' do
delivery.deliver_to_all
Textris::Delivery::Test.deliveries.clear
expect(Textris::Delivery::Test.deliveries).to be_empty
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/spec/textris/delay/sidekiq_spec.rb | spec/textris/delay/sidekiq_spec.rb | describe Textris::Delay::Sidekiq do
before do
class MyTexter < Textris::Base
def delayed_action(phone, body)
text :to => phone, :body => body
end
def serialized_action(user)
text :to => user.id, :body => 'Hello'
end
def serialized_array_action(users)
text :to => users.first.id, :body => 'Hello all'
end
end
module ActiveRecord
class RecordNotFound < Exception; end
class Base
attr_reader :id
def initialize(id)
@id = id
end
def self.find(id)
if id.is_a?(Array)
id.collect do |id|
id.to_i > 0 ? new(id) : raise(RecordNotFound)
end
else
id.to_i > 0 ? new(id) : raise(RecordNotFound)
end
end
end
class Relation
attr_reader :model, :items
delegate :map, :to => :items
def initialize(model, items)
@model = model
@items = items
end
end
end
class XModel < ActiveRecord::Base; end
class YModel < ActiveRecord::Base; end
class XRelation < ActiveRecord::Relation; end
end
context 'sidekiq gem present' do
describe '#delay' do
it 'schedules action with proper params' do
MyTexter.delay.delayed_action('48111222333', 'Hi')
expect_any_instance_of(MyTexter).to receive(:text).with(
:to => "48111222333", :body => "Hi").and_call_original
expect_any_instance_of(Textris::Message).to receive(:deliver)
Textris::Delay::Sidekiq::Worker.drain
end
it 'serializes and deserializes ActiveRecord records' do
user = XModel.new('48666777888')
MyTexter.delay.serialized_action(user)
expect_any_instance_of(MyTexter).to receive(:text).with(
:to => "48666777888", :body => "Hello").and_call_original
expect_any_instance_of(Textris::Message).to receive(:deliver)
expect do
Textris::Delay::Sidekiq::Worker.drain
end.not_to raise_error
end
it 'serializes and deserializes ActiveRecord relations' do
users = XRelation.new(XModel, [XModel.new('48666777888'), XModel.new('48666777889')])
MyTexter.delay.serialized_array_action(users)
expect_any_instance_of(MyTexter).to receive(:text).with(
:to => "48666777888", :body => "Hello all").and_call_original
expect_any_instance_of(Textris::Message).to receive(:deliver)
expect do
Textris::Delay::Sidekiq::Worker.drain
end.not_to raise_error
end
it 'serializes and deserializes ActiveRecord object arrays' do
users = [XModel.new('48666777888'), XModel.new('48666777889')]
MyTexter.delay.serialized_array_action(users)
expect_any_instance_of(MyTexter).to receive(:text).with(
:to => "48666777888", :body => "Hello all").and_call_original
expect_any_instance_of(Textris::Message).to receive(:deliver)
expect do
Textris::Delay::Sidekiq::Worker.drain
end.not_to raise_error
end
it 'does not serialize wrong ActiveRecord object arrays' do
users = [XModel.new('48666777888'), YModel.new('48666777889')]
MyTexter.delay.serialized_array_action(users)
expect do
Textris::Delay::Sidekiq::Worker.drain
end.to raise_error(NoMethodError)
end
it 'does not raise when ActiveRecord not loaded' do
Object.send(:remove_const, :XModel)
Object.send(:remove_const, :YModel)
Object.send(:remove_const, :XRelation)
Object.send(:remove_const, :ActiveRecord)
MyTexter.delay.serialized_array_action('x')
expect do
Textris::Delay::Sidekiq::Worker.drain
end.to raise_error(NoMethodError)
end
end
describe '#delay_for' do
it 'schedules action with proper params and execution time' do
MyTexter.delay_for(300).delayed_action('48111222333', 'Hi')
expect_any_instance_of(MyTexter).to receive(:text).with(
:to => "48111222333", :body => "Hi").and_call_original
expect_any_instance_of(Textris::Message).to receive(:deliver)
scheduled_at = Time.at(Textris::Delay::Sidekiq::Worker.jobs.last['at'])
expect(scheduled_at).to be > Time.now + 250
Textris::Delay::Sidekiq::Worker.drain
end
it 'raises with wrong interval' do
expect do
MyTexter.delay_for('x')
end.to raise_error(ArgumentError)
end
end
describe '#delay_until' do
it 'schedules action with proper params and execution time' do
MyTexter.delay_until(Time.new(2020, 1, 1)).delayed_action(
'48111222333', 'Hi')
expect_any_instance_of(MyTexter).to receive(:text).with(
:to => "48111222333", :body => "Hi").and_call_original
expect_any_instance_of(Textris::Message).to receive(:deliver)
scheduled_at = Time.at(Textris::Delay::Sidekiq::Worker.jobs.last['at'])
expect(scheduled_at).to eq Time.new(2020, 1, 1)
Textris::Delay::Sidekiq::Worker.drain
end
it 'raises with wrong timestamp' do
expect do
MyTexter.delay_until(nil)
end.to raise_error(ArgumentError)
end
end
end
context 'sidekiq gem not present' do
before do
delegate = Class.new.extend(Textris::Delay::Sidekiq::Missing)
[:delay, :delay_for, :delay_until].each do |method|
allow(Textris::Base).to receive(method) { delegate.send(method) }
end
end
describe '#delay' do
it 'raises' do
expect do
MyTexter.delay
end.to raise_error(LoadError)
end
end
describe '#delay_for' do
it 'raises' do
expect do
MyTexter.delay_for(300)
end.to raise_error(LoadError)
end
end
describe '#delay_until' do
it 'raises' do
expect do
MyTexter.delay_until(Time.new(2005, 1, 1))
end.to raise_error(LoadError)
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/spec/textris/delay/active_job_spec.rb | spec/textris/delay/active_job_spec.rb | describe Textris::Delay::ActiveJob do
before do
class MyTexter < Textris::Base
def delayed_action(phone)
text :to => phone
end
end
class ActiveJob::Logging::LogSubscriber
def info(*args, &block)
end
end
end
context 'ActiveJob not present' do
let(:message) do
Textris::Message.new(
:content => 'X',
:from => 'X',
:to => '+48 111 222 333')
end
before do
delegate = Class.new.include(Textris::Delay::ActiveJob::Missing)
delegate = delegate.new
[:deliver_now, :deliver_later].each do |method|
allow(message).to receive(method) { delegate.send(method) }
end
end
describe '#deliver_now' do
it 'raises' do
expect do
message.deliver_now
end.to raise_error(LoadError)
end
end
describe '#deliver_later' do
it 'raises' do
expect do
message.deliver_later
end.to raise_error(LoadError)
end
end
end
context 'ActiveJob present' do
describe '#deliver_now' do
before do
class XDelivery < Textris::Delivery::Base
def deliver(to); end
end
class YDelivery < Textris::Delivery::Base
def deliver(to); end
end
end
it 'works the same as #deliver' do
expect(Textris::Delivery).to receive(:get).
and_return([XDelivery, YDelivery])
message = Textris::Message.new(
:content => 'X',
:from => 'X',
:to => '+48 111 222 333')
expect_any_instance_of(XDelivery).to receive(:deliver_to_all)
expect_any_instance_of(YDelivery).to receive(:deliver_to_all)
message.deliver_now
end
end
describe '#deliver_later' do
before do
Object.send(:remove_const, :Rails) if defined?(Rails)
Rails = OpenStruct.new(
:application => OpenStruct.new(
:config => OpenStruct.new(
:textris_delivery_method => [:null]
)
)
)
end
after do
Object.send(:remove_const, :Rails) if defined?(Rails)
end
it 'schedules action with proper params' do
job = MyTexter.delayed_action('48111222333').deliver_later
expect(job.queue_name).to eq 'textris'
job = MyTexter.delayed_action('48111222333').deliver_later(:queue => :custom)
expect(job.queue_name).to eq 'custom'
end
it 'executes job properly' do
job = Textris::Delay::ActiveJob::Job.new
expect_any_instance_of(Textris::Message).to receive(:deliver_now)
job.perform('MyTexter', :delayed_action, ['48111222333'])
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/app/texters/user_texter.rb | example/rails-4.2/app/texters/user_texter.rb | class UserTexter < Textris::Base
default :from => "Our Team <+48 666-777-888>"
def welcome(user)
@user = user
text :to => @user.phone
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/app/helpers/application_helper.rb | example/rails-4.2/app/helpers/application_helper.rb | module ApplicationHelper
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/app/controllers/users_controller.rb | example/rails-4.2/app/controllers/users_controller.rb | class UsersController < ApplicationController
def index
@users = User.order('created_at DESC, id DESC')
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to users_url, notice: 'User was created and SMS notification was sent. Check server log for yourself!'
else
render :new
end
end
private
def user_params
params.require(:user).permit(:name, :phone)
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/app/controllers/application_controller.rb | example/rails-4.2/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/app/models/user.rb | example/rails-4.2/app/models/user.rb | class User < ActiveRecord::Base
validates :name, :phone, :presence => true, :uniqueness => true
validate :phone_plausible
def phone_plausible
errors.add(:phone, :invalid) if phone.present? && !Phony.plausible?(phone)
end
def phone=(value)
Phony.plausible?(value) ? super(Phony.normalize(value)) : super(value)
end
after_create do
## This would send SMS instantly and slow app down...
# UserTexter.welcome(self).deliver_now
## ...so let's use shiny, async ActiveJob instead
UserTexter.welcome(self).deliver_later
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/db/seeds.rb | example/rails-4.2/db/seeds.rb | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/db/schema.rb | example/rails-4.2/db/schema.rb | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20150220111225) do
create_table "users", force: :cascade do |t|
t.string "name"
t.string "phone"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/db/migrate/20150220111225_create_users.rb | example/rails-4.2/db/migrate/20150220111225_create_users.rb | class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :phone
t.timestamps null: false
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/application.rb | example/rails-4.2/config/application.rb | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module TextrisExample
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/environment.rb | example/rails-4.2/config/environment.rb | # Load the Rails application.
require File.expand_path('../application', __FILE__)
# Initialize the Rails application.
Rails.application.initialize!
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/routes.rb | example/rails-4.2/config/routes.rb | Rails.application.routes.draw do
resources :users, :only => [:index, :new, :create]
root :to => 'users#new'
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/boot.rb | example/rails-4.2/config/boot.rb | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' # Set up gems listed in the Gemfile.
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/initializers/filter_parameter_logging.rb | example/rails-4.2/config/initializers/filter_parameter_logging.rb | # Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/initializers/session_store.rb | example/rails-4.2/config/initializers/session_store.rb | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_textris_example_session'
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/initializers/wrap_parameters.rb | example/rails-4.2/config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/initializers/inflections.rb | example/rails-4.2/config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/initializers/cookies_serializer.rb | example/rails-4.2/config/initializers/cookies_serializer.rb | # Be sure to restart your server when you modify this file.
Rails.application.config.action_dispatch.cookies_serializer = :json
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/initializers/assets.rb | example/rails-4.2/config/initializers/assets.rb | # Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/initializers/backtrace_silencers.rb | example/rails-4.2/config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/initializers/mime_types.rb | example/rails-4.2/config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/environments/test.rb | example/rails-4.2/config/environments/test.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static file server for tests with Cache-Control for performance.
config.serve_static_files = true
config.static_cache_control = 'public, max-age=3600'
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Randomize the order test cases are executed.
config.active_support.test_order = :random
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/environments/development.rb | example/rails-4.2/config/environments/development.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/example/rails-4.2/config/environments/production.rb | example/rails-4.2/config/environments/production.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris.rb | lib/textris.rb | require 'action_controller'
require 'action_mailer'
require 'active_support'
require 'phony'
begin
require 'twilio-ruby'
rescue LoadError
end
begin
require 'sidekiq'
rescue LoadError
require 'textris/delay/sidekiq/missing'
Textris::Delay::Sidekiq.include(Textris::Delay::Sidekiq::Missing)
else
require 'textris/delay/sidekiq'
require 'textris/delay/sidekiq/proxy'
require 'textris/delay/sidekiq/serializer'
require 'textris/delay/sidekiq/worker'
end
require 'textris/base'
require 'textris/phone_formatter'
require 'textris/message'
begin
require 'active_job'
rescue LoadError
require 'textris/delay/active_job/missing'
Textris::Message.include(Textris::Delay::ActiveJob::Missing)
else
require 'textris/delay/active_job'
require 'textris/delay/active_job/job'
Textris::Message.include(Textris::Delay::ActiveJob)
end
require 'textris/delivery'
require 'textris/delivery/base'
require 'textris/delivery/test'
require 'textris/delivery/mail'
require 'textris/delivery/log'
require 'textris/delivery/twilio'
require 'textris/delivery/nexmo'
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/version.rb | lib/textris/version.rb | module Textris
VERSION = '0.7.1'
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/base.rb | lib/textris/base.rb | require 'render_anywhere'
module Textris
class Base
class RenderingController < RenderAnywhere::RenderingController
layout false
def default_url_options
ActionMailer::Base.default_url_options || {}
end
end
include RenderAnywhere
extend Textris::Delay::Sidekiq
class << self
def deliveries
::Textris::Delivery::Test.deliveries
end
def with_defaults(options)
defaults.merge(options)
end
def defaults
@defaults ||= superclass.respond_to?(:defaults) ? superclass.defaults.dup : {}
end
protected
def default(options)
defaults.merge!(options)
end
private
def method_missing(method_name, *args)
new(method_name, *args).call_action
end
def respond_to_missing?(method, *args)
public_instance_methods(true).include?(method) || super
end
end
def initialize(action, *args)
@action = action
@args = args
end
def call_action
send(@action, *@args)
end
def render_content
set_instance_variables_for_rendering
render(:template => template_name, :formats => ['text'], :locale => @locale)
end
protected
def text(options = {})
@locale = options[:locale] || I18n.locale
options = self.class.with_defaults(options)
options.merge!(
:texter => self.class,
:action => @action,
:args => @args,
:content => options[:body].is_a?(String) ? options[:body] : nil,
:renderer => self)
::Textris::Message.new(options)
end
private
def template_name
class_name = self.class.to_s.underscore.sub('texter/', '')
action_name = @action
"#{class_name}/#{action_name}"
end
def set_instance_variables_for_rendering
instance_variables.each do |var|
set_instance_variable(var.to_s.sub('@', ''), instance_variable_get(var))
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/message.rb | lib/textris/message.rb | module Textris
class Message
attr_reader :content, :from_name, :from_phone, :to, :texter, :action, :args,
:media_urls, :twilio_messaging_service_sid
def initialize(options = {})
initialize_content(options)
initialize_author(options)
initialize_recipients(options)
@texter = options[:texter]
@action = options[:action]
@args = options[:args]
@media_urls = options[:media_urls]
end
def deliver
deliveries = ::Textris::Delivery.get
deliveries.each do |delivery|
delivery.new(self).deliver_to_all
end
self
end
def texter(options = {})
if options[:raw]
@texter
elsif @texter.present?
@texter.to_s.split('::').last.to_s.sub(/Texter$/, '')
end
end
def from
if @from_phone.present?
if @from_name.present?
if PhoneFormatter.is_alphameric?(@from_phone)
@from_phone
else
if PhoneFormatter.is_a_short_code?(@from_phone)
"#{@from_name} <#{@from_phone}>"
else
"#{@from_name} <#{Phony.format(@from_phone)}>"
end
end
else
Phony.format(@from_phone)
end
elsif @from_name.present?
@from_name
end
end
def content
@content ||= parse_content(@renderer.render_content)
end
private
def initialize_content(options)
if options[:content].present?
@content = parse_content options[:content]
elsif options[:renderer].present?
@renderer = options[:renderer]
else
raise(ArgumentError, "Content must be provided")
end
end
def initialize_author(options)
if options.has_key?(:twilio_messaging_service_sid)
@twilio_messaging_service_sid = options[:twilio_messaging_service_sid]
elsif options.has_key?(:from)
@from_name, @from_phone = parse_from options[:from]
else
@from_name = options[:from_name]
@from_phone = options[:from_phone]
end
end
def initialize_recipients(options)
@to = parse_to options[:to]
unless @to.present?
raise(ArgumentError, "Recipients must be provided and E.164 compliant")
end
end
def parse_from(from)
parse_from_dual(from) || parse_from_singular(from)
end
def parse_from_dual(from)
matches = from.match(/(.*)\<(.*)\>\s*$/)
return unless matches
name, sender_id = matches.captures
return unless name && sender_id
if Phony.plausible?(sender_id) || PhoneFormatter.is_a_short_code?(sender_id)
[name.strip, Phony.normalize(sender_id)]
elsif PhoneFormatter.is_alphameric?(sender_id)
[name.strip, sender_id]
end
end
def parse_from_singular(from)
if Phony.plausible?(from)
[nil, Phony.normalize(from)]
elsif PhoneFormatter.is_a_short_code?(from)
[nil, from.to_s]
elsif from.present?
[from.strip, nil]
end
end
def parse_to(to)
to = [*to]
to = to.select { |phone| Phony.plausible?(phone.to_s) }
to = to.map { |phone| Phony.normalize(phone.to_s) }
to
end
def parse_content(content)
content = content.to_s
content = content.rstrip
content
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delivery.rb | lib/textris/delivery.rb | module Textris
module Delivery
module_function
def get
methods = Rails.application.config.try(:textris_delivery_method)
methods = [*methods].compact
if methods.blank?
if Rails.env.development?
methods = [:log]
elsif Rails.env.test?
methods = [:test]
else
methods = [:mail]
end
end
methods.map do |method|
"Textris::Delivery::#{method.to_s.camelize}".safe_constantize ||
"#{method.to_s.camelize}Delivery".safe_constantize
end.compact
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/phone_formatter.rb | lib/textris/phone_formatter.rb | module Textris
class PhoneFormatter
class << self
def format(phone = '')
return phone if is_a_short_code?(phone) || is_alphameric?(phone) || phone.nil?
"#{'+' unless phone.start_with?('+')}#{phone}"
end
# Short codes have more dependencies and limitations;
# but this is a good general start
def is_a_short_code?(phone)
!!phone.to_s.match(/\A\d{4,6}\z/)
end
def is_a_phone_number?(phone)
Phony.plausible?(phone)
end
def is_alphameric?(phone)
# \A # Start of the string
# (?=.*[a-zA-Z]) # Lookahead to ensure there is at least one letter in the entire string
# [a-zA-z\d]{1,11} # Between 1 and 11 characters in the string
# \z # End of the string
!!phone.to_s.match(/\A(?=.*[a-zA-Z])[a-zA-z\d]{1,11}\z/)
end
end
end
end | ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delivery/test.rb | lib/textris/delivery/test.rb | module Textris
module Delivery
class Test < Textris::Delivery::Base
class << self
def deliveries
@deliveries ||= []
end
end
def deliver(to)
self.class.deliveries.push(::Textris::Message.new(
:content => message.content,
:from_name => message.from_name,
:from_phone => message.from_phone,
:texter => message.texter,
:action => message.action,
:to => to,
:media_urls => message.media_urls))
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delivery/log.rb | lib/textris/delivery/log.rb | module Textris
module Delivery
class Log < Textris::Delivery::Base
AVAILABLE_LOG_LEVELS = %w{debug info warn error fatal unknown}
def deliver(to)
log :info, "Sent text to #{Phony.format(to)}"
log :debug, "Texter: #{message.texter || 'UnknownTexter'}" + "#" +
"#{message.action || 'unknown_action'}"
log :debug, "Date: #{Time.now}"
log :debug, "From: #{message.from || message.twilio_messaging_service_sid || 'unknown'}"
log :debug, "To: #{message.to.map { |i| Phony.format(to) }.join(', ')}"
log :debug, "Content: #{message.content}"
(message.media_urls || []).each_with_index do |media_url, index|
logged_message = index == 0 ? "Media URLs: " : " "
logged_message << media_url
log :debug, logged_message
end
end
private
def log(level, message)
level = Rails.application.config.try(:textris_log_level) || level
unless AVAILABLE_LOG_LEVELS.include?(level.to_s)
raise(ArgumentError, "Wrong log level: #{level}")
end
Rails.logger.send(level, message)
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delivery/nexmo.rb | lib/textris/delivery/nexmo.rb | module Textris
module Delivery
class Nexmo < Textris::Delivery::Base
def deliver(phone)
client.send_message(
from: sender_id,
to: phone,
text: message.content
)
end
private
def client
@client ||= ::Nexmo::Client.new
end
def sender_id
message.from_phone || message.from_name
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delivery/twilio.rb | lib/textris/delivery/twilio.rb | module Textris
module Delivery
class Twilio < Textris::Delivery::Base
def deliver(to)
options = {
:to => PhoneFormatter.format(to),
:body => message.content
}
if message.twilio_messaging_service_sid
options[:messaging_service_sid] = message.twilio_messaging_service_sid
else
options[:from] = PhoneFormatter.format(message.from_phone)
end
if message.media_urls.is_a?(Array)
options[:media_url] = message.media_urls
end
client.messages.create(options)
end
private
def client
@client ||= ::Twilio::REST::Client.new
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delivery/base.rb | lib/textris/delivery/base.rb | module Textris
module Delivery
class Base
attr_reader :message
def initialize(message)
@message = message
end
def deliver_to_all
message.to.each do |to|
deliver(to)
end
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delivery/mail.rb | lib/textris/delivery/mail.rb | module Textris
module Delivery
class Mail < Textris::Delivery::Base
class Mailer < ActionMailer::Base
def notify(from, to, subject, body)
mail :from => from, :to => to, :subject => subject, :body => body
end
end
def deliver(to)
template_vars = { :to_phone => to }
from = apply_template from_template, template_vars
to = apply_template to_template, template_vars
subject = apply_template subject_template, template_vars
body = apply_template body_template, template_vars
::Textris::Delivery::Mail::Mailer.notify(
from, to, subject, body).deliver
end
private
def from_template
Rails.application.config.try(:textris_mail_from_template) ||
"#{from_format}@%{env:d}.%{app:d}.com"
end
def from_format
if message.twilio_messaging_service_sid
'%{twilio_messaging_service_sid}'
else
'%{from_name:d}-%{from_phone}'
end
end
def to_template
Rails.application.config.try(:textris_mail_to_template) ||
"%{app:d}-%{env:d}-%{to_phone}-texts@mailinator.com"
end
def subject_template
Rails.application.config.try(:textris_mail_subject_template) ||
"%{texter:dh} texter: %{action:h}"
end
def body_template
Rails.application.config.try(:textris_mail_body_template) ||
"%{content}"
end
def apply_template(template, variables)
template.gsub(/\%\{[a-z_:]+\}/) do |match|
directive = match.gsub(/[%{}]/, '')
key = directive.split(':').first
modifiers = directive.split(':')[1] || ''
content = get_template_interpolation(key, variables)
content = apply_template_modifiers(content, modifiers.chars)
content = 'unknown' unless content.present?
content
end
end
def get_template_interpolation(key, variables)
case key
when 'app', 'env'
get_rails_variable(key)
when 'texter', 'action', 'from_name', 'from_phone', 'content', 'twilio_messaging_service_sid'
message.send(key)
when 'media_urls'
message.media_urls.join(', ')
else
variables[key.to_sym]
end.to_s.strip
end
def get_rails_variable(var)
case var
when 'app'
Rails.application.class.parent_name
when 'env'
Rails.env
end
end
def apply_template_modifiers(content, modifiers)
modifiers.each do |modifier|
case modifier
when 'd'
content = content.underscore.dasherize
when 'h'
content = content.humanize.gsub(/[-_]/, ' ')
when 'p'
content = Phony.format(content) rescue content
end
end
content
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delay/active_job.rb | lib/textris/delay/active_job.rb | module Textris
module Delay
module ActiveJob
def deliver_now
deliver
end
def deliver_later(options = {})
job = Textris::Delay::ActiveJob::Job
job.new(texter(:raw => true).to_s, action.to_s, args).enqueue(options)
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delay/sidekiq.rb | lib/textris/delay/sidekiq.rb | module Textris
module Delay
module Sidekiq
def delay
::Textris::Delay::Sidekiq::Proxy.new(self.to_s)
end
def delay_for(interval)
unless interval.is_a?(Integer)
raise(ArgumentError, "Proper interval must be provided")
end
::Textris::Delay::Sidekiq::Proxy.new(self.to_s, :perform_in => interval)
end
def delay_until(timestamp)
unless timestamp.respond_to?(:to_time)
raise(ArgumentError, "Proper timestamp must be provided")
end
::Textris::Delay::Sidekiq::Proxy.new(self.to_s, :perform_at => timestamp)
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delay/sidekiq/proxy.rb | lib/textris/delay/sidekiq/proxy.rb | module Textris
module Delay
module Sidekiq
class Proxy
def initialize(texter, options = {})
@texter = texter
@perform_in = options[:perform_in]
@perform_at = options[:perform_at]
end
def method_missing(method_name, *args)
args = ::Textris::Delay::Sidekiq::Serializer.serialize(args)
args = [@texter, method_name, args]
if @perform_in
::Textris::Delay::Sidekiq::Worker.perform_in(@perform_in, *args)
elsif @perform_at
::Textris::Delay::Sidekiq::Worker.perform_at(@perform_at, *args)
else
::Textris::Delay::Sidekiq::Worker.perform_async(*args)
end
end
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delay/sidekiq/missing.rb | lib/textris/delay/sidekiq/missing.rb | module Textris
module Delay
module Sidekiq
module Missing
def sidekiq_missing(*args)
raise(LoadError, "Sidekiq is required to delay sending messages")
end
alias_method :delay, :sidekiq_missing
alias_method :delay_for, :sidekiq_missing
alias_method :delay_until, :sidekiq_missing
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delay/sidekiq/serializer.rb | lib/textris/delay/sidekiq/serializer.rb | module Textris
module Delay
module Sidekiq
module Serializer
ACTIVERECORD_POINTER = 'Textris::ActiveRecordPointer'
ACTIVERECORD_ARRAY_POINTER = 'Textris::ActiveRecordArrayPointer'
class << self
def serialize(objects)
objects.collect do |object|
serialize_active_record_object(object) ||
serialize_active_record_array(object) ||
serialize_active_record_relation(object) ||
object
end
rescue NameError
objects
end
def deserialize(objects)
objects.collect do |object|
deserialize_active_record_object(object) ||
object
end
end
private
def serialize_active_record_object(object)
if object.class < ActiveRecord::Base && object.id.present?
[ACTIVERECORD_POINTER, object.class.to_s, object.id]
end
end
def serialize_active_record_relation(array)
if array.class < ActiveRecord::Relation
[ACTIVERECORD_ARRAY_POINTER, array.model.to_s, array.map(&:id)]
end
end
def serialize_active_record_array(array)
if array.is_a?(Array) &&
(model = get_active_record_common_model(array))
[ACTIVERECORD_ARRAY_POINTER, model, array.map(&:id)]
end
end
def deserialize_active_record_object(object)
if object.is_a?(Array) &&
object.try(:length) == 3 &&
[ACTIVERECORD_POINTER,
ACTIVERECORD_ARRAY_POINTER].include?(object[0])
object[1].constantize.find(object[2])
end
end
def get_active_record_common_model(items)
items = items.collect do |item|
if item.class < ActiveRecord::Base
item.class.to_s
end
end.uniq
if items.size == 1
items.first
end
end
end
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delay/sidekiq/worker.rb | lib/textris/delay/sidekiq/worker.rb | module Textris
module Delay
module Sidekiq
class Worker
include ::Sidekiq::Worker
def perform(texter, action, args)
texter = texter.safe_constantize
if texter.present?
args = ::Textris::Delay::Sidekiq::Serializer.deserialize(args)
texter.new(action, *args).call_action.deliver
end
end
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delay/active_job/missing.rb | lib/textris/delay/active_job/missing.rb | module Textris
module Delay
module ActiveJob
module Missing
def active_job_missing(*args)
raise(LoadError, "ActiveJob is required to delay sending messages")
end
alias_method :deliver_now, :active_job_missing
alias_method :deliver_later, :active_job_missing
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
visualitypl/textris | https://github.com/visualitypl/textris/blob/e95954a869198d66b976692114a834f48d6f937c/lib/textris/delay/active_job/job.rb | lib/textris/delay/active_job/job.rb | module Textris
module Delay
module ActiveJob
class Job < ::ActiveJob::Base
queue_as :textris
def perform(texter, action, args)
texter = texter.safe_constantize
if texter.present?
texter.new(action, *args).call_action.deliver_now
end
end
end
end
end
end
| ruby | MIT | e95954a869198d66b976692114a834f48d6f937c | 2026-01-04T17:47:39.808354Z | false |
rubymotion-community/motion-support | https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/app/app_delegate.rb | app/app_delegate.rb | class AppDelegate
def application(application, didFinishLaunchingWithOptions:launchOptions)
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/spec/motion-support/concern_spec.rb | spec/motion-support/concern_spec.rb | class ConcernTest
module Baz
extend MotionSupport::Concern
module ClassMethods
def baz
"baz"
end
def included_ran=(value)
@@included_ran = value
end
def included_ran
@@included_ran
end
end
included do
self.included_ran = true
end
def baz
"baz"
end
end
module Bar
extend MotionSupport::Concern
include Baz
def bar
"bar"
end
def baz
"bar+" + super
end
end
module Foo
extend MotionSupport::Concern
include Bar, Baz
end
end
describe "Concern" do
before do
@klass = Class.new
end
it "should be included normally" do
@klass.send(:include, ConcernTest::Baz)
@klass.new.baz.should == "baz"
@klass.included_modules.include?(ConcernTest::Baz).should.be.true
@klass.send(:include, ConcernTest::Baz)
@klass.new.baz.should == "baz"
@klass.included_modules.include?(ConcernTest::Baz).should.be.true
end
it "should extend class methods" do
@klass.send(:include, ConcernTest::Baz)
@klass.baz.should == "baz"
(class << @klass; self.included_modules; end)[0].should == ConcernTest::Baz::ClassMethods
end
it "should include instance methods" do
@klass.send(:include, ConcernTest::Baz)
@klass.new.baz.should == "baz"
@klass.included_modules.include?(ConcernTest::Baz).should.be.true
end
it "should run included block" do
@klass.send(:include, ConcernTest::Baz)
@klass.included_ran.should.be.true
end
it "should meet dependencies" do
@klass.send(:include, ConcernTest::Bar)
@klass.new.bar.should == "bar"
@klass.new.baz.should == "bar+baz"
@klass.baz.should == "baz"
@klass.included_modules.include?(ConcernTest::Bar).should.be.true
end
it "should meet dependencies with multiple modules" do
@klass.send(:include, ConcernTest::Foo)
@klass.included_modules[0..2].should == [ConcernTest::Foo, ConcernTest::Bar, ConcernTest::Baz]
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/descendants_tracker_spec.rb | spec/motion-support/descendants_tracker_spec.rb | module DescendantsTrackerSpec
class Parent
extend MotionSupport::DescendantsTracker
end
class Child1 < Parent
end
class Child2 < Parent
end
class Grandchild1 < Child1
end
class Grandchild2 < Child1
end
ALL = [Parent, Child1, Child2, Grandchild1, Grandchild2]
end
describe "DescendantsTracker" do
describe "descendants" do
it "should get all descendants from parent class" do
[DescendantsTrackerSpec::Child1, DescendantsTrackerSpec::Child2, DescendantsTrackerSpec::Grandchild1, DescendantsTrackerSpec::Grandchild2].should == DescendantsTrackerSpec::Parent.descendants
end
it "should get descendants from subclass" do
[DescendantsTrackerSpec::Grandchild1, DescendantsTrackerSpec::Grandchild2].should == DescendantsTrackerSpec::Child1.descendants
end
it "should return empty array for leaf class" do
[].should == DescendantsTrackerSpec::Child2.descendants
end
end
describe "direct_descendants" do
it "should get direct descendants from parent class" do
[DescendantsTrackerSpec::Child1, DescendantsTrackerSpec::Child2].should == DescendantsTrackerSpec::Parent.direct_descendants
end
it "should get direct descendants from subclass" do
[DescendantsTrackerSpec::Grandchild1, DescendantsTrackerSpec::Grandchild2].should == DescendantsTrackerSpec::Child1.direct_descendants
end
it "should return empty array for leaf class" do
[].should == DescendantsTrackerSpec::Child2.direct_descendants
end
end
describe "clear" do
it "should remove all tracked descendants" do
MotionSupport::DescendantsTracker.clear
DescendantsTrackerSpec::ALL.each do |k|
MotionSupport::DescendantsTracker.descendants(k).should.be.empty
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/inflector_spec.rb | spec/motion-support/inflector_spec.rb | module InflectorHelper
# Dups the singleton and yields, restoring the original inflections later.
# Use this in tests what modify the state of the singleton.
#
# This helper is implemented by setting @__instance__ because in some tests
# there are module functions that access MotionSupport::Inflector.inflections,
# so we need to replace the singleton itself.
def with_dup
original = MotionSupport::Inflector::Inflections.instance_variable_get(:@__instance__)
MotionSupport::Inflector::Inflections.instance_variable_set(:@__instance__, original.dup)
yield
ensure
MotionSupport::Inflector::Inflections.instance_variable_set(:@__instance__, original)
end
end
describe "Inflector" do
describe "singularize/pluralize" do
extend InflectorHelper
it "should pluralize plurals" do
MotionSupport::Inflector.pluralize("plurals").should == "plurals"
MotionSupport::Inflector.pluralize("Plurals").should == "Plurals"
end
it "should pluralize empty string" do
MotionSupport::Inflector.pluralize("").should == ""
end
MotionSupport::Inflector.inflections.uncountable.each do |word|
it "should treat #{word} as uncountable" do
MotionSupport::Inflector.singularize(word).should == word
MotionSupport::Inflector.pluralize(word).should == word
MotionSupport::Inflector.singularize(word).should == MotionSupport::Inflector.pluralize(word)
end
end
InflectorTestCases::SingularToPlural.each do |singular, plural|
it "should pluralize singular #{singular}" do
MotionSupport::Inflector.pluralize(singular).should == plural
MotionSupport::Inflector.pluralize(singular.capitalize).should == plural.capitalize
end
it "should singularize plural #{plural}" do
MotionSupport::Inflector.singularize(plural).should == singular
MotionSupport::Inflector.singularize(plural.capitalize).should == singular.capitalize
end
it "should pluralize plural #{plural}" do
MotionSupport::Inflector.pluralize(plural).should == plural
MotionSupport::Inflector.pluralize(plural.capitalize).should == plural.capitalize
end
it "should singularize singular #{singular}" do
MotionSupport::Inflector.singularize(singular).should == singular
MotionSupport::Inflector.singularize(singular.capitalize).should == singular.capitalize
end
end
it "should handle uncountable words non-greedily" do
with_dup do
uncountable_word = "ors"
countable_word = "sponsor"
MotionSupport::Inflector.inflections.uncountable << uncountable_word
MotionSupport::Inflector.singularize(uncountable_word).should == uncountable_word
MotionSupport::Inflector.pluralize(uncountable_word).should == uncountable_word
MotionSupport::Inflector.pluralize(uncountable_word).should == MotionSupport::Inflector.singularize(uncountable_word)
MotionSupport::Inflector.singularize(countable_word).should == "sponsor"
MotionSupport::Inflector.pluralize(countable_word).should == "sponsors"
MotionSupport::Inflector.singularize(MotionSupport::Inflector.pluralize(countable_word)).should == "sponsor"
end
end
end
describe "titleize" do
InflectorTestCases::MixtureToTitleCase.each do |before, titleized|
it "should titleize #{before}" do
MotionSupport::Inflector.titleize(before).should == titleized
end
end
end
describe "underscore" do
InflectorTestCases::CamelToUnderscore.each do |camel, underscore|
it "should underscore #{camel}" do
MotionSupport::Inflector.underscore(camel).should == underscore
end
end
InflectorTestCases::CamelToUnderscoreWithoutReverse.each do |camel, underscore|
it "should underscore #{camel}" do
MotionSupport::Inflector.underscore(camel).should == underscore
end
end
InflectorTestCases::CamelWithModuleToUnderscoreWithSlash.each do |camel, underscore|
it "should underscore #{camel}" do
MotionSupport::Inflector.underscore(camel).should == underscore
end
end
end
describe "camelize" do
InflectorTestCases::CamelToUnderscore.each do |camel, underscore|
it "should camelize #{underscore}" do
MotionSupport::Inflector.camelize(underscore).should == camel
end
end
InflectorTestCases::CamelWithModuleToUnderscoreWithSlash.each do |camel, underscore|
it "should camelize #{underscore}" do
MotionSupport::Inflector.camelize(underscore).should == camel
end
end
it "should downcase first letter if called with lower" do
MotionSupport::Inflector.camelize('Capital', false).should == 'capital'
end
it "should remove underscores" do
MotionSupport::Inflector.camelize('Camel_Case').should == "CamelCase"
end
InflectorTestCases::UnderscoreToLowerCamel.each do |underscored, lower_camel|
it "should lower-camelize #{underscored}" do
MotionSupport::Inflector.camelize(underscored, false).should == lower_camel
end
end
InflectorTestCases::SymbolToLowerCamel.each do |symbol, lower_camel|
it "should lower-camelize symbol :#{symbol}" do
MotionSupport::Inflector.camelize(symbol, false).should == lower_camel
end
end
end
describe "irregularities" do
InflectorTestCases::Irregularities.each do |irregularity|
singular, plural = *irregularity
MotionSupport::Inflector.inflections do |inflect|
it "should singularize #{plural} as #{singular}" do
inflect.irregular(singular, plural)
MotionSupport::Inflector.singularize(plural).should == singular
end
it "should pluralize #{singular} as #{plural}" do
inflect.irregular(singular, plural)
MotionSupport::Inflector.pluralize(singular).should == plural
end
end
MotionSupport::Inflector.inflections do |inflect|
it "should return same string when pluralizing irregular plural #{plural}" do
inflect.irregular(singular, plural)
MotionSupport::Inflector.pluralize(plural).should == plural
end
end
MotionSupport::Inflector.inflections do |inflect|
it "should return same string when singularizing irregular singular #{singular}" do
inflect.irregular(singular, plural)
MotionSupport::Inflector.singularize(singular).should == singular
end
end
end
end
it "should overwrite previous inflectors" do
MotionSupport::Inflector.singularize("series").should == "series"
MotionSupport::Inflector.inflections.singular "series", "serie"
MotionSupport::Inflector.singularize("series").should == "serie"
MotionSupport::Inflector.inflections.uncountable "series" # Return to normal
end
describe "acronym" do
before do
MotionSupport::Inflector.inflections do |inflect|
inflect.acronym("API")
inflect.acronym("HTML")
inflect.acronym("HTTP")
inflect.acronym("RESTful")
inflect.acronym("W3C")
inflect.acronym("PhD")
inflect.acronym("RoR")
inflect.acronym("SSL")
end
end
# camelize underscore humanize titleize
[
["API", "api", "API", "API"],
["APIController", "api_controller", "API controller", "API Controller"],
["Nokogiri::HTML", "nokogiri/html", "Nokogiri/HTML", "Nokogiri/HTML"],
["HTTPAPI", "http_api", "HTTP API", "HTTP API"],
["HTTP::Get", "http/get", "HTTP/get", "HTTP/Get"],
["SSLError", "ssl_error", "SSL error", "SSL Error"],
["RESTful", "restful", "RESTful", "RESTful"],
["RESTfulController", "restful_controller", "RESTful controller", "RESTful Controller"],
["IHeartW3C", "i_heart_w3c", "I heart W3C", "I Heart W3C"],
["PhDRequired", "phd_required", "PhD required", "PhD Required"],
["IRoRU", "i_ror_u", "I RoR u", "I RoR U"],
["RESTfulHTTPAPI", "restful_http_api", "RESTful HTTP API", "RESTful HTTP API"],
["UIImage", "ui_image", "UI image", "UI Image"],
# misdirection
["Capistrano", "capistrano", "Capistrano", "Capistrano"],
["CapiController", "capi_controller", "Capi controller", "Capi Controller"],
["HttpsApis", "https_apis", "Https apis", "Https Apis"],
["Html5", "html5", "Html5", "Html5"],
["Restfully", "restfully", "Restfully", "Restfully"],
["RoRails", "ro_rails", "Ro rails", "Ro Rails"]
].each do |camel, under, human, title|
it "should camelize #{under} as #{camel}" do
MotionSupport::Inflector.camelize(under).should == camel
end
it "should keep #{camel} camelized" do
MotionSupport::Inflector.camelize(camel).should == camel
end
it "should keep #{under} underscored" do
MotionSupport::Inflector.underscore(under).should == under
end
it "should underscore #{camel} as #{under}" do
MotionSupport::Inflector.underscore(camel).should == under
end
it "should titleize #{under} as #{title}" do
MotionSupport::Inflector.titleize(under).should == title
end
it "should titleize #{camel} as #{title}" do
MotionSupport::Inflector.titleize(camel).should == title
end
it "should humanize #{under} as #{human}" do
MotionSupport::Inflector.humanize(under).should == human
end
end
describe "override acronyms" do
before do
MotionSupport::Inflector.inflections do |inflect|
inflect.acronym("API")
inflect.acronym("LegacyApi")
end
end
{
"legacyapi" => "LegacyApi",
"legacy_api" => "LegacyAPI",
"some_legacyapi" => "SomeLegacyApi",
"nonlegacyapi" => "Nonlegacyapi"
}.each do |from, to|
it "should camelize #{from} as #{to}" do
MotionSupport::Inflector.camelize(from).should == to
end
end
end
describe "lower-camelize with acronym parts" do
before do
MotionSupport::Inflector.inflections do |inflect|
inflect.acronym("API")
inflect.acronym("HTML")
end
end
{
"html_api" => "htmlAPI",
"htmlAPI" => "htmlAPI",
"HTMLAPI" => "htmlAPI"
}.each do |from, to|
it "should lower-camelize #{from} as #{to}" do
MotionSupport::Inflector.camelize(from, false).should == to
end
end
end
it "should underscore acronym sequence" do
MotionSupport::Inflector.inflections do |inflect|
inflect.acronym("API")
inflect.acronym("JSON")
inflect.acronym("HTML")
end
MotionSupport::Inflector.underscore("JSONHTMLAPI").should == "json_html_api"
end
end
describe "demodulize" do
{
"MyApplication::Billing::Account" => "Account",
"Account" => "Account",
"" => ""
}.each do |from, to|
it "should transform #{from} to #{to}" do
MotionSupport::Inflector.demodulize(from).should == to
end
end
end
describe "deconstantize" do
{
"MyApplication::Billing::Account" => "MyApplication::Billing",
"::MyApplication::Billing::Account" => "::MyApplication::Billing",
"MyApplication::Billing" => "MyApplication",
"::MyApplication::Billing" => "::MyApplication",
"Account" => "",
"::Account" => "",
"" => ""
}.each do |from, to|
it "should deconstantize #{from} as #{to}" do
MotionSupport::Inflector.deconstantize(from).should == to
end
end
end
describe "foreign_key" do
InflectorTestCases::ClassNameToForeignKeyWithUnderscore.each do |klass, foreign_key|
it "should create foreign key for class name #{klass}" do
MotionSupport::Inflector.foreign_key(klass).should == foreign_key
end
end
InflectorTestCases::ClassNameToForeignKeyWithoutUnderscore.each do |klass, foreign_key|
it "should create foreign key for class name #{klass} without underscore" do
MotionSupport::Inflector.foreign_key(klass, false).should == foreign_key
end
end
end
describe "tableize" do
InflectorTestCases::ClassNameToTableName.each do |class_name, table_name|
it "should create table name from class name #{class_name}" do
MotionSupport::Inflector.tableize(class_name).should == table_name
end
end
end
describe "classify" do
InflectorTestCases::ClassNameToTableName.each do |class_name, table_name|
it "should classify #{table_name}" do
MotionSupport::Inflector.classify(table_name).should == class_name
end
it "should classify #{table_name} with table prefix" do
MotionSupport::Inflector.classify("table_prefix." + table_name).should == class_name
end
end
it "should classify with symbol" do
lambda do
MotionSupport::Inflector.classify(:foo_bars).should == 'FooBar'
end.should.not.raise
end
it "should classify with leading schema name" do
MotionSupport::Inflector.classify('schema.foo_bar').should == 'FooBar'
end
end
describe "humanize" do
InflectorTestCases::UnderscoreToHuman.each do |underscore, human|
it "should humanize #{underscore}" do
MotionSupport::Inflector.humanize(underscore).should == human
end
end
it "should humanize by rule" do
MotionSupport::Inflector.inflections do |inflect|
inflect.human(/_cnt$/i, '\1_count')
inflect.human(/^prefx_/i, '\1')
end
MotionSupport::Inflector.humanize("jargon_cnt").should == "Jargon count"
MotionSupport::Inflector.humanize("prefx_request").should == "Request"
end
it "should humanize by string" do
MotionSupport::Inflector.inflections do |inflect|
inflect.human("col_rpted_bugs", "Reported bugs")
end
MotionSupport::Inflector.humanize("col_rpted_bugs").should == "Reported bugs"
MotionSupport::Inflector.humanize("COL_rpted_bugs").should == "Col rpted bugs"
end
end
describe "constantize" do
extend ConstantizeTestCases
it "should constantize" do
run_constantize_tests_on do |string|
MotionSupport::Inflector.constantize(string)
end
end
end
describe "safe_constantize" do
extend ConstantizeTestCases
it "should safe_constantize" do
run_safe_constantize_tests_on do |string|
MotionSupport::Inflector.safe_constantize(string)
end
end
end
describe "ordinal" do
InflectorTestCases::OrdinalNumbers.each do |number, ordinalized|
it "should return ordinal of number #{number}" do
(number + MotionSupport::Inflector.ordinal(number)).should == ordinalized
end
end
end
describe "ordinalize" do
InflectorTestCases::OrdinalNumbers.each do |number, ordinalized|
it "should ordinalize number #{number}" do
MotionSupport::Inflector.ordinalize(number).should == ordinalized
end
end
end
describe "dasherize" do
InflectorTestCases::UnderscoresToDashes.each do |underscored, dasherized|
it "should dasherize #{underscored}" do
MotionSupport::Inflector.dasherize(underscored).should == dasherized
end
end
InflectorTestCases::UnderscoresToDashes.each_key do |underscored|
it "should dasherize and then underscore #{underscored}, returning #{underscored}" do
MotionSupport::Inflector.underscore(MotionSupport::Inflector.dasherize(underscored)).should == underscored
end
end
end
describe "clear" do
extend InflectorHelper
%w{plurals singulars uncountables humans acronyms}.each do |inflection_type|
it "should clear #{inflection_type}" do
with_dup do
MotionSupport::Inflector.inflections.clear inflection_type.to_sym
MotionSupport::Inflector.inflections.send(inflection_type).should.be.empty
end
end
end
it "should clear all" do
with_dup do
MotionSupport::Inflector.inflections do |inflect|
# ensure any data is present
inflect.plural(/(quiz)$/i, '\1zes')
inflect.singular(/(database)s$/i, '\1')
inflect.uncountable('series')
inflect.human("col_rpted_bugs", "Reported bugs")
inflect.clear :all
inflect.plurals.should.be.empty
inflect.singulars.should.be.empty
inflect.uncountables.should.be.empty
inflect.humans.should.be.empty
end
end
end
it "should clear with default" do
with_dup do
MotionSupport::Inflector.inflections do |inflect|
# ensure any data is present
inflect.plural(/(quiz)$/i, '\1zes')
inflect.singular(/(database)s$/i, '\1')
inflect.uncountable('series')
inflect.human("col_rpted_bugs", "Reported bugs")
inflect.clear
inflect.plurals.should.be.empty
inflect.singulars.should.be.empty
inflect.uncountables.should.be.empty
inflect.humans.should.be.empty
end
end
end
%w(plurals singulars uncountables humans acronyms).each do |scope|
it "should clear inflections with #{scope}" do
with_dup do
MotionSupport::Inflector.inflections do |inflect|
# clear the inflections
inflect.clear(scope)
inflect.send(scope).should == []
end
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/ns_dictionary_spec.rb | spec/motion-support/ns_dictionary_spec.rb | describe "NSDictionary" do
describe "to_hash" do
before do
dict = NSMutableDictionary.alloc.init
dict.setValue('bar', forKey:'foo')
@hash = dict.to_hash
end
it "should convert NSDictionary to Hash" do
@hash.class.should == Hash
end
it "should preserve all keys" do
@hash.keys.should == ['foo']
end
it "should preserve all values" do
@hash.values.should == ['bar']
end
end
def describe_with_bang(method, &block)
bang_method = "#{method}!"
describe(method) do
it "should work for NSDictionary instances" do
block.call(method)
end
end
describe(bang_method) do
it "should work for NSDictionary instances" do
block.call(bang_method)
end
end
end
describe_with_bang "symbolize_keys" do |method|
dict = NSMutableDictionary.alloc.init
dict.setValue('bar', forKey:'foo')
dict.send(method).should == { :foo => 'bar' }
end
describe_with_bang "deep_symbolize_keys" do |method|
dict = NSMutableDictionary.alloc.init
innerDict = NSMutableDictionary.alloc.init
innerDict.setValue('foobar', forKey: 'bar')
dict.setValue(innerDict, forKey:'foo')
dict.send(method).should == {foo: {bar: 'foobar'}}
end
describe_with_bang "stringify_keys" do |method|
dict = NSMutableDictionary.alloc.init
dict.setValue('bar', forKey: :foo)
dict.send(method).should == {'foo' => 'bar'}
end
describe_with_bang "deep_stringify_keys" do |method|
dict = NSMutableDictionary.alloc.init
innerDict = NSMutableDictionary.alloc.init
innerDict.setValue('foobar', forKey: :bar)
dict.setValue(innerDict, forKey: :foo)
dict.send(method).should == {'foo' => {'bar' => 'foobar'}}
end
describe "with_indifferent_access" do
it "should work for NSDictionary instances" do
dict = NSMutableDictionary.alloc.init
dict.setValue('bar', forKey:'foo')
dict_indifferent = dict.with_indifferent_access
dict_indifferent['foo'].should == 'bar'
dict_indifferent[:foo].should == dict_indifferent['foo']
end
it "should work with nested NSDictionary instances" do
dict = NSMutableDictionary.alloc.init
dict_inner = NSMutableDictionary.alloc.init
dict_inner.setValue('value', forKey: 'key')
dict.setValue('bar', forKey:'foo')
dict.setValue(dict_inner, forKey: 'inner')
dict_indifferent = dict.with_indifferent_access
inner_indifferent = dict_indifferent['inner']
dict_indifferent[:inner].should == inner_indifferent
inner_indifferent['key'].should == dict_inner['key']
inner_indifferent[:key].should == inner_indifferent['key']
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/number_helper_spec.rb | spec/motion-support/number_helper_spec.rb | describe "NumberHelper" do
class TestClassWithInstanceNumberHelpers
include MotionSupport::NumberHelper
end
class TestClassWithClassNumberHelpers
extend MotionSupport::NumberHelper
end
before do
@instance_with_helpers = TestClassWithInstanceNumberHelpers.new
end
describe "number_to_phone" do
it "should convert number to phone" do
[@instance_with_helpers, TestClassWithClassNumberHelpers, MotionSupport::NumberHelper].each do |number_helper|
number_helper.number_to_phone(5551234).should == "555-1234"
number_helper.number_to_phone(8005551212).should == "800-555-1212"
number_helper.number_to_phone(8005551212, {:area_code => true}).should == "(800) 555-1212"
number_helper.number_to_phone("", {:area_code => true}).should == ""
number_helper.number_to_phone(8005551212, {:delimiter => " "}).should == "800 555 1212"
number_helper.number_to_phone(8005551212, {:area_code => true, :extension => 123}).should == "(800) 555-1212 x 123"
number_helper.number_to_phone(8005551212, :extension => " ").should == "800-555-1212"
number_helper.number_to_phone(5551212, :delimiter => '.').should == "555.1212"
number_helper.number_to_phone("8005551212").should == "800-555-1212"
number_helper.number_to_phone(8005551212, :country_code => 1).should == "+1-800-555-1212"
number_helper.number_to_phone(8005551212, :country_code => 1, :delimiter => '').should == "+18005551212"
number_helper.number_to_phone(225551212).should == "22-555-1212"
number_helper.number_to_phone(225551212, :country_code => 45).should == "+45-22-555-1212"
end
end
it "should return nil when given nil" do
[@instance_with_helpers, TestClassWithClassNumberHelpers, MotionSupport::NumberHelper].each do |number_helper|
number_helper.number_to_phone(nil).should.be.nil
end
end
it "should not mutate options hash" do
[@instance_with_helpers, TestClassWithClassNumberHelpers, MotionSupport::NumberHelper].each do |number_helper|
options = { 'raise' => true }
number_helper.number_to_phone(1, options)
options.should == { 'raise' => true }
end
end
it "should return non-numeric parameter unchanged" do
[@instance_with_helpers, TestClassWithClassNumberHelpers, MotionSupport::NumberHelper].each do |number_helper|
number_helper.number_to_phone("x", :country_code => 1, :extension => 123).should == "+1-x x 123"
number_helper.number_to_phone("x").should == "x"
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/duration_spec.rb | spec/motion-support/duration_spec.rb | describe "Duration" do
describe "threequals" do
it "should be a day" do
MotionSupport::Duration.should === 1.day
end
it "should not be an int" do
MotionSupport::Duration.should.not === 1.day.to_i
end
it "should not be a string" do
MotionSupport::Duration.should.not === 'foo'
end
end
describe "equals" do
it "should equal itself" do
1.day.should == 1.day
end
it "should equal integer representation" do
1.day.should == 1.day.to_i
end
it "should not equal string" do
1.day.should.not == 'foo'
end
end
describe "inspect" do
it "should convert to string representation" do
0.seconds.inspect.should == '0 seconds'
1.month.inspect.should == '1 month'
(1.month + 1.day).inspect.should == '1 month and 1 day'
(6.months - 2.days).inspect.should == '6 months and -2 days'
10.seconds.inspect.should == '10 seconds'
(10.years + 2.months + 1.day).inspect.should == '10 years, 2 months, and 1 day'
1.week.inspect.should == '7 days'
1.fortnight.inspect.should == '14 days'
end
end
describe "arithmetic" do
it "should not break when subtracting time from itself" do
lambda { Date.today - Date.today }.should.not.raise
end
it "should add with time" do
(1.second + 1).should == 1 + 1.second
end
def test_plus_with_time
assert_equal 1 + 1.second, 1.second + 1, "Duration + Numeric should == Numeric + Duration"
end
end
describe "fractions" do
describe "days" do
it "should support fractional days" do
1.5.weeks.should == (86400 * 7) * 1.5
1.7.weeks.should == (86400 * 7) * 1.7
end
it "should support since" do
t = Date.new(1982,6,15)
1.5.days.since(t).should == 36.hours.since(t)
end
it "should support ago" do
t = Date.new(1982,6,15)
1.5.days.ago(t).should == 36.hours.ago(t)
end
end
describe "weeks" do
it "should support fractional weeks" do
1.5.days.should == 86400 * 1.5
1.7.days.should == 86400 * 1.7
end
it "should support since" do
t = Date.new(1982,6,15)
1.5.weeks.since(t).should == (7 * 36).hours.since(t)
end
it "should support ago" do
t = Date.new(1982,6,15)
1.5.weeks.ago(t).should == (7 * 36).hours.ago(t)
end
end
end
describe "delegation" do
it "should delegate with block" do
counter = 0
lambda { 1.minute.times { counter += 1 } }.should.not.raise
counter.should == 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/hash_with_indifferent_access_spec.rb | spec/motion-support/hash_with_indifferent_access_spec.rb | class IndifferentHash < MotionSupport::HashWithIndifferentAccess
end
class SubclassingArray < Array
end
class SubclassingHash < Hash
end
class NonIndifferentHash < Hash
def nested_under_indifferent_access
self
end
end
describe "HashWithIndifferentAccess" do
before do
@strings = { 'a' => 1, 'b' => 2 }
@nested_strings = { 'a' => { 'b' => { 'c' => 3 } } }
@symbols = { :a => 1, :b => 2 }
@nested_symbols = { :a => { :b => { :c => 3 } } }
@mixed = { :a => 1, 'b' => 2 }
@nested_mixed = { 'a' => { :b => { 'c' => 3 } } }
@fixnums = { 0 => 1, 1 => 2 }
@nested_fixnums = { 0 => { 1 => { 2 => 3} } }
@illegal_symbols = { [] => 3 }
@nested_illegal_symbols = { [] => { [] => 3} }
@upcase_strings = { 'A' => 1, 'B' => 2 }
@nested_upcase_strings = { 'A' => { 'B' => { 'C' => 3 } } }
end
describe "constructor" do
it "should construct hash" do
hash = HashWithIndifferentAccess[:foo, 1]
hash[:foo].should == 1
hash['foo'].should == 1
hash[:foo] = 3
hash[:foo].should == 3
hash['foo'].should == 3
end
it "should return duplicate for with_indifferent_access" do
hash_wia = HashWithIndifferentAccess.new
hash_wia.with_indifferent_access.should == hash_wia
hash_wia.with_indifferent_access.object_id.should.not == hash_wia.object_id
end
end
describe "conversion" do
it "should not convert other key objects" do
original = {Object.new => 2, 1 => 2, [] => true}
indiff = original.with_indifferent_access
indiff.keys.any? {|k| k.kind_of? String}.should == false
end
end
describe "symbolize_keys" do
it "should return normal hash instance" do
@symbols.with_indifferent_access.symbolize_keys.should.is_a Hash
end
it "should symbolize keys" do
@symbols.with_indifferent_access.symbolize_keys.should == @symbols
@strings.with_indifferent_access.symbolize_keys.should == @symbols
@mixed.with_indifferent_access.symbolize_keys.should == @symbols
end
it "should preserve keys that can't be symbolized" do
@illegal_symbols.with_indifferent_access.symbolize_keys.should == @illegal_symbols
lambda { @illegal_symbols.with_indifferent_access.dup.symbolize_keys! }.should.raise NoMethodError
end
it "should preserve Fixnum keys" do
@fixnums.with_indifferent_access.symbolize_keys.should == @fixnums
lambda { @fixnums.with_indifferent_access.dup.symbolize_keys! }.should.raise NoMethodError
end
it "should preserve hash" do
h = HashWithIndifferentAccess.new
h['first'] = 1
h = h.symbolize_keys
h[:first].should == 1
end
end
describe "symbolize_keys!" do
it "should not work" do
lambda { @symbols.with_indifferent_access.dup.symbolize_keys! }.should.raise NoMethodError
lambda { @strings.with_indifferent_access.dup.symbolize_keys! }.should.raise NoMethodError
lambda { @mixed.with_indifferent_access.dup.symbolize_keys! }.should.raise NoMethodError
end
end
describe "deep_symbolize_keys" do
it "should return normal hash instance" do
@symbols.with_indifferent_access.deep_symbolize_keys.should.is_a Hash
end
it "should deep symbolize keys" do
@nested_symbols.with_indifferent_access.deep_symbolize_keys.should == @nested_symbols
@nested_strings.with_indifferent_access.deep_symbolize_keys.should == @nested_symbols
@nested_mixed.with_indifferent_access.deep_symbolize_keys.should == @nested_symbols
end
it "should preserve keys that can't be symbolized" do
@nested_illegal_symbols.with_indifferent_access.deep_symbolize_keys.should == @nested_illegal_symbols
lambda { @nested_illegal_symbols.with_indifferent_access.deep_dup.deep_symbolize_keys! }.should.raise NoMethodError
end
it "should preserve Fixnum keys for" do
@nested_fixnums.with_indifferent_access.deep_symbolize_keys.should == @nested_fixnums
lambda { @nested_fixnums.with_indifferent_access.deep_dup.deep_symbolize_keys! }.should.raise NoMethodError
end
it "should preserve hash" do
h = HashWithIndifferentAccess.new
h['first'] = 1
h = h.deep_symbolize_keys
h[:first].should == 1
end
end
describe "deep_symbolize_keys!" do
it "should not work" do
lambda { @nested_symbols.with_indifferent_access.deep_dup.deep_symbolize_keys! }.should.raise NoMethodError
lambda { @nested_strings.with_indifferent_access.deep_dup.deep_symbolize_keys! }.should.raise NoMethodError
lambda { @nested_mixed.with_indifferent_access.deep_dup.deep_symbolize_keys! }.should.raise NoMethodError
end
end
describe "stringify_keys" do
it "should return hash with indifferent access" do
@symbols.with_indifferent_access.stringify_keys.should.is_a MotionSupport::HashWithIndifferentAccess
end
it "should stringify keys" do
@symbols.with_indifferent_access.stringify_keys.should == @strings
@strings.with_indifferent_access.stringify_keys.should == @strings
@mixed.with_indifferent_access.stringify_keys.should == @strings
end
it "should preserve hash" do
h = HashWithIndifferentAccess.new
h[:first] = 1
h = h.stringify_keys
h['first'].should == 1
end
end
describe "deep_stringify_keys" do
it "should return hash with indifferent access" do
@nested_symbols.with_indifferent_access.deep_stringify_keys.should.is_a MotionSupport::HashWithIndifferentAccess
end
it "should deep stringify keys" do
@nested_symbols.with_indifferent_access.deep_stringify_keys.should == @nested_strings
@nested_strings.with_indifferent_access.deep_stringify_keys.should == @nested_strings
@nested_mixed.with_indifferent_access.deep_stringify_keys.should == @nested_strings
end
it "should preserve hash" do
h = HashWithIndifferentAccess.new
h[:first] = 1
h = h.deep_stringify_keys
h['first'].should == 1
end
end
describe "stringify_keys!" do
it "should return hash with indifferent access" do
@symbols.with_indifferent_access.dup.stringify_keys!.should.is_a MotionSupport::HashWithIndifferentAccess
end
it "should stringify keys (for dupped instance)" do
@symbols.with_indifferent_access.dup.stringify_keys!.should == @strings
@strings.with_indifferent_access.dup.stringify_keys!.should == @strings
@mixed.with_indifferent_access.dup.stringify_keys!.should == @strings
end
end
describe "deep_stringify_keys!" do
it "should return hash with indifferent access" do
@nested_symbols.with_indifferent_access.dup.deep_stringify_keys!.should.is_a MotionSupport::HashWithIndifferentAccess
end
it "should stringify keys (for deep_dupped instance)" do
@nested_symbols.with_indifferent_access.deep_dup.deep_stringify_keys!.should == @nested_strings
@nested_strings.with_indifferent_access.deep_dup.deep_stringify_keys!.should == @nested_strings
@nested_mixed.with_indifferent_access.deep_dup.deep_stringify_keys!.should == @nested_strings
end
end
describe "reading" do
it "should read string keys with symbol access" do
hash = HashWithIndifferentAccess.new
hash["a"] = 1
hash["b"] = true
hash["c"] = false
hash["d"] = nil
hash[:a].should == 1
hash[:b].should == true
hash[:c].should == false
hash[:d].should == nil
hash[:e].should == nil
end
it "should read string keys with symbol access and nonnil default" do
hash = HashWithIndifferentAccess.new(1)
hash["a"] = 1
hash["b"] = true
hash["c"] = false
hash["d"] = nil
hash[:a].should == 1
hash[:b].should == true
hash[:c].should == false
hash[:d].should == nil
hash[:e].should == 1
end
it "should return the same object that is stored" do
hash = HashWithIndifferentAccess.new {|h, k| h[k] = []}
hash[:a] << 1
hash[:a].should == [1]
end
end
describe "writing" do
it "should write with symbols and strings" do
hash = HashWithIndifferentAccess.new
hash[:a] = 1
hash['b'] = 2
hash['a'].should == 1
hash['b'].should == 2
hash[:a].should == 1
hash[:b].should == 2
end
it "should not symbolize or stringify numbers" do
hash = HashWithIndifferentAccess.new
hash[3] = 3
hash[3].should == 3
hash[:'3'].should == nil
hash['3'].should == nil
end
it "should store values" do
hash = HashWithIndifferentAccess.new
hash.store(:test1, 1)
hash.store('test1', 11)
hash[:test2] = 2
hash['test2'] = 22
expected = { "test1" => 11, "test2" => 22 }
hash.should == expected
end
end
describe "update" do
before do
@hash = HashWithIndifferentAccess.new
@hash[:a] = 'a'
@hash['b'] = 'b'
end
it "should update with string keys" do
updated_with_strings = @hash.update(@strings)
updated_with_strings[:a].should == 1
updated_with_strings['a'].should == 1
updated_with_strings['b'].should == 2
updated_with_strings.keys.size.should == 2
end
it "should update with symbol keys" do
updated_with_symbols = @hash.update(@symbols)
updated_with_symbols[:a].should == 1
updated_with_symbols['b'].should == 2
updated_with_symbols[:b].should == 2
updated_with_symbols.keys.size.should == 2
end
it "should update with mixed keys" do
updated_with_mixed = @hash.update(@mixed)
updated_with_mixed[:a].should == 1
updated_with_mixed['b'].should == 2
updated_with_mixed.keys.size.should == 2
end
end
describe "merge" do
describe "without block" do
before do
@hash = HashWithIndifferentAccess.new
@hash[:a] = 'failure'
@hash['b'] = 'failure'
@other = { 'a' => 1, :b => 2 }
end
it "should merge with mixed hash" do
merged = @hash.merge(@other)
merged.class.should == HashWithIndifferentAccess
merged[:a].should == 1
merged['b'].should == 2
end
it "should have the same effect inplace when updating" do
@hash.update(@other)
@hash[:a].should == 1
@hash['b'].should == 2
end
end
describe "with block" do
before do
@hash = HashWithIndifferentAccess.new
@hash[:a] = 1
@hash['b'] = 3
end
it "should merge with block" do
other = { 'a' => 4, :b => 2, 'c' => 10 }
merged = @hash.merge(other) { |key, old, new| old > new ? old : new }
merged.class.should == HashWithIndifferentAccess
merged[:a].should == 4
merged['b'].should == 3
merged[:c].should == 10
end
it "should merge with block one more time" do
other_indifferent = HashWithIndifferentAccess.new('a' => 9, :b => 2)
merged = @hash.merge(other_indifferent) { |key, old, new| old + new }
merged.class.should == HashWithIndifferentAccess
merged[:a].should == 10
merged[:b].should == 5
end
end
end
describe "reverse_merge" do
it "should reverse merge" do
hash = HashWithIndifferentAccess.new('some' => 'value', 'other' => 'value')
hash.reverse_merge!(:some => 'noclobber', :another => 'clobber')
hash[:some].should == 'value'
hash[:another].should == 'clobber'
end
end
describe "replace" do
before do
@hash = HashWithIndifferentAccess.new
@hash[:a] = 42
@replaced = @hash.replace(b: 12)
end
it "should replace with regular hash" do
@hash.key?('b').should == true
@hash.key?(:a).should == false
@hash[:b].should == 12
end
it "should be the same class" do
@replaced.class.should == HashWithIndifferentAccess
end
it "should be the same object" do
@hash.object_id.should == @replaced.object_id
end
end
describe "delete" do
before do
@hash = { :a => 'foo' }.with_indifferent_access
end
it "should delete with symbol keys" do
@hash.delete(:a).should == 'foo'
@hash.delete(:a).should == nil
end
it "should delete with string keys" do
@hash.delete('a').should == 'foo'
@hash.delete('a').should == nil
end
end
describe "to_hash" do
it "should return a hash with string keys" do
@mixed.with_indifferent_access.to_hash.should == @strings
end
it "should preserve the default value" do
mixed_with_default = @mixed.dup
mixed_with_default.default = '1234'
roundtrip = mixed_with_default.with_indifferent_access.to_hash
roundtrip.should == @strings
roundtrip.default.should == '1234'
end
end
describe "to_options" do
it "should preserve hash" do
h = HashWithIndifferentAccess.new
h['first'] = 1
h.to_options!
h['first'].should == 1
end
end
describe "nesting" do
it "should preserve hash subclasses in nested hashes" do
foo = { "foo" => SubclassingHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
foo["foo"].should.is_a MotionSupport::HashWithIndifferentAccess
foo = { "foo" => NonIndifferentHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
foo["foo"].should.is_a NonIndifferentHash
foo = { "foo" => IndifferentHash.new.tap { |h| h["bar"] = "baz" } }.with_indifferent_access
foo["foo"].should.is_a IndifferentHash
end
it "should deep apply indifferent access" do
hash = { "urls" => { "url" => [ { "address" => "1" }, { "address" => "2" } ] }}.with_indifferent_access
hash[:urls][:url].first[:address].should == "1"
end
it "should preserve array subclass when value is array" do
array = SubclassingArray.new
array << { "address" => "1" }
hash = { "urls" => { "url" => array }}.with_indifferent_access
hash[:urls][:url].class.should == SubclassingArray
end
it "should preserve array class when hash value is frozen array" do
array = SubclassingArray.new
array << { "address" => "1" }
hash = { "urls" => { "url" => array.freeze }}.with_indifferent_access
hash[:urls][:url].class.should == SubclassingArray
end
it "should allow indifferent access on sub hashes" do
h = {'user' => {'id' => 5}}.with_indifferent_access
['user', :user].each { |user| [:id, 'id'].each { |id| h[user][id].should == 5 } }
h = {:user => {:id => 5}}.with_indifferent_access
['user', :user].each { |user| [:id, 'id'].each { |id| h[user][id].should == 5 } }
end
end
describe "dup" do
it "should preserve default value" do
h = HashWithIndifferentAccess.new
h.default = '1234'
h.dup.default.should == h.default
end
it "should preserve class for subclasses" do
h = IndifferentHash.new
h.dup.class.should == h.class
end
end
describe "deep_merge" do
it "should deep merge" do
hash_1 = HashWithIndifferentAccess.new({ :a => "a", :b => "b", :c => { :c1 => "c1", :c2 => "c2", :c3 => { :d1 => "d1" } } })
hash_2 = HashWithIndifferentAccess.new({ :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } })
hash_3 = { :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } }
expected = { "a" => 1, "b" => "b", "c" => { "c1" => 2, "c2" => "c2", "c3" => { "d1" => "d1", "d2" => "d2" } } }
hash_1.deep_merge(hash_2).should == expected
hash_1.deep_merge(hash_3).should == expected
hash_1.deep_merge!(hash_2)
hash_1.should == expected
end
end
describe "slice" do
it "should slice with indiffent keys" do
original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access
expected = { :a => 'x', :b => 'y' }.with_indifferent_access
[['a', 'b'], [:a, :b]].each do |keys|
# Should return a new hash with only the given keys.
original.slice(*keys).should == expected
original.should.not == expected
end
end
it "should silce in place" do
original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access
expected = { :c => 10 }.with_indifferent_access
[['a', 'b'], [:a, :b]].each do |keys|
# Should replace the hash with only the given keys.
copy = original.dup
copy.slice!(*keys).should == expected
end
end
it "should slice sliced hash" do
original = {'login' => 'bender', 'password' => 'shiny', 'stuff' => 'foo'}
original = original.with_indifferent_access
slice = original.slice(:login, :password)
slice[:login].should == 'bender'
slice['login'].should == 'bender'
end
end
describe "extract!" do
it "should extract values with indifferent keys" do
original = {:a => 1, 'b' => 2, :c => 3, 'd' => 4}.with_indifferent_access
expected = {:a => 1, :b => 2}.with_indifferent_access
remaining = {:c => 3, :d => 4}.with_indifferent_access
[['a', 'b'], [:a, :b]].each do |keys|
copy = original.dup
copy.extract!(*keys).should == expected
copy.should == remaining
end
end
end
describe "default value" do
it "should use the default value for unknown key" do
hash_wia = HashWithIndifferentAccess.new(3)
hash_wia[:new_key].should == 3
end
it "should use default value if no key is supplied" do
hash_wia = HashWithIndifferentAccess.new(3)
hash_wia.default.should == 3
end
it "should nil if no default value is supplied" do
hash_wia = HashWithIndifferentAccess.new
hash_wia.default.should.be.nil
end
it "should copy the default value when converting to hash with indifferent access" do
hash = Hash.new(3)
hash_wia = hash.with_indifferent_access
hash_wia.default.should == 3
end
end
describe "fetch" do
it "should fetch with indifferent access" do
@strings = @strings.with_indifferent_access
@strings.fetch('a').should == 1
@strings.fetch(:a.to_s).should == 1
@strings.fetch(:a).should == 1
end
end
describe "values_at" do
it "should return values for multiple keys" do
@strings = @strings.with_indifferent_access
@symbols = @symbols.with_indifferent_access
@mixed = @mixed.with_indifferent_access
@strings.values_at('a', 'b').should == [1, 2]
@strings.values_at(:a, :b).should == [1, 2]
@symbols.values_at('a', 'b').should == [1, 2]
@symbols.values_at(:a, :b).should == [1, 2]
@mixed.values_at('a', 'b').should == [1, 2]
@mixed.values_at(:a, :b).should == [1, 2]
end
end
describe "misc methods" do
it "should work as expected" do
@strings = @strings.with_indifferent_access
@symbols = @symbols.with_indifferent_access
@mixed = @mixed.with_indifferent_access
hashes = { :@strings => @strings, :@symbols => @symbols, :@mixed => @mixed }
method_map = { :'[]' => 1, :fetch => 1, :values_at => [1],
:has_key? => true, :include? => true, :key? => true,
:member? => true }
hashes.each do |name, hash|
method_map.sort_by { |m| m.to_s }.each do |meth, expected|
hash.__send__(meth, 'a').should == expected
hash.__send__(meth, :a).should == expected
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/callback_spec.rb | spec/motion-support/callback_spec.rb | module CallbacksTest
class Record
include MotionSupport::Callbacks
define_callbacks :save
def self.before_save(*filters, &blk)
set_callback(:save, :before, *filters, &blk)
end
def self.after_save(*filters, &blk)
set_callback(:save, :after, *filters, &blk)
end
class << self
def callback_symbol(callback_method)
method_name = :"#{callback_method}_method"
define_method(method_name) do
history << [callback_method, :symbol]
end
method_name
end
def callback_proc(callback_method)
Proc.new { |model| model.history << [callback_method, :proc] }
end
def callback_object(callback_method)
klass = Class.new
klass.send(:define_method, callback_method) do |model|
model.history << [:"#{callback_method}_save", :object]
end
klass.new
end
end
def history
@history ||= []
end
end
class Person < Record
[:before_save, :after_save].each do |callback_method|
callback_method_sym = callback_method.to_sym
send(callback_method, callback_symbol(callback_method_sym))
send(callback_method, callback_proc(callback_method_sym))
send(callback_method, callback_object(callback_method_sym.to_s.gsub(/_save/, '')))
send(callback_method) { |model| model.history << [callback_method_sym, :block] }
end
def save
run_callbacks :save
end
end
class PersonSkipper < Person
skip_callback :save, :before, :before_save_method, :if => :yes
skip_callback :save, :after, :before_save_method, :unless => :yes
skip_callback :save, :after, :before_save_method, :if => :no
skip_callback :save, :before, :before_save_method, :unless => :no
def yes; true; end
def no; false; end
end
class ParentController
include MotionSupport::Callbacks
define_callbacks :dispatch
set_callback :dispatch, :before, :log, :unless => proc {|c| c.action_name == :index || c.action_name == :show }
set_callback :dispatch, :after, :log2
attr_reader :action_name, :logger
def initialize(action_name)
@action_name, @logger = action_name, []
end
def log
@logger << action_name
end
def log2
@logger << action_name
end
def dispatch
run_callbacks :dispatch do
@logger << "Done"
end
self
end
end
class Child < ParentController
skip_callback :dispatch, :before, :log, :if => proc {|c| c.action_name == :update}
skip_callback :dispatch, :after, :log2
end
class OneTimeCompile < Record
@@starts_true, @@starts_false = true, false
def initialize
super
end
before_save Proc.new {|r| r.history << [:before_save, :starts_true, :if] }, :if => :starts_true
before_save Proc.new {|r| r.history << [:before_save, :starts_false, :if] }, :if => :starts_false
before_save Proc.new {|r| r.history << [:before_save, :starts_true, :unless] }, :unless => :starts_true
before_save Proc.new {|r| r.history << [:before_save, :starts_false, :unless] }, :unless => :starts_false
def starts_true
if @@starts_true
@@starts_true = false
return true
end
@@starts_true
end
def starts_false
unless @@starts_false
@@starts_false = true
return false
end
@@starts_false
end
def save
run_callbacks :save
end
end
class AfterSaveConditionalPerson < Record
after_save Proc.new { |r| r.history << [:after_save, :string1] }
after_save Proc.new { |r| r.history << [:after_save, :string2] }
def save
run_callbacks :save
end
end
class ConditionalPerson < Record
# proc
before_save Proc.new { |r| r.history << [:before_save, :proc] }, :if => Proc.new { |r| true }
before_save Proc.new { |r| r.history << "b00m" }, :if => Proc.new { |r| false }
before_save Proc.new { |r| r.history << [:before_save, :proc] }, :unless => Proc.new { |r| false }
before_save Proc.new { |r| r.history << "b00m" }, :unless => Proc.new { |r| true }
# symbol
before_save Proc.new { |r| r.history << [:before_save, :symbol] }, :if => :yes
before_save Proc.new { |r| r.history << "b00m" }, :if => :no
before_save Proc.new { |r| r.history << [:before_save, :symbol] }, :unless => :no
before_save Proc.new { |r| r.history << "b00m" }, :unless => :yes
# string
before_save Proc.new { |r| r.history << [:before_save, :string] }, :if => 'yes'
before_save Proc.new { |r| r.history << "b00m" }, :if => 'no'
before_save Proc.new { |r| r.history << [:before_save, :string] }, :unless => 'no'
before_save Proc.new { |r| r.history << "b00m" }, :unless => 'yes'
# Combined if and unless
before_save Proc.new { |r| r.history << [:before_save, :combined_symbol] }, :if => :yes, :unless => :no
before_save Proc.new { |r| r.history << "b00m" }, :if => :yes, :unless => :yes
def yes; true; end
def other_yes; true; end
def no; false; end
def other_no; false; end
def save
run_callbacks :save
end
end
class CleanPerson < ConditionalPerson
reset_callbacks :save
end
class MySuper
include MotionSupport::Callbacks
define_callbacks :save
end
class AroundPerson < MySuper
attr_reader :history
set_callback :save, :before, :nope, :if => :no
set_callback :save, :before, :nope, :unless => :yes
set_callback :save, :after, :tweedle
set_callback :save, :before, "tweedle_dee"
set_callback :save, :before, proc {|m| m.history << "yup" }
set_callback :save, :before, :nope, :if => proc { false }
set_callback :save, :before, :nope, :unless => proc { true }
set_callback :save, :before, :yup, :if => proc { true }
set_callback :save, :before, :yup, :unless => proc { false }
set_callback :save, :around, :tweedle_dum
set_callback :save, :around, :w0tyes, :if => :yes
set_callback :save, :around, :w0tno, :if => :no
set_callback :save, :around, :tweedle_deedle
def no; false; end
def yes; true; end
def nope
@history << "boom"
end
def yup
@history << "yup"
end
def w0tyes
@history << "w0tyes before"
yield
@history << "w0tyes after"
end
def w0tno
@history << "boom"
yield
end
def tweedle_dee
@history << "tweedle dee"
end
def tweedle_dum
@history << "tweedle dum pre"
yield
@history << "tweedle dum post"
end
def tweedle
@history << "tweedle"
end
def tweedle_deedle
@history << "tweedle deedle pre"
yield
@history << "tweedle deedle post"
end
def initialize
@history = []
end
def save
run_callbacks :save do
@history << "running"
end
end
end
class AroundPersonResult < MySuper
attr_reader :result
set_callback :save, :after, :tweedle_1
set_callback :save, :around, :tweedle_dum
set_callback :save, :after, :tweedle_2
def tweedle_dum
@result = yield
end
def tweedle_1
:tweedle_1
end
def tweedle_2
:tweedle_2
end
def save
run_callbacks :save do
:running
end
end
end
class HyphenatedCallbacks
include MotionSupport::Callbacks
define_callbacks :save
attr_reader :stuff
set_callback :save, :before, :action, :if => :yes
def yes() true end
def action
@stuff = "ACTION"
end
def save
run_callbacks :save do
@stuff
end
end
end
module ExtendModule
def self.extended(base)
base.class_eval do
set_callback :save, :before, :record3
end
end
def record3
@recorder << 3
end
end
module IncludeModule
def self.included(base)
base.class_eval do
set_callback :save, :before, :record2
end
end
def record2
@recorder << 2
end
end
class ExtendCallbacks
include MotionSupport::Callbacks
define_callbacks :save
set_callback :save, :before, :record1
include IncludeModule
def save
run_callbacks :save
end
attr_reader :recorder
def initialize
@recorder = []
end
private
def record1
@recorder << 1
end
end
class CallbackTerminator
include MotionSupport::Callbacks
define_callbacks :save, :terminator => lambda { |result| result == :halt }
set_callback :save, :before, :first
set_callback :save, :before, :second
set_callback :save, :around, :around_it
set_callback :save, :before, :third
set_callback :save, :after, :first
set_callback :save, :around, :around_it
set_callback :save, :after, :second
set_callback :save, :around, :around_it
set_callback :save, :after, :third
attr_reader :history, :saved, :halted
def initialize
@history = []
end
def around_it
@history << "around1"
yield
@history << "around2"
end
def first
@history << "first"
end
def second
@history << "second"
:halt
end
def third
@history << "third"
end
def save
run_callbacks :save do
@saved = true
end
end
def halted_callback_hook(filter)
@halted = filter
end
end
class CallbackObject
def before(caller)
caller.record << "before"
end
def before_save(caller)
caller.record << "before save"
end
def around(caller)
caller.record << "around before"
yield
caller.record << "around after"
end
end
class UsingObjectBefore
include MotionSupport::Callbacks
define_callbacks :save
set_callback :save, :before, CallbackObject.new
attr_accessor :record
def initialize
@record = []
end
def save
run_callbacks :save do
@record << "yielded"
end
end
end
class UsingObjectAround
include MotionSupport::Callbacks
define_callbacks :save
set_callback :save, :around, CallbackObject.new
attr_accessor :record
def initialize
@record = []
end
def save
run_callbacks :save do
@record << "yielded"
end
end
end
class CustomScopeObject
include MotionSupport::Callbacks
define_callbacks :save, :scope => [:kind, :name]
set_callback :save, :before, CallbackObject.new
attr_accessor :record
def initialize
@record = []
end
def save
run_callbacks :save do
@record << "yielded"
"CallbackResult"
end
end
end
class OneTwoThreeSave
include MotionSupport::Callbacks
define_callbacks :save
attr_accessor :record
def initialize
@record = []
end
def save
run_callbacks :save do
@record << "yielded"
end
end
def first
@record << "one"
end
def second
@record << "two"
end
def third
@record << "three"
end
end
class DuplicatingCallbacks < OneTwoThreeSave
set_callback :save, :before, :first, :second
set_callback :save, :before, :first, :third
end
class DuplicatingCallbacksInSameCall < OneTwoThreeSave
set_callback :save, :before, :first, :second, :first, :third
end
class WriterSkipper < Person
attr_accessor :age
skip_callback :save, :before, :before_save_method, :if => lambda { |obj| obj.age > 21 }
end
end
describe "Callbacks" do
describe "around filter" do
it "should optimize on first compile" do
around = CallbacksTest::OneTimeCompile.new
around.save
around.history.should == [
[:before_save, :starts_true, :if],
[:before_save, :starts_true, :unless]
]
end
it "should call nested around filter" do
around = CallbacksTest::AroundPerson.new
around.save
around.history.should == [
"tweedle dee",
"yup", "yup",
"tweedle dum pre",
"w0tyes before",
"tweedle deedle pre",
"running",
"tweedle deedle post",
"w0tyes after",
"tweedle dum post",
"tweedle"
]
end
it "should return result" do
around = CallbacksTest::AroundPersonResult.new
around.save
around.result.should == :running
end
end
describe "after save" do
it "should run in reverse order" do
person = CallbacksTest::AfterSaveConditionalPerson.new
person.save
person.history.should == [
[:after_save, :string2],
[:after_save, :string1]
]
end
end
describe "skip callbacks" do
it "should skip callback" do
person = CallbacksTest::PersonSkipper.new
person.history.should == []
person.save
person.history.should == [
[:before_save, :proc],
[:before_save, :object],
[:before_save, :block],
[:after_save, :block],
[:after_save, :object],
[:after_save, :proc],
[:after_save, :symbol]
]
end
it "should not skip if condition is not met" do
writer = CallbacksTest::WriterSkipper.new
writer.age = 18
writer.history.should == []
writer.save
writer.history.should == [
[:before_save, :symbol],
[:before_save, :proc],
[:before_save, :object],
[:before_save, :block],
[:after_save, :block],
[:after_save, :object],
[:after_save, :proc],
[:after_save, :symbol]
]
end
end
it "should run callbacks" do
person = CallbacksTest::Person.new
person.history.should == []
person.save
person.history.should == [
[:before_save, :symbol],
[:before_save, :proc],
[:before_save, :object],
[:before_save, :block],
[:after_save, :block],
[:after_save, :object],
[:after_save, :proc],
[:after_save, :symbol]
]
end
it "should run conditional callbacks" do
person = CallbacksTest::ConditionalPerson.new
person.save
person.history.should == [
[:before_save, :proc],
[:before_save, :proc],
[:before_save, :symbol],
[:before_save, :symbol],
[:before_save, :string],
[:before_save, :string],
[:before_save, :combined_symbol],
]
end
it "should return result" do
obj = CallbacksTest::HyphenatedCallbacks.new
obj.save
obj.stuff.should == "ACTION"
end
describe "reset_callbacks" do
it "should reset callbacks" do
person = CallbacksTest::CleanPerson.new
person.save
person.history.should == []
end
end
describe "callback object" do
it "should use callback object for before callback" do
u = CallbacksTest::UsingObjectBefore.new
u.save
u.record.should == ["before", "yielded"]
end
it "should use callback object for around callback" do
u = CallbacksTest::UsingObjectAround.new
u.save
u.record.should == ["around before", "yielded", "around after"]
end
describe "custom scope" do
it "should use custom scope" do
u = CallbacksTest::CustomScopeObject.new
u.save
u.record.should == ["before save", "yielded"]
end
it "should return block result" do
u = CallbacksTest::CustomScopeObject.new
u.save.should == "CallbackResult"
end
end
end
describe "callback terminator" do
it "should terminate" do
terminator = CallbacksTest::CallbackTerminator.new
terminator.save
terminator.history.should == ["first", "second", "third", "second", "first"]
end
it "should invoke hook" do
terminator = CallbacksTest::CallbackTerminator.new
terminator.save
terminator.halted.should == ":second"
end
it "should never call block if terminated" do
obj = CallbacksTest::CallbackTerminator.new
obj.save
obj.saved.should.be.nil
end
end
describe "extending object" do
it "should work with extending object" do
model = CallbacksTest::ExtendCallbacks.new.extend CallbacksTest::ExtendModule
model.save
model.recorder.should == [1, 2, 3]
end
end
describe "exclude duplicates" do
it "should exclude duplicates in separate calls" do
model = CallbacksTest::DuplicatingCallbacks.new
model.save
model.record.should == ["two", "one", "three", "yielded"]
end
it "should exclude duplicates in one call" do
model = CallbacksTest::DuplicatingCallbacksInSameCall.new
model.save
model.record.should == ["two", "one", "three", "yielded"]
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/ns_string_spec.rb | spec/motion-support/ns_string_spec.rb | describe "NSString" do
before do
@string = NSString.stringWithString("ruby_motion")
end
describe "to_s" do
it "should convert NSDictionary to Hash" do
@string.to_s.class.should == String
end
it "should preserve the value" do
@string.to_s.should == @string
end
end
describe "at" do
it "should return character at NSString position" do
@string.at(0).should == 'r'
end
end
describe "blank?" do
it "should be true for empty NSString" do
NSString.stringWithString("").blank?.should == true
end
it "should be false for non-empty NSString" do
@string.blank?.should == false
end
end
describe "camelize" do
it "should camelize NSString" do
@string.camelize.should == "RubyMotion"
end
end
describe "classify" do
it "should classify NSString" do
@string.classify.should == "RubyMotion"
end
end
describe "constantize" do
it "should constantize NSString" do
NSString.stringWithString("Object").constantize.should == Object
end
end
describe "dasherize" do
it "should dasherize NSString" do
@string.dasherize.should == "ruby-motion"
end
end
describe "deconstantize" do
it "should deconstantize NSString" do
NSString.stringWithString("Ruby::Motion").deconstantize.should == "Ruby"
end
end
describe "demodulize" do
it "should demodulize NSString" do
NSString.stringWithString("Ruby::Motion").demodulize.should == "Motion"
end
end
describe "exclude?" do
it "should return true if NSString excludes substring" do
@string.exclude?("foo").should == true
@string.exclude?("ruby").should == false
end
end
describe "first" do
it "should return first character NSString" do
@string.first.should == "r"
end
end
describe "foreign_key" do
it "should return NSString" do
@string.foreign_key.should == "ruby_motion_id"
end
end
describe "from" do
it "should return substring of NSString starting at position" do
@string.from(5).should == "motion"
end
end
describe "humanize" do
it "should humanize NSString" do
@string.humanize.should == "Ruby motion"
end
end
describe "indent" do
it "should indent NSString" do
@string.indent(2).should == " ruby_motion"
end
end
describe "indent!" do
it "should indent NSString in place" do
@string.indent!(2).should == " ruby_motion"
end
end
describe "last" do
it "should return last character of NSString" do
@string.last.should == "n"
end
end
describe "pluralize" do
it "should pluralize NSString" do
NSString.stringWithString("thing").pluralize.should == "things"
end
end
describe "safe_constantize" do
it "should safe_constantize NSString" do
NSString.stringWithString("Object").safe_constantize.should == Object
end
end
describe "singularize" do
it "should singularize NSString" do
NSString.stringWithString("things").singularize.should == "thing"
end
end
describe "squish" do
it "should squish NSString" do
NSString.stringWithString(" ruby\n motion").squish.should == "ruby motion"
end
end
describe "squish!" do
it "should squish NSString in place" do
NSString.stringWithString(" ruby\n motion").squish!.should == "ruby motion"
end
end
describe "strip_heredoc" do
it "should strip heredoc NSString" do
NSString.stringWithString(" ruby\n motion").strip_heredoc.should == "ruby\nmotion"
end
end
describe "tableize" do
it "should tableize NSString" do
@string.tableize.should == "ruby_motions"
end
end
describe "titleize" do
it "should titleize NSString" do
@string.titleize.should == "Ruby Motion"
end
end
describe "to" do
it "should return substring of NSString up to position" do
@string.to(3).should == "ruby"
end
end
describe "truncate" do
it "should truncate NSString" do
@string.truncate(5).should == "ru..."
end
end
describe "underscore" do
it "should underscore NSString" do
NSString.stringWithString("RubyMotion").underscore.should == "ruby_motion"
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/string_spec.rb | spec/motion-support/core_ext/string_spec.rb | describe "string" do
describe "constantize" do
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
it "should lookup nested constant" do
"Ace::Base::Case".constantize.should == Ace::Base::Case
end
it "should lookup nested absolute constant" do
"::Ace::Base::Case".constantize.should == Ace::Base::Case
end
it "should lookup nested inherited constant" do
"Ace::Base::Fase::Dice".constantize.should == Ace::Base::Fase::Dice
end
it "should lookup nested included constant" do
"Ace::Gas::Case".constantize.should == Ace::Gas::Case
end
it "should lookup nested constant included into Object" do
"Case::Dice".constantize.should == Case::Dice
end
it "should lookup nested absolute constant included into Object" do
"Object::Case::Dice".constantize.should == Case::Dice
end
it "should lookup constant" do
"String".constantize.should == String
end
it "should lookup absolute constant" do
"::Ace".constantize.should == Ace
end
it "should return Object for empty string" do
"".constantize.should == Object
end
it "should return Object for double colon" do
"::".constantize.should == Object
end
it "should raise NameError for unknown constant" do
lambda { "UnknownClass".constantize }.should.raise NameError
end
it "should raise NameError for unknown nested constant" do
lambda { "UnknownClass::Ace".constantize }.should.raise NameError
lambda { "UnknownClass::Ace::Base".constantize }.should.raise NameError
end
it "should raise NameError for invalid string" do
lambda { "An invalid string".constantize }.should.raise NameError
lambda { "InvalidClass\n".constantize }.should.raise NameError
end
it "should raise NameError for nested unknown constant in known constant" do
lambda { "Ace::ConstantizeTestCases".constantize }.should.raise NameError
lambda { "Ace::Base::ConstantizeTestCases".constantize }.should.raise NameError
lambda { "Ace::Gas::Base".constantize }.should.raise NameError
lambda { "Ace::Gas::ConstantizeTestCases".constantize }.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/metaclass_spec.rb | spec/motion-support/core_ext/metaclass_spec.rb | describe "metaclass" do
it "should return the metaclass for a class" do
String.metaclass.is_a?(Class).should == true
end
it "should return the metaclass for an object" do
"string".metaclass.is_a?(Class).should == 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/spec/motion-support/core_ext/array_spec.rb | spec/motion-support/core_ext/array_spec.rb | describe 'array' do
it 'finds hash values' do
array_of_hashes = [
{
line1: 3,
line2: 5
},
{
line3: 7,
line4: 9
}
]
array_of_hashes.has_hash_value?(5).should.be.true
array_of_hashes.has_hash_value?(4).should.not.be.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/spec/motion-support/core_ext/enumerable_spec.rb | spec/motion-support/core_ext/enumerable_spec.rb | describe "enumerable" do
describe "collect_with_index" do
describe "on Array" do
it "should return an empty array on an empty array" do
[].collect_with_index { |x, i| x }.should == []
end
it "should yield an index for each element" do
[1, 2, 3].collect_with_index { |x, i| [i, x] }.should == [[0, 1], [1, 2], [2, 3]]
end
it "should apply the block to each element" do
[1, 2, 3].collect_with_index { |x, i| x * i }.should == [0, 2, 6]
end
end
describe "on Hash" do
it "should return an empty array on an empty hash" do
{}.collect_with_index { |x, i| x }.should == []
end
it "should apply the block to each element" do
result = {:foo => 1, :bar => 2, :baz => 3}.collect_with_index { |p, i| [p.first, p.last, i] }
result.should == [[:foo, 1, 0], [:bar, 2, 1], [:baz, 3, 2]]
end
end
end
describe "sum" do
it "should return the sum of an integer array" do
[5, 15, 10].sum.should == 30
end
it "should concatenate strings in a string array" do
['foo', 'bar'].sum.should == "foobar"
end
it "should concatenate arrays" do
[[1, 2], [3, 1, 5]].sum.should == [1, 2, 3, 1, 5]
end
it "should yield a block to each element before summing if given" do
[1, 2, 3].sum { |p| p * 2 }.should == 12
end
it "should allow a custom result for an empty list" do
[].sum("empty") { |i| i.amount }.should == "empty"
end
end
describe "index_by" do
class Person < Struct.new(:first_name, :last_name)
end
before do
@peter = Person.new('Peter', 'Griffin')
@homer = Person.new('Homer', 'Simpson')
end
it "should create hash with keys given by block result" do
[@peter, @homer].index_by { |x| x.first_name }.should == { 'Peter' => @peter, 'Homer' => @homer }
end
it "should create enumerator if no block is given" do
[@peter, @homer].index_by.should.is_a Enumerator
end
end
describe "many?" do
it "should return false for an empty enumerable" do
[].many?.should == false
{}.many?.should == false
end
it "should return false for an enumerable with only one element" do
[1].many?.should == false
{:foo => :bar}.many?.should == false
end
it "should return true for an enumerable with more than one element" do
[1, 2].many?.should == true
[1, 2, 3].many?.should == true
{:foo => :bar, :baz => :bingo}.many?.should == true
{:a => :b, :c => :d, :e => :f}.many?.should == true
end
it "should return false if there are less than two elements satisfying the block if given" do
[1].many? { |x| x * 10 > 100 }.should == false
[1, 2, 3, 4, 5].many? { |x| x >= 5 }.should == false
end
it "should return true if there is more than one element satisfying the block if given" do
[1, 2, 3, 4, 5].many? { |x| x < 4 }.should == true
end
end
describe "exclude?" do
it "should return true if the element is not in the array" do
[1, 2, 3].exclude?(4).should == true
end
it "should return false if the element is in the array" do
[1, 2, 3].exclude?(2).should == false
end
it "should always return true for an empty array" do
[].exclude?(rand).should == true
end
end
end
describe "Range" do
describe "sum" do
it "should return the sum of integers in an inclusive range" do
(3..5).sum.should == 12
end
it "should return the sum of integers in an exclusive range" do
(3...5).sum.should == 7
end
it "should return zero for an empty range" do
(1...1).sum.should == 0
end
it "should return custom identity for an empty range if given" do
(1...1).sum("empty").should == "empty"
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/regexp_spec.rb | spec/motion-support/core_ext/regexp_spec.rb | describe "Regexp" do
it "should find out if regexp is multiline" do
//m.multiline?.should.be.true
//.multiline?.should.be.false
/(?m:)/.multiline?.should.be.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/spec/motion-support/core_ext/string/inflection_spec.rb | spec/motion-support/core_ext/string/inflection_spec.rb | describe "String" do
describe "Inflections" do
describe "singularize" do
InflectorTestCases::SingularToPlural.each do |singular, plural|
it "should pluralize singular #{singular}" do
singular.pluralize.should == plural
end
end
it "should pluralize plural" do
"plurals".pluralize.should == "plurals"
end
it "should pluralize with number" do
"blargle".pluralize(0).should == "blargles"
"blargle".pluralize(1).should == "blargle"
"blargle".pluralize(2).should == "blargles"
end
end
describe "singularize" do
InflectorTestCases::SingularToPlural.each do |singular, plural|
it "should singularize plural #{plural}" do
plural.singularize.should == singular
end
end
end
describe "titleize" do
InflectorTestCases::MixtureToTitleCase.each do |before, titleized|
it "should titleize #{before}" do
before.titleize.should == titleized
end
end
end
describe "camelize" do
InflectorTestCases::CamelToUnderscore.each do |camel, underscore|
it "should camelize #{underscore}" do
underscore.camelize.should == camel
end
end
it "should lower-camelize" do
'Capital'.camelize(:lower).should == 'capital'
end
end
describe "dasherize" do
InflectorTestCases::UnderscoresToDashes.each do |underscored, dasherized|
it "should dasherize #{underscored}" do
underscored.dasherize.should == dasherized
end
end
end
describe "underscore" do
InflectorTestCases::CamelToUnderscore.each do |camel, underscore|
it "should underscore #{camel}" do
camel.underscore.should == underscore
end
end
it "should underscore acronyms" do
"HTMLTidy".underscore.should == "html_tidy"
"HTMLTidyGenerator".underscore.should == "html_tidy_generator"
end
InflectorTestCases::UnderscoreToLowerCamel.each do |underscored, lower_camel|
it "should lower-camelize #{underscored}" do
underscored.camelize(:lower).should == lower_camel
end
end
end
it "should demodulize" do
"MyApplication::Billing::Account".demodulize.should == "Account"
end
it "should deconstantize" do
"MyApplication::Billing::Account".deconstantize.should == "MyApplication::Billing"
end
describe "foreign_key" do
InflectorTestCases::ClassNameToForeignKeyWithUnderscore.each do |klass, foreign_key|
it "should build foreign key from #{klass}" do
klass.foreign_key.should == foreign_key
end
end
InflectorTestCases::ClassNameToForeignKeyWithoutUnderscore.each do |klass, foreign_key|
it "should build foreign key from #{klass} without underscore" do
klass.foreign_key(false).should == foreign_key
end
end
end
describe "tableize" do
InflectorTestCases::ClassNameToTableName.each do |class_name, table_name|
it "should tableize #{class_name}" do
class_name.tableize.should == table_name
end
end
end
describe "classify" do
InflectorTestCases::ClassNameToTableName.each do |class_name, table_name|
it "should classify #{table_name}" do
table_name.classify.should == class_name
end
end
end
describe "humanize" do
InflectorTestCases::UnderscoreToHuman.each do |underscore, human|
it "should humanize #{underscore}" do
underscore.humanize.should == human
end
end
end
describe "constantize" do
extend ConstantizeTestCases
it "should constantize" do
run_constantize_tests_on do |string|
string.constantize
end
end
end
describe "safe_constantize" do
extend ConstantizeTestCases
it "should safe_constantize" do
run_safe_constantize_tests_on do |string|
string.safe_constantize
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/string/indent_spec.rb | spec/motion-support/core_ext/string/indent_spec.rb | describe "String" do
describe "indent" do
it "should not indent strings that only contain newlines (edge cases)" do
['', "\n", "\n" * 7].each do |str|
str.indent!(8).should.be.nil
str.indent(8).should == str
str.indent(1, "\t").should == str
end
end
it "should indent by default with spaces if the existing indentation uses them" do
"foo\n bar".indent(4).should == " foo\n bar"
end
it "should indent by default with tabs if the existing indentation uses them" do
"foo\n\t\bar".indent(1).should == "\tfoo\n\t\t\bar"
end
it "should indent by default with spaces as a fallback if there is no indentation" do
"foo\nbar\nbaz".indent(3).should == " foo\n bar\n baz"
end
# Nothing is said about existing indentation that mixes spaces and tabs, so
# there is nothing to test.
it "should use the indent char if passed" do
<<ACTUAL.indent(4, '.').should == <<EXPECTED
def some_method(x, y)
some_code
end
ACTUAL
.... def some_method(x, y)
.... some_code
.... end
EXPECTED
<<ACTUAL.indent(2, ' ').should == <<EXPECTED
def some_method(x, y)
some_code
end
ACTUAL
def some_method(x, y)
some_code
end
EXPECTED
end
it "should not indent blank lines by default" do
"foo\n\nbar".indent(1).should == " foo\n\n bar"
end
it "should indent blank lines if told so" do
"foo\n\nbar".indent(1, nil, true).should == " foo\n \n bar"
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/string/filter_spec.rb | spec/motion-support/core_ext/string/filter_spec.rb | describe "String" do
describe "filters" do
describe "squish" do
before do
@original = %{ A string surrounded by spaces, with tabs(\t\t),
newlines(\n\n), unicode nextlines(\u0085\u0085) and many spaces( ). }
@expected = "A string surrounded by spaces, with tabs( ), newlines( )," \
" unicode nextlines( ) and many spaces( )."
end
it "should squish string" do
@original.squish.should == @expected
@original.should.not == @expected
end
it "should squish! string" do
@original.squish!.should == @expected
@original.should == @expected
end
end
describe "truncate" do
it "should truncate string" do
"Hello World!".truncate(12).should == "Hello World!"
"Hello World!!".truncate(12).should == "Hello Wor..."
end
it "should truncate with omission and seperator" do
"Hello World!".truncate(10, :omission => "[...]").should == "Hello[...]"
"Hello Big World!".truncate(13, :omission => "[...]", :separator => ' ').should == "Hello[...]"
"Hello Big World!".truncate(14, :omission => "[...]", :separator => ' ').should == "Hello Big[...]"
"Hello Big World!".truncate(15, :omission => "[...]", :separator => ' ').should == "Hello Big[...]"
end
it "should truncate with omission and regexp seperator" do
"Hello Big World!".truncate(13, :omission => "[...]", :separator => /\s/).should == "Hello[...]"
"Hello Big World!".truncate(14, :omission => "[...]", :separator => /\s/).should == "Hello Big[...]"
"Hello Big World!".truncate(15, :omission => "[...]", :separator => /\s/).should == "Hello Big[...]"
end
it "should truncate multibyte" do
"\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding(Encoding::UTF_8).truncate(10).should ==
"\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".force_encoding(Encoding::UTF_8)
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/string/starts_end_with_spec.rb | spec/motion-support/core_ext/string/starts_end_with_spec.rb | describe "String" do
describe "starts_with?/ends_with?" do
it "should have starts/ends_with? alias" do
s = "hello"
s.starts_with?('h').should.be.true
s.starts_with?('hel').should.be.true
s.starts_with?('el').should.be.false
s.ends_with?('o').should.be.true
s.ends_with?('lo').should.be.true
s.ends_with?('el').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/string/strip_spec.rb | spec/motion-support/core_ext/string/strip_spec.rb | describe "String" do
describe "strip_heredoc" do
it "should strip heredoc on an empty string" do
''.strip_heredoc.should == ''
end
it "should strip heredoc on a string with no lines" do
'x'.strip_heredoc.should == 'x'
' x'.strip_heredoc.should == 'x'
end
it "should strip heredoc on a heredoc with no margin" do
"foo\nbar".strip_heredoc.should == "foo\nbar"
"foo\n bar".strip_heredoc.should == "foo\n bar"
end
it "should strip heredoc on a regular indented heredoc" do
<<-EOS.strip_heredoc.should == "foo\n bar\nbaz\n"
foo
bar
baz
EOS
end
it "should strip heredoc on a regular indented heredoc with blank lines" do
<<-EOS.strip_heredoc.should == "foo\n bar\n\nbaz\n"
foo
bar
baz
EOS
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/string/behavior_spec.rb | spec/motion-support/core_ext/string/behavior_spec.rb | describe "String" do
describe "behavior" do
it "should acts like string" do
'Bambi'.acts_like_string?.should == true
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/string/access_spec.rb | spec/motion-support/core_ext/string/access_spec.rb | describe "String" do
describe "access" do
it "should access" do
s = "hello"
s.at(0).should == "h"
s.from(2).should == "llo"
s.to(2).should == "hel"
s.first.should == "h"
s.first(2).should == "he"
s.first(0).should == ""
s.last.should == "o"
s.last(3).should == "llo"
s.last(10).should == "hello"
s.last(0).should == ""
'x'.first.should == 'x'
'x'.first(4).should == 'x'
'x'.last.should == 'x'
'x'.last(4).should == 'x'
end
it "should access returns a real string" do
hash = {}
hash["h"] = true
hash["hello123".at(0)] = true
hash.keys.should == %w(h)
hash = {}
hash["llo"] = true
hash["hello".from(2)] = true
hash.keys.should == %w(llo)
hash = {}
hash["hel"] = true
hash["hello".to(2)] = true
hash.keys.should == %w(hel)
hash = {}
hash["hello"] = true
hash["123hello".last(5)] = true
hash.keys.should == %w(hello)
hash = {}
hash["hello"] = true
hash["hello123".first(5)] = true
hash.keys.should == %w(hello)
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/string/exclude_spec.rb | spec/motion-support/core_ext/string/exclude_spec.rb | describe "String" do
describe "exclude?" do
it "should be the inverse of #include" do
'foo'.exclude?('o').should.be.false
'foo'.exclude?('p').should.be.true
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/hash/key_spec.rb | spec/motion-support/core_ext/hash/key_spec.rb | describe "Hash" do
describe "keys" do
before do
@strings = { 'a' => 1, 'b' => 2 }
@nested_strings = { 'a' => { 'b' => { 'c' => 3 } } }
@symbols = { :a => 1, :b => 2 }
@nested_symbols = { :a => { :b => { :c => 3 } } }
@mixed = { :a => 1, 'b' => 2 }
@nested_mixed = { 'a' => { :b => { 'c' => 3 } } }
@fixnums = { 0 => 1, 1 => 2 }
@nested_fixnums = { 0 => { 1 => { 2 => 3} } }
@illegal_symbols = { [] => 3 }
@nested_illegal_symbols = { [] => { [] => 3} }
@upcase_strings = { 'A' => 1, 'B' => 2 }
@nested_upcase_strings = { 'A' => { 'B' => { 'C' => 3 } } }
@nested_array_symbols = { :a => [ { :a => 1 }, { :b => 2 } ] }
@nested_array_strings = { 'a' => [ { 'a' => 1 }, { 'b' => 2 } ] }
end
it "should have all key methods defined on literal hash" do
h = {}
h.should.respond_to :transform_keys
h.should.respond_to :transform_keys!
h.should.respond_to :deep_transform_keys
h.should.respond_to :deep_transform_keys!
h.should.respond_to :symbolize_keys
h.should.respond_to :symbolize_keys!
h.should.respond_to :deep_symbolize_keys
h.should.respond_to :deep_symbolize_keys!
h.should.respond_to :stringify_keys
h.should.respond_to :stringify_keys!
h.should.respond_to :deep_stringify_keys
h.should.respond_to :deep_stringify_keys!
h.should.respond_to :to_options
h.should.respond_to :to_options!
end
describe "transform_keys" do
it "should transform keys" do
@strings.transform_keys{ |key| key.to_s.upcase }.should == @upcase_strings
@symbols.transform_keys{ |key| key.to_s.upcase }.should == @upcase_strings
@mixed.transform_keys{ |key| key.to_s.upcase }.should == @upcase_strings
end
it "should not mutate" do
transformed_hash = @mixed.dup
transformed_hash.transform_keys{ |key| key.to_s.upcase }
transformed_hash.should == @mixed
end
end
describe "deep_transform_keys" do
it "should deep transform keys" do
@nested_symbols.deep_transform_keys{ |key| key.to_s.upcase }.should == @nested_upcase_strings
@nested_strings.deep_transform_keys{ |key| key.to_s.upcase }.should == @nested_upcase_strings
@nested_mixed.deep_transform_keys{ |key| key.to_s.upcase }.should == @nested_upcase_strings
end
it "should not mutate" do
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_transform_keys{ |key| key.to_s.upcase }
transformed_hash.should == @nested_mixed
end
end
describe "transform_keys!" do
it "should transform keys" do
@symbols.dup.transform_keys!{ |key| key.to_s.upcase }.should == @upcase_strings
@strings.dup.transform_keys!{ |key| key.to_s.upcase }.should == @upcase_strings
@mixed.dup.transform_keys!{ |key| key.to_s.upcase }.should == @upcase_strings
end
it "should mutate" do
transformed_hash = @mixed.dup
transformed_hash.transform_keys!{ |key| key.to_s.upcase }
transformed_hash.should == @upcase_strings
{ :a => 1, "b" => 2 }.should == @mixed
end
end
describe "deep_transform_keys!" do
it "should deep transform keys" do
@nested_symbols.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }.should == @nested_upcase_strings
@nested_strings.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }.should == @nested_upcase_strings
@nested_mixed.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }.should == @nested_upcase_strings
end
it "should mutate" do
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_transform_keys!{ |key| key.to_s.upcase }
transformed_hash.should == @nested_upcase_strings
{ 'a' => { :b => { 'c' => 3 } } }.should == @nested_mixed
end
end
describe "symbolize_keys" do
it "should symbolize keys" do
@symbols.symbolize_keys.should == @symbols
@strings.symbolize_keys.should == @symbols
@mixed.symbolize_keys.should == @symbols
end
it "should not mutate" do
transformed_hash = @mixed.dup
transformed_hash.symbolize_keys
transformed_hash.should == @mixed
end
it "should preserve keys that can't be symbolized" do
@illegal_symbols.symbolize_keys.should == @illegal_symbols
@illegal_symbols.dup.symbolize_keys!.should == @illegal_symbols
end
it "should preserve fixnum keys" do
@fixnums.symbolize_keys.should == @fixnums
@fixnums.dup.symbolize_keys!.should == @fixnums
end
end
describe "deep_symbolize_keys" do
it "should deep symbolize keys" do
@nested_symbols.deep_symbolize_keys.should == @nested_symbols
@nested_strings.deep_symbolize_keys.should == @nested_symbols
@nested_mixed.deep_symbolize_keys.should == @nested_symbols
@nested_array_strings.deep_symbolize_keys.should == @nested_array_symbols
end
it "should not mutate" do
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_symbolize_keys
transformed_hash.should == @nested_mixed
end
it "should preserve keys that can't be symbolized" do
@nested_illegal_symbols.deep_symbolize_keys.should == @nested_illegal_symbols
@nested_illegal_symbols.deep_dup.deep_symbolize_keys!.should == @nested_illegal_symbols
end
it "should preserve fixnum keys" do
@nested_fixnums.deep_symbolize_keys.should == @nested_fixnums
@nested_fixnums.deep_dup.deep_symbolize_keys!.should == @nested_fixnums
end
end
describe "symbolize_keys!" do
it "should symbolize keys" do
@symbols.dup.symbolize_keys!.should == @symbols
@strings.dup.symbolize_keys!.should == @symbols
@mixed.dup.symbolize_keys!.should == @symbols
end
it "should mutate" do
transformed_hash = @mixed.dup
transformed_hash.deep_symbolize_keys!
transformed_hash.should == @symbols
{ :a => 1, "b" => 2 }.should == @mixed
end
end
describe "deep_symbolize_keys!" do
it "should deep symbolize keys" do
@nested_symbols.deep_dup.deep_symbolize_keys!.should == @nested_symbols
@nested_strings.deep_dup.deep_symbolize_keys!.should == @nested_symbols
@nested_mixed.deep_dup.deep_symbolize_keys!.should == @nested_symbols
@nested_array_strings.deep_symbolize_keys!.should == @nested_array_symbols
end
it "should mutate" do
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_symbolize_keys!
transformed_hash.should == @nested_symbols
{ 'a' => { :b => { 'c' => 3 } } }.should == @nested_mixed
end
end
describe "stringify_keys" do
it "should stringify keys" do
@symbols.stringify_keys.should == @strings
@strings.stringify_keys.should == @strings
@mixed.stringify_keys.should == @strings
end
it "should not mutate" do
transformed_hash = @mixed.dup
transformed_hash.stringify_keys
transformed_hash.should == @mixed
end
end
describe "deep stringify_keys" do
it "should deep stringify keys" do
@nested_symbols.deep_stringify_keys.should == @nested_strings
@nested_strings.deep_stringify_keys.should == @nested_strings
@nested_mixed.deep_stringify_keys.should == @nested_strings
@nested_array_symbols.deep_stringify_keys.should == @nested_array_strings
end
it "should not mutate" do
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_stringify_keys
transformed_hash.should == @nested_mixed
end
end
describe "stringify_keys!" do
it "should stringify keys" do
@symbols.dup.stringify_keys!.should == @strings
@strings.dup.stringify_keys!.should == @strings
@mixed.dup.stringify_keys!.should == @strings
end
it "should mutate" do
transformed_hash = @mixed.dup
transformed_hash.stringify_keys!
transformed_hash.should == @strings
{ :a => 1, "b" => 2 }.should == @mixed
end
end
describe "deep_stringify_keys!" do
it "should deep stringify keys" do
@nested_symbols.deep_dup.deep_stringify_keys!.should == @nested_strings
@nested_strings.deep_dup.deep_stringify_keys!.should == @nested_strings
@nested_mixed.deep_dup.deep_stringify_keys!.should == @nested_strings
@nested_array_symbols.deep_stringify_keys!.should == @nested_array_strings
end
it "should mutate" do
transformed_hash = @nested_mixed.deep_dup
transformed_hash.deep_stringify_keys!
transformed_hash.should == @nested_strings
{ 'a' => { :b => { 'c' => 3 } } }.should == @nested_mixed
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/hash/deep_delete_if_spec.rb | spec/motion-support/core_ext/hash/deep_delete_if_spec.rb | describe "hash" do
before do
@hash = { :a => 1, :b => [ { :c => 2, :d => 3 }, :b ], :d => { :f => 4 } }
end
describe "deep_delete_if" do
it "should delete a top level key recursively" do
@hash.deep_delete_if { |k,v| k == :a }.should == { :b => [ { :c => 2, :d => 3 }, :b ], :d => { :f => 4 } }
end
it "should delete a key within an array recursively" do
@hash.deep_delete_if { |k,v| v == 2 }.should == { :a => 1, :b => [ { :d => 3 }, :b ], :d => { :f => 4 } }
end
it "should delete a key within a hash recursively" do
@hash.deep_delete_if { |k,v| v == 4 }.should == { :a => 1, :b => [ { :c => 2, :d => 3 }, :b ], :d => {} }
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/hash/except_spec.rb | spec/motion-support/core_ext/hash/except_spec.rb | describe "hash" do
describe "except" do
it "should remove key" do
original = { :a => 'x', :b => 'y', :c => 10 }
expected = { :a => 'x', :b => 'y' }
original.except(:c).should == expected
original.should.not == expected
end
it "should remove more than one key" do
original = { :a => 'x', :b => 'y', :c => 10 }
expected = { :a => 'x' }
original.except(:b, :c).should == expected
end
it "should work on frozen hash" do
original = { :a => 'x', :b => 'y' }
original.freeze
lambda { original.except(:a) }.should.not.raise
end
end
describe "except!" do
it "should remove key in place" do
original = { :a => 'x', :b => 'y', :c => 10 }
expected = { :a => 'x', :b => 'y' }
original.should.not == expected
original.except!(:c).should == expected
original.should == expected
end
it "should remove more than one key in place" do
original = { :a => 'x', :b => 'y', :c => 10 }
expected = { :a => 'x' }
original.should.not == expected
original.except!(:b, :c).should == expected
original.should == expected
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/hash/reverse_merge_spec.rb | spec/motion-support/core_ext/hash/reverse_merge_spec.rb | describe "hash" do
describe "reverse_merge" do
before do
@defaults = { :a => "x", :b => "y", :c => 10 }.freeze
@options = { :a => 1, :b => 2 }
@expected = { :a => 1, :b => 2, :c => 10 }
end
it "should merge defaults into options, creating a new hash" do
@options.reverse_merge(@defaults).should == @expected
@options.should.not == @expected
end
it "should merge! defaults into options, replacing options" do
merged = @options.dup
merged.reverse_merge!(@defaults).should == @expected
merged.should == @expected
end
it "should be an alias for reverse_merge!" do
merged = @options.dup
merged.reverse_update(@defaults).should == @expected
merged.should == @expected
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/hash/deep_merge_spec.rb | spec/motion-support/core_ext/hash/deep_merge_spec.rb | describe "hash" do
before do
@hash_1 = { :a => "a", :b => "b", :c => { :c1 => "c1", :c2 => "c2", :c3 => { :d1 => "d1" } } }
@hash_2 = { :a => 1, :c => { :c1 => 2, :c3 => { :d2 => "d2" } } }
end
describe "deep_merge" do
it "should deep merge" do
expected = { :a => 1, :b => "b", :c => { :c1 => 2, :c2 => "c2", :c3 => { :d1 => "d1", :d2 => "d2" } } }
@hash_1.deep_merge(@hash_2).should == expected
end
it "should deep merge with block" do
expected = { :a => [:a, "a", 1], :b => "b", :c => { :c1 => [:c1, "c1", 2], :c2 => "c2", :c3 => { :d1 => "d1", :d2 => "d2" } } }
(@hash_1.deep_merge(@hash_2) { |k,o,n| [k, o, n] }).should == expected
end
end
describe "deep_merge!" do
it "should deep merge" do
expected = { :a => 1, :b => "b", :c => { :c1 => 2, :c2 => "c2", :c3 => { :d1 => "d1", :d2 => "d2" } } }
@hash_1.deep_merge!(@hash_2)
@hash_1.should == expected
end
it "should deep merge with block" do
expected = { :a => [:a, "a", 1], :b => "b", :c => { :c1 => [:c1, "c1", 2], :c2 => "c2", :c3 => { :d1 => "d1", :d2 => "d2" } } }
@hash_1.deep_merge!(@hash_2) { |k,o,n| [k, o, n] }
@hash_1.should == expected
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/hash/slice_spec.rb | spec/motion-support/core_ext/hash/slice_spec.rb | describe "hash" do
describe "slice" do
it "should return a new hash with only the given keys" do
original = { :a => 'x', :b => 'y', :c => 10 }
expected = { :a => 'x', :b => 'y' }
original.slice(:a, :b).should == expected
original.should.not == expected
end
it "should replace the hash with only the given keys" do
original = { :a => 'x', :b => 'y', :c => 10 }
expected = { :c => 10 }
original.slice!(:a, :b).should == expected
end
it "should return a new hash with only the given keys when given an array key" do
original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
expected = { [:a, :b] => "an array key", :c => 10 }
original.slice([:a, :b], :c).should == expected
original.should.not == expected
end
it "should replace the hash with only the given keys when given an array key" do
original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
expected = { :a => 'x', :b => 'y' }
original.slice!([:a, :b], :c).should == expected
end
it "should grab each of the splatted keys" do
original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
expected = { :a => 'x', :b => "y" }
original.slice(*[:a, :b]).should == expected
end
end
describe "extract!" do
it "should extract subhash" do
original = {:a => 1, :b => 2, :c => 3, :d => 4}
expected = {:a => 1, :b => 2}
remaining = {:c => 3, :d => 4}
original.extract!(:a, :b, :x).should == expected
original.should == remaining
end
it "should extract nils" do
original = {:a => nil, :b => nil}
expected = {:a => nil}
extracted = original.extract!(:a, :x)
extracted.should == expected
extracted[:a].should == nil
extracted[:x].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/date/calculation_spec.rb | spec/motion-support/core_ext/date/calculation_spec.rb | describe "Date" do
describe "calculations" do
describe "yesterday" do
it "should calculate yesterday's date" do
Date.new(1982,10,15).yesterday.should == Date.new(1982,10,14)
end
it "should construct yesterday's date" do
Date.yesterday.should == Date.current - 1
end
end
describe "tomorrow" do
it "should calculate tomorrow's date" do
Date.new(1982,10,4).tomorrow.should == Date.new(1982,10,5)
end
it "should construct tomorrow's date" do
Date.tomorrow.should == Date.current + 1
end
end
describe "change" do
it "should change correctly" do
Date.new(2005,2,11).change(:day => 21).should == Date.new(2005,2,21)
Date.new(2005,2,11).change(:year => 2007, :month => 5).should == Date.new(2007,5,11)
Date.new(2005,2,22).change(:year => 2006).should == Date.new(2006,2,22)
Date.new(2005,2,22).change(:month => 6).should == Date.new(2005,6,22)
end
end
describe "sunday" do
it "should calculate correctly" do
Date.new(2008,3,02).sunday.should == Date.new(2008,3,2)
Date.new(2008,2,29).sunday.should == Date.new(2008,3,2)
end
end
describe "beginning_of_week" do
it "should calculate correctly" do
Date.new(1982,10,15).beginning_of_week.should == Date.new(1982,10,11)
end
end
describe "end_of_week" do
it "should calculate correctly" do
Date.new(1982,10,4).end_of_week.should == Date.new(1982,10,10)
end
end
describe "end_of_year" do
it "should calculate correctly" do
Date.new(2008,2,22).end_of_year.should == Date.new(2008,12,31)
end
end
describe "end_of_month" do
it "should calculate correctly" do
Date.new(2005,3,20).end_of_month.should == Date.new(2005,3,31)
Date.new(2005,2,20).end_of_month.should == Date.new(2005,2,28)
Date.new(2005,4,20).end_of_month.should == Date.new(2005,4,30)
end
end
describe "prev_year" do
it "should calculate correctly" do
Date.new(1983,10,14).prev_year.should == Date.new(1982,10,14)
end
it "should work with leap years" do
Date.new(2000,2,29).prev_year.should == Date.new(1999,2,28)
end
end
describe "last_year" do
it "should calculate correctly" do
Date.new(2005,6,5).last_year.should == Date.new(2004,6,5)
Date.new(1983,10,14).last_year.should == Date.new(1982,10,14)
end
it "should work with leap years" do
Date.new(2000,2,29).last_year.should == Date.new(1999,2,28)
end
end
describe "next_year" do
it "should calculate correctly" do
Date.new(1981,10,10).next_year.should == Date.new(1982,10,10)
end
it "should work with leap years" do
Date.new(2000,2,29).next_year.should == Date.new(2001,2,28)
end
end
describe "advance" do
it "should calculate correctly" do
Date.new(2005,2,28).advance(:years => 1).should == Date.new(2006,2,28)
Date.new(2005,2,28).advance(:months => 4).should == Date.new(2005,6,28)
Date.new(2005,2,28).advance(:weeks => 3).should == Date.new(2005,3,21)
Date.new(2005,2,28).advance(:days => 5).should == Date.new(2005,3,5)
Date.new(2005,2,28).advance(:years => 7, :months => 7).should == Date.new(2012,9,28)
Date.new(2005,2,28).advance(:years => 7, :months => 19, :days => 5).should == Date.new(2013,10,3)
Date.new(2005,2,28).advance(:years => 7, :months => 19, :weeks => 2, :days => 5).should == Date.new(2013,10,17)
Date.new(2004,2,29).advance(:years => 1).should == Date.new(2005,2,28)
end
it "should advance years before days" do
Date.new(2011, 2, 28).advance(:years => 1, :days => 1).should == Date.new(2012, 2, 29)
end
it "should advance months before days" do
Date.new(2010, 2, 28).advance(:months => 1, :days => 1).should == Date.new(2010, 3, 29)
end
it "should not change passed option hash" do
options = { :years => 3, :months => 11, :days => 2 }
Date.new(2005,2,28).advance(options)
options.should == { :years => 3, :months => 11, :days => 2 }
end
end
describe "last_week" do
it "should calculate correctly" do
Date.new(2005,5,17).last_week.should == Date.new(2005,5,9)
Date.new(2007,1,7).last_week.should == Date.new(2006,12,25)
Date.new(2010,2,19).last_week(:friday).should == Date.new(2010,2,12)
Date.new(2010,2,19).last_week(:saturday).should == Date.new(2010,2,13)
Date.new(2010,3,4).last_week(:saturday).should == Date.new(2010,2,27)
end
end
describe "last_month" do
it "should calculate correctly on the 31st" do
Date.new(2004, 3, 31).last_month.should == Date.new(2004, 2, 29)
end
end
describe "last_quarter" do
it "should calculate correctly on the 31st" do
Date.new(2004, 5, 31).last_quarter.should == Date.new(2004, 2, 29)
end
end
describe "since" do
it "should calculate correctly" do
Date.new(2005,2,21).since(45).should == Time.local(2005,2,21,0,0,45)
end
end
describe "ago" do
it "should calculate correctly" do
Date.new(2005,2,21).ago(45).should == Time.local(2005,2,20,23,59,15)
end
end
describe "beginning_of_day" do
it "should calculate correctly" do
Date.new(2005,2,21).beginning_of_day.should == Time.local(2005,2,21,0,0,0)
end
end
describe "end_of_day" do
it "should calculate correctly" do
Date.new(2005,2,21).end_of_day.should == Time.local(2005,2,21,23,59,59,Rational(999999999, 1000))
end
end
describe "past?" do
it "should calculate correctly" do
Date.yesterday.should.be.past
Date.today.last_week.should.be.past
Date.tomorrow.should.not.be.past
end
end
describe "future?" do
it "should calculate correctly" do
Date.tomorrow.should.be.future
Date.today.next_week.should.be.future
Date.yesterday.should.not.be.future
end
end
describe "plus_with_duration" do
it "should calculate correctly" do
(Date.new(1982,10,4) + 1.day).should == Date.new(1982,10,5)
(Date.new(1982,10,4) + 1.month).should == Date.new(1982,11,4)
(Date.new(1982,10,4) + 1.year).should == Date.new(1983,10,4)
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/date/acts_like_spec.rb | spec/motion-support/core_ext/date/acts_like_spec.rb | describe "Date" do
describe "acts_like" do
it "should act like date" do
Date.new.should.acts_like(:date)
end
it "should not act like time" do
Date.new.should.not.acts_like(:time)
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/conversion_spec.rb | spec/motion-support/core_ext/date/conversion_spec.rb | describe 'date' do
describe 'conversions' do
before { @date = Date.new(2005, 2, 21) }
describe '#iso8601' do
it 'should convert to iso8601 format' do
@date.iso8601.should == '2005-02-21'
end
end
describe '#to_s' do
it 'should convert to db format by default' do
@date.to_s.should == '2005-2-21'
end
it 'should convert to short format' do
@date.to_s(:short).should == '21 Feb'
end
it 'should convert to long format' do
@date.to_s(:long).should == 'February 21, 2005'
end
it 'should convert to long_ordinal format' do
@date.to_s(:long_ordinal).should == 'February 21st, 2005'
end
it 'should convert to db format' do
@date.to_s(:db).should == '2005-02-21'
end
it 'should convert to rfc822 format' do
@date.to_s(:rfc822).should == '21 Feb 2005'
end
it 'should convert to iso8601 format' do
@date.to_s(:iso8601).should == '2005-02-21'
end
it 'should convert to xmlschema format' do
@date.to_s(:xmlschema).should == '2005-02-21T00:00:00Z'
end
end
describe '#readable_inspect' do
it 'should convert to a readable string' do
@date.readable_inspect.should == 'Mon, 21 Feb 2005'
end
it 'should also respond to #inspect' do
@date.readable_inspect.should == @date.inspect
end
end
describe '#xmlschema' do
it 'should convert to xmlschema format' do
@date.xmlschema.should == '2005-02-21T00:00:00Z'
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/integer/multiple_spec.rb | spec/motion-support/core_ext/integer/multiple_spec.rb | PRIME = 22953686867719691230002707821868552601124472329079
describe "Integer" do
describe "multiple_of" do
it "should determine if an integer is a multiple of another" do
[ -7, 0, 7, 14 ].each { |i| i.should.be.multiple_of 7 }
[ -7, 7, 14 ].each { |i| i.should.not.be.multiple_of 6 }
end
it "should work with edge cases" do
0.should.be.multiple_of 0
5.should.not.be.multiple_of 0
end
it "should work with a prime" do
[2, 3, 5, 7].each { |i| PRIME.should.not.be.multiple_of i }
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/integer/inflection_spec.rb | spec/motion-support/core_ext/integer/inflection_spec.rb | # These tests are mostly just to ensure that the ordinalize method exists.
# Its results are tested comprehensively in the inflector test cases.
describe "Integer" do
describe "ordinalize" do
it "should ordinalize 1" do
1.ordinalize.should == '1st'
end
it "should ordinalize 8" do
8.ordinalize.should == '8th'
end
end
describe "ordinal" do
it "should get ordinal of 1" do
1.ordinal.should == 'st'
end
it "should get ordinal of 8" do
8.ordinal.should == 'th'
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/kernel/singleton_class_spec.rb | spec/motion-support/core_ext/kernel/singleton_class_spec.rb | describe "Kernel" do
describe "class_eval" do
it "should delegate to singleton class" do
o = Object.new
class << o; @x = 1; end
o.class_eval { @x }.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/range/include_range_spec.rb | spec/motion-support/core_ext/range/include_range_spec.rb | describe "Range" do
describe "include?" do
it "should should include identical inclusive" do
(1..10).should.include(1..10)
end
it "should should include identical exclusive" do
(1...10).should.include(1...10)
end
it "should should include other with exlusive end" do
(1..10).should.include(1...10)
end
it "should exclusive end should not include identical with inclusive end" do
(1...10).should.not.include(1..10)
end
it "should should not include overlapping first" do
(2..8).should.not.include(1..3)
end
it "should should not include overlapping last" do
(2..8).should.not.include(5..9)
end
it "should should include identical exclusive with floats" do
(1.0...10.0).should.include(1.0...10.0)
end
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.