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 platform_path [:linux, :darwin, :cygwin, :windows].each do |sys| return self.send("#{sys}_path") if Vagrant::Util::Platform.respond_to?("#{sys}?") && Vagrant::Util::Platform.send("#{sys}?") end nil end
Makes an educated guess where the GuestAdditions iso file could be found on the host system depending on the OS. Returns +nil+ if no the file is not in it's place.
platform_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 linux_path paths = [ "/usr/share/virtualbox/VBoxGuestAdditions.iso", "/usr/lib/virtualbox/additions/VBoxGuestAdditions.iso" ] paths.unshift(File.join(ENV['HOME'], '.VirtualBox', "VBoxGuestAdditions_#{version}.iso")) if ENV['HOME'] paths end
Makes an educated guess where the GuestAdditions iso file on linux based systems
linux_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 windows_path if (p = ENV["VBOX_INSTALL_PATH"] || ENV["VBOX_MSI_INSTALL_PATH"]) && !p.empty? File.join(p, "VBoxGuestAdditions.iso") elsif (p = ENV["PROGRAM_FILES"] || ENV["ProgramW6432"] || ENV["PROGRAMFILES"]) && !p.empty? File.join(p, "/Oracle/VirtualBox/VBoxGuestAdditions.iso") end end
Makes an educated guess where the GuestAdditions iso file on windows systems
windows_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 versionize(path) super(path.gsub('$VBOX_VERSION', version)) end
overwrite the default version string to allow lagacy '$VBOX_VERSION' as a placerholder
versionize
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 install(opts=nil, &block) # Update the package list communicate.sudo("pacman -Sy", opts, &block) # Install the dependencies communicate.sudo(install_dependencies_cmd, opts, &block) super end
Install missing deps and yield up to regular linux installation
install
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/archlinux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/archlinux.rb
MIT
def vboxadd_tools_available? raise NotImplementedError end
Is the tooling to manually start or rebuild guest additions installed on the guest? @return [Boolean]
vboxadd_tools_available?
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/base.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/base.rb
MIT
def guest_version(reload=false) return @guest_version if @guest_version && !reload @guest_version = VagrantVbguest::Version(@host.read_guest_additions_version) end
Determinates the GuestAdditions version installed on the guest system. @param reload [Boolean] Whether to read the value again or use the cached value form an earlier call. @return [Gem::Version] The version code of the VirtualBox Guest Additions available on the guest, or `nil` if none installed.
guest_version
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/base.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/base.rb
MIT
def host_version(reload=false) return @host_version if @host_version && !reload @host_version = VagrantVbguest::Version(@host.version) end
Determinates the host (eg VirtualBox) version @param reload [Boolean] Whether to read the value again or use the cached value form an earlier call. @return [Gem::Version] The version code of the host provider
host_version
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/base.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/base.rb
MIT
def installer_version(path_to_installer) version = nil communicate.sudo("#{path_to_installer} --info", :error_check => false) do |type, data| v = VagrantVbguest::Version(data, /\AIdentification.*\s(\d+\.\d+.\d+)/i) version = v if v end version end
Determinates the version of the GuestAdditions installer in use @return [Gem::Version] The version code of the GuestAdditions installer
installer_version
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/base.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/base.rb
MIT
def yield_installation_warning(path_to_installer) @env.ui.warn I18n.t( "vagrant_vbguest.installing#{@options[:force] ? '_forced' : ''}", guest_version: (guest_version || I18n.t("vagrant_vbguest.unknown")), installer_version: (installer_version(path_to_installer) || I18n.t("vagrant_vbguest.unknown"))) end
Helper to yield a warning message to the user, that the installation will start _now_. The message includes the host and installer version strings.
yield_installation_warning
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/base.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/base.rb
MIT
def yield_rebuild_warning @env.ui.warn I18n.t( "vagrant_vbguest.rebuild#{@options[:force] ? '_forced' : ''}", :guest_version => guest_version(true), :host_version => @host.version) end
Helper to yield a warning message to the user, that the installation will be rebuild using the installed GuestAdditions. The message includes the host and installer version strings.
yield_rebuild_warning
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/base.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/base.rb
MIT
def yield_installation_error_warning(path_to_installer) @env.ui.warn I18n.t( "vagrant_vbguest.install_error", installer_version: (installer_version(path_to_installer) || I18n.t("vagrant_vbguest.unknown"))) end
Helper to yield a warning message to the user in the event that the installer returned a non-zero exit status. Because lack of a window system will cause this result in VirtualBox 4.2.8+, we don't want to kill the entire boot process, but we do want to make sure the user knows there could be a problem. The message includles the installer version.
yield_installation_error_warning
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/base.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/base.rb
MIT
def upload(file) env.ui.info(I18n.t("vagrant_vbguest.start_copy_iso", from: file, to: tmp_path)) communicate.upload(file, tmp_path) end
A helper method to handle the GuestAdditions iso file upload into the guest box. The file will uploaded to the location given by the +temp_path+ method. @example Default upload upload(file) @param file [String] Path of the file to upload to the +tmp_path*
upload
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/base.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/base.rb
MIT
def cleanup(opts, &block) unless options[:no_cleanup] @host.cleanup opts = (opts || {}).merge(:error_check => false) block ||= proc { |type, data| env.ui.error(data.chomp, :prefix => false) } communicate.execute("test -f #{tmp_path} && rm #{tmp_path}", opts, &block) end end
A helper method to delete the uploaded GuestAdditions iso file from the guest box
cleanup
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/base.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/base.rb
MIT
def install(opts=nil, &block) if upgrade_kernel? upgrade_kernel(opts, &block) else install_kernel_deps(opts, &block) end super end
Install missing deps and yield up to regular linux installation
install
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/centos.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/centos.rb
MIT
def install(opts=nil, &block) begin communicate.sudo(install_dependencies_cmd, opts, &block) rescue communicate.sudo('apt-get -y --force-yes update', (opts || {}).merge(:error_check => false), &block) communicate.sudo(install_dependencies_cmd, opts, &block) end super end
installs the correct linux-headers package installs `dkms` package for dynamic kernel module loading @param opts [Hash] Optional options Hash which might get passed to {Vagrant::Communication::SSH#execute} and friends @yield [type, data] Takes a Block like {Vagrant::Communication::Base#execute} for realtime output of the command being executed @yieldparam [String] type Type of the output, `:stdout`, `:stderr`, etc. @yieldparam [String] data Data for the given output.
install
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/debian.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/debian.rb
MIT
def install(opts=nil, &block) communicate.sudo(install_dependencies_cmd, opts, &block) super end
Install missing deps and yield up to regular linux installation
install
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/fedora.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/fedora.rb
MIT
def tmp_path options[:iso_upload_path] || '/tmp/VBoxGuestAdditions.iso' end
The temporary path where to upload the iso file to. Configurable via `config.vbguest.iso_upload_path`. Defaults the temp path to `/tmp/VBoxGuestAdditions.iso" for all Linux based systems
tmp_path
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def mount_point options[:iso_mount_point] || '/mnt' end
Mount point for the iso file. Configurable via `config.vbguest.iso_mount_point`. defaults to "/mnt" for all Linux based systems.
mount_point
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def install(opts=nil, &block) env.ui.warn I18n.t("vagrant_vbguest.errors.installer.generic_linux_installer", distro: self.class.distro(vm)) if self.class == Linux upload(iso_file) mount_iso(opts, &block) execute_installer(opts, &block) start(opts, &block) end
a generic way of installing GuestAdditions assuming all dependencies on the guest are installed @param opts [Hash] Optional options Hash wich meight get passed to {Vagrant::Communication::SSH#execute} and firends @yield [type, data] Takes a Block like {Vagrant::Communication::Base#execute} for realtime output of the command being executed @yieldparam [String] type Type of the output, `:stdout`, `:stderr`, etc. @yieldparam [String] data Data for the given output.
install
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def running?(opts=nil, &block) kmods = [] communicate.sudo('cat /proc/modules', opts) do |type, data| block.call(type, data) if block kmods << data if type == :stdout && data end if kmods.empty? env.ui.warn "Could not read /proc/modules" return true end Array(installer_options[:running_kernel_modules]).all? do |mod| regexp = /^#{mod}\b/i kmods.any? { |d| regexp.match(d) } end end
@param opts [Hash] Optional options Hash wich meight get passed to {Vagrant::Communication::SSH#execute} and firends @yield [type, data] Takes a Block like {Vagrant::Communication::Base#execute} for realtime output of the command being executed @yieldparam [String] type Type of the output, `:stdout`, `:stderr`, etc. @yieldparam [String] data Data for the given output.
running?
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def guest_version(reload = false) return @guest_version if @guest_version && !reload driver_version = VagrantVbguest::Version(super) communicate.sudo('VBoxService --version', :error_check => false) do |type, data| service_version = VagrantVbguest::Version(data) if service_version if driver_version != service_version @env.ui.warn(I18n.t("vagrant_vbguest.guest_version_reports_differ", :driver => driver_version, :service => service_version)) end @guest_version = service_version end end @guest_version end
This overrides {VagrantVbguest::Installers::Base#guest_version} to also query the `VBoxService` on the host system (if available) for it's version. In some scenarios the results of the VirtualBox driver and the additions installed on the host may differ. If this happens, we assume, that the host binaries are right and yield a warning message. @return [Gem::Version] The version code of the VirtualBox Guest Additions available on the guest, or `nil` if none installed.
guest_version
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def rebuild(opts=nil, &block) communicate.sudo("#{find_tool('vboxadd')} setup", opts, &block) end
@param opts [Hash] Optional options Hash wich meight get passed to {Vagrant::Communication::SSH#execute} and firends @yield [type, data] Takes a Block like {Vagrant::Communication::Base#execute} for realtime output of the command being executed @yieldparam [String] type Type of the output, `:stdout`, `:stderr`, etc. @yieldparam [String] data Data for the given output.
rebuild
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def start(opts=nil, &block) opts = {:error_check => false}.merge(opts || {}) if systemd_tool communicate.sudo("#{systemd_tool[:path]} vboxadd #{systemd_tool[:up]}", opts, &block) else communicate.sudo("#{find_tool('vboxadd')} start", opts, &block) end if guest_version && guest_version >= Gem::Version.new('5.1') if systemd_tool communicate.sudo("#{systemd_tool[:path]} vboxadd-service #{systemd_tool[:up]}", opts, &block) else communicate.sudo("#{find_tool('vboxadd-service')} start", opts, &block) end end end
@param opts [Hash] Optional options Hash wich meight get passed to {Vagrant::Communication::SSH#execute} and firends @yield [type, data] Takes a Block like {Vagrant::Communication::Base#execute} for realtime output of the command being executed @yieldparam [String] type Type of the output, `:stdout`, `:stderr`, etc. @yieldparam [String] data Data for the given output.
start
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def systemd_tool return nil if @systemd_tool == false result = nil communicate.sudo('(which chkconfg || which service) 2>/dev/null', {:error_check => false}) do |type, data| path = data.to_s.strip case path when /\bservice\b/ result = { path: path, up: "start", down: "stop" } when /\bchkconfg\b/ result = { path: path, up: "on", down: "off" } end end if result.nil? @systemd_tool = false nil else @systemd_tool = result end end
Check for the presence of 'systemd' chkconfg or service command. systemd_tool # => {:path=>"/usr/sbin/service", :up=>"start"} @return [Hash|nil] Hash with an absolute +path+ to the tool and the command string for starting. +nil* if neither was found.
systemd_tool
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def find_tool(tool) candidates = [ "/usr/lib/i386-linux-gnu/VBoxGuestAdditions/#{tool}", "/usr/lib/x86_64-linux-gnu/VBoxGuestAdditions/#{tool}", "/usr/lib64/VBoxGuestAdditions/#{tool}", "/usr/lib/VBoxGuestAdditions/#{tool}", "/lib64/VBoxGuestAdditions/#{tool}", "/lib/VBoxGuestAdditions/#{tool}", "/etc/init.d/#{tool}", "/usr/sbin/rc#{tool}", "/sbin/rc#{tool}" ] cmd = <<-SHELL for c in #{candidates.join(" ")}; do if test -x "$c"; then echo $c break fi done SHELL path = nil communicate.sudo(cmd, {:error_check => false}) do |type, data| path = data.strip unless data.empty? end path end
Checks for the correct location of the tool provided. It checks for a given list of possible locations. This list got extracted from the 'VBoxLinuxAdditions.run' script. @return [String|nil] Absolute path to the tool, or +nil+ if none found.
find_tool
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def execute_installer(opts=nil, &block) yield_installation_warning(installer) opts = {:error_check => false}.merge(opts || {}) exit_status = communicate.sudo("#{yes}#{installer} #{installer_arguments}", opts, &block) yield_installation_error_warning(installer) unless exit_status == 0 exit_status end
A generic helper method to execute the installer. This also yields a installation warning to the user, and an error warning in the event that the installer returns a non-zero exit status. @param opts [Hash] Optional options Hash wich meight get passed to {Vagrant::Communication::SSH#execute} and firends @yield [type, data] Takes a Block like {Vagrant::Communication::Base#execute} for realtime output of the command being executed @yieldparam [String] type Type of the output, `:stdout`, `:stderr`, etc. @yieldparam [String] data Data for the given output.
execute_installer
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def installer @installer ||= File.join(mount_point, 'VBoxLinuxAdditions.run') end
The absolute path to the GuestAdditions installer script. The iso file has to be mounted on +mount_point+.
installer
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def installer_arguments @installer_arguments ||= Array(options[:installer_arguments]).join " " end
The arguments string, which gets passed to the installer script
installer_arguments
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def yes value = @options[:yes] # Simple yes if explicitly boolean true return "yes | " if !!value == value && value # Nothing if set to false return "" if !value # Otherwise pass input string to yes "yes #{value} | " end
Determine if yes needs to be called or not
yes
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def mount_iso(opts=nil, &block) env.ui.info(I18n.t("vagrant_vbguest.mounting_iso", :mount_point => mount_point)) communicate.sudo("mount #{tmp_path} -o loop #{mount_point}", opts, &block) @mounted = true end
A generic helper method for mounting the GuestAdditions iso file on most linux system. Mounts the given uploaded file from +tmp_path+ on +mount_point+. @param opts [Hash] Optional options Hash wich meight get passed to {Vagrant::Communication::SSH#execute} and firends @yield [type, data] Takes a Block like {Vagrant::Communication::Base#execute} for realtime output of the command being executed @yieldparam [String] type Type of the output, `:stdout`, `:stderr`, etc. @yieldparam [String] data Data for the given output.
mount_iso
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def unmount_iso(opts=nil, &block) unless @mounted env.ui.info(I18n.t("vagrant_vbguest.skip_unmounting_iso")) return end env.ui.info(I18n.t("vagrant_vbguest.unmounting_iso", :mount_point => mount_point)) opts = (opts || {}).merge(:error_check => false) communicate.sudo("umount #{mount_point}", opts, &block) @mounted = false end
A generic helper method for un-mounting the GuestAdditions iso file on most linux system Unmounts the +mount_point+. @param opts [Hash] Optional options Hash wich meight get passed to {Vagrant::Communication::SSH#execute} and firends @yield [type, data] Takes a Block like {Vagrant::Communication::Base#execute} for realtime output of the command being executed @yieldparam [String] type Type of the output, `:stdout`, `:stderr`, etc. @yieldparam [String] data Data for the given output.
unmount_iso
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/linux.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/linux.rb
MIT
def install(opts=nil, &block) communicate.sudo(uninstall_dist_install_cmd, (opts || {}).merge(:error_check => false), &block) communicate.sudo(install_dependencies_cmd, opts, &block) super end
Install missing deps and yield up to regular linux installation
install
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/opensuse.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/opensuse.rb
MIT
def install(opts=nil, &block) communicate.sudo(install_dependencies_cmd, opts, &block) super end
Install missing deps and yield up to regular linux installation
install
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/redhat.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/redhat.rb
MIT
def install(opts=nil, &block) communicate.sudo(install_dependencies_cmd, opts, &block) super end
Install missing deps and yield up to regular linux installation
install
ruby
dotless-de/vagrant-vbguest
lib/vagrant-vbguest/installers/suse.rb
https://github.com/dotless-de/vagrant-vbguest/blob/master/lib/vagrant-vbguest/installers/suse.rb
MIT
def find_some_without_failing(ids, options = {}) return [] if !ids or ids.empty? conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions] ids_list = ids.map { |id| quote_value(id,columns_hash[primary_key]) }.join(',') options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} IN (#{ids_list})#{conditions}" result = find_every(options) result end
Send an array to ActiveRecord without fear that some elements don't exist.
find_some_without_failing
ruby
maccman/acts_as_recommendable
lib/acts_as_recommendable.rb
https://github.com/maccman/acts_as_recommendable/blob/master/lib/acts_as_recommendable.rb
MIT
def eta if @current == 0 "ETA: --:--:--" else elapsed = Time.now - @start_time eta = elapsed * @total / @current - elapsed; sprintf("ETA: %s", format_time(eta)) end end
ETA stands for Estimated Time of Arrival.
eta
ruby
maccman/acts_as_recommendable
lib/progress_bar.rb
https://github.com/maccman/acts_as_recommendable/blob/master/lib/progress_bar.rb
MIT
def set_vault @vault = params[:vault_id] ? Vault.find_by_id(params[:vault_id]) : Vault.find_by_id(params[:id]) redirect_to root_url if @vault.nil? || @vault.user_username != params[:username] end
Use callbacks to share common setup or constraints between actions.
set_vault
ruby
codervault/codervault
app/controllers/application_controller.rb
https://github.com/codervault/codervault/blob/master/app/controllers/application_controller.rb
MIT
def update respond_to do |format| if @snippet.update(snippet_params) format.html { redirect_to [@snippet.vault, @snippet], notice: 'Snippet was successfully updated.' } format.json { render :show, status: :ok, location: @snippet } else format.html { render :edit } format.json { render json: @snippet.errors, status: :unprocessable_entity } end end end
PATCH/PUT /snippets/1 PATCH/PUT /snippets/1.json
update
ruby
codervault/codervault
app/controllers/snippets_controller.rb
https://github.com/codervault/codervault/blob/master/app/controllers/snippets_controller.rb
MIT
def snippet_params params.require(:snippet).permit(:name, :language, :code) end
Never trust parameters from the scary internet, only allow the white list through.
snippet_params
ruby
codervault/codervault
app/controllers/snippets_controller.rb
https://github.com/codervault/codervault/blob/master/app/controllers/snippets_controller.rb
MIT
def update respond_to do |format| if @vault.update(vault_params) format.html { redirect_to @vault, notice: 'Vault was successfully updated.' } format.json { render :show, status: :ok, location: @vault } else format.html { render :edit } format.json { render json: @vault.errors, status: :unprocessable_entity } end end end
PATCH/PUT /vaults/1 PATCH/PUT /vaults/1.json
update
ruby
codervault/codervault
app/controllers/vaults_controller.rb
https://github.com/codervault/codervault/blob/master/app/controllers/vaults_controller.rb
MIT
def vault_params params.require(:vault).permit(:name, :readme, :exposure) end
Never trust parameters from the scary internet, only allow the white list through.
vault_params
ruby
codervault/codervault
app/controllers/vaults_controller.rb
https://github.com/codervault/codervault/blob/master/app/controllers/vaults_controller.rb
MIT
def aggregate_failures(label=nil, metadata={}, &block) Expectations::FailureAggregator.new(label, metadata).aggregate(&block) end
@!method self.alias_matcher(new_name, old_name, options={}, &description_override) Extended from {RSpec::Matchers::DSL#alias_matcher}. @!method self.define(name, &declarations) Extended from {RSpec::Matchers::DSL#define}. @!method self.define_negated_matcher(negated_name, base_name, &description_override) Extended from {RSpec::Matchers::DSL#define_negated_matcher}. @method expect Supports `expect(actual).to matcher` syntax by wrapping `actual` in an `ExpectationTarget`. @example expect(actual).to eq(expected) expect(actual).not_to eq(expected) @return [Expectations::ExpectationTarget] @see Expectations::ExpectationTarget#to @see Expectations::ExpectationTarget#not_to Allows multiple expectations in the provided block to fail, and then aggregates them into a single exception, rather than aborting on the first expectation failure like normal. This allows you to see all failures from an entire set of expectations without splitting each off into its own example (which may slow things down if the example setup is expensive). @param label [String] label for this aggregation block, which will be included in the aggregated exception message. @param metadata [Hash] additional metadata about this failure aggregation block. If multiple expectations fail, it will be exposed from the {Expectations::MultipleExpectationsNotMetError} exception. Mostly intended for internal RSpec use but you can use it as well. @yield Block containing as many expectation as you want. The block is simply yielded to, so you can trust that anything that works outside the block should work within it. @raise [Expectations::MultipleExpectationsNotMetError] raised when multiple expectations fail. @raise [Expectations::ExpectationNotMetError] raised when a single expectation fails. @raise [Exception] other sorts of exceptions will be raised as normal. @example aggregate_failures("verifying response") do expect(response.status).to eq(200) expect(response.headers).to include("Content-Type" => "text/plain") expect(response.body).to include("Success") end @note The implementation of this feature uses a thread-local variable, which means that if you have an expectation failure in another thread, it'll abort like normal.
aggregate_failures
ruby
rspec/rspec-expectations
lib/rspec/matchers.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers.rb
MIT
def be(*args) args.empty? ? Matchers::BuiltIn::Be.new : equal(*args) end
@example expect(actual).to be_truthy expect(actual).to be_falsey expect(actual).to be_nil expect(actual).to be_[arbitrary_predicate](*args) expect(actual).not_to be_nil expect(actual).not_to be_[arbitrary_predicate](*args) Given true, false, or nil, will pass if actual value is true, false or nil (respectively). Given no args means the caller should satisfy an if condition (to be or not to be). Predicates are any Ruby method that ends in a "?" and returns true or false. Given be_ followed by arbitrary_predicate (without the "?"), RSpec will match convert that into a query against the target object. The arbitrary_predicate feature will handle any predicate prefixed with "be_an_" (e.g. be_an_instance_of), "be_a_" (e.g. be_a_kind_of) or "be_" (e.g. be_empty), letting you choose the prefix that best suits the predicate.
be
ruby
rspec/rspec-expectations
lib/rspec/matchers.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers.rb
MIT
def be_between(min, max) BuiltIn::BeBetween.new(min, max) end
Passes if actual.between?(min, max). Works with any Comparable object, including String, Symbol, Time, or Numeric (Fixnum, Bignum, Integer, Float, Complex, and Rational). By default, `be_between` is inclusive (i.e. passes when given either the max or min value), but you can make it `exclusive` by chaining that off the matcher. @example expect(5).to be_between(1, 10) expect(11).not_to be_between(1, 10) expect(10).not_to be_between(1, 10).exclusive
be_between
ruby
rspec/rspec-expectations
lib/rspec/matchers.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers.rb
MIT
def change(receiver=nil, message=nil, &block) BuiltIn::Change.new(receiver, message, &block) end
Applied to a proc, specifies that its execution will cause some value to change. @param [Object] receiver @param [Symbol] message the message to send the receiver You can either pass <tt>receiver</tt> and <tt>message</tt>, or a block, but not both. When passing a block, it must use the `{ ... }` format, not do/end, as `{ ... }` binds to the `change` method, whereas do/end would errantly bind to the `expect(..).to` or `expect(...).not_to` method. You can chain any of the following off of the end to specify details about the change: * `from` * `to` or any one of: * `by` * `by_at_least` * `by_at_most` @example expect { team.add_player(player) }.to change(roster, :count) expect { team.add_player(player) }.to change(roster, :count).by(1) expect { team.add_player(player) }.to change(roster, :count).by_at_least(1) expect { team.add_player(player) }.to change(roster, :count).by_at_most(1) string = "string" expect { string.reverse! }.to change { string }.from("string").to("gnirts") string = "string" expect { string }.not_to change { string }.from("string") expect { person.happy_birthday }.to change(person, :birthday).from(32).to(33) expect { employee.develop_great_new_social_networking_app }.to change(employee, :title).from("Mail Clerk").to("CEO") expect { doctor.leave_office }.to change(doctor, :sign).from(/is in/).to(/is out/) user = User.new(:type => "admin") expect { user.symbolize_type }.to change(user, :type).from(String).to(Symbol) == Notes Evaluates `receiver.message` or `block` before and after it evaluates the block passed to `expect`. If the value is the same object, its before/after `hash` value is used to see if it has changed. Therefore, your object needs to properly implement `hash` to work correctly with this matcher. `expect( ... ).not_to change` supports the form that specifies `from` (which specifies what you expect the starting, unchanged value to be) but does not support forms with subsequent calls to `by`, `by_at_least`, `by_at_most` or `to`.
change
ruby
rspec/rspec-expectations
lib/rspec/matchers.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers.rb
MIT
def raise_error(error=BuiltIn::RaiseError::UndefinedValue, message=nil, &block) BuiltIn::RaiseError.new(error, message, &block) end
With no args, matches if any error is raised. With a named error, matches only if that specific error is raised. With a named error and message specified as a String, matches only if both match. With a named error and message specified as a Regexp, matches only if both match. Pass an optional block to perform extra verifications on the exception matched @example expect { do_something_risky }.to raise_error expect { do_something_risky }.to raise_error(PoorRiskDecisionError) expect { do_something_risky }.to raise_error(PoorRiskDecisionError) { |error| expect(error.data).to eq 42 } expect { do_something_risky }.to raise_error { |error| expect(error.data).to eq 42 } expect { do_something_risky }.to raise_error(PoorRiskDecisionError, "that was too risky") expect { do_something_risky }.to raise_error(PoorRiskDecisionError, /oo ri/) expect { do_something_risky }.to raise_error("that was too risky") expect { do_something_risky }.not_to raise_error
raise_error
ruby
rspec/rspec-expectations
lib/rspec/matchers.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers.rb
MIT
def throw_symbol(expected_symbol=nil, expected_arg=nil) BuiltIn::ThrowSymbol.new(expected_symbol, expected_arg) end
Given no argument, matches if a proc throws any Symbol. Given a Symbol, matches if the given proc throws the specified Symbol. Given a Symbol and an arg, matches if the given proc throws the specified Symbol with the specified arg. @example expect { do_something_risky }.to throw_symbol expect { do_something_risky }.to throw_symbol(:that_was_risky) expect { do_something_risky }.to throw_symbol(:that_was_risky, 'culprit') expect { do_something_risky }.not_to throw_symbol expect { do_something_risky }.not_to throw_symbol(:that_was_risky) expect { do_something_risky }.not_to throw_symbol(:that_was_risky, 'culprit')
throw_symbol
ruby
rspec/rspec-expectations
lib/rspec/matchers.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers.rb
MIT
def append_features(mod) return super if mod < self # `mod < self` indicates a re-inclusion. subclasses = ObjectSpace.each_object(Class).select { |c| c < mod && c < self } return super unless subclasses.any? subclasses.reject! { |s| subclasses.any? { |s2| s < s2 } } # Filter to the root ancestor. subclasses = subclasses.map { |s| "`#{s}`" }.join(", ") RSpec.warning "`#{self}` has been included in a superclass (`#{mod}`) " \ "after previously being included in subclasses (#{subclasses}), " \ "which can trigger infinite recursion from `super` due to an MRI 1.9 bug " \ "(https://redmine.ruby-lang.org/issues/3351). To work around this, " \ "either upgrade to MRI 2.0+, include a dup of the module (e.g. " \ "`include #{self}.dup`), or find a way to include `#{self}` in `#{mod}` " \ "before it is included in subclasses (#{subclasses}). See " \ "https://github.com/rspec/rspec-expectations/issues/814 for more info" super end
Note that `included` doesn't work for this because it is triggered _after_ `RSpec::Matchers` is an ancestor of the inclusion host, rather than _before_, like `append_features`. It's important we check this before in order to find the cases where it was already previously included. @api private :nocov:
append_features
ruby
rspec/rspec-expectations
lib/rspec/matchers.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers.rb
MIT
def syntax syntaxes = [] syntaxes << :should if Expectations::Syntax.should_enabled? syntaxes << :expect if Expectations::Syntax.expect_enabled? syntaxes end
The list of configured syntaxes. @return [Array<Symbol>] the list of configured syntaxes. @example unless RSpec::Matchers.configuration.syntax.include?(:expect) raise "this RSpec extension gem requires the rspec-expectations `:expect` syntax" end
syntax
ruby
rspec/rspec-expectations
lib/rspec/expectations/configuration.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/configuration.rb
MIT
def color? defined?(@color) && @color end
Indicates whether or not diffs should be colored. Delegates to rspec-core's color option if rspec-core is loaded; otherwise you can set it here.
color?
ruby
rspec/rspec-expectations
lib/rspec/expectations/configuration.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/configuration.rb
MIT
def add_should_and_should_not_to(*modules) modules.each do |mod| Expectations::Syntax.enable_should(mod) end end
:nocov: Because this is only really _useful_ on 1.8, and hard to test elsewhere. Adds `should` and `should_not` to the given classes or modules. This can be used to ensure `should` works properly on things like proxy objects (particular `Delegator`-subclassed objects on 1.8). @param [Array<Module>] modules the list of classes or modules to add `should` and `should_not` to.
add_should_and_should_not_to
ruby
rspec/rspec-expectations
lib/rspec/expectations/configuration.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/configuration.rb
MIT
def include_chain_clauses_in_custom_matcher_descriptions? @include_chain_clauses_in_custom_matcher_descriptions ||= false end
Indicates whether or not custom matcher descriptions and failure messages should include clauses from methods defined using `chain`. It is false by default for backwards compatibility.
include_chain_clauses_in_custom_matcher_descriptions?
ruby
rspec/rspec-expectations
lib/rspec/expectations/configuration.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/configuration.rb
MIT
def warn_about_potential_false_positives? on_potential_false_positives == :warn end
Indicates whether RSpec will warn about matcher use which will potentially cause false positives in tests, generally you want to avoid such scenarios so this defaults to `true`.
warn_about_potential_false_positives?
ruby
rspec/rspec-expectations
lib/rspec/expectations/configuration.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/configuration.rb
MIT
def to(matcher=nil, message=nil, &block) prevent_operator_matchers(:to) unless matcher RSpec::Expectations::PositiveExpectationHandler.handle_matcher(target, matcher, message, &block) end
Runs the given expectation, passing if `matcher` returns true. @example expect(value).to eq(5) expect { perform }.to raise_error @param [Matcher] matcher @param [String, Proc] message optional message to display when the expectation fails @return [Boolean] true if the expectation succeeds (else raises) @see RSpec::Matchers
to
ruby
rspec/rspec-expectations
lib/rspec/expectations/expectation_target.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/expectation_target.rb
MIT
def not_to(matcher=nil, message=nil, &block) prevent_operator_matchers(:not_to) unless matcher RSpec::Expectations::NegativeExpectationHandler.handle_matcher(target, matcher, message, &block) end
Runs the given expectation, passing if `matcher` returns false. @example expect(value).not_to eq(5) @param [Matcher] matcher @param [String, Proc] message optional message to display when the expectation fails @return [Boolean] false if the negative expectation succeeds (else raises) @see RSpec::Matchers
not_to
ruby
rspec/rspec-expectations
lib/rspec/expectations/expectation_target.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/expectation_target.rb
MIT
def call(failure, options) source_id = options[:source_id] return if source_id && @seen_source_ids.key?(source_id) @seen_source_ids[source_id] = true assign_backtrace(failure) unless failure.backtrace failures << failure AGGREGATED_FAILURE end
This method is defined to satisfy the callable interface expected by `RSpec::Support.with_failure_notifier`.
call
ruby
rspec/rspec-expectations
lib/rspec/expectations/failure_aggregator.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/failure_aggregator.rb
MIT
def assign_backtrace(failure) raise failure rescue failure.class => e failure.set_backtrace(e.backtrace) end
On JRuby 9.1.x.x and before, `caller` and `raise` produce different backtraces with regards to `.java` stack frames. It's important that we use `raise` for JRuby to produce a backtrace that has a continuous common section with the raised `MultipleExpectationsNotMetError`, so that rspec-core's truncation logic can work properly on it to list the backtrace relative to the `aggregate_failures` block. :nocov:
assign_backtrace
ruby
rspec/rspec-expectations
lib/rspec/expectations/failure_aggregator.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/failure_aggregator.rb
MIT
def message @message ||= (["#{summary}:"] + enumerated_failures + enumerated_errors).join("\n\n") end
@return [String] The fully formatted exception message.
message
ruby
rspec/rspec-expectations
lib/rspec/expectations/failure_aggregator.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/failure_aggregator.rb
MIT
def summary "Got #{exception_count_description} from failure aggregation " \ "block#{block_description}" end
@return [String] A summary of the failure, including the block label and a count of failures.
summary
ruby
rspec/rspec-expectations
lib/rspec/expectations/failure_aggregator.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/failure_aggregator.rb
MIT
def exception_count_description failure_count = pluralize("failure", failures.size) return failure_count if other_errors.empty? error_count = pluralize("other error", other_errors.size) "#{failure_count} and #{error_count}" end
return [String] A description of the failure/error counts.
exception_count_description
ruby
rspec/rspec-expectations
lib/rspec/expectations/failure_aggregator.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/failure_aggregator.rb
MIT
def fail_with(message, expected=nil, actual=nil) unless message raise ArgumentError, "Failure message is nil. Does your matcher define the " \ "appropriate failure_message[_when_negated] method to return a string?" end message = ::RSpec::Matchers::MultiMatcherDiff.from(expected, actual).message_with_diff(message, differ) RSpec::Support.notify_failure(RSpec::Expectations::ExpectationNotMetError.new message) end
Raises an RSpec::Expectations::ExpectationNotMetError with message. @param [String] message @param [Object] expected @param [Object] actual Adds a diff to the failure message when `expected` and `actual` are both present.
fail_with
ruby
rspec/rspec-expectations
lib/rspec/expectations/fail_with.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/fail_with.rb
MIT
def expect(*a, &b) self.assertions += 1 super end
This `expect` will only be called if the user is using Minitest < 5.6 or if they are _not_ using Minitest::Spec on 5.6+. Minitest::Spec on 5.6+ defines its own `expect` and will have the assertions incremented via our definitions of `to`/`not_to`/`to_not` below.
expect
ruby
rspec/rspec-expectations
lib/rspec/expectations/minitest_integration.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/minitest_integration.rb
MIT
def aggregate_failures(*args, &block) super rescue RSpec::Expectations::MultipleExpectationsNotMetError => e assertion_failed = Minitest::Assertion.new(e.message) assertion_failed.set_backtrace e.backtrace raise assertion_failed end
Convert a `MultipleExpectationsNotMetError` to a `Minitest::Assertion` error so it gets counted in minitest's summary stats as a failure rather than an error. It would be nice to make `MultipleExpectationsNotMetError` subclass `Minitest::Assertion`, but Minitest's implementation does not treat subclasses the same, so this is the best we can do.
aggregate_failures
ruby
rspec/rspec-expectations
lib/rspec/expectations/minitest_integration.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/minitest_integration.rb
MIT
def default_should_host @default_should_host ||= ::Object.ancestors.last end
@api private Determines where we add `should` and `should_not`.
default_should_host
ruby
rspec/rspec-expectations
lib/rspec/expectations/syntax.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/syntax.rb
MIT
def warn_about_should! @warn_about_should = true end
@api private Instructs rspec-expectations to warn on first usage of `should` or `should_not`. Enabled by default. This is largely here to facilitate testing.
warn_about_should!
ruby
rspec/rspec-expectations
lib/rspec/expectations/syntax.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/syntax.rb
MIT
def warn_about_should_unless_configured(method_name) return unless @warn_about_should RSpec.deprecate( "Using `#{method_name}` from rspec-expectations' old `:should` syntax without explicitly enabling the syntax", :replacement => "the new `:expect` syntax or explicitly enable `:should` with `config.expect_with(:rspec) { |c| c.syntax = :should }`" ) @warn_about_should = false end
@api private Generates a deprecation warning for the given method if no warning has already been issued.
warn_about_should_unless_configured
ruby
rspec/rspec-expectations
lib/rspec/expectations/syntax.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/syntax.rb
MIT
def enable_should(syntax_host=default_should_host) @warn_about_should = false if syntax_host == default_should_host return if should_enabled?(syntax_host) syntax_host.module_exec do def should(matcher=nil, message=nil, &block) ::RSpec::Expectations::Syntax.warn_about_should_unless_configured(::Kernel.__method__) ::RSpec::Expectations::PositiveExpectationHandler.handle_matcher(self, matcher, message, &block) end def should_not(matcher=nil, message=nil, &block) ::RSpec::Expectations::Syntax.warn_about_should_unless_configured(::Kernel.__method__) ::RSpec::Expectations::NegativeExpectationHandler.handle_matcher(self, matcher, message, &block) end end end
@api private Enables the `should` syntax.
enable_should
ruby
rspec/rspec-expectations
lib/rspec/expectations/syntax.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/syntax.rb
MIT
def disable_should(syntax_host=default_should_host) return unless should_enabled?(syntax_host) syntax_host.module_exec do undef should undef should_not end end
@api private Disables the `should` syntax.
disable_should
ruby
rspec/rspec-expectations
lib/rspec/expectations/syntax.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/syntax.rb
MIT
def enable_expect(syntax_host=::RSpec::Matchers) return if expect_enabled?(syntax_host) syntax_host.module_exec do def expect(value=::RSpec::Expectations::ExpectationTarget::UndefinedValue, &block) ::RSpec::Expectations::ExpectationTarget.for(value, block) end end end
@api private Enables the `expect` syntax.
enable_expect
ruby
rspec/rspec-expectations
lib/rspec/expectations/syntax.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/syntax.rb
MIT
def disable_expect(syntax_host=::RSpec::Matchers) return unless expect_enabled?(syntax_host) syntax_host.module_exec do undef expect end end
@api private Disables the `expect` syntax.
disable_expect
ruby
rspec/rspec-expectations
lib/rspec/expectations/syntax.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/expectations/syntax.rb
MIT
def method_missing(*) return_val = super return return_val unless RSpec::Matchers.is_a_matcher?(return_val) self.class.new(return_val, @description_block) end
Forward messages on to the wrapped matcher. Since many matchers provide a fluent interface (e.g. `a_value_within(0.1).of(3)`), we need to wrap the returned value if it responds to `description`, so that our override can be applied when it is eventually used.
method_missing
ruby
rspec/rspec-expectations
lib/rspec/matchers/aliased_matcher.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/aliased_matcher.rb
MIT
def optimal_failure_message(same, inverted) if DefaultFailureMessages.has_default_failure_messages?(@base_matcher) base_message = @base_matcher.__send__(same) overridden = @description_block.call(base_message) return overridden if overridden != base_message end @base_matcher.__send__(inverted) end
For a matcher that uses the default failure messages, we prefer to use the override provided by the `description_block`, because it includes the phrasing that the user has expressed a preference for by going through the effort of defining a negated matcher. However, if the override didn't actually change anything, then we should return the opposite failure message instead -- the overridden message is going to be confusing if we return it as-is, as it represents the non-negated failure message for a negated match (or vice versa).
optimal_failure_message
ruby
rspec/rspec-expectations
lib/rspec/matchers/aliased_matcher.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/aliased_matcher.rb
MIT
def and(matcher) BuiltIn::Compound::And.new self, matcher end
Creates a compound `and` expectation. The matcher will only pass if both sub-matchers pass. This can be chained together to form an arbitrarily long chain of matchers. @example expect(alphabet).to start_with("a").and end_with("z") expect(alphabet).to start_with("a") & end_with("z") @note The negative form (`expect(...).not_to matcher.and other`) is not supported at this time.
and
ruby
rspec/rspec-expectations
lib/rspec/matchers/composable.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/composable.rb
MIT
def or(matcher) BuiltIn::Compound::Or.new self, matcher end
Creates a compound `or` expectation. The matcher will pass if either sub-matcher passes. This can be chained together to form an arbitrarily long chain of matchers. @example expect(stoplight.color).to eq("red").or eq("green").or eq("yellow") expect(stoplight.color).to eq("red") | eq("green") | eq("yellow") @note The negative form (`expect(...).not_to matcher.or other`) is not supported at this time.
or
ruby
rspec/rspec-expectations
lib/rspec/matchers/composable.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/composable.rb
MIT
def values_match?(expected, actual) expected = with_matchers_cloned(expected) Support::FuzzyMatcher.values_match?(expected, actual) end
This provides a generic way to fuzzy-match an expected value against an actual value. It understands nested data structures (e.g. hashes and arrays) and is able to match against a matcher being used as the expected value or within the expected value at any level of nesting. Within a custom matcher you are encouraged to use this whenever your matcher needs to match two values, unless it needs more precise semantics. For example, the `eq` matcher _does not_ use this as it is meant to use `==` (and only `==`) for matching. @param expected [Object] what is expected @param actual [Object] the actual value @!visibility public
values_match?
ruby
rspec/rspec-expectations
lib/rspec/matchers/composable.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/composable.rb
MIT
def surface_descriptions_in(item) if Matchers.is_a_describable_matcher?(item) DescribableItem.new(item) elsif Hash === item Hash[surface_descriptions_in(item.to_a)] elsif Struct === item || unreadable_io?(item) RSpec::Support::ObjectFormatter.format(item) elsif should_enumerate?(item) item.map { |subitem| surface_descriptions_in(subitem) } else item end end
Transforms the given data structure (typically a hash or array) into a new data structure that, when `#inspect` is called on it, will provide descriptions of any contained matchers rather than the normal `#inspect` output. You are encouraged to use this in your custom matcher's `description`, `failure_message` or `failure_message_when_negated` implementation if you are supporting any arguments which may be a data structure containing matchers. @!visibility public
surface_descriptions_in
ruby
rspec/rspec-expectations
lib/rspec/matchers/composable.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/composable.rb
MIT
def with_matchers_cloned(object) if Matchers.is_a_matcher?(object) object.clone elsif Hash === object Hash[with_matchers_cloned(object.to_a)] elsif should_enumerate?(object) object.map { |subobject| with_matchers_cloned(subobject) } else object end end
@private Historically, a single matcher instance was only checked against a single value. Given that the matcher was only used once, it's been common to memoize some intermediate calculation that is derived from the `actual` value in order to reuse that intermediate result in the failure message. This can cause a problem when using such a matcher as an argument to another matcher in a composed matcher expression, since the matcher instance may be checked against multiple values and produce invalid results due to the memoization. To deal with this, we clone any matchers in `expected` via this method when using `values_match?`, so that any memoization does not "leak" between checks.
with_matchers_cloned
ruby
rspec/rspec-expectations
lib/rspec/matchers/composable.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/composable.rb
MIT
def should_enumerate?(item) Array === item && item.none? { |subitem| subitem.equal?(item) } end
@api private We should enumerate arrays as long as they are not recursive.
should_enumerate?
ruby
rspec/rspec-expectations
lib/rspec/matchers/composable.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/composable.rb
MIT
def pretty_print(pp) pp.text "(#{item.description})" end
A pretty printed version of the item description.
pretty_print
ruby
rspec/rspec-expectations
lib/rspec/matchers/composable.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/composable.rb
MIT
def alias_matcher(new_name, old_name, options={}, &description_override) description_override ||= lambda do |old_desc| old_desc.gsub(EnglishPhrasing.split_words(old_name), EnglishPhrasing.split_words(new_name)) end klass = options.fetch(:klass) { AliasedMatcher } define_method(new_name) do |*args, &block| matcher = __send__(old_name, *args, &block) matcher.matcher_name = new_name if matcher.respond_to?(:matcher_name=) klass.new(matcher, description_override) end ruby2_keywords new_name if respond_to?(:ruby2_keywords, true) end
Defines a matcher alias. The returned matcher's `description` will be overridden to reflect the phrasing of the new name, which will be used in failure messages when passed as an argument to another matcher in a composed matcher expression. @example RSpec::Matchers.alias_matcher :a_list_that_sums_to, :sum_to sum_to(3).description # => "sum to 3" a_list_that_sums_to(3).description # => "a list that sums to 3" @example RSpec::Matchers.alias_matcher :a_list_sorted_by, :be_sorted_by do |description| description.sub("be sorted by", "a list sorted by") end be_sorted_by(:age).description # => "be sorted by age" a_list_sorted_by(:age).description # => "a list sorted by age" @param new_name [Symbol] the new name for the matcher @param old_name [Symbol] the original name for the matcher @param options [Hash] options for the aliased matcher @option options [Class] :klass the ruby class to use as the decorator. (Not normally used). @yield [String] optional block that, when given, is used to define the overridden logic. The yielded arg is the original description or failure message. If no block is provided, a default override is used based on the old and new names. @see RSpec::Matchers
alias_matcher
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def define_negated_matcher(negated_name, base_name, &description_override) alias_matcher(negated_name, base_name, :klass => AliasedNegatedMatcher, &description_override) end
Defines a negated matcher. The returned matcher's `description` and `failure_message` will be overridden to reflect the phrasing of the new name, and the match logic will be based on the original matcher but negated. @example RSpec::Matchers.define_negated_matcher :exclude, :include include(1, 2).description # => "include 1 and 2" exclude(1, 2).description # => "exclude 1 and 2" @param negated_name [Symbol] the name for the negated matcher @param base_name [Symbol] the name of the original matcher that will be negated @yield [String] optional block that, when given, is used to define the overridden logic. The yielded arg is the original description or failure message. If no block is provided, a default override is used based on the old and new names. @see RSpec::Matchers
define_negated_matcher
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def define(name, &declarations) warn_about_block_args(name, declarations) define_method name do |*expected, &block_arg| RSpec::Matchers::DSL::Matcher.new(name, declarations, self, *expected, &block_arg) end end
Defines a custom matcher. @param name [Symbol] the name for the matcher @yield [Object] block that is used to define the matcher. The block is evaluated in the context of your custom matcher class. When args are passed to your matcher, they will be yielded here, usually representing the expected value(s). @see RSpec::Matchers
define
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def match(options={}, &match_block) define_user_override(:matches?, match_block) do |actual| @actual = actual RSpec::Support.with_failure_notifier(RAISE_NOTIFIER) do begin super(*actual_arg_for(match_block)) rescue RSpec::Expectations::ExpectationNotMetError raise if options[:notify_expectation_failures] false end end end end
Stores the block that is used to determine whether this matcher passes or fails. The block should return a boolean value. When the matcher is passed to `expect(...).to` and the block returns `true`, then the expectation passes. Similarly, when the matcher is passed to `expect(...).not_to` and the block returns `false`, then the expectation passes. @example RSpec::Matchers.define :be_even do match do |actual| actual.even? end end expect(4).to be_even # passes expect(3).not_to be_even # passes expect(3).to be_even # fails expect(4).not_to be_even # fails By default the match block will swallow expectation errors (e.g. caused by using an expectation such as `expect(1).to eq 2`), if you wish to allow these to bubble up, pass in the option `:notify_expectation_failures => true`. @param [Hash] options for defining the behavior of the match block. @yield [Object] actual the actual value (i.e. the value wrapped by `expect`)
match
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def match_when_negated(options={}, &match_block) define_user_override(:does_not_match?, match_block) do |actual| begin @actual = actual RSpec::Support.with_failure_notifier(RAISE_NOTIFIER) do super(*actual_arg_for(match_block)) end rescue RSpec::Expectations::ExpectationNotMetError raise if options[:notify_expectation_failures] false end end end
Use this to define the block for a negative expectation (`expect(...).not_to`) when the positive and negative forms require different handling. This is rarely necessary, but can be helpful, for example, when specifying asynchronous processes that require different timeouts. By default the match block will swallow expectation errors (e.g. caused by using an expectation such as `expect(1).to eq 2`), if you wish to allow these to bubble up, pass in the option `:notify_expectation_failures => true`. @param [Hash] options for defining the behavior of the match block. @yield [Object] actual the actual value (i.e. the value wrapped by `expect`)
match_when_negated
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def match_unless_raises(expected_exception=Exception, &match_block) define_user_override(:matches?, match_block) do |actual| @actual = actual begin super(*actual_arg_for(match_block)) rescue expected_exception => @rescued_exception false else true end end end
Use this instead of `match` when the block will raise an exception rather than returning false to indicate a failure. @example RSpec::Matchers.define :accept_as_valid do |candidate_address| match_unless_raises ValidationException do |validator| validator.validate(candidate_address) end end expect(email_validator).to accept_as_valid("person@company.com") @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
match_unless_raises
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def failure_message(&definition) define_user_override(__method__, definition) end
Customizes the failure message to use when this matcher is asked to positively match. Only use this when the message generated by default doesn't suit your needs. @example RSpec::Matchers.define :have_strength do |expected| match { your_match_logic } failure_message do |actual| "Expected strength of #{expected}, but had #{actual.strength}" end end @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
failure_message
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def failure_message_when_negated(&definition) define_user_override(__method__, definition) end
Customize the failure message to use when this matcher is asked to negatively match. Only use this when the message generated by default doesn't suit your needs. @example RSpec::Matchers.define :have_strength do |expected| match { your_match_logic } failure_message_when_negated do |actual| "Expected not to have strength of #{expected}, but did" end end @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
failure_message_when_negated
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def description(&definition) define_user_override(__method__, definition) end
Customize the description to use for one-liners. Only use this when the description generated by default doesn't suit your needs. @example RSpec::Matchers.define :qualify_for do |expected| match { your_match_logic } description do "qualify for #{expected}" end end @yield [Object] actual the actual object (i.e. the value wrapped by `expect`)
description
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def diffable define_method(:diffable?) { true } end
Tells the matcher to diff the actual and expected values in the failure message.
diffable
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def supports_block_expectations define_method(:supports_block_expectations?) { true } end
Declares that the matcher can be used in a block expectation. Users will not be able to use your matcher in a block expectation without declaring this. (e.g. `expect { do_something }.to matcher`).
supports_block_expectations
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def chain(method_name, *attr_names, &definition) unless block_given? ^ attr_names.any? raise ArgumentError, "You must pass either a block or some attribute names (but not both) to `chain`." end definition = assign_attributes(attr_names) if attr_names.any? define_user_override(method_name, definition) do |*args, &block| super(*args, &block) @chained_method_clauses.push([method_name, args]) self end end
Convenience for defining methods on this matcher to create a fluent interface. The trick about fluent interfaces is that each method must return self in order to chain methods together. `chain` handles that for you. If the method is invoked and the `include_chain_clauses_in_custom_matcher_descriptions` config option hash been enabled, the chained method name and args will be added to the default description and failure message. In the common case where you just want the chained method to store some value(s) for later use (e.g. in `match`), you can provide one or more attribute names instead of a block; the chained method will store its arguments in instance variables with those names, and the values will be exposed via getters. @example RSpec::Matchers.define :have_errors_on do |key| chain :with do |message| @message = message end match do |actual| actual.errors[key] == @message end end expect(minor).to have_errors_on(:age).with("Not old enough to participate")
chain
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def define_user_override(method_name, user_def, &our_def) @user_method_defs.__send__(:define_method, method_name, &user_def) our_def ||= lambda { super(*actual_arg_for(user_def)) } define_method(method_name, &our_def) end
Does the following: - Defines the named method using a user-provided block in @user_method_defs, which is included as an ancestor in the singleton class in which we eval the `define` block. - Defines an overridden definition for the same method usign the provided `our_def` block. - Provides a default `our_def` block for the common case of needing to call the user's definition with `@actual` as an arg, but only if their block's arity can handle it. This compiles the user block into an actual method, allowing them to use normal method constructs like `return` (e.g. for an early guard statement), while allowing us to define an override that can provide the wrapped handling (e.g. assigning `@actual`, rescueing errors, etc) and can `super` to the user's definition.
define_user_override
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def expected if expected_as_array.size == 1 expected_as_array[0] else expected_as_array end end
Provides the expected value. This will return an array if multiple arguments were passed to the matcher; otherwise it will return a single value. @see #expected_as_array
expected
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def inspect "#<#{self.class.name} #{name}>" end
Adds the name (rather than a cryptic hex number) so we can identify an instance of the matcher in error messages (e.g. for `NoMethodError`)
inspect
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def respond_to_missing?(method, include_private=false) super || @matcher_execution_context.respond_to?(method, include_private) end
Indicates that this matcher responds to messages from the `@matcher_execution_context` as well. Also, supports getting a method object for such methods.
respond_to_missing?
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def respond_to?(method, include_private=false) super || @matcher_execution_context.respond_to?(method, include_private) end
:nocov: Indicates that this matcher responds to messages from the `@matcher_execution_context` as well.
respond_to?
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def method_missing(method, *args, &block) if @matcher_execution_context.respond_to?(method) @matcher_execution_context.__send__ method, *args, &block else super(method, *args, &block) end end
Takes care of forwarding unhandled messages to the `@matcher_execution_context` (typically the current running `RSpec::Core::Example`). This is needed by rspec-rails so that it can define matchers that wrap Rails' test helper methods, but it's also a useful feature in its own right.
method_missing
ruby
rspec/rspec-expectations
lib/rspec/matchers/dsl.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/dsl.rb
MIT
def fail(&block) raise_error(RSpec::Expectations::ExpectationNotMetError, &block) end
Matches if an expectation fails @example expect { some_expectation }.to fail
fail
ruby
rspec/rspec-expectations
lib/rspec/matchers/fail_matchers.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/fail_matchers.rb
MIT
def fail_with(message) raise_error(RSpec::Expectations::ExpectationNotMetError, message) end
Matches if an expectation fails with the provided message @example expect { some_expectation }.to fail_with("some failure message") expect { some_expectation }.to fail_with(/some failure message/)
fail_with
ruby
rspec/rspec-expectations
lib/rspec/matchers/fail_matchers.rb
https://github.com/rspec/rspec-expectations/blob/master/lib/rspec/matchers/fail_matchers.rb
MIT