code
stringlengths 26
124k
| docstring
stringlengths 23
125k
| func_name
stringlengths 1
98
| language
stringclasses 1
value | repo
stringlengths 5
53
| path
stringlengths 7
151
| url
stringlengths 50
211
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def initialize(table)
@table = table
end
|
@param keyspace [Keyspace] keyspace in which to create the table
@param table [Table] object representation of table schema
|
initialize
|
ruby
|
cequel/cequel
|
lib/cequel/schema/table_writer.rb
|
https://github.com/cequel/cequel/blob/master/lib/cequel/schema/table_writer.rb
|
MIT
|
def apply(keyspace)
statements.each { |statement| keyspace.execute(statement) }
end
|
Create the table in the keyspace
@return [void]
@api private
|
apply
|
ruby
|
cequel/cequel
|
lib/cequel/schema/table_writer.rb
|
https://github.com/cequel/cequel/blob/master/lib/cequel/schema/table_writer.rb
|
MIT
|
def drop_keyspace
keyspace = Cequel::Record.connection.schema
keyspace.drop! if keyspace.exists?
self
end
|
Ensure the current keyspace does not exist.
@return [Preparation] self
|
drop_keyspace
|
ruby
|
cequel/cequel
|
lib/cequel/spec_support/preparation.rb
|
https://github.com/cequel/cequel/blob/master/lib/cequel/spec_support/preparation.rb
|
MIT
|
def create_keyspace
keyspace = Cequel::Record.connection.schema
keyspace.create! unless keyspace.exists?
self
end
|
Ensure that the necessary keyspace exists.
@return [Preparation] self
|
create_keyspace
|
ruby
|
cequel/cequel
|
lib/cequel/spec_support/preparation.rb
|
https://github.com/cequel/cequel/blob/master/lib/cequel/spec_support/preparation.rb
|
MIT
|
def sync_schema
record_classes.each do |record_class|
begin
record_class.synchronize_schema
unless options[:quiet]
puts "Synchronized schema for #{record_class.name}"
end
rescue Record::MissingTableNameError
# It is obviously not a real record class if it doesn't have a
# table name.
unless options[:quiet]
STDERR.puts "Skipping anonymous record class without an " \
"explicit table name"
end
end
end
self
end
|
Ensure that the necessary column families exist and match the
models.
@return [Preparation] self
|
sync_schema
|
ruby
|
cequel/cequel
|
lib/cequel/spec_support/preparation.rb
|
https://github.com/cequel/cequel/blob/master/lib/cequel/spec_support/preparation.rb
|
MIT
|
def record_classes
load_all_models
Cequel::Record.descendants
end
|
@return [Array<Class>] all Cequel record classes
|
record_classes
|
ruby
|
cequel/cequel
|
lib/cequel/spec_support/preparation.rb
|
https://github.com/cequel/cequel/blob/master/lib/cequel/spec_support/preparation.rb
|
MIT
|
def load_all_models
model_dirs.each do |directory|
Dir.glob(Pathname(directory).join("**", "*.rb")).each do |file_name|
require_dependency(file_name)
end
end
end
|
Loads all files in the models directory under the assumption
that Cequel record classes live there.
|
load_all_models
|
ruby
|
cequel/cequel
|
lib/cequel/spec_support/preparation.rb
|
https://github.com/cequel/cequel/blob/master/lib/cequel/spec_support/preparation.rb
|
MIT
|
def unique_table_name(base_name, example)
max_suffix = 45 - base_name.size
:"#{base_name}_#{example_slug(example, max_suffix)}"
end
|
figures a table name starting with `base_name` that is unique to the
specified example
Examples
let(:table_name) { |ex| unique_table_name("posts", ex) }
|
unique_table_name
|
ruby
|
cequel/cequel
|
spec/support/helpers.rb
|
https://github.com/cequel/cequel/blob/master/spec/support/helpers.rb
|
MIT
|
def use_before_action(callback)
CallbackMatcher.new(callback, :before, :action)
end
|
The `use_before_action` matcher is used to test that a before_action
callback is defined within your controller.
class UsersController < ApplicationController
before_action :authenticate_user!
end
# RSpec
RSpec.describe UsersController, type: :controller do
it { should use_before_action(:authenticate_user!) }
it { should_not use_before_action(:prevent_ssl) }
end
# Minitest (Shoulda)
class UsersControllerTest < ActionController::TestCase
should use_before_action(:authenticate_user!)
should_not use_before_action(:prevent_ssl)
end
@return [CallbackMatcher]
|
use_before_action
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/action_controller/callback_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/action_controller/callback_matcher.rb
|
MIT
|
def use_after_action(callback)
CallbackMatcher.new(callback, :after, :action)
end
|
The `use_after_action` matcher is used to test that an after_action
callback is defined within your controller.
class IssuesController < ApplicationController
after_action :log_activity
end
# RSpec
RSpec.describe IssuesController, type: :controller do
it { should use_after_action(:log_activity) }
it { should_not use_after_action(:destroy_user) }
end
# Minitest (Shoulda)
class IssuesControllerTest < ActionController::TestCase
should use_after_action(:log_activity)
should_not use_after_action(:destroy_user)
end
@return [CallbackMatcher]
|
use_after_action
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/action_controller/callback_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/action_controller/callback_matcher.rb
|
MIT
|
def use_around_action(callback)
CallbackMatcher.new(callback, :around, :action)
end
|
The `use_around_action` matcher is used to test that an around_action
callback is defined within your controller.
class ChangesController < ApplicationController
around_action :wrap_in_transaction
end
# RSpec
RSpec.describe ChangesController, type: :controller do
it { should use_around_action(:wrap_in_transaction) }
it { should_not use_around_action(:save_view_context) }
end
# Minitest (Shoulda)
class ChangesControllerTest < ActionController::TestCase
should use_around_action(:wrap_in_transaction)
should_not use_around_action(:save_view_context)
end
@return [CallbackMatcher]
|
use_around_action
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/action_controller/callback_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/action_controller/callback_matcher.rb
|
MIT
|
def redirect_to(url_or_description, &block)
RedirectToMatcher.new(url_or_description, self, &block)
end
|
The `redirect_to` matcher tests that an action redirects to a certain
location. In a test suite using RSpec, it is very similar to
rspec-rails's `redirect_to` matcher. In a test suite using Minitest +
Shoulda, it provides a more expressive syntax over
`assert_redirected_to`.
class PostsController < ApplicationController
def show
redirect_to :index
end
end
# RSpec
RSpec.describe PostsController, type: :controller do
describe 'GET #show' do
before { get :show }
it { should redirect_to(posts_path) }
it { should redirect_to(action: :index) }
end
end
# Minitest (Shoulda)
class PostsControllerTest < ActionController::TestCase
context 'GET #show' do
setup { get :show }
should redirect_to('/posts') { posts_path }
should redirect_to(action: :index)
end
end
@return [RedirectToMatcher]
|
redirect_to
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/action_controller/redirect_to_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/action_controller/redirect_to_matcher.rb
|
MIT
|
def render_template(options = {}, message = nil)
RenderTemplateMatcher.new(options, message, self)
end
|
The `render_template` matcher tests that an action renders a template
or partial. In RSpec, it is very similar to rspec-rails's
`render_template` matcher. In a test suite using Minitest + Shoulda, it
provides a more expressive syntax over `assert_template`.
class PostsController < ApplicationController
def show
end
end
# app/views/posts/show.html.erb
<%= render 'sidebar' %>
# RSpec
RSpec.describe PostsController, type: :controller do
describe 'GET #show' do
before { get :show }
it { should render_template('show') }
it { should render_template(partial: '_sidebar') }
end
end
# Minitest (Shoulda)
class PostsControllerTest < ActionController::TestCase
context 'GET #show' do
setup { get :show }
should render_template('show')
should render_template(partial: '_sidebar')
end
end
@return [RenderTemplateMatcher]
|
render_template
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/action_controller/render_template_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/action_controller/render_template_matcher.rb
|
MIT
|
def in_context(context)
@context = context
self
end
|
Used to provide access to layouts recorded by
ActionController::TemplateAssertions in Rails 3
|
in_context
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/action_controller/render_with_layout_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/action_controller/render_with_layout_matcher.rb
|
MIT
|
def rescue_from(exception)
RescueFromMatcher.new exception
end
|
The `rescue_from` matcher tests usage of the `rescue_from` macro. It
asserts that an exception and method are present in the list of
exception handlers, and that the handler method exists.
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :handle_not_found
private
def handle_not_found
# ...
end
end
# RSpec
RSpec.describe ApplicationController, type: :controller do
it do
should rescue_from(ActiveRecord::RecordNotFound).
with(:handle_not_found)
end
end
# Minitest (Shoulda)
class ApplicationControllerTest < ActionController::TestCase
should rescue_from(ActiveRecord::RecordNotFound).
with(:handle_not_found)
end
@return [RescueFromMatcher]
|
rescue_from
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/action_controller/rescue_from_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/action_controller/rescue_from_matcher.rb
|
MIT
|
def allow_value(*values)
if values.empty?
raise ArgumentError, 'need at least one argument'
else
AllowValueMatcher.new(*values)
end
end
|
The `allow_value` matcher (or its alias, `allow_values`) is used to
ensure that an attribute is valid or invalid if set to one or more
values.
Take this model for example:
class UserProfile
include ActiveModel::Model
attr_accessor :website_url
validates_format_of :website_url, with: URI.regexp
end
You can use `allow_value` to test one value at a time:
# RSpec
RSpec.describe UserProfile, type: :model do
it { should allow_value('https://foo.com').for(:website_url) }
it { should allow_value('https://bar.com').for(:website_url) }
end
# Minitest (Shoulda)
class UserProfileTest < ActiveSupport::TestCase
should allow_value('https://foo.com').for(:website_url)
should allow_value('https://bar.com').for(:website_url)
end
You can also test multiple values in one go, if you like. In the
positive sense, this makes an assertion that none of the values cause the
record to be invalid. In the negative sense, this makes an assertion
that none of the values cause the record to be valid:
# RSpec
RSpec.describe UserProfile, type: :model do
it do
should allow_values('https://foo.com', 'https://bar.com').
for(:website_url)
end
it do
should_not allow_values('foo', 'buz').
for(:website_url)
end
end
# Minitest (Shoulda)
class UserProfileTest < ActiveSupport::TestCase
should allow_values('https://foo.com', 'https://bar.com/baz').
for(:website_url)
should_not allow_values('foo', 'buz').
for(:website_url)
end
#### Caveats
When using `allow_value` or any matchers that depend on it, you may
encounter an AttributeChangedValueError. This exception is raised if the
matcher, in attempting to set a value on the attribute, detects that
the value set is different from the value that the attribute returns
upon reading it back.
This usually happens if the writer method (`foo=`, `bar=`, etc.) for
that attribute has custom logic to ignore certain incoming values or
change them in any way. Here are three examples we've seen:
* You're attempting to assert that an attribute should not allow nil,
yet the attribute's writer method contains a conditional to do nothing
if the attribute is set to nil:
class Foo
include ActiveModel::Model
attr_reader :bar
def bar=(value)
return if value.nil?
@bar = value
end
end
RSpec.describe Foo, type: :model do
it do
foo = Foo.new
foo.bar = "baz"
# This will raise an AttributeChangedValueError since `foo.bar` is now "123"
expect(foo).not_to allow_value(nil).for(:bar)
end
end
* You're attempting to assert that a numeric attribute should not allow
a string that contains non-numeric characters, yet the writer method
for that attribute strips out non-numeric characters:
class Foo
include ActiveModel::Model
attr_reader :bar
def bar=(value)
@bar = value.gsub(/\D+/, '')
end
end
RSpec.describe Foo, type: :model do
it do
foo = Foo.new
# This will raise an AttributeChangedValueError since `foo.bar` is now "123"
expect(foo).not_to allow_value("abc123").for(:bar)
end
end
* You're passing a value to `allow_value` that the model typecasts into
another value:
RSpec.describe Foo, type: :model do
# Assume that `attr` is a string
# This will raise an AttributeChangedValueError since `attr` typecasts `[]` to `"[]"`
it { should_not allow_value([]).for(:attr) }
end
Fortunately, if you understand why this is happening, and wish to get
around this exception, it is possible to do so. You can use the
`ignoring_interference_by_writer` qualifier like so:
it do
should_not allow_value([]).
for(:attr).
ignoring_interference_by_writer
end
Please note, however, that this qualifier won't magically cause your
test to pass. It may just so happen that the final value that ends up
being set causes the model to fail validation. In that case, you'll have
to figure out what to do. You may need to write your own test, or
perhaps even remove your test altogether.
#### Qualifiers
##### on
Use `on` if your validation applies only under a certain context.
class UserProfile
include ActiveModel::Model
attr_accessor :birthday_as_string
validates_format_of :birthday_as_string,
with: /^(\d+)-(\d+)-(\d+)$/,
on: :create
end
# RSpec
RSpec.describe UserProfile, type: :model do
it do
should allow_value('2013-01-01').
for(:birthday_as_string).
on(:create)
end
end
# Minitest (Shoulda)
class UserProfileTest < ActiveSupport::TestCase
should allow_value('2013-01-01').
for(:birthday_as_string).
on(:create)
end
##### against
Use `against` if the validation is on an attribute
other than the attribute being validated:
class UserProfile
include ActiveModel::Model
attr_accessor :website_url
alias_attribute :url, :website_url
validates_format_of :url, with: URI.regexp
end
# RSpec
RSpec.describe UserProfile, type: :model do
it do
should allow_value('https://foo.com').
for(:website_url).
against(:url)
end
end
# Minitest (Shoulda)
class UserProfileTest < ActiveSupport::TestCase
should allow_value('https://foo.com').
for(:website_url).
against(:url)
end
##### with_message
Use `with_message` if you are using a custom validation message.
class UserProfile
include ActiveModel::Model
attr_accessor :state
validates_format_of :state,
with: /^(open|closed)$/,
message: 'State must be open or closed'
end
# RSpec
RSpec.describe UserProfile, type: :model do
it do
should allow_value('open', 'closed').
for(:state).
with_message('State must be open or closed')
end
end
# Minitest (Shoulda)
class UserProfileTest < ActiveSupport::TestCase
should allow_value('open', 'closed').
for(:state).
with_message('State must be open or closed')
end
Use `with_message` with a regexp to perform a partial match:
class UserProfile
include ActiveModel::Model
attr_accessor :state
validates_format_of :state,
with: /^(open|closed)$/,
message: 'State must be open or closed'
end
# RSpec
RSpec.describe UserProfile, type: :model do
it do
should allow_value('open', 'closed').
for(:state).
with_message(/open or closed/)
end
end
# Minitest (Shoulda)
class UserProfileTest < ActiveSupport::TestCase
should allow_value('open', 'closed').
for(:state).
with_message(/open or closed/)
end
Use `with_message` with the `:against` option if the attribute the
validation message is stored under is different from the attribute
being validated:
class UserProfile
include ActiveModel::Model
attr_accessor :sports_team
validate :sports_team_must_be_valid
private
def sports_team_must_be_valid
if sports_team !~ /^(Broncos|Titans)$/i
self.errors.add :chosen_sports_team,
'Must be either a Broncos fan or a Titans fan'
end
end
end
# RSpec
RSpec.describe UserProfile, type: :model do
it do
should allow_value('Broncos', 'Titans').
for(:sports_team).
with_message('Must be either a Broncos or Titans fan',
against: :chosen_sports_team
)
end
end
# Minitest (Shoulda)
class UserProfileTest < ActiveSupport::TestCase
should allow_value('Broncos', 'Titans').
for(:sports_team).
with_message('Must be either a Broncos or Titans fan',
against: :chosen_sports_team
)
end
##### ignoring_interference_by_writer
Use `ignoring_interference_by_writer` to bypass an
AttributeChangedValueError that you have encountered. Please read the
Caveats section above for more information.
class Address < ActiveRecord::Base
# Address has a zip_code field which is a string
end
# RSpec
RSpec.describe Address, type: :model do
it do
should_not allow_value([]).
for(:zip_code).
ignoring_interference_by_writer
end
end
# Minitest (Shoulda)
class AddressTest < ActiveSupport::TestCase
should_not allow_value([]).
for(:zip_code).
ignoring_interference_by_writer
end
@return [AllowValueMatcher]
|
allow_value
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/active_model/allow_value_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_model/allow_value_matcher.rb
|
MIT
|
def belong_to(name)
AssociationMatcher.new(:belongs_to, name)
end
|
The `belong_to` matcher is used to ensure that a `belong_to` association
exists on your model.
class Person < ActiveRecord::Base
belongs_to :organization
end
# RSpec
RSpec.describe Person, type: :model do
it { should belong_to(:organization) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:organization)
end
Note that polymorphic associations are automatically detected and do not
need any qualifiers:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
# RSpec
RSpec.describe Comment, type: :model do
it { should belong_to(:commentable) }
end
# Minitest (Shoulda)
class CommentTest < ActiveSupport::TestCase
should belong_to(:commentable)
end
#### Qualifiers
##### conditions
Use `conditions` if your association is defined with a scope that sets
the `where` clause.
class Person < ActiveRecord::Base
belongs_to :family, -> { where(everyone_is_perfect: false) }
end
# RSpec
RSpec.describe Person, type: :model do
it do
should belong_to(:family).
conditions(everyone_is_perfect: false)
end
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:family).
conditions(everyone_is_perfect: false)
end
##### order
Use `order` if your association is defined with a scope that sets the
`order` clause.
class Person < ActiveRecord::Base
belongs_to :previous_company, -> { order('hired_on desc') }
end
# RSpec
RSpec.describe Person, type: :model do
it { should belong_to(:previous_company).order('hired_on desc') }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:previous_company).order('hired_on desc')
end
##### class_name
Use `class_name` to test usage of the `:class_name` option. This
asserts that the model you're referring to actually exists.
class Person < ActiveRecord::Base
belongs_to :ancient_city, class_name: 'City'
end
# RSpec
RSpec.describe Person, type: :model do
it { should belong_to(:ancient_city).class_name('City') }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:ancient_city).class_name('City')
end
##### with_primary_key
Use `with_primary_key` to test usage of the `:primary_key` option.
class Person < ActiveRecord::Base
belongs_to :great_country, primary_key: 'country_id'
end
# RSpec
RSpec.describe Person, type: :model do
it do
should belong_to(:great_country).
with_primary_key('country_id')
end
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:great_country).
with_primary_key('country_id')
end
##### with_foreign_key
Use `with_foreign_key` to test usage of the `:foreign_key` option.
class Person < ActiveRecord::Base
belongs_to :great_country, foreign_key: 'country_id'
end
# RSpec
RSpec.describe Person, type: :model do
it do
should belong_to(:great_country).
with_foreign_key('country_id')
end
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:great_country).
with_foreign_key('country_id')
end
##### with_foreign_type
Use `with_foreign_type` to test usage of the `:foreign_type` option.
class Visitor < ActiveRecord::Base
belongs_to :location, foreign_type: 'facility_type', polymorphic: true
end
# RSpec
RSpec.describe Visitor, type: :model do
it do
should belong_to(:location).
with_foreign_type('facility_type')
end
end
# Minitest (Shoulda)
class VisitorTest < ActiveSupport::TestCase
should belong_to(:location).
with_foreign_type('facility_type')
end
##### dependent
Use `dependent` to assert that the `:dependent` option was specified.
class Person < ActiveRecord::Base
belongs_to :world, dependent: :destroy
end
# RSpec
RSpec.describe Person, type: :model do
it { should belong_to(:world).dependent(:destroy) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:world).dependent(:destroy)
end
To assert that *any* `:dependent` option was specified, use `true`:
# RSpec
RSpec.describe Person, type: :model do
it { should belong_to(:world).dependent(true) }
end
To assert that *no* `:dependent` option was specified, use `false`:
class Person < ActiveRecord::Base
belongs_to :company
end
# RSpec
RSpec.describe Person, type: :model do
it { should belong_to(:company).dependent(false) }
end
##### counter_cache
Use `counter_cache` to assert that the `:counter_cache` option was
specified.
class Person < ActiveRecord::Base
belongs_to :organization, counter_cache: true
end
# RSpec
RSpec.describe Person, type: :model do
it { should belong_to(:organization).counter_cache(true) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:organization).counter_cache(true)
end
##### touch
Use `touch` to assert that the `:touch` option was specified.
class Person < ActiveRecord::Base
belongs_to :organization, touch: true
end
# RSpec
RSpec.describe Person, type: :model do
it { should belong_to(:organization).touch(true) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:organization).touch(true)
end
##### strict_loading
Use `strict_loading` to assert that the `:strict_loading` option was specified.
class Organization < ActiveRecord::Base
has_many :people, strict_loading: true
end
# RSpec
RSpec.describe Organization, type: :model do
it { should have_many(:people).strict_loading(true) }
end
# Minitest (Shoulda)
class OrganizationTest < ActiveSupport::TestCase
should have_many(:people).strict_loading(true)
end
Default value is true when no argument is specified
# RSpec
RSpec.describe Organization, type: :model do
it { should have_many(:people).strict_loading }
end
# Minitest (Shoulda)
class OrganizationTest < ActiveSupport::TestCase
should have_many(:people).strict_loading
end
##### autosave
Use `autosave` to assert that the `:autosave` option was specified.
class Account < ActiveRecord::Base
belongs_to :bank, autosave: true
end
# RSpec
RSpec.describe Account, type: :model do
it { should belong_to(:bank).autosave(true) }
end
# Minitest (Shoulda)
class AccountTest < ActiveSupport::TestCase
should belong_to(:bank).autosave(true)
end
##### inverse_of
Use `inverse_of` to assert that the `:inverse_of` option was specified.
class Person < ActiveRecord::Base
belongs_to :organization, inverse_of: :employees
end
# RSpec
describe Person
it { should belong_to(:organization).inverse_of(:employees) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:organization).inverse_of(:employees)
end
##### required
Use `required` to assert that the association is not allowed to be nil.
(Enabled by default in Rails 5+.)
class Person < ActiveRecord::Base
belongs_to :organization, required: true
end
# RSpec
describe Person
it { should belong_to(:organization).required }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:organization).required
end
##### without_validating_presence
Use `without_validating_presence` with `belong_to` to prevent the
matcher from checking whether the association disallows nil (Rails 5+
only). This can be helpful if you have a custom hook that always sets
the association to a meaningful value:
class Person < ActiveRecord::Base
belongs_to :organization
before_validation :autoassign_organization
private
def autoassign_organization
self.organization = Organization.create!
end
end
# RSpec
describe Person
it { should belong_to(:organization).without_validating_presence }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:organization).without_validating_presence
end
##### optional
Use `optional` to assert that the association is allowed to be nil.
(Rails 5+ only.)
class Person < ActiveRecord::Base
belongs_to :organization, optional: true
end
# RSpec
describe Person
it { should belong_to(:organization).optional }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should belong_to(:organization).optional
end
@return [AssociationMatcher]
|
belong_to
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/active_record/association_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/association_matcher.rb
|
MIT
|
def have_delegated_type(name)
AssociationMatcher.new(:belongs_to, name)
end
|
The `have_delegated_type` matcher is used to ensure that a `belong_to` association
exists on your model using the delegated_type macro.
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck)
end
# RSpec
RSpec.describe Vehicle, type: :model do
it { should have_delegated_type(:drivable) }
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable)
end
#### Qualifiers
##### types
Use `types` to test the types that are allowed for the association.
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck)
end
# RSpec
RSpec.describe Vehicle, type: :model do
it do
should have_delegated_type(:drivable).
types(%w(Car Truck))
end
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).
types(%w(Car Truck))
end
##### conditions
Use `conditions` if your association is defined with a scope that sets
the `where` clause.
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck), scope: -> { where(with_wheels: true) }
end
# RSpec
RSpec.describe Vehicle, type: :model do
it do
should have_delegated_type(:drivable).
conditions(with_wheels: true)
end
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).
conditions(everyone_is_perfect: false)
end
##### order
Use `order` if your association is defined with a scope that sets the
`order` clause.
class Person < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck), scope: -> { order('wheels desc') }
end
# RSpec
RSpec.describe Vehicle, type: :model do
it { should have_delegated_type(:drivable).order('wheels desc') }
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).order('wheels desc')
end
##### with_primary_key
Use `with_primary_key` to test usage of the `:primary_key` option.
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck), primary_key: 'vehicle_id'
end
# RSpec
RSpec.describe Vehicle, type: :model do
it do
should have_delegated_type(:drivable).
with_primary_key('vehicle_id')
end
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).
with_primary_key('vehicle_id')
end
##### with_foreign_key
Use `with_foreign_key` to test usage of the `:foreign_key` option.
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck), foreign_key: 'drivable_uuid'
end
# RSpec
RSpec.describe Vehicle, type: :model do
it do
should have_delegated_type(:drivable).
with_foreign_key('drivable_uuid')
end
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).
with_foreign_key('drivable_uuid')
end
##### dependent
Use `dependent` to assert that the `:dependent` option was specified.
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck), dependent: :destroy
end
# RSpec
RSpec.describe Vehicle, type: :model do
it { should have_delegated_type(:drivable).dependent(:destroy) }
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).dependent(:destroy)
end
To assert that *any* `:dependent` option was specified, use `true`:
# RSpec
RSpec.describe Vehicle, type: :model do
it { should have_delegated_type(:drivable).dependent(true) }
end
To assert that *no* `:dependent` option was specified, use `false`:
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck)
end
# RSpec
RSpec.describe Vehicle, type: :model do
it { should have_delegated_type(:drivable).dependent(false) }
end
##### counter_cache
Use `counter_cache` to assert that the `:counter_cache` option was
specified.
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck), counter_cache: true
end
# RSpec
RSpec.describe Vehicle, type: :model do
it { should have_delegated_type(:drivable).counter_cache(true) }
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).counter_cache(true)
end
##### touch
Use `touch` to assert that the `:touch` option was specified.
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck), touch: true
end
# RSpec
RSpec.describe Vehicle, type: :model do
it { should have_delegated_type(:drivable).touch(true) }
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).touch(true)
end
##### autosave
Use `autosave` to assert that the `:autosave` option was specified.
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck), autosave: true
end
# RSpec
RSpec.describe Vehicle, type: :model do
it { should have_delegated_type(:drivable).autosave(true) }
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).autosave(true)
end
##### inverse_of
Use `inverse_of` to assert that the `:inverse_of` option was specified.
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck), inverse_of: :vehicle
end
# RSpec
describe Vehicle
it { should have_delegated_type(:drivable).inverse_of(:vehicle) }
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).inverse_of(:vehicle)
end
##### required
Use `required` to assert that the association is not allowed to be nil.
(Enabled by default in Rails 5+.)
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck), required: true
end
# RSpec
describe Vehicle
it { should have_delegated_type(:drivable).required }
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).required
end
##### without_validating_presence
Use `without_validating_presence` with `belong_to` to prevent the
matcher from checking whether the association disallows nil (Rails 5+
only). This can be helpful if you have a custom hook that always sets
the association to a meaningful value:
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck)
before_validation :autoassign_drivable
private
def autoassign_drivable
self.drivable = Car.create!
end
end
# RSpec
describe Vehicle
it { should have_delegated_type(:drivable).without_validating_presence }
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).without_validating_presence
end
##### optional
Use `optional` to assert that the association is allowed to be nil.
(Rails 5+ only.)
class Vehicle < ActiveRecord::Base
delegated_type :drivable, types: %w(Car Truck), optional: true
end
# RSpec
describe Vehicle
it { should have_delegated_type(:drivable).optional }
end
# Minitest (Shoulda)
class VehicleTest < ActiveSupport::TestCase
should have_delegated_type(:drivable).optional
end
@return [AssociationMatcher]
|
have_delegated_type
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/active_record/association_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/association_matcher.rb
|
MIT
|
def have_many(name)
AssociationMatcher.new(:has_many, name)
end
|
The `have_many` matcher is used to test that a `has_many` or `has_many
:through` association exists on your model.
class Person < ActiveRecord::Base
has_many :friends
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_many(:friends) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_many(:friends)
end
Note that polymorphic associations are automatically detected and do not
need any qualifiers:
class Person < ActiveRecord::Base
has_many :pictures, as: :imageable
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_many(:pictures) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_many(:pictures)
end
#### Qualifiers
##### conditions
Use `conditions` if your association is defined with a scope that sets
the `where` clause.
class Person < ActiveRecord::Base
has_many :coins, -> { where(quality: 'mint') }
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_many(:coins).conditions(quality: 'mint') }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_many(:coins).conditions(quality: 'mint')
end
##### order
Use `order` if your association is defined with a scope that sets the
`order` clause.
class Person < ActiveRecord::Base
has_many :shirts, -> { order('color') }
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_many(:shirts).order('color') }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_many(:shirts).order('color')
end
##### class_name
Use `class_name` to test usage of the `:class_name` option. This
asserts that the model you're referring to actually exists.
class Person < ActiveRecord::Base
has_many :hopes, class_name: 'Dream'
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_many(:hopes).class_name('Dream') }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_many(:hopes).class_name('Dream')
end
##### with_primary_key
Use `with_primary_key` to test usage of the `:primary_key` option.
class Person < ActiveRecord::Base
has_many :worries, primary_key: 'worrier_id'
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_many(:worries).with_primary_key('worrier_id') }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_many(:worries).with_primary_key('worrier_id')
end
##### with_foreign_key
Use `with_foreign_key` to test usage of the `:foreign_key` option.
class Person < ActiveRecord::Base
has_many :worries, foreign_key: 'worrier_id'
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_many(:worries).with_foreign_key('worrier_id') }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_many(:worries).with_foreign_key('worrier_id')
end
##### with_foreign_type
Use `with_foreign_type` to test usage of the `:foreign_type` option.
class Hotel < ActiveRecord::Base
has_many :visitors, foreign_key: 'facility_type', as: :location
end
# RSpec
RSpec.describe Hotel, type: :model do
it { should have_many(:visitors).with_foreign_type('facility_type') }
end
# Minitest (Shoulda)
class HotelTest < ActiveSupport::TestCase
should have_many(:visitors).with_foreign_type('facility_type')
end
##### dependent
Use `dependent` to assert that the `:dependent` option was specified.
class Person < ActiveRecord::Base
has_many :secret_documents, dependent: :destroy
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_many(:secret_documents).dependent(:destroy) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_many(:secret_documents).dependent(:destroy)
end
##### through
Use `through` to test usage of the `:through` option. This asserts that
the association you are going through actually exists.
class Person < ActiveRecord::Base
has_many :acquaintances, through: :friends
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_many(:acquaintances).through(:friends) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_many(:acquaintances).through(:friends)
end
##### source
Use `source` to test usage of the `:source` option on a `:through`
association.
class Person < ActiveRecord::Base
has_many :job_offers, through: :friends, source: :opportunities
end
# RSpec
RSpec.describe Person, type: :model do
it do
should have_many(:job_offers).
through(:friends).
source(:opportunities)
end
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_many(:job_offers).
through(:friends).
source(:opportunities)
end
##### validate
Use `validate` to assert that the `:validate` option was specified.
class Person < ActiveRecord::Base
has_many :ideas, validate: false
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_many(:ideas).validate(false) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_many(:ideas).validate(false)
end
##### autosave
Use `autosave` to assert that the `:autosave` option was specified.
class Player < ActiveRecord::Base
has_many :games, autosave: true
end
# RSpec
RSpec.describe Player, type: :model do
it { should have_many(:games).autosave(true) }
end
# Minitest (Shoulda)
class PlayerTest < ActiveSupport::TestCase
should have_many(:games).autosave(true)
end
##### index_errors
Use `index_errors` to assert that the `:index_errors` option was
specified.
class Player < ActiveRecord::Base
has_many :games, index_errors: true
end
# RSpec
RSpec.describe Player, type: :model do
it { should have_many(:games).index_errors(true) }
end
# Minitest (Shoulda)
class PlayerTest < ActiveSupport::TestCase
should have_many(:games).index_errors(true)
end
##### inverse_of
Use `inverse_of` to assert that the `:inverse_of` option was specified.
class Organization < ActiveRecord::Base
has_many :employees, inverse_of: :company
end
# RSpec
describe Organization
it { should have_many(:employees).inverse_of(:company) }
end
# Minitest (Shoulda)
class OrganizationTest < ActiveSupport::TestCase
should have_many(:employees).inverse_of(:company)
end
@return [AssociationMatcher]
|
have_many
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/active_record/association_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/association_matcher.rb
|
MIT
|
def have_one(name)
AssociationMatcher.new(:has_one, name)
end
|
The `have_one` matcher is used to test that a `has_one` or `has_one
:through` association exists on your model.
class Person < ActiveRecord::Base
has_one :partner
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_one(:partner) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_one(:partner)
end
#### Qualifiers
##### conditions
Use `conditions` if your association is defined with a scope that sets
the `where` clause.
class Person < ActiveRecord::Base
has_one :pet, -> { where('weight < 80') }
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_one(:pet).conditions('weight < 80') }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_one(:pet).conditions('weight < 80')
end
##### order
Use `order` if your association is defined with a scope that sets the
`order` clause.
class Person < ActiveRecord::Base
has_one :focus, -> { order('priority desc') }
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_one(:focus).order('priority desc') }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_one(:focus).order('priority desc')
end
##### class_name
Use `class_name` to test usage of the `:class_name` option. This
asserts that the model you're referring to actually exists.
class Person < ActiveRecord::Base
has_one :chance, class_name: 'Opportunity'
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_one(:chance).class_name('Opportunity') }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_one(:chance).class_name('Opportunity')
end
##### dependent
Use `dependent` to test that the `:dependent` option was specified.
class Person < ActiveRecord::Base
has_one :contract, dependent: :nullify
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_one(:contract).dependent(:nullify) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_one(:contract).dependent(:nullify)
end
##### with_primary_key
Use `with_primary_key` to test usage of the `:primary_key` option.
class Person < ActiveRecord::Base
has_one :job, primary_key: 'worker_id'
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_one(:job).with_primary_key('worker_id') }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_one(:job).with_primary_key('worker_id')
end
##### with_foreign_key
Use `with_foreign_key` to test usage of the `:foreign_key` option.
class Person < ActiveRecord::Base
has_one :job, foreign_key: 'worker_id'
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_one(:job).with_foreign_key('worker_id') }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_one(:job).with_foreign_key('worker_id')
end
##### with_foreign_type
Use `with_foreign_type` to test usage of the `:foreign_type` option.
class Hotel < ActiveRecord::Base
has_one :special_guest, foreign_type: 'facility_type', as: :location
end
# RSpec
RSpec.describe Hotel, type: :model do
it { should have_one(:special_guest).with_foreign_type('facility_type') }
end
# Minitest (Shoulda)
class HotelTest < ActiveSupport::TestCase
should have_one(:special_guest).with_foreign_type('facility_type')
end
##### through
Use `through` to test usage of the `:through` option. This asserts that
the association you are going through actually exists.
class Person < ActiveRecord::Base
has_one :life, through: :partner
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_one(:life).through(:partner) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_one(:life).through(:partner)
end
##### source
Use `source` to test usage of the `:source` option on a `:through`
association.
class Person < ActiveRecord::Base
has_one :car, through: :partner, source: :vehicle
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_one(:car).through(:partner).source(:vehicle) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_one(:car).through(:partner).source(:vehicle)
end
##### validate
Use `validate` to assert that the the `:validate` option was specified.
class Person < ActiveRecord::Base
has_one :parking_card, validate: false
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_one(:parking_card).validate(false) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_one(:parking_card).validate(false)
end
##### autosave
Use `autosave` to assert that the `:autosave` option was specified.
class Account < ActiveRecord::Base
has_one :bank, autosave: true
end
# RSpec
RSpec.describe Account, type: :model do
it { should have_one(:bank).autosave(true) }
end
# Minitest (Shoulda)
class AccountTest < ActiveSupport::TestCase
should have_one(:bank).autosave(true)
end
##### required
Use `required` to assert that the association is not allowed to be nil.
(Rails 5+ only.)
class Person < ActiveRecord::Base
has_one :brain, required: true
end
# RSpec
describe Person
it { should have_one(:brain).required }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_one(:brain).required
end
@return [AssociationMatcher]
|
have_one
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/active_record/association_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/association_matcher.rb
|
MIT
|
def have_and_belong_to_many(name)
AssociationMatcher.new(:has_and_belongs_to_many, name)
end
|
The `have_and_belong_to_many` matcher is used to test that a
`has_and_belongs_to_many` association exists on your model and that the
join table exists in the database.
class Person < ActiveRecord::Base
has_and_belongs_to_many :awards
end
# RSpec
RSpec.describe Person, type: :model do
it { should have_and_belong_to_many(:awards) }
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_and_belong_to_many(:awards)
end
#### Qualifiers
##### conditions
Use `conditions` if your association is defined with a scope that sets
the `where` clause.
class Person < ActiveRecord::Base
has_and_belongs_to_many :issues, -> { where(difficulty: 'hard') }
end
# RSpec
RSpec.describe Person, type: :model do
it do
should have_and_belong_to_many(:issues).
conditions(difficulty: 'hard')
end
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_and_belong_to_many(:issues).
conditions(difficulty: 'hard')
end
##### order
Use `order` if your association is defined with a scope that sets the
`order` clause.
class Person < ActiveRecord::Base
has_and_belongs_to_many :projects, -> { order('time_spent') }
end
# RSpec
RSpec.describe Person, type: :model do
it do
should have_and_belong_to_many(:projects).
order('time_spent')
end
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_and_belong_to_many(:projects).
order('time_spent')
end
##### class_name
Use `class_name` to test usage of the `:class_name` option. This
asserts that the model you're referring to actually exists.
class Person < ActiveRecord::Base
has_and_belongs_to_many :places_visited, class_name: 'City'
end
# RSpec
RSpec.describe Person, type: :model do
it do
should have_and_belong_to_many(:places_visited).
class_name('City')
end
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_and_belong_to_many(:places_visited).
class_name('City')
end
##### join_table
Use `join_table` to test usage of the `:join_table` option. This
asserts that the table you're referring to actually exists.
class Person < ActiveRecord::Base
has_and_belongs_to_many :issues, join_table: :people_tickets
end
# RSpec
RSpec.describe Person, type: :model do
it do
should have_and_belong_to_many(:issues).
join_table(:people_tickets)
end
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_and_belong_to_many(:issues).
join_table(:people_tickets)
end
##### validate
Use `validate` to test that the `:validate` option was specified.
class Person < ActiveRecord::Base
has_and_belongs_to_many :interviews, validate: false
end
# RSpec
RSpec.describe Person, type: :model do
it do
should have_and_belong_to_many(:interviews).
validate(false)
end
end
# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
should have_and_belong_to_many(:interviews).
validate(false)
end
##### autosave
Use `autosave` to assert that the `:autosave` option was specified.
class Publisher < ActiveRecord::Base
has_and_belongs_to_many :advertisers, autosave: true
end
# RSpec
RSpec.describe Publisher, type: :model do
it { should have_and_belong_to_many(:advertisers).autosave(true) }
end
# Minitest (Shoulda)
class AccountTest < ActiveSupport::TestCase
should have_and_belong_to_many(:advertisers).autosave(true)
end
@return [AssociationMatcher]
|
have_and_belong_to_many
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/active_record/association_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/association_matcher.rb
|
MIT
|
def have_one_attached(name)
HaveAttachedMatcher.new(:one, name)
end
|
The `have_one_attached` matcher tests usage of the
`has_one_attached` macro.
#### Example
class User < ApplicationRecord
has_one_attached :avatar
end
# RSpec
RSpec.describe User, type: :model do
it { should have_one_attached(:avatar) }
end
# Minitest (Shoulda)
class UserTest < ActiveSupport::TestCase
should have_one_attached(:avatar)
end
@return [HaveAttachedMatcher]
|
have_one_attached
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/active_record/have_attached_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/have_attached_matcher.rb
|
MIT
|
def have_many_attached(name)
HaveAttachedMatcher.new(:many, name)
end
|
The `have_many_attached` matcher tests usage of the
`has_many_attached` macro.
#### Example
class Message < ApplicationRecord
has_many_attached :images
end
# RSpec
RSpec.describe Message, type: :model do
it { should have_many_attached(:images) }
end
# Minitest (Shoulda)
class MessageTest < ActiveSupport::TestCase
should have_many_attached(:images)
end
@return [HaveAttachedMatcher]
|
have_many_attached
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/active_record/have_attached_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/have_attached_matcher.rb
|
MIT
|
def normalize(*attributes)
if attributes.empty?
raise ArgumentError, 'need at least one attribute'
else
NormalizeMatcher.new(*attributes)
end
end
|
The `normalize` matcher is used to ensure attribute normalizations
are transforming attribute values as expected.
Take this model for example:
class User < ActiveRecord::Base
normalizes :email, with: -> email { email.strip.downcase }
end
You can use `normalize` providing an input and defining the expected
normalization output:
# RSpec
RSpec.describe User, type: :model do
it do
should normalize(:email).from(" ME@XYZ.COM\n").to("me@xyz.com")
end
end
# Minitest (Shoulda)
class User < ActiveSupport::TestCase
should normalize(:email).from(" ME@XYZ.COM\n").to("me@xyz.com")
end
You can use `normalize` to test multiple attributes at once:
class User < ActiveRecord::Base
normalizes :email, :handle, with: -> value { value.strip.downcase }
end
# RSpec
RSpec.describe User, type: :model do
it do
should normalize(:email, :handle).from(" Example\n").to("example")
end
end
# Minitest (Shoulda)
class User < ActiveSupport::TestCase
should normalize(:email, :handle).from(" Example\n").to("example")
end
If the normalization accepts nil values with the `apply_to_nil` option,
you just need to use `.from(nil).to("Your expected value here")`.
class User < ActiveRecord::Base
normalizes :name, with: -> name { name&.titleize || 'Untitled' },
apply_to_nil: true
end
# RSpec
RSpec.describe User, type: :model do
it { should normalize(:name).from("jane doe").to("Jane Doe") }
it { should normalize(:name).from(nil).to("Untitled") }
end
# Minitest (Shoulda)
class User < ActiveSupport::TestCase
should normalize(:name).from("jane doe").to("Jane Doe")
should normalize(:name).from(nil).to("Untitled")
end
@return [NormalizeMatcher]
|
normalize
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/active_record/normalize_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/normalize_matcher.rb
|
MIT
|
def alternatives(values)
@options[:alternatives] = values
self
end
|
@param values [String, Array<String>]
Alternative value(s) to use for testing uniqueness instead of using
the `succ` operator on the existing value.
@return [ValidateUniquenessOfMatcher]
@example
it { should validate_uniqueness_of(:title).alternatives('Alternative Title') }
it { should validate_uniqueness_of(:title).alternatives(['Title 1', 'Title 2']) }
|
alternatives
|
ruby
|
thoughtbot/shoulda-matchers
|
lib/shoulda/matchers/active_record/validate_uniqueness_of_matcher.rb
|
https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/validate_uniqueness_of_matcher.rb
|
MIT
|
def find_index_of(obj)
elements.index { |el| el.equal?(obj) }
end
|
Returns the first index of +obj+ in self.
Uses equal? for the comparator.
|
find_index_of
|
ruby
|
dmendel/bindata
|
lib/bindata/array.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/array.rb
|
BSD-2-Clause
|
def first(n = nil)
if n.nil? && empty?
# explicitly return nil as arrays grow automatically
nil
elsif n.nil?
self[0]
else
self[0, n]
end
end
|
Returns the first element, or the first +n+ elements, of the array.
If the array is empty, the first form returns nil, and the second
form returns an empty array.
|
first
|
ruby
|
dmendel/bindata
|
lib/bindata/array.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/array.rb
|
BSD-2-Clause
|
def last(n = nil)
if n.nil?
self[-1]
else
n = length if n > length
self[-n, n]
end
end
|
Returns the last element, or the last +n+ elements, of the array.
If the array is empty, the first form returns nil, and the second
form returns an empty array.
|
last
|
ruby
|
dmendel/bindata
|
lib/bindata/array.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/array.rb
|
BSD-2-Clause
|
def to_ary
collect { |el| el }
end
|
Allow this object to be used in array context.
|
to_ary
|
ruby
|
dmendel/bindata
|
lib/bindata/array.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/array.rb
|
BSD-2-Clause
|
def read(io, *args, &block)
obj = new(*args)
obj.read(io, &block)
obj
end
|
Instantiates this class and reads from +io+, returning the newly
created data object. +args+ will be used when instantiating.
|
read
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def arg_processor(name = nil)
@arg_processor ||= nil
if name
@arg_processor = "#{name}_arg_processor".gsub(/(?:^|_)(.)/) { $1.upcase }.to_sym
elsif @arg_processor.is_a? Symbol
@arg_processor = BinData.const_get(@arg_processor).new
elsif @arg_processor.nil?
@arg_processor = superclass.arg_processor
else
@arg_processor
end
end
|
The arg processor for this class.
|
arg_processor
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def register_subclasses # :nodoc:
singleton_class.send(:undef_method, :inherited)
define_singleton_method(:inherited) do |subclass|
RegisteredClasses.register(subclass.name, subclass)
register_subclasses
end
end
|
Registers all subclasses of this class for use
|
register_subclasses
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def initialize(*args)
value, @params, @parent = extract_args(args)
initialize_shared_instance
initialize_instance
assign(value) if value
end
|
Creates a new data object.
Args are optional, but if present, must be in the following order.
+value+ is a value that is +assign+ed immediately after initialization.
+parameters+ is a hash containing symbol keys. Some parameters may
reference callable objects (methods or procs).
+parent+ is the parent data object (e.g. struct, array, choice) this
object resides under.
|
initialize
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def new(value = nil, parent = nil)
obj = clone
obj.parent = parent if parent
obj.initialize_instance
obj.assign(value) if value
obj
end
|
Creates a new data object based on this instance.
This implements the prototype design pattern.
All parameters will be be duplicated. Use this method
when creating multiple objects with the same parameters.
|
new
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def eval_parameter(key, overrides = nil)
value = get_parameter(key)
if value.is_a?(Symbol) || value.respond_to?(:arity)
lazy_evaluator.lazy_eval(value, overrides)
else
value
end
end
|
Returns the result of evaluating the parameter identified by +key+.
+overrides+ is an optional +parameters+ like hash that allow the
parameters given at object construction to be overridden.
Returns nil if +key+ does not refer to any parameter.
|
eval_parameter
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def lazy_evaluator # :nodoc:
@lazy_evaluator ||= LazyEvaluator.new(self)
end
|
Returns a lazy evaluator for this object.
|
lazy_evaluator
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def read(io, &block)
io = BinData::IO::Read.new(io) unless BinData::IO::Read === io
start_read do
clear
do_read(io)
end
block.call(self) if block_given?
self
end
|
Reads data into this data object.
|
read
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def write(io, &block)
io = BinData::IO::Write.new(io) unless BinData::IO::Write === io
do_write(io)
io.flush
block.call(self) if block_given?
self
end
|
Writes the value for this data object to +io+.
|
write
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def to_binary_s(&block)
io = BinData::IO.create_string_io
write(io, &block)
io.string
end
|
Returns the string representation of this data object.
|
to_binary_s
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def debug_name
@parent ? @parent.debug_name_of(self) : 'obj'
end
|
Returns a user friendly name of this object for debugging purposes.
|
debug_name
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def abs_offset
@parent ? @parent.abs_offset + @parent.offset_of(self) : 0
end
|
Returns the offset (in bytes) of this object with respect to its most
distant ancestor.
|
abs_offset
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def rel_offset
@parent ? @parent.offset_of(self) : 0
end
|
Returns the offset (in bytes) of this object with respect to its parent.
|
rel_offset
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def safe_respond_to?(symbol, include_private = false) # :nodoc:
base_respond_to?(symbol, include_private)
end
|
A version of +respond_to?+ used by the lazy evaluator. It doesn't
reinvoke the evaluator so as to avoid infinite evaluation loops.
|
safe_respond_to?
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def extract_args(obj_class, obj_args)
value, params, parent = separate_args(obj_class, obj_args)
sanitized_params = SanitizedParameters.sanitize(params, obj_class)
[value, sanitized_params, parent]
end
|
Takes the arguments passed to BinData::Base.new and
extracts [value, sanitized_parameters, parent].
|
extract_args
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def separate_args(_obj_class, obj_args)
args = obj_args.dup
value = parameters = parent = nil
if args.length > 1 && args.last.is_a?(BinData::Base)
parent = args.pop
end
if args.length > 0 && args.last.is_a?(Hash)
parameters = args.pop
end
if args.length > 0
value = args.pop
end
parameters ||= @@empty_hash
[value, parameters, parent]
end
|
Separates the arguments passed to BinData::Base.new into
[value, parameters, parent]. Called by #extract_args.
|
separate_args
|
ruby
|
dmendel/bindata
|
lib/bindata/base.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base.rb
|
BSD-2-Clause
|
def _value
@value != nil ? @value : sensible_default
end
|
The unmodified value of this data object. Note that #snapshot calls this
method. This indirection is so that #snapshot can be overridden in
subclasses to modify the presentation value.
|
_value
|
ruby
|
dmendel/bindata
|
lib/bindata/base_primitive.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base_primitive.rb
|
BSD-2-Clause
|
def value_to_binary_string(val)
raise NotImplementedError
end
|
##########################################################################
To be implemented by subclasses
Return the string representation that +val+ will take when written.
|
value_to_binary_string
|
ruby
|
dmendel/bindata
|
lib/bindata/base_primitive.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base_primitive.rb
|
BSD-2-Clause
|
def read_and_return_value(io)
raise NotImplementedError
end
|
Read a number of bytes from +io+ and return the value they represent.
|
read_and_return_value
|
ruby
|
dmendel/bindata
|
lib/bindata/base_primitive.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base_primitive.rb
|
BSD-2-Clause
|
def sensible_default
raise NotImplementedError
end
|
Return a sensible default for this data.
|
sensible_default
|
ruby
|
dmendel/bindata
|
lib/bindata/base_primitive.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/base_primitive.rb
|
BSD-2-Clause
|
def read_now!
return unless include_obj?
raise IOError, "read from where?" unless @read_io
@read_io.seek_to_abs_offset(abs_offset)
start_read do
@type.do_read(@read_io)
end
end
|
DelayedIO objects aren't read when #read is called.
The reading is delayed until this method is called.
|
read_now!
|
ruby
|
dmendel/bindata
|
lib/bindata/delayed_io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/delayed_io.rb
|
BSD-2-Clause
|
def write_now!
return unless include_obj?
raise IOError, "write to where?" unless @write_io
@write_io.seek_to_abs_offset(abs_offset)
@type.do_write(@write_io)
end
|
DelayedIO objects aren't written when #write is called.
The writing is delayed until this method is called.
|
write_now!
|
ruby
|
dmendel/bindata
|
lib/bindata/delayed_io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/delayed_io.rb
|
BSD-2-Clause
|
def auto_call_delayed_io
include AutoCallDelayedIO
return if DelayedIO.method_defined? :initialize_instance_without_record_io
DelayedIO.send(:alias_method, :initialize_instance_without_record_io, :initialize_instance)
DelayedIO.send(:define_method, :initialize_instance) do
if @parent && !defined? @delayed_io_recorded
@delayed_io_recorded = true
list = top_level_get(:delayed_ios)
list << self if list
end
initialize_instance_without_record_io
end
end
|
The +auto_call_delayed_io+ keyword sets a data object tree to perform
multi pass I/O automatically.
|
auto_call_delayed_io
|
ruby
|
dmendel/bindata
|
lib/bindata/delayed_io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/delayed_io.rb
|
BSD-2-Clause
|
def clear?
raise NotImplementedError
end
|
Returns true if the object has not been changed since creation.
|
clear?
|
ruby
|
dmendel/bindata
|
lib/bindata/framework.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/framework.rb
|
BSD-2-Clause
|
def assign(val)
raise NotImplementedError
end
|
Assigns the value of +val+ to this data object. Note that +val+ must
always be deep copied to ensure no aliasing problems can occur.
|
assign
|
ruby
|
dmendel/bindata
|
lib/bindata/framework.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/framework.rb
|
BSD-2-Clause
|
def snapshot
raise NotImplementedError
end
|
Returns a snapshot of this data object.
|
snapshot
|
ruby
|
dmendel/bindata
|
lib/bindata/framework.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/framework.rb
|
BSD-2-Clause
|
def do_read(io) # :nodoc:
raise NotImplementedError
end
|
Reads the data for this data object from +io+.
|
do_read
|
ruby
|
dmendel/bindata
|
lib/bindata/framework.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/framework.rb
|
BSD-2-Clause
|
def do_write(io) # :nodoc:
raise NotImplementedError
end
|
Writes the value for this data to +io+.
|
do_write
|
ruby
|
dmendel/bindata
|
lib/bindata/framework.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/framework.rb
|
BSD-2-Clause
|
def do_num_bytes # :nodoc:
raise NotImplementedError
end
|
Returns the number of bytes it will take to write this data.
|
do_num_bytes
|
ruby
|
dmendel/bindata
|
lib/bindata/framework.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/framework.rb
|
BSD-2-Clause
|
def transform(io)
reset_read_bits
saved = @io
@io = io.prepend_to_chain(@io)
yield(self, io)
io.after_read_transform
ensure
@io = saved
end
|
Allow transforming data in the input stream.
See +BinData::Buffer+ as an example.
+io+ must be an instance of +Transform+.
yields +self+ and +io+ to the given block
|
transform
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def skipbytes(n)
reset_read_bits
@io.skip(n)
end
|
Seek +n+ bytes from the current position in the io stream.
|
skipbytes
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def seek_to_abs_offset(n)
reset_read_bits
@io.seek_abs(n)
end
|
Seek to an absolute offset within the io stream.
|
seek_to_abs_offset
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def readbytes(n)
reset_read_bits
read(n)
end
|
Reads exactly +n+ bytes from +io+.
If the data read is nil an EOFError is raised.
If the data read is too short an IOError is raised.
|
readbytes
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def read_all_bytes
reset_read_bits
read
end
|
Reads all remaining bytes from the stream.
|
read_all_bytes
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def readbits(nbits, endian)
if @rendian != endian
# don't mix bits of differing endian
reset_read_bits
@rendian = endian
end
if endian == :big
read_big_endian_bits(nbits)
else
read_little_endian_bits(nbits)
end
end
|
Reads exactly +nbits+ bits from the stream. +endian+ specifies whether
the bits are stored in +:big+ or +:little+ endian format.
|
readbits
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def reset_read_bits
@rnbits = 0
@rval = 0
end
|
Discards any read bits so the stream becomes aligned at the
next byte boundary.
|
reset_read_bits
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def transform(io)
flushbits
saved = @io
@io = io.prepend_to_chain(@io)
yield(self, io)
io.after_write_transform
ensure
@io = saved
end
|
Allow transforming data in the output stream.
See +BinData::Buffer+ as an example.
+io+ must be an instance of +Transform+.
yields +self+ and +io+ to the given block
|
transform
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def seek_to_abs_offset(n)
raise IOError, "stream is unseekable" unless @io.seekable?
flushbits
@io.seek_abs(n)
end
|
Seek to an absolute offset within the io stream.
|
seek_to_abs_offset
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def writebytes(str)
flushbits
write(str)
end
|
Writes the given string of bytes to the io stream.
|
writebytes
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def writebits(val, nbits, endian)
if @wendian != endian
# don't mix bits of differing endian
flushbits
@wendian = endian
end
clamped_val = val & mask(nbits)
if endian == :big
write_big_endian_bits(clamped_val, nbits)
else
write_little_endian_bits(clamped_val, nbits)
end
end
|
Writes +nbits+ bits from +val+ to the stream. +endian+ specifies whether
the bits are to be stored in +:big+ or +:little+ endian format.
|
writebits
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def flushbits
raise "Internal state error nbits = #{@wnbits}" if @wnbits >= 8
if @wnbits > 0
writebits(0, 8 - @wnbits, @wendian)
end
end
|
To be called after all +writebits+ have been applied.
|
flushbits
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def prepend_to_chain(chain)
@chain_io = chain
before_transform
self
end
|
Prepends this transform to the given +chain+.
Returns self (the new head of chain).
|
prepend_to_chain
|
ruby
|
dmendel/bindata
|
lib/bindata/io.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/io.rb
|
BSD-2-Clause
|
def initialize(obj)
@obj = obj
end
|
Creates a new evaluator. All lazy evaluation is performed in the
context of +obj+.
|
initialize
|
ruby
|
dmendel/bindata
|
lib/bindata/lazy.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/lazy.rb
|
BSD-2-Clause
|
def parent
if @obj.parent
@obj.parent.lazy_evaluator
else
nil
end
end
|
Returns a LazyEvaluator for the parent of this data object.
|
parent
|
ruby
|
dmendel/bindata
|
lib/bindata/lazy.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/lazy.rb
|
BSD-2-Clause
|
def index
return @overrides[:index] if defined?(@overrides) && @overrides.key?(:index)
child = @obj
parent = @obj.parent
while parent
if parent.respond_to?(:find_index_of)
return parent.find_index_of(child)
end
child = parent
parent = parent.parent
end
raise NoMethodError, "no index found"
end
|
Returns the index of this data object inside it's nearest container
array.
|
index
|
ruby
|
dmendel/bindata
|
lib/bindata/lazy.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/lazy.rb
|
BSD-2-Clause
|
def get
raise NotImplementedError
end
|
##########################################################################
To be implemented by subclasses
Extracts the value for this data object from the fields of the
internal struct.
|
get
|
ruby
|
dmendel/bindata
|
lib/bindata/primitive.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/primitive.rb
|
BSD-2-Clause
|
def set(v)
raise NotImplementedError
end
|
Sets the fields of the internal struct to represent +v+.
|
set
|
ruby
|
dmendel/bindata
|
lib/bindata/primitive.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/primitive.rb
|
BSD-2-Clause
|
def underscore_name(name)
name
.to_s
.sub(/.*::/, "")
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.tr('-', '_')
.downcase
end
|
Convert CamelCase +name+ to underscore style.
|
underscore_name
|
ruby
|
dmendel/bindata
|
lib/bindata/registry.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/registry.rb
|
BSD-2-Clause
|
def must_be_integer(*keys)
keys.each do |key|
if has_parameter?(key)
parameter = self[key]
unless Symbol === parameter ||
parameter.respond_to?(:arity) ||
parameter.respond_to?(:to_int)
raise ArgumentError, "parameter '#{key}' in #{@the_class} must " \
"evaluate to an integer, got #{parameter.class}"
end
end
end
end
|
def warn_renamed_parameter(old_key, new_key)
val = delete(old_key)
if val
self[new_key] = val
Kernel.warn ":#{old_key} has been renamed to :#{new_key} in #{@the_class}. " \
"Using :#{old_key} is now deprecated and will be removed in the future"
end
end
|
must_be_integer
|
ruby
|
dmendel/bindata
|
lib/bindata/sanitize.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/sanitize.rb
|
BSD-2-Clause
|
def fast_search_for_obj(obj)
if BinData::Struct === obj
obj.each_pair(true) do |_, field|
fs = fast_search_for(field)
return fs if fs
end
elsif BinData::BasePrimitive === obj
return fast_search_for(obj)
end
nil
end
|
If a search object has an +asserted_value+ field then we
perform a faster search for a valid object.
|
fast_search_for_obj
|
ruby
|
dmendel/bindata
|
lib/bindata/skip.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/skip.rb
|
BSD-2-Clause
|
def field_names(include_hidden = false)
if include_hidden
@field_names.compact
else
hidden = get_parameter(:hide) || []
@field_names.compact - hidden
end
end
|
Returns a list of the names of all fields accessible through this
object. +include_hidden+ specifies whether to include hidden names
in the listing.
|
field_names
|
ruby
|
dmendel/bindata
|
lib/bindata/struct.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/struct.rb
|
BSD-2-Clause
|
def each_pair(include_all = false)
instantiate_all_objs
pairs = @field_names.zip(@field_objs).select do |name, _obj|
name || include_all
end
if block_given?
pairs.each { |el| yield(el) }
else
pairs.each
end
end
|
Calls the given block for each field_name-field_obj pair.
Does not include anonymous or hidden fields unless
+include_all+ is true.
|
each_pair
|
ruby
|
dmendel/bindata
|
lib/bindata/struct.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/struct.rb
|
BSD-2-Clause
|
def trace_reading(io = STDERR)
@tracer = Tracer.new(io)
[BasePrimitive, Choice].each(&:turn_on_tracing)
if block_given?
begin
yield
ensure
[BasePrimitive, Choice].each(&:turn_off_tracing)
@tracer = nil
end
end
end
|
Turn on trace information when reading a BinData object.
If +block+ is given then the tracing only occurs for that block.
This is useful for debugging a BinData declaration.
|
trace_reading
|
ruby
|
dmendel/bindata
|
lib/bindata/trace.rb
|
https://github.com/dmendel/bindata/blob/master/lib/bindata/trace.rb
|
BSD-2-Clause
|
def value
rewind
read
end
|
Returns the value that was written to the io
|
value
|
ruby
|
dmendel/bindata
|
test/test_helper.rb
|
https://github.com/dmendel/bindata/blob/master/test/test_helper.rb
|
BSD-2-Clause
|
def execute
options = {
:_method => :run,
:_rebootable => true,
:auto_reboot => false
}
opts = OptionParser.new do |opts|
opts.banner = "Usage: vagrant vbguest [vm-name] "\
"[--do start|rebuild|install] "\
"[--status] "\
"[-f|--force] "\
"[-b|--auto-reboot] "\
"[-R|--no-remote] "\
"[--iso VBoxGuestAdditions.iso] "\
"[--no-cleanup]"
opts.separator ""
opts.on("--do COMMAND", [:start, :rebuild, :install], "Manually `start`, `rebuild` or `install` GuestAdditions.") do |command|
options[:_method] = command
options[:force] = true
end
opts.on("--status", "Print current GuestAdditions status and exit.") do
options[:_method] = :status
options[:_rebootable] = false
end
opts.on("-f", "--force", "Whether to force the installation. (Implied by --do start|rebuild|install)") do
options[:force] = true
end
opts.on("--auto-reboot", "-b", "Allow rebooting the VM after installation. (when GuestAdditions won't start)") do
options[:auto_reboot] = true
end
opts.on("--no-remote", "-R", "Do not attempt do download the iso file from a webserver") do
options[:no_remote] = true
end
opts.on("--iso file_or_uri", "Full path or URI to the VBoxGuestAdditions.iso") do |file_or_uri|
options[:iso_path] = file_or_uri
end
opts.on("--no-cleanup", "Do not run cleanup tasks after installation. (for debugging)") do
options[:no_cleanup] = true
end
build_start_options(opts, options)
end
argv = parse_options(opts)
return if !argv
if argv.empty?
with_target_vms(nil) { |vm| execute_on_vm(vm, options) }
else
argv.each do |vm_name|
with_target_vms(vm_name) { |vm| execute_on_vm(vm, options) }
end
end
end
|
Runs the vbguest installer on the VMs that are represented
by this environment.
|
execute
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/command.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/command.rb
|
MIT
|
def execute_on_vm(vm, options)
check_runable_on(vm)
options = options.clone
_method = options.delete(:_method)
_rebootable = options.delete(:_rebootable)
options = vm.config.vbguest.to_hash.merge(options)
machine = VagrantVbguest::Machine.new(vm, options)
status = machine.state
vm.env.ui.send((:ok == status ? :success : :warn), I18n.t("vagrant_vbguest.status.#{status}", **machine.info))
if _method != :status
machine.send(_method)
end
reboot!(vm, options) if _rebootable && machine.reboot?
rescue VagrantVbguest::Installer::NoInstallerFoundError => e
vm.env.ui.error e.message
end
|
Executes a task on a specific VM.
@param vm [Vagrant::VM]
@param options [Hash] Parsed options from the command line
|
execute_on_vm
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/command.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/command.rb
|
MIT
|
def to_hash
{
:installer => installer,
:installer_arguments => installer_arguments,
:installer_options => installer_options,
:installer_hooks => installer_hooks,
:iso_path => iso_path,
:iso_upload_path => iso_upload_path,
:iso_mount_point => iso_mount_point,
:auto_update => auto_update,
:auto_reboot => auto_reboot,
:no_install => no_install,
:no_remote => no_remote,
:yes => yes,
:allow_downgrade => allow_downgrade
}
end
|
explicit hash, to get symbols in hash keys
|
to_hash
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/config.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/config.rb
|
MIT
|
def detect(vm, options)
@installers.keys.sort.reverse.each do |prio|
klass = @installers[prio].detect { |k| k.match?(vm) }
return klass if klass
end
return nil
end
|
#
Returns the class of the registered Installer class which
matches first (according to it's priority) or `nil` if none matches.
@param vm [Vagrant::VM]
@param options [Hash]
|
detect
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/installer.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installer.rb
|
MIT
|
def guest_installer
return @guest_installer if @guest_installer
if (klass = guest_installer_class)
@guest_installer = klass.new(@vm, @options)
end
@guest_installer
end
|
Returns an installer instance for the current vm
This is either the one configured via `installer` option or
detected from all registered installers (see {Installer.detect})
@return [Installers::Base]
|
guest_installer
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/installer.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installer.rb
|
MIT
|
def version
@version ||= driver.version
end
|
Determinates the host's version
@return [String] The version code of the *host*'s virtualisation
|
version
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/hosts/base.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/hosts/base.rb
|
MIT
|
def additions_file
return @additions_file if @additions_file
path = options[:iso_path]
if !path || path.empty? || path == :auto
path = local_path
path = web_path if !options[:no_remote] && !path
end
raise VagrantVbguest::IsoPathAutodetectionError if !path || path.empty?
path = versionize(path)
if file_match? path
@additions_file = path
else
# :TODO: This will also raise, if the iso_url points to an invalid local path
raise VagrantVbguest::DownloadingDisabledError.new(:from => path) if options[:no_remote]
@additions_file = download path
end
end
|
Additions-file-detection-magig.
Detection runs in those stages:
1. Uses the +iso_path+ config option, if present and not set to +:auto+
2. Look out for a local additions file
3. Use the default web URI
If the detected or configured path is not a local file and remote downloads
are allowed (the config option +:no_remote+ is NOT set) it will try to
download that file into a temp file using Vagrants Downloaders.
If remote downloads are prohibited (the config option +:no_remote+ IS set)
a +VagrantVbguest::IsoPathAutodetectionError+ will be thrown
@return [String] A absolute path to the GuestAdditions iso file.
This might be a temp-file, e.g. when downloaded from web.
|
additions_file
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/hosts/base.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/hosts/base.rb
|
MIT
|
def cleanup
@download.cleanup if @download
end
|
If needed, remove downloaded temp file
|
cleanup
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/hosts/base.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/hosts/base.rb
|
MIT
|
def file_match?(uri)
extracted = ::URI.extract(uri, "file")
return true if extracted && extracted.include?(uri)
return ::File.file?(::File.expand_path(uri))
end
|
fix bug when the vagrant version is higher than 1.2, by moving method Vagrant::Vagrant::File.match? here
|
file_match?
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/hosts/base.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/hosts/base.rb
|
MIT
|
def web_path
raise NotImplementedError
end
|
Default web URI, where "additions file" can be downloaded.
@return [String] A URI template containing the versions placeholder.
|
web_path
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/hosts/base.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/hosts/base.rb
|
MIT
|
def local_path
raise NotImplementedError
end
|
Finds the "additions file" on the host system.
Returns +nil+ if none found.
@return [String] Absolute path to the local "additions file", or +nil+ if not found.
|
local_path
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/hosts/base.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/hosts/base.rb
|
MIT
|
def versionize(path)
path % {:version => version}
end
|
replaces the veriosn placeholder with the additions
version string
@param path [String] A path or URL (or any other String)
@return [String] A copy of the passed string, with verision
placeholder replaced
|
versionize
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/hosts/base.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/hosts/base.rb
|
MIT
|
def download(path)
@download = VagrantVbguest::Download.new(path, @env.tmp_path, :ui => @env.ui)
@download.download!
@download.destination
end
|
Kicks off +VagrantVbguest::Download+ to download the additions file
into a temp file.
To remove the created tempfile call +cleanup+
@param path [String] The path or URI to download
@return [String] The path to the downloaded file
|
download
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/hosts/base.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/hosts/base.rb
|
MIT
|
def local_path
media_manager_iso || guess_local_iso
end
|
Finds GuestAdditions iso file on the host system.
Returns +nil+ if none found.
@return [String] Absolute path to the local GuestAdditions iso file, or +nil+ if not found.
|
local_path
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/hosts/virtualbox.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/hosts/virtualbox.rb
|
MIT
|
def download(path)
temp_path = File.join(@env.tmp_path, "VBoxGuestAdditions_#{version}.iso")
@download = VagrantVbguest::Download.new(path, temp_path, :ui => @env.ui)
@download.download!
@download.destination
end
|
Kicks off +VagrantVbguest::Download+ to download the additions file
into a temp file.
To remove the created tempfile call +cleanup+
@param path [String] The path or URI to download
@return [String] The path to the downloaded file
|
download
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/hosts/virtualbox.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/hosts/virtualbox.rb
|
MIT
|
def media_manager_iso
driver.execute('list', 'dvds').scan(/^.+:\s+(.*VBoxGuestAdditions(?:_#{version})?\.iso)$/i).map { |path, _|
path if File.exist?(path)
}.compact.first
end
|
Helper method which queries the VirtualBox media manager
for the first existing path that looks like a
+VBoxGuestAdditions.iso+ file.
@return [String] Absolute path to the local GuestAdditions iso file, or +nil+ if not found.
|
media_manager_iso
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/hosts/virtualbox.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/hosts/virtualbox.rb
|
MIT
|
def guess_local_iso
Array(platform_path).find do |path|
path && File.exists?(path)
end
end
|
Find the first GuestAdditions iso file which exists on the host system
@return [String] Absolute path to the local GuestAdditions iso file, or +nil+ if not found.
|
guess_local_iso
|
ruby
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/hosts/virtualbox.rb
|
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/hosts/virtualbox.rb
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.