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 _attribute_type(attribute_name) attributes[attribute_name][:type] || Object end
Calculates an attribute type @private @since 0.5.0
_attribute_type
ruby
cgriego/active_attr
lib/active_attr/typecasted_attributes.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasted_attributes.rb
MIT
def typecast_attribute(typecaster, value) raise ArgumentError, "a typecaster must be given" unless typecaster.respond_to?(:call) return value if value.nil? typecaster.call(value) end
Typecasts a value using a Class @param [#call] typecaster The typecaster to use for typecasting @param [Object] value The value to be typecasted @return [Object, nil] The typecasted value or nil if it cannot be typecasted @since 0.5.0
typecast_attribute
ruby
cgriego/active_attr
lib/active_attr/typecasting.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasting.rb
MIT
def typecaster_for(type) typecaster = TYPECASTER_MAP[type] typecaster.new if typecaster end
Resolve a Class to a typecaster @param [Class] type The type to cast to @return [#call, nil] The typecaster to use @since 0.6.0
typecaster_for
ruby
cgriego/active_attr
lib/active_attr/typecasting.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasting.rb
MIT
def of_type(type) @attribute_options[:type] = type @description << " of type #{type}" @expected_ancestors << "ActiveAttr::TypecastedAttributes" @attribute_expectations << lambda { @model_class._attribute_type(attribute_name) == type } self end
Specify that the attribute should have the given type @example Person's first name should be a String describe Person do it { should have_attribute(:first_name).of_type(String) } end @param [Class] type The expected type @return [HaveAttributeMatcher] The matcher @since 0.5.0
of_type
ruby
cgriego/active_attr
lib/active_attr/matchers/have_attribute_matcher.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/matchers/have_attribute_matcher.rb
MIT
def with_default_value_of(default_value) @attribute_options[:default] = default_value @description << " with a default value of #{default_value.inspect}" @expected_ancestors << "ActiveAttr::AttributeDefaults" @attribute_expectations << lambda { @model_class.allocate.send(:_attribute_default, @attribute_name) == default_value } self end
Specify that the attribute should have the given default value @example Person's first name should default to John describe Person do it do should have_attribute(:first_name).with_default_value_of("John") end end @param [Object] default_value The expected default value @return [HaveAttributeMatcher] The matcher @since 0.5.0
with_default_value_of
ruby
cgriego/active_attr
lib/active_attr/matchers/have_attribute_matcher.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/matchers/have_attribute_matcher.rb
MIT
def failure_message_when_negated "expected not: #{expected_attribute_definition.inspect}\n" + " got: #{actual_attribute_definition.inspect}" end
@return [String] Negative failure message @private
failure_message_when_negated
ruby
cgriego/active_attr
lib/active_attr/matchers/have_attribute_matcher.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/matchers/have_attribute_matcher.rb
MIT
def call(value) if value.is_a? BigDecimal value elsif value.is_a? Rational value.to_f.to_d elsif value.blank? nil elsif value.respond_to? :to_d value.to_d else BigDecimal(value.to_s) end rescue ArgumentError BigDecimal("0") end
Typecasts an object to a BigDecimal Attempt to convert using #to_d, else it creates a BigDecimal using the String representation of the value. @example Typecast an Integer typecaster.call(1).to_s #=> "0.1E1" @param [Object, #to_d, #to_s] value The object to typecast @return [BigDecimal, nil] The result of typecasting @since 0.5.0
call
ruby
cgriego/active_attr
lib/active_attr/typecasting/big_decimal_typecaster.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasting/big_decimal_typecaster.rb
MIT
def call(value) case value when *FALSE_VALUES then false when *NIL_VALUES then nil when Numeric, /\A[-+]?(0++\.?0*|0*+\.?0+)\z/ then !value.to_f.zero? else value.present? end end
Typecasts an object to true or false Similar to ActiveRecord, when the attribute is a zero value or is a string that represents false, typecasting returns false. Otherwise typecasting just checks the presence of a value. @example Typecast an Integer typecaster.call(1) #=> true @param [Object] value The object to typecast @return [true, false] The result of typecasting @since 0.5.0
call
ruby
cgriego/active_attr
lib/active_attr/typecasting/boolean_typecaster.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasting/boolean_typecaster.rb
MIT
def call(value) value.to_datetime if value.respond_to? :to_datetime rescue ArgumentError end
Typecasts an object to a DateTime Attempts to convert using #to_datetime. @example Typecast a String typecaster.call("2012-01-01") #=> Sun, 01 Jan 2012 00:00:00 +0000 @param [Object, #to_datetime] value The object to typecast @return [DateTime, nil] The result of typecasting @since 0.5.0
call
ruby
cgriego/active_attr
lib/active_attr/typecasting/date_time_typecaster.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasting/date_time_typecaster.rb
MIT
def call(value) value.to_date if value.respond_to? :to_date rescue NoMethodError, ArgumentError end
Typecasts an object to a Date Attempts to convert using #to_date. @example Typecast a String typecaster.call("2012-01-01") #=> Sun, 01 Jan 2012 @param [Object, #to_date] value The object to typecast @return [Date, nil] The result of typecasting @since 0.5.0
call
ruby
cgriego/active_attr
lib/active_attr/typecasting/date_typecaster.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasting/date_typecaster.rb
MIT
def call(value) value.to_f if value.present? && value.respond_to?(:to_f) end
Typecasts an object to a Float Attempts to convert using #to_f. @example Typecast an Integer typecaster.call(1) #=> 1.0 @param [Object, #to_f] value The object to typecast @return [Float, nil] The result of typecasting @since 0.5.0
call
ruby
cgriego/active_attr
lib/active_attr/typecasting/float_typecaster.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasting/float_typecaster.rb
MIT
def call(value) value.to_i if value.present? && value.respond_to?(:to_i) rescue FloatDomainError end
Typecasts an object to an Integer Attempts to convert using #to_i. Handles FloatDomainError if the object is INFINITY or NAN. @example Typecast a String typecaster.call("1") #=> 1 @param [Object, #to_i] value The object to typecast @return [Integer, nil] The result of typecasting @since 0.5.0
call
ruby
cgriego/active_attr
lib/active_attr/typecasting/integer_typecaster.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasting/integer_typecaster.rb
MIT
def call(value) value.to_s if value.respond_to? :to_s end
Typecasts an object to a String Attempts to convert using #to_s. @example Typecast an Integer typecaster.call(1) #=> "1" @param [Object, #to_s] value The object to typecast @return [String, nil] The result of typecasting @since 0.5.0
call
ruby
cgriego/active_attr
lib/active_attr/typecasting/string_typecaster.rb
https://github.com/cgriego/active_attr/blob/master/lib/active_attr/typecasting/string_typecaster.rb
MIT
def erbify(section) require 'erb' erb_doc = File.read(template(section)) ERB.new(erb_doc).result(binding) end
Creates a new erb evaluated result from the passed in section. @param section String The section name of @return String The erb evaluated string
erbify
ruby
jscruggs/metric_fu
lib/base/base_template.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/base_template.rb
MIT
def create_instance_var(section, contents) instance_variable_set("@#{section}", contents) end
Copies an instance variable mimicing the name of the section we are trying to render, with a value equal to the passed in constant. Allows the concrete template classes to refer to that instance variable from their ERB rendering @param section String The name of the instance variable to create @param contents Object The value to set as the value of the created instance variable
create_instance_var
ruby
jscruggs/metric_fu
lib/base/base_template.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/base_template.rb
MIT
def template(section) File.join(this_directory, section.to_s + ".html.erb") end
Generates the filename of the template file to load and evaluate. In this case, the path to the template directory + the section name + .html.erb @param section String A section of the template to render @return String A file path
template
ruby
jscruggs/metric_fu
lib/base/base_template.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/base_template.rb
MIT
def output_filename(section) section.to_s + ".html" end
Returns the filename that the template will render into for a given section. In this case, the section name + '.html' @param section String A section of the template to render @return String The output filename
output_filename
ruby
jscruggs/metric_fu
lib/base/base_template.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/base_template.rb
MIT
def inline_css(css) open(File.join(this_directory, css)) { |f| f.read } end
Returns the contents of a given css file in order to render it inline into a template. @param css String The name of a css file to open @return String The contents of the css file
inline_css
ruby
jscruggs/metric_fu
lib/base/base_template.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/base_template.rb
MIT
def link_to_filename(name, line = nil, link_content = nil) "<a href='#{file_url(name, line)}'>#{link_content(name, line, link_content)}</a>" end
Provides a link to open a file through the textmate protocol on Darwin, or otherwise, a simple file link. @param name String @param line Integer The line number to link to, if textmate is available. Defaults to nil @return String An anchor link to a textmate reference or a file reference
link_to_filename
ruby
jscruggs/metric_fu
lib/base/base_template.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/base_template.rb
MIT
def cycle(first_value, second_value, iteration) return first_value if iteration % 2 == 0 return second_value end
Provides a brain dead way to cycle between two values during an iteration of some sort. Pass in the first_value, the second_value, and the cardinality of the iteration. @param first_value Object @param second_value Object @param iteration Integer The number of times through the iteration. @return Object The first_value if iteration is even. The second_value if iteration is odd.
cycle
ruby
jscruggs/metric_fu
lib/base/base_template.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/base_template.rb
MIT
def add_class_methods_to_metric_fu instance_variables.each do |name| method_name = name[1..-1].to_sym method = <<-EOF def self.#{method_name} configuration.send(:#{method_name}) end EOF MetricFu.module_eval(method) end end
Searches through the instance variables of the class and creates a class method on the MetricFu module to read the value of the instance variable from the Configuration class.
add_class_methods_to_metric_fu
ruby
jscruggs/metric_fu
lib/base/configuration.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/configuration.rb
MIT
def add_attr_accessors_to_self instance_variables.each do |name| method_name = name[1..-1].to_sym MetricFu::Configuration.send(:attr_accessor, method_name) end end
Searches through the instance variables of the class and creates an attribute accessor on this instance of the Configuration class for each instance variable.
add_attr_accessors_to_self
ruby
jscruggs/metric_fu
lib/base/configuration.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/configuration.rb
MIT
def reset @base_directory = ENV['CC_BUILD_ARTIFACTS'] || 'tmp/metric_fu' @scratch_directory = File.join(@base_directory, 'scratch') @output_directory = File.join(@base_directory, 'output') @data_directory = File.join('tmp/metric_fu', '_data') @metric_fu_root_directory = File.join(File.dirname(__FILE__), '..', '..') @template_directory = File.join(@metric_fu_root_directory, 'lib', 'templates') @template_class = AwesomeTemplate set_metrics set_graphs set_code_dirs @flay = { :dirs_to_flay => @code_dirs, :minimum_score => 100, :filetypes => ['rb'] } @flog = { :dirs_to_flog => @code_dirs } @reek = { :dirs_to_reek => @code_dirs, :config_file_pattern => nil} @roodi = { :dirs_to_roodi => @code_dirs, :roodi_config => nil} @saikuro = { :output_directory => @scratch_directory + '/saikuro', :input_directory => @code_dirs, :cyclo => "", :filter_cyclo => "0", :warn_cyclo => "5", :error_cyclo => "7", :formater => "text"} @churn = {} @stats = {} @rcov = { :environment => 'test', :test_files => ['test/**/*_test.rb', 'spec/**/*_spec.rb'], :rcov_opts => ["--sort coverage", "--no-html", "--text-coverage", "--no-color", "--profile", "--rails", "--exclude /gems/,/Library/,/usr/,spec"], :external => nil } @rails_best_practices = {} @hotspots = {} @file_globs_to_ignore = [] @verbose = false @graph_engine = :bluff # can be :bluff or :gchart @darwin_txmt_protocol_no_thanks = false @syntax_highlighting = true #Can be set to false to avoid UTF-8 issues with Ruby 1.9.2 and Syntax 1.0 end
This does the real work of the Configuration class, by setting up a bunch of instance variables to represent the configuration of the MetricFu app.
reset
ruby
jscruggs/metric_fu
lib/base/configuration.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/configuration.rb
MIT
def rails? @rails = File.exist?("config/environment.rb") end
Perform a simple check to try and guess if we're running against a rails app. @todo This should probably be made a bit more robust.
rails?
ruby
jscruggs/metric_fu
lib/base/configuration.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/configuration.rb
MIT
def set_metrics if rails? @metrics = MetricFu::AVAILABLE_METRICS + [:stats, :rails_best_practices] else @metrics = MetricFu::AVAILABLE_METRICS end end
Add the :stats task to the AVAILABLE_METRICS constant if we're running within rails.
set_metrics
ruby
jscruggs/metric_fu
lib/base/configuration.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/configuration.rb
MIT
def set_code_dirs if rails? @code_dirs = ['app', 'lib'] else @code_dirs = ['lib'] end end
Add the 'app' directory if we're running within rails.
set_code_dirs
ruby
jscruggs/metric_fu
lib/base/configuration.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/configuration.rb
MIT
def eql?(other) [self.file_path.to_s, self.class_name.to_s, self.method_name.to_s] == [other.file_path.to_s, other.class_name.to_s, other.method_name.to_s] end
TODO - we need this method (and hash accessor above) as a temporary hack where we're using Location as a hash key
eql?
ruby
jscruggs/metric_fu
lib/base/location.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/location.rb
MIT
def problems_with(item, value, details = :summary, exclude_details = []) sub_table = get_sub_table(item, value) #grouping = Ruport::Data::Grouping.new(sub_table, :by => 'metric') grouping = get_grouping(sub_table, :by => 'metric') problems = {} grouping.each do |metric, table| if details == :summary || exclude_details.include?(metric) problems[metric] = present_group(metric,table) else problems[metric] = present_group_details(metric,table) end end problems end
todo redo as item,value, options = {} Note that the other option for 'details' is :detailed (this isn't at all clear from this method itself
problems_with
ruby
jscruggs/metric_fu
lib/base/metric_analyzer.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/metric_analyzer.rb
MIT
def present_group(metric, group) occurences = group.size case(metric) when :reek "found #{occurences} code smells" when :roodi "found #{occurences} design problems" when :churn "detected high level of churn (changed #{group[0].times_changed} times)" when :flog complexity = get_mean(group.column("score")) "#{"average " if occurences > 1}complexity is %.1f" % complexity when :saikuro complexity = get_mean(group.column("complexity")) "#{"average " if occurences > 1}complexity is %.1f" % complexity when :flay "found #{occurences} code duplications" when :rcov average_code_uncoverage = get_mean(group.column("percentage_uncovered")) "#{"average " if occurences > 1}uncovered code is %.1f%" % average_code_uncoverage else raise AnalysisError, "Unknown metric #{metric}" end end
TODO: As we get fancier, the presenter should be its own class, not just a method with a long case statement
present_group
ruby
jscruggs/metric_fu
lib/base/metric_analyzer.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/metric_analyzer.rb
MIT
def save_templatized_report @template = MetricFu.template_class.new @template.report = report_hash @template.per_file_data = per_file_data @template.write end
Instantiates a new template class based on the configuration set in MetricFu::Configuration, or through the MetricFu.config block in your rake file (defaults to the included AwesomeTemplate), assigns the report_hash to the report_hash in the template, and tells the template to to write itself out.
save_templatized_report
ruby
jscruggs/metric_fu
lib/base/report.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/report.rb
MIT
def add(report_type) clazz = MetricFu.const_get(report_type.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }) inst = clazz.new report_hash.merge!(inst.generate_report) inst.per_file_info(per_file_data) if inst.respond_to?(:per_file_info) end
Adds a hash from a passed report, produced by one of the Generator classes to the aggregate report_hash managed by this hash. @param report_type Hash The hash to add to the aggregate report_hash
add
ruby
jscruggs/metric_fu
lib/base/report.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/report.rb
MIT
def save_output(content, dir, file='index.html') open("#{dir}/#{file}", "w") do |f| f.puts content end end
Saves the passed in content to the passed in directory. If a filename is passed in it will be used as the name of the file, otherwise it will default to 'index.html' @param content String A string containing the content (usually html) to be written to the file. @param dir String A dir containing the path to the directory to write the file in. @param file String A filename to save the path as. Defaults to 'index.html'.
save_output
ruby
jscruggs/metric_fu
lib/base/report.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/report.rb
MIT
def open_in_browser? MetricFu.configuration.platform.include?('darwin') && ! MetricFu.configuration.is_cruise_control_rb? end
Checks to discover whether we should try and open the results of the report in the browser on this system. We only try and open in the browser if we're on OS X and we're not running in a CruiseControl.rb environment. See MetricFu.configuration for more details about how we make those guesses. @return Boolean Should we open in the browser or not?
open_in_browser?
ruby
jscruggs/metric_fu
lib/base/report.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/report.rb
MIT
def show_in_browser(dir) system("open #{dir}/index.html") if open_in_browser? end
Shows 'index.html' from the passed directory in the browser if we're able to open the browser on this platform. @param dir String The directory path where the 'index.html' we want to open is stored
show_in_browser
ruby
jscruggs/metric_fu
lib/base/report.rb
https://github.com/jscruggs/metric_fu/blob/master/lib/base/report.rb
MIT
def action_methods @action_methods ||= begin # All public instance methods of this class, including ancestors methods = (public_instance_methods(true) - # Except for public instance methods of Base and its ancestors Base.public_instance_methods(true) + # Be sure to include shadowed public instance methods of this class public_instance_methods(false)) methods.map!(&:to_s) methods.to_set end end
See https://github.com/rails/rails/blob/b13a5cb83ea00d6a3d71320fd276ca21049c2544/actionpack/lib/abstract_controller/base.rb#L74
action_methods
ruby
palkan/active_delivery
lib/abstract_notifier/base.rb
https://github.com/palkan/active_delivery/blob/master/lib/abstract_notifier/base.rb
MIT
def notify!(mid, *, **hargs) notify(mid, *, **hargs, sync: true) end
The same as .notify but delivers synchronously (i.e. #deliver_now for mailers)
notify!
ruby
palkan/active_delivery
lib/active_delivery/base.rb
https://github.com/palkan/active_delivery/blob/master/lib/active_delivery/base.rb
MIT
def delivers(*actions) actions.each do |mid| class_eval <<~CODE, __FILE__, __LINE__ + 1 def self.#{mid}(...) new.#{mid}(...) end def #{mid}(*args, **kwargs) delivery( notification: :#{mid}, params: args, options: kwargs ) end CODE end end
Specify explicitly which actions are supported by the delivery.
delivers
ruby
palkan/active_delivery
lib/active_delivery/base.rb
https://github.com/palkan/active_delivery/blob/master/lib/active_delivery/base.rb
MIT
def notify!(mid, *args, **kwargs) perform_notify( delivery(notification: mid, params: args, options: kwargs), sync: true ) end
The same as .notify but delivers synchronously (i.e. #deliver_now for mailers)
notify!
ruby
palkan/active_delivery
lib/active_delivery/base.rb
https://github.com/palkan/active_delivery/blob/master/lib/active_delivery/base.rb
MIT
def capture_exceptions(&block) super(&block) rescue Interrupt => e Maxitest.interrupted = true failures << Minitest::UnexpectedError.new(e) end
capture interrupt and treat it as a regular error so we get a backtrace
capture_exceptions
ruby
grosser/maxitest
lib/maxitest/interrupt.rb
https://github.com/grosser/maxitest/blob/master/lib/maxitest/interrupt.rb
MIT
def run if Maxitest.interrupted # produce a real error so we do not crash in -v mode failures << begin raise Minitest::Skip, 'Maxitest::Interrupted' rescue Minitest::Skip $! end result = Minitest::Result.from(self) result.time = 0 result else super() end end
skip remaining tests if we were interrupted
run
ruby
grosser/maxitest
lib/maxitest/interrupt.rb
https://github.com/grosser/maxitest/blob/master/lib/maxitest/interrupt.rb
MIT
def maxitest_extra_threads @maxitest_threads_before ? Thread.list - @maxitest_threads_before : [] end
if setup crashes we do not return anything to make the initial error visible
maxitest_extra_threads
ruby
grosser/maxitest
lib/maxitest/threads.rb
https://github.com/grosser/maxitest/blob/master/lib/maxitest/threads.rb
MIT
def around(*args, &block) raise ArgumentError, "only :each or no argument is supported" if args != [] && args != [:each] fib = nil before do fib = Fiber.new do |context, resume| begin context.instance_exec(resume, &block) rescue Object fib = :failed raise end end fib.resume(self, lambda { Fiber.yield }) end after { fib.resume if fib && fib != :failed } end
- resume to call first part - execute test - resume fiber to execute last part
around
ruby
grosser/maxitest
lib/maxitest/vendor/around.rb
https://github.com/grosser/maxitest/blob/master/lib/maxitest/vendor/around.rb
MIT
def line_pattern_option(file, line) [file, "-n", "/#{pattern_from_file(File.readlines(file), line)}/"] end
overwritten by maxitest to just return line
line_pattern_option
ruby
grosser/maxitest
lib/maxitest/vendor/testrbl.rb
https://github.com/grosser/maxitest/blob/master/lib/maxitest/vendor/testrbl.rb
MIT
def pattern_from_file(lines, line) possible_lines = lines[0..(line.to_i-1)].reverse found = possible_lines.map { |line| test_pattern_from_line(line) || block_start_from_line(line) }.compact # pattern and the groups it is nested under (like describe - describe - it) last_spaces = " " * 100 patterns = found.select do |spaces, name| last_spaces = spaces if spaces.size < last_spaces.size end.map(&:last).compact return filter_duplicate_final(patterns).reverse.join(".*") if found.size > 0 raise "no test found before line #{line}" end
usable via external tools like zeus
pattern_from_file
ruby
grosser/maxitest
lib/maxitest/vendor/testrbl.rb
https://github.com/grosser/maxitest/blob/master/lib/maxitest/vendor/testrbl.rb
MIT
def filter_duplicate_final(patterns) found_final = 0 patterns.reject { |p| p.end_with?("$") and (found_final += 1) > 1 } end
only keep 1 pattern that stops matching via $
filter_duplicate_final
ruby
grosser/maxitest
lib/maxitest/vendor/testrbl.rb
https://github.com/grosser/maxitest/blob/master/lib/maxitest/vendor/testrbl.rb
MIT
def localize(file) file =~ /^[-a-z\d_]/ ? "./#{file}" : file end
fix 1.9 not being able to load local files
localize
ruby
grosser/maxitest
lib/maxitest/vendor/testrbl.rb
https://github.com/grosser/maxitest/blob/master/lib/maxitest/vendor/testrbl.rb
MIT
def kill_process_with_name(file, signal='INT') running_processes = `ps -f`.split("\n").map{ |line| line.split(/\s+/) } pid_index = running_processes.detect { |p| p.include?("UID") }.index("UID") + 1 parent = running_processes.detect { |p| p.include?(file) and not p.include?("sh") } raise "Unable to find parent in #{running_processes} with #{file}" unless parent `kill -s #{signal} #{parent.fetch(pid_index)}` end
copied from https://github.com/grosser/parallel/blob/master/spec/parallel_spec.rb#L10-L15
kill_process_with_name
ruby
grosser/maxitest
spec/maxitest_spec.rb
https://github.com/grosser/maxitest/blob/master/spec/maxitest_spec.rb
MIT
def initialize(assigns = {}, helpers = nil, &block) assigns = assigns || {} @_assigns = assigns.symbolize_keys @_helpers = helpers @_current_arbre_element_buffer = [self] super(self) instance_eval(&block) if block end
Initialize a new Arbre::Context @param [Hash] assigns A hash of objects that you would like to be available as local variables within the Context @param [Object] helpers An object that has methods on it which will become instance methods within the context. @yield [] The block that will get instance eval'd in the context
initialize
ruby
activeadmin/arbre
lib/arbre/context.rb
https://github.com/activeadmin/arbre/blob/master/lib/arbre/context.rb
MIT
def cached_html if defined?(@cached_html) @cached_html else html = to_s @cached_html = html if html.length > 0 html end end
Caches the rendered HTML so that we don't re-render just to get the content length or to delegate a method to the HTML
cached_html
ruby
activeadmin/arbre
lib/arbre/context.rb
https://github.com/activeadmin/arbre/blob/master/lib/arbre/context.rb
MIT
def append_return_block(tag) return nil if current_arbre_element.children? if appendable_tag?(tag) current_arbre_element << Arbre::HTML::TextNode.from_string(tag.to_s) end end
Appends the value to the current DOM element if there are no existing DOM Children and it responds to #to_s
append_return_block
ruby
activeadmin/arbre
lib/arbre/element/builder_methods.rb
https://github.com/activeadmin/arbre/blob/master/lib/arbre/element/builder_methods.rb
MIT
def appendable_tag?(tag) # Array.new.to_s prints out an empty array ("[]"). In # Arbre, we append the return value of blocks to the output, which # can cause empty arrays to show up within the output. To get # around this, we check if the object responds to #empty? if tag.respond_to?(:empty?) && tag.empty? false else !tag.is_a?(Arbre::Element) && tag.respond_to?(:to_s) end end
Returns true if the object should be converted into a text node and appended into the DOM.
appendable_tag?
ruby
activeadmin/arbre
lib/arbre/element/builder_methods.rb
https://github.com/activeadmin/arbre/blob/master/lib/arbre/element/builder_methods.rb
MIT
def id! return id if id self.id = object_id.to_s id end
Generates and id for the object if it doesn't exist already
id!
ruby
activeadmin/arbre
lib/arbre/html/tag.rb
https://github.com/activeadmin/arbre/blob/master/lib/arbre/html/tag.rb
MIT
def label(*args) proxy_call_to_form :label, *args end
Since label and select are Arbre Elements already, we must override it here instead of letting method_missing deal with it
label
ruby
activeadmin/arbre
lib/arbre/rails/forms.rb
https://github.com/activeadmin/arbre/blob/master/lib/arbre/rails/forms.rb
MIT
def database_connection_config case self[:db_adapter] when "sqlite3" { max_connections: 1 }.merge(self[:db_connection_options]) when "postgres", "mysql", "mysql2" { max_connections: (self[:puma_workers] * self[:puma_threads]) + 1 }.merge(self[:db_connection_options]) else raise "Unsupported DB adapter: '#{self[:db_adapter]}'" end end
@return [Hash] Sequel connection configuration hash
database_connection_config
ruby
rubygems/gemstash
lib/gemstash/configuration.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/configuration.rb
MIT
def initialize(folder, root: true) @folder = folder check_storage_version if root FileUtils.mkpath(@folder) unless Dir.exist?(@folder) end
This object should not be constructed directly, but instead via {for} and {#for}.
initialize
ruby
rubygems/gemstash
lib/gemstash/storage.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/storage.rb
MIT
def resource(id) Resource.new(@folder, id) end
Fetch the resource with the given +id+ within this storage. @param id [String] the id of the resource to fetch @return [Gemstash::Resource] a new resource instance from the +id+
resource
ruby
rubygems/gemstash
lib/gemstash/storage.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/storage.rb
MIT
def for(child) Storage.new(File.join(@folder, child), root: false) end
Fetch a nested entry from this instance in the storage engine. @param child [String] the name of the nested entry to load @return [Gemstash::Storage] a new storage instance for the +child+
for
ruby
rubygems/gemstash
lib/gemstash/storage.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/storage.rb
MIT
def initialize(folder, name) @base_path = folder @name = name # Avoid odd characters in paths, in case of issues with the file system safe_name = sanitize(@name) # Use a trie structure to avoid file system limits causing too many files in 1 folder # Downcase to avoid issues with case insensitive file systems trie_parents = safe_name[0...3].downcase.split("") # The digest is included in case the name differs only by case # Some file systems are case insensitive, so such collisions will be a problem digest = Digest::MD5.hexdigest(@name) child_folder = "#{safe_name}-#{digest}" @folder = File.join(@base_path, *trie_parents, child_folder) @properties = nil end
This object should not be constructed directly, but instead via {Gemstash::Storage#resource}.
initialize
ruby
rubygems/gemstash
lib/gemstash/storage.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/storage.rb
MIT
def exist?(key = nil) if key File.exist?(properties_filename) && File.exist?(content_filename(key)) else File.exist?(properties_filename) && content? end end
When +key+ is nil, this will test if this resource exists with any content. If a +key+ is provided, this will test that the resource exists with at least the given +key+ file. The +key+ corresponds to the +content+ key provided to {#save}. @param key [Symbol, nil] the key of the content to check existence @return [Boolean] true if the indicated content exists
exist?
ruby
rubygems/gemstash
lib/gemstash/storage.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/storage.rb
MIT
def save(content, properties = nil) content.each do |key, value| save_content(key, value) end update_properties(properties) self end
Save one or more files for this resource given by the +content+ hash. Metadata properties about the file(s) may be provided in the optional +properties+ parameter. The keys in the content hash correspond to the file name for this resource, while the values will be the content stored for that key. Separate calls to save for the same resource will replace existing files, and add new ones. Properties on additional calls will be merged with existing properties. Nested hashes in properties will also be merged. Examples: Gemstash::Storage.for("foo").resource("bar").save(baz: "qux") Gemstash::Storage.for("foo").resource("bar").save(baz: "one", qux: "two") Gemstash::Storage.for("foo").resource("bar").save({ baz: "qux" }, meta: true) @param content [Hash{Symbol => String}] files to save, *must not be nil* @param properties [Hash, nil] metadata properties related to this resource @return [Gemstash::Resource] self for chaining purposes
save
ruby
rubygems/gemstash
lib/gemstash/storage.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/storage.rb
MIT
def content(key) @content ||= {} load(key) unless @content.include?(key) @content[key] end
Fetch the content for the given +key+. This will load and cache the properties and the content of the +key+. The +key+ corresponds to the +content+ key provided to {#save}. @param key [Symbol] the key of the content to load @return [String] the content stored in the +key+
content
ruby
rubygems/gemstash
lib/gemstash/storage.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/storage.rb
MIT
def properties load_properties @properties || {} end
Fetch the metadata properties for this resource. The properties will be cached for future calls. @return [Hash] the metadata properties for this resource
properties
ruby
rubygems/gemstash
lib/gemstash/storage.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/storage.rb
MIT
def update_properties(props) load_properties(force: true) deep_merge = proc do |_, old_value, new_value| if old_value.is_a?(Hash) && new_value.is_a?(Hash) old_value.merge(new_value, &deep_merge) else new_value end end props = properties.merge(props || {}, &deep_merge) save_properties(properties.merge(props || {})) self end
Update the metadata properties of this resource. The +props+ will be merged with any existing properties. Nested hashes in the properties will also be merged. @param props [Hash] the properties to add @return [Gemstash::Resource] self for chaining purposes
update_properties
ruby
rubygems/gemstash
lib/gemstash/storage.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/storage.rb
MIT
def property?(*keys) keys.inject(node: properties, result: true) do |memo, key| if memo[:result] memo[:result] = memo[:node].is_a?(Hash) && memo[:node].include?(key) memo[:node] = memo[:node][key] if memo[:result] end memo end[:result] end
Check if the metadata properties includes the +keys+. The +keys+ represent a nested path in the properties to check. Examples: resource = Gemstash::Storage.for("x").resource("y") resource.save({ file: "content" }, foo: "one", bar: { baz: "qux" }) resource.has_property?(:foo) # true resource.has_property?(:bar, :baz) # true resource.has_property?(:missing) # false resource.has_property?(:foo, :bar) # false @param keys [Array<Object>] one or more keys pointing to a property @return [Boolean] whether the nested keys points to a valid property
property?
ruby
rubygems/gemstash
lib/gemstash/storage.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/storage.rb
MIT
def delete(key) return self unless exist?(key) begin File.delete(content_filename(key)) rescue StandardError => e log_error "Failed to delete stored content at #{content_filename(key)}", e, level: :warn end begin File.delete(properties_filename) unless content? rescue StandardError => e log_error "Failed to delete stored properties at #{properties_filename}", e, level: :warn end self ensure reset end
Delete the content for the given +key+. If the +key+ is the last one for this resource, the metadata properties will be deleted as well. The +key+ corresponds to the +content+ key provided to {#save}. The resource will be reset afterwards, clearing any cached content or properties. Does nothing if the key doesn't {#exist?}. @param key [Symbol] the key of the content to delete @return [Gemstash::Resource] self for chaining purposes
delete
ruby
rubygems/gemstash
lib/gemstash/storage.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/storage.rb
MIT
def host_id @host_id ||= "#{host}_#{hash}" end
Utilized as the parent directory for cached gems
host_id
ruby
rubygems/gemstash
lib/gemstash/upstream.rb
https://github.com/rubygems/gemstash/blob/master/lib/gemstash/upstream.rb
MIT
def authenticate(params) session_params = params.require(:session) Clearance.configuration.user_model.authenticate( session_params[:email], session_params[:password] ) end
Authenticate a user with a provided email and password @param [ActionController::Parameters] params The parameters from the sign in form. `params[:session][:email]` and `params[:session][:password]` are required. @return [User, nil] The user or nil if authentication fails.
authenticate
ruby
thoughtbot/clearance
lib/clearance/authentication.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/authentication.rb
MIT
def sign_in(user, &block) clearance_session.sign_in(user, &block) if signed_in? && Clearance.configuration.rotate_csrf_on_sign_in? if request.respond_to?(:reset_csrf_token) # Rails 7.1+ request.reset_csrf_token else request.session.try(:delete, :_csrf_token) end form_authenticity_token end end
Sign in the provided user. @param [User] user Signing in will run the stack of {Configuration#sign_in_guards}. You can provide a block to this method to handle the result of that stack. Your block will receive either a {SuccessStatus} or {FailureStatus} sign_in(user) do |status| if status.success? # ... else # ... end end For an example of how clearance uses this internally, see {SessionsController#create}. Signing in will also regenerate the CSRF token for the current session, provided {Configuration#rotate_csrf_on_sign_in?} is set.
sign_in
ruby
thoughtbot/clearance
lib/clearance/authentication.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/authentication.rb
MIT
def handle_unverified_request super sign_out end
CSRF protection in Rails >= 3.0.4 http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails @private
handle_unverified_request
ruby
thoughtbot/clearance
lib/clearance/authentication.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/authentication.rb
MIT
def require_login unless signed_in? deny_access(I18n.t("flashes.failure_when_not_signed_in")) end end
Use as a `before_action` to require a user be signed in to proceed. {Authentication#signed_in?} is used to determine if there is a signed in user or not. class PostsController < ApplicationController before_action :require_login def index # ... end end
require_login
ruby
thoughtbot/clearance
lib/clearance/authorization.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/authorization.rb
MIT
def deny_access(flash_message = nil) respond_to do |format| format.any(:js, :json, :xml) { head :unauthorized } format.any { redirect_request(flash_message) } end end
Responds to unauthorized requests in a manner fitting the request format. `js`, `json`, and `xml` requests will receive a 401 with no body. All other formats will be redirected appropriately and can optionally have the flash message set. When redirecting, the originally requested url will be stored in the session (`session[:return_to]`), allowing it to be used as a redirect url once the user has successfully signed in. If there is a signed in user, the request will be redirected according to the value returned from {#url_after_denied_access_when_signed_in}. If there is no signed in user, the request will be redirected according to the value returned from {#url_after_denied_access_when_signed_out}. For the exact redirect behavior, see {#redirect_request}. @param [String] flash_message
deny_access
ruby
thoughtbot/clearance
lib/clearance/authorization.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/authorization.rb
MIT
def url_after_denied_access_when_signed_out Clearance.configuration.url_after_denied_access_when_signed_out || sign_in_url end
Used as the redirect location when {#deny_access} is called and there is no currently signed in user. @return [String]
url_after_denied_access_when_signed_out
ruby
thoughtbot/clearance
lib/clearance/authorization.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/authorization.rb
MIT
def user_model (@user_model || "User").to_s.constantize end
The class representing the configured user model. In the default configuration, this is the `User` class. @return [Class]
user_model
ruby
thoughtbot/clearance
lib/clearance/configuration.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/configuration.rb
MIT
def parent_controller (@parent_controller || "ApplicationController").to_s.constantize end
The class representing the configured base controller. In the default configuration, this is the `ApplicationController` class. @return [Class]
parent_controller
ruby
thoughtbot/clearance
lib/clearance/configuration.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/configuration.rb
MIT
def user_actions if allow_sign_up? [:create] else [] end end
Specifies which controller actions are allowed for user resources. This will be `[:create]` is `allow_sign_up` is true (the default), and empty otherwise. @return [Array<Symbol>]
user_actions
ruby
thoughtbot/clearance
lib/clearance/configuration.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/configuration.rb
MIT
def user_parameter @user_parameter ||= user_model.model_name.singular.to_sym end
The name of user parameter for the configured user model. This is derived from the `model_name` of the `user_model` setting. In the default configuration, this is `user`. @return [Symbol]
user_parameter
ruby
thoughtbot/clearance
lib/clearance/configuration.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/configuration.rb
MIT
def reload_user_model if @user_model.present? @user_model = @user_model.to_s.constantize end end
Reloads the clearance user model class. This is called from the Clearance engine to reload the configured user class during each request while in development mode, but only once in production. @api private
reload_user_model
ruby
thoughtbot/clearance
lib/clearance/configuration.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/configuration.rb
MIT
def call if session.signed_in? success else failure default_failure_message.html_safe end end
Runs the default sign in guard. If there is a value set in the clearance session object, then the guard returns {SuccessStatus}. Otherwise, it returns {FailureStatus} with the message returned by {#default_failure_message}. @return [SuccessStatus, FailureStatus]
call
ruby
thoughtbot/clearance
lib/clearance/default_sign_in_guard.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/default_sign_in_guard.rb
MIT
def default_failure_message I18n.t( :bad_email_or_password, scope: [:clearance, :controllers, :sessions], default: I18n.t('flashes.failure_after_create').html_safe ) end
The default failure message pulled from the i18n framework. Will use the value returned from the following i18n keys, in this order: * `clearance.controllers.sessions.bad_email_or_password` * `flashes.failure_after_create` @return [String]
default_failure_message
ruby
thoughtbot/clearance
lib/clearance/default_sign_in_guard.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/default_sign_in_guard.rb
MIT
def call(env) session = Clearance::Session.new(env) env[:clearance] = session response = @app.call(env) if session.authentication_successful? session.add_cookie_to_headers end response end
Reads previously existing sessions from a cookie and maintains the cookie on each response.
call
ruby
thoughtbot/clearance
lib/clearance/rack_session.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/rack_session.rb
MIT
def initialize(env) @env = env @current_user = nil @cookies = nil end
@param env The current rack environment
initialize
ruby
thoughtbot/clearance
lib/clearance/session.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/session.rb
MIT
def add_cookie_to_headers if signed_in_with_remember_token? set_remember_token(current_user.remember_token) end end
Called by {RackSession} to add the Clearance session cookie to a response. @return [void]
add_cookie_to_headers
ruby
thoughtbot/clearance
lib/clearance/session.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/session.rb
MIT
def current_user if remember_token.present? @current_user ||= user_from_remember_token(remember_token) end @current_user end
The current user represented by this session. @return [User, nil]
current_user
ruby
thoughtbot/clearance
lib/clearance/session.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/session.rb
MIT
def sign_in(user, &block) @current_user = user status = run_sign_in_stack if status.success? # Sign in succeeded, and when {RackSession} is run and calls # {#add_cookie_to_headers} it will set the cookie with the # remember_token for the current_user else @current_user = nil end if block_given? block.call(status) end end
Sign the provided user in, if approved by the configured sign in guards. If the sign in guard stack returns {SuccessStatus}, the {#current_user} will be set and then remember token cookie will be set to the user's remember token. If the stack returns {FailureStatus}, {#current_user} will be nil. In either event, the resulting status will be yielded to a provided block, if provided. See {SessionsController#create} for an example of how this can be used. @param [User] user @yieldparam [SuccessStatus,FailureStatus] status Result of the sign in operation. @return [void]
sign_in
ruby
thoughtbot/clearance
lib/clearance/session.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/session.rb
MIT
def sign_out if signed_in? current_user.reset_remember_token! end @current_user = nil cookies.delete remember_token_cookie, delete_cookie_options end
Invalidates the users remember token and removes the remember token cookie from the store. The invalidation of the remember token causes any other sessions that are signed in from other locations to also be invalidated on their next request. This is because all Clearance sessions for a given user share a remember token. @return [void]
sign_out
ruby
thoughtbot/clearance
lib/clearance/session.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/session.rb
MIT
def signed_out? ! signed_in? end
True if {#current_user} is not set @return [Boolean]
signed_out?
ruby
thoughtbot/clearance
lib/clearance/session.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/session.rb
MIT
def initialize(failure_message) @failure_message = failure_message end
@param [String] failure_message The reason the sign in failed.
initialize
ruby
thoughtbot/clearance
lib/clearance/session_status.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/session_status.rb
MIT
def initialize(session, stack = []) @session = session @stack = stack end
Creates an instance of a sign in guard. This is called by {Session} automatically using the array of guards configured in {Configuration#sign_in_guards} and the {DefaultSignInGuard}. There is no reason for users of Clearance to concern themselves with the initialization of each guard or the stack as a whole. @param [Session] session The current clearance session @param [[SignInGuard]] stack The sign in guards that come after this guard in the stack
initialize
ruby
thoughtbot/clearance
lib/clearance/sign_in_guard.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/sign_in_guard.rb
MIT
def forgot_password! generate_confirmation_token save validate: false end
Generates a {#confirmation_token} for the user, which allows them to reset their password via an email link. Calling `forgot_password!` will cause the user model to be saved without validations. Any other changes you made to this user instance will also be persisted, without validation. It is inteded to be called on an instance with no changes (`dirty? == false`). @return [Boolean] Was the save successful?
forgot_password!
ruby
thoughtbot/clearance
lib/clearance/user.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/user.rb
MIT
def reset_remember_token! generate_remember_token save validate: false end
Generates a new {#remember_token} for the user, which will have the effect of signing all of the user's current sessions out. This is called internally by {Session#sign_out}. Calling `reset_remember_token!` will cause the user model to be saved without validations. Any other changes you made to this user instance will also be persisted, without validation. It is inteded to be called on an instance with no changes (`dirty? == false`). @return [Boolean] Was the save successful?
reset_remember_token!
ruby
thoughtbot/clearance
lib/clearance/user.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/user.rb
MIT
def update_password(new_password) self.password = new_password if valid? self.confirmation_token = nil generate_remember_token end save end
Sets the user's password to the new value, using the `password=` method on the configured password strategy. By default, this is {PasswordStrategies::BCrypt#password=}. This also has the side-effect of blanking the {#confirmation_token} and rotating the `#remember_token`. Validations will be run as part of this update. If the user instance is not valid, the password change will not be persisted, and this method will return `false`. @return [Boolean] Was the save successful?
update_password
ruby
thoughtbot/clearance
lib/clearance/user.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/user.rb
MIT
def normalize_email self.email = self.class.normalize_email(email) end
Sets the email on this instance to the value returned by {.normalize_email} @return [String]
normalize_email
ruby
thoughtbot/clearance
lib/clearance/user.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/user.rb
MIT
def skip_password_validation? password_optional? || (encrypted_password.present? && !encrypted_password_changed?) end
True if {#password_optional?} is true or if the user already has an {#encrypted_password} that is not changing. @return [Boolean]
skip_password_validation?
ruby
thoughtbot/clearance
lib/clearance/user.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/user.rb
MIT
def generate_confirmation_token self.confirmation_token = Clearance::Token.new end
Sets the {#confirmation_token} on the instance to a new value generated by {Token.new}. The change is not automatically persisted. If you would like to generate and save in a single method call, use {#forgot_password!}. @return [String] The new confirmation token
generate_confirmation_token
ruby
thoughtbot/clearance
lib/clearance/user.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/user.rb
MIT
def generate_remember_token self.remember_token = Clearance::Token.new end
Sets the {#remember_token} on the instance to a new value generated by {Token.new}. The change is not automatically persisted. If you would like to generate and save in a single method call, use {#reset_remember_token!}. @return [String] The new remember token
generate_remember_token
ruby
thoughtbot/clearance
lib/clearance/user.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/user.rb
MIT
def sign_in constructor = factory_module("sign_in") factory = Clearance.configuration.user_model.to_s.underscore.to_sym sign_in_as constructor.create(factory) end
Signs in a user that is created using FactoryGirl. The factory name is derrived from your `user_class` Clearance configuration. @raise [RuntimeError] if FactoryGirl is not defined.
sign_in
ruby
thoughtbot/clearance
lib/clearance/testing/controller_helpers.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/testing/controller_helpers.rb
MIT
def sign_in_as(user) @request.env[:clearance].sign_in(user) user end
Signs in the provided user. @return user
sign_in_as
ruby
thoughtbot/clearance
lib/clearance/testing/controller_helpers.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/testing/controller_helpers.rb
MIT
def factory_module(provider) if defined?(FactoryBot) FactoryBot elsif defined?(FactoryGirl) FactoryGirl else raise("Clearance's `#{provider}` helper requires factory_bot") end end
Determines the appropriate factory library @api private @raise [RuntimeError] if both FactoryGirl and FactoryBot are not defined.
factory_module
ruby
thoughtbot/clearance
lib/clearance/testing/controller_helpers.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/testing/controller_helpers.rb
MIT
def deny_access(opts = {}) DenyAccessMatcher.new(self, opts) end
The `deny_access` matcher is used to assert that a request is denied access by clearance. @option opts [String] :flash The expected flash alert message. Defaults to nil, which means the flash will not be checked. @option opts [String] :redirect The expected redirect url. Defaults to `'/'` if signed in or the `sign_in_url` if signed out. class PostsController < ActionController::Base before_action :require_login def index @posts = Post.all end end describe PostsController do describe "#index" do it "denies access to users not signed in" do get :index expect(controller).to deny_access end end end
deny_access
ruby
thoughtbot/clearance
lib/clearance/testing/deny_access_matcher.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/testing/deny_access_matcher.rb
MIT
def sign_in view.current_user = Clearance.configuration.user_model.new end
Sets current_user on the view under test to a new instance of your user model.
sign_in
ruby
thoughtbot/clearance
lib/clearance/testing/view_helpers.rb
https://github.com/thoughtbot/clearance/blob/master/lib/clearance/testing/view_helpers.rb
MIT