repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/events/test_step_started.rb
lib/cucumber/events/test_step_started.rb
# frozen_string_literal: true require 'cucumber/core/events' module Cucumber module Events # Signals that a {Cucumber::Core::Test::Step} is about to be executed class TestStepStarted < Core::Events::TestStepStarted # @return [Cucumber::Core::Test::Step] the test step to be executed attr_reader :test_step end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/gated_receiver.rb
lib/cucumber/filters/gated_receiver.rb
# frozen_string_literal: true module Cucumber module Filters class GatedReceiver def initialize(receiver) @receiver = receiver @test_cases = [] end def test_case(test_case) @test_cases << test_case self end def done @test_cases.map do |test_case| test_case.describe_to(@receiver) end @receiver.done self end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/apply_after_hooks.rb
lib/cucumber/filters/apply_after_hooks.rb
# frozen_string_literal: true module Cucumber module Filters class ApplyAfterHooks < Core::Filter.new(:hooks) def test_case(test_case) hooks.apply_after_hooks(test_case).describe_to(receiver) end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/tag_limits.rb
lib/cucumber/filters/tag_limits.rb
# frozen_string_literal: true require 'cucumber/filters/gated_receiver' require 'cucumber/filters/tag_limits/test_case_index' require 'cucumber/filters/tag_limits/verifier' module Cucumber module Filters class TagLimitExceededError < StandardError def initialize(*limit_breaches) super(limit_breaches.map(&:to_s).join("\n")) end end class TagLimits def initialize(tag_limits, receiver = nil) @tag_limits = tag_limits @gated_receiver = GatedReceiver.new(receiver) @test_case_index = TestCaseIndex.new @verifier = Verifier.new(@tag_limits) end def test_case(test_case) gated_receiver.test_case(test_case) test_case_index.add(test_case) self end def done verifier.verify!(test_case_index) gated_receiver.done self end def with_receiver(receiver) self.class.new(@tag_limits, receiver) end private attr_reader :gated_receiver, :test_case_index, :verifier end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/activate_steps.rb
lib/cucumber/filters/activate_steps.rb
# frozen_string_literal: true require 'cucumber/core/filter' require 'cucumber/step_match' require 'cucumber/events' require 'cucumber/errors' module Cucumber module Filters class ActivateSteps < Core::Filter.new(:step_match_search, :configuration) def test_case(test_case) CaseFilter.new(test_case, step_match_search, configuration).test_case.describe_to receiver end class CaseFilter def initialize(test_case, step_match_search, configuration) @original_test_case = test_case @step_match_search = step_match_search @configuration = configuration end def test_case @original_test_case.with_steps(new_test_steps) end private def new_test_steps @original_test_case.test_steps.map(&method(:attempt_to_activate)) end def attempt_to_activate(test_step) find_match(test_step).activate(test_step) end def find_match(test_step) FindMatch.new(@step_match_search, @configuration, test_step).result end class FindMatch attr_reader :step_match_search, :configuration, :test_step private :step_match_search, :configuration, :test_step def initialize(step_match_search, configuration, test_step) @step_match_search = step_match_search @configuration = configuration @test_step = test_step end def result begin return NoStepMatch.new(test_step, test_step.text) unless matches.any? rescue Cucumber::Ambiguous => e return AmbiguousStepMatch.new(e) end configuration.notify :step_activated, test_step, match return SkippingStepMatch.new if configuration.dry_run? match end private def match matches.first end def matches step_match_search.call(test_step.text) end end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/randomizer.rb
lib/cucumber/filters/randomizer.rb
# frozen_string_literal: true require 'digest/sha2' module Cucumber module Filters # Batches up all test cases, randomizes them, and then sends them on class Randomizer def initialize(seed, receiver = nil) @receiver = receiver @test_cases = [] @seed = seed end def test_case(test_case) @test_cases << test_case self end def done shuffled_test_cases.each do |test_case| test_case.describe_to(@receiver) end @receiver.done self end def with_receiver(receiver) self.class.new(@seed, receiver) end private def shuffled_test_cases digester = Digest::SHA2.new(256) @test_cases.map.with_index .sort_by { |_, index| digester.digest((@seed + index).to_s) } .map { |test_case, _| test_case } end attr_reader :seed private :seed end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/apply_after_step_hooks.rb
lib/cucumber/filters/apply_after_step_hooks.rb
# frozen_string_literal: true require 'cucumber/core/filter' module Cucumber module Filters class ApplyAfterStepHooks < Core::Filter.new(:hooks) def test_case(test_case) test_steps = hooks.find_after_step_hooks(test_case).apply(test_case.test_steps) test_case.with_steps(test_steps).describe_to(receiver) end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/quit.rb
lib/cucumber/filters/quit.rb
# frozen_string_literal: true module Cucumber module Filters class Quit def initialize(receiver = nil) @receiver = receiver end def test_case(test_case) test_case.describe_to @receiver unless Cucumber.wants_to_quit self end def done @receiver.done self end def with_receiver(receiver) self.class.new(receiver) end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/broadcast_test_case_ready_event.rb
lib/cucumber/filters/broadcast_test_case_ready_event.rb
# frozen_string_literal: true module Cucumber module Filters class BroadcastTestCaseReadyEvent < Core::Filter.new(:config) def test_case(test_case) config.notify(:test_case_ready, test_case) test_case.describe_to(receiver) end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/apply_around_hooks.rb
lib/cucumber/filters/apply_around_hooks.rb
# frozen_string_literal: true require 'cucumber/core/filter' module Cucumber module Filters class ApplyAroundHooks < Core::Filter.new(:hooks) def test_case(test_case) around_hooks = hooks.find_around_hooks(test_case) test_case.with_around_hooks(around_hooks).describe_to(receiver) end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/retry.rb
lib/cucumber/filters/retry.rb
# frozen_string_literal: true require 'cucumber/core/filter' require 'cucumber/running_test_case' require 'cucumber/events' module Cucumber module Filters class Retry < Core::Filter.new(:configuration) def initialize(*_args) super @total_permanently_failed = 0 end def test_case(test_case) configuration.on_event(:test_case_finished) do |event| next unless retry_required?(test_case, event) test_case_counts[test_case] += 1 test_case.describe_to(receiver) end super end private def retry_required?(test_case, event) return false unless event.test_case == test_case return false unless event.result.failed? return false if @total_permanently_failed >= configuration.retry_total_tests retry_required = test_case_counts[test_case] < configuration.retry_attempts if retry_required # retry test true else # test failed after max. attempts @total_permanently_failed += 1 false end end def test_case_counts @test_case_counts ||= Hash.new { |h, k| h[k] = 0 } end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/prepare_world.rb
lib/cucumber/filters/prepare_world.rb
# frozen_string_literal: true require 'cucumber/core/filter' require 'cucumber/core/test/location' require 'cucumber/running_test_case' module Cucumber module Filters class PrepareWorld < Core::Filter.new(:runtime) def test_case(test_case) CaseFilter.new(runtime, test_case).test_case.describe_to receiver end class CaseFilter def initialize(runtime, original_test_case) @runtime = runtime @original_test_case = original_test_case end def test_case init_scenario = Cucumber::Hooks.around_hook do |continue| @runtime.begin_scenario(scenario) continue.call @runtime.end_scenario(scenario) end around_hooks = [init_scenario] + @original_test_case.around_hooks @original_test_case.with_around_hooks(around_hooks).with_steps(@original_test_case.test_steps) end private def scenario @scenario ||= RunningTestCase.new(test_case) end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/broadcast_test_run_started_event.rb
lib/cucumber/filters/broadcast_test_run_started_event.rb
# frozen_string_literal: true module Cucumber module Filters # Added at the end of the filter chain to broadcast a list of # all of the test cases that have made it through the filters. class BroadcastTestRunStartedEvent < Core::Filter.new(:config) def initialize(config, receiver = nil) super @test_cases = [] end def test_case(test_case) @test_cases << test_case self end def done config.notify :test_run_started, @test_cases @test_cases.map do |test_case| test_case.describe_to(@receiver) end super self end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/apply_before_hooks.rb
lib/cucumber/filters/apply_before_hooks.rb
# frozen_string_literal: true module Cucumber module Filters class ApplyBeforeHooks < Core::Filter.new(:hooks) def test_case(test_case) hooks.apply_before_hooks(test_case).describe_to(receiver) end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/tag_limits/test_case_index.rb
lib/cucumber/filters/tag_limits/test_case_index.rb
# frozen_string_literal: true module Cucumber module Filters class TagLimits class TestCaseIndex def initialize @index = Hash.new { |hash, key| hash[key] = [] } end def add(test_case) test_case.tags.map(&:name).each do |tag_name| index[tag_name] << test_case end end def count_by_tag_name(tag_name) index[tag_name].count end def locations_of_tag_name(tag_name) index[tag_name].map(&:location) end private attr_accessor :index end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/filters/tag_limits/verifier.rb
lib/cucumber/filters/tag_limits/verifier.rb
# frozen_string_literal: true module Cucumber module Filters class TagLimits class Verifier def initialize(tag_limits) @tag_limits = tag_limits end def verify!(test_case_index) breaches = collect_breaches(test_case_index) raise TagLimitExceededError.new(*breaches) unless breaches.empty? end private def collect_breaches(test_case_index) tag_limits.reduce([]) do |breaches, (tag_name, limit)| breaches.tap do |breach| breach << Breach.new(tag_name, limit, test_case_index.locations_of_tag_name(tag_name)) if test_case_index.count_by_tag_name(tag_name) > limit end end end attr_reader :tag_limits class Breach INDENT = (' ' * 2).freeze def initialize(tag_name, limit, locations) @tag_name = tag_name @limit = limit @locations = locations end def to_s [ "#{tag_name} occurred #{tag_count} times, but the limit was set to #{limit}", *locations.map(&:to_s) ].join("\n#{INDENT}") end private def tag_count locations.count end attr_reader :tag_name, :limit, :locations end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/rake/task.rb
lib/cucumber/rake/task.rb
# frozen_string_literal: true require 'cucumber/platform' require 'cucumber/gherkin/formatter/ansi_escapes' require 'rake/dsl_definition' module Cucumber module Rake # Defines a Rake task for running features. # # The simplest use of it goes something like: # # Cucumber::Rake::Task.new # # This will define a task named <tt>cucumber</tt> described as 'Run Cucumber features'. # It will use steps from 'features/**/*.rb' and features in 'features/**/*.feature'. # # To further configure the task, you can pass a block: # # Cucumber::Rake::Task.new do |t| # t.cucumber_opts = %w{--format progress} # end # # See the attributes for additional configuration possibilities. class Task include Cucumber::Gherkin::Formatter::AnsiEscapes include ::Rake::DSL if defined?(::Rake::DSL) class InProcessCucumberRunner # :nodoc: include ::Rake::DSL if defined?(::Rake::DSL) attr_reader :args def initialize(libs, cucumber_opts, feature_files) raise 'libs must be an Array when running in-process' unless libs.instance_of? Array libs.reverse_each { |lib| $LOAD_PATH.unshift(lib) } @args = ( cucumber_opts + feature_files ).flatten.compact end def run require 'cucumber/cli/main' failure = Cucumber::Cli::Main.execute(args) raise 'Cucumber failed' if failure end end class ForkedCucumberRunner # :nodoc: include ::Rake::DSL if defined?(::Rake::DSL) def initialize(libs, cucumber_bin, cucumber_opts, bundler, feature_files) @libs = libs @cucumber_bin = cucumber_bin @cucumber_opts = cucumber_opts @bundler = bundler @feature_files = feature_files end def load_path [format('"%<path>s"', path: @libs.join(File::PATH_SEPARATOR))] end def quoted_binary(cucumber_bin) [format('"%<path>s"', path: cucumber_bin)] end def use_bundler @bundler.nil? ? File.exist?('./Gemfile') && bundler_gem_available? : @bundler end def bundler_gem_available? Gem::Specification.find_by_name('bundler') rescue Gem::LoadError false end def cmd if use_bundler [ Cucumber::RUBY_BINARY, '-S', 'bundle', 'exec', 'cucumber', @cucumber_opts, @feature_files ].flatten else [ Cucumber::RUBY_BINARY, '-I', load_path, quoted_binary(@cucumber_bin), @cucumber_opts, @feature_files ].flatten end end def run sh cmd.join(' ') do |ok, res| exit res.exitstatus unless ok end end end # Directories to add to the Ruby $LOAD_PATH attr_accessor :libs # Name of the cucumber binary to use for running features. Defaults to Cucumber::BINARY attr_accessor :binary # Extra options to pass to the cucumber binary. Can be overridden by the CUCUMBER_OPTS environment variable. # It's recommended to pass an Array, but if it's a String it will be #split by ' '. attr_reader :cucumber_opts def cucumber_opts=(opts) # :nodoc: unless opts.instance_of? String @cucumber_opts = opts return end @cucumber_opts = opts.split(' ') return if @cucumber_opts.length <= 1 $stderr.puts 'WARNING: consider using an array rather than a space-delimited string with cucumber_opts to avoid undesired behavior.' end # Whether or not to fork a new ruby interpreter. Defaults to true. You may gain # some startup speed if you set it to false, but this may also cause issues with # your load path and gems. attr_accessor :fork # Define what profile to be used. When used with cucumber_opts it is simply appended # to it. Will be ignored when CUCUMBER_OPTS is used. attr_accessor :profile # Whether or not to run with bundler (bundle exec). Setting this to false may speed # up the execution. The default value is true if Bundler is installed and you have # a Gemfile, false otherwise. # # Note that this attribute has no effect if you don't run in forked mode. attr_accessor :bundler # Name of the running task attr_reader :task_name # Define Cucumber Rake task def initialize(task_name = 'cucumber', desc = 'Run Cucumber features') @task_name = task_name @desc = desc @fork = true @libs = ['lib'] @rcov_opts = %w[--rails --exclude osx\/objc,gems\/] yield self if block_given? @binary = binary.nil? ? Cucumber::BINARY : File.expand_path(binary) define_task end def define_task # :nodoc: desc @desc task @task_name do runner.run end end def runner(_task_args = nil) # :nodoc: cucumber_opts = [ENV['CUCUMBER_OPTS']&.split(/\s+/) || cucumber_opts_with_profile] return ForkedCucumberRunner.new(libs, binary, cucumber_opts, bundler, feature_files) if fork InProcessCucumberRunner.new(libs, cucumber_opts, feature_files) end def cucumber_opts_with_profile # :nodoc: Array(cucumber_opts).concat(Array(@profile).flat_map { |p| ['--profile', p] }) end def feature_files # :nodoc: make_command_line_safe(FileList[ENV['FEATURE'] || []]) end def make_command_line_safe(list) list.map { |string| string.gsub(' ', '\ ') } end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/cli/main.rb
lib/cucumber/cli/main.rb
# frozen_string_literal: true require 'optparse' require 'cucumber' require 'logger' require 'cucumber/cli/configuration' module Cucumber module Cli class Main class << self def execute(args) new(args).execute! end end def initialize(args, out = $stdout, err = $stderr, kernel = Kernel) @args = args @out = out @err = err @kernel = kernel end def execute!(existing_runtime = nil) trap_interrupt runtime = runtime(existing_runtime) runtime.run! if Cucumber.wants_to_quit exit_unable_to_finish elsif runtime.failure? exit_tests_failed else exit_ok end rescue SystemExit => e @kernel.exit(e.status) rescue FileNotFoundException => e @err.puts(e.message) @err.puts("Couldn't open #{e.path}") exit_unable_to_finish rescue FeatureFolderNotFoundException => e @err.puts("#{e.message}. You can use `cucumber --init` to get started.") exit_unable_to_finish rescue ProfilesNotDefinedError, YmlLoadError, ProfileNotFound => e @err.puts(e.message) exit_unable_to_finish rescue Errno::EACCES, Errno::ENOENT => e @err.puts("#{e.message} (#{e.class})") exit_unable_to_finish rescue Exception => e @err.puts("#{e.message} (#{e.class})") @err.puts(e.backtrace.join("\n")) exit_unable_to_finish end def configuration @configuration ||= Configuration.new(@out, @err).tap do |configuration| configuration.parse!(@args) Cucumber.logger = configuration.log end end private def exit_ok @kernel.exit 0 end def exit_tests_failed @kernel.exit 1 end def exit_unable_to_finish @kernel.exit 2 end # stops the program immediately, without running at_exit blocks def exit_unable_to_finish! @kernel.exit! 2 end def trap_interrupt trap('INT') do exit_unable_to_finish! if Cucumber.wants_to_quit Cucumber.wants_to_quit = true $stderr.puts "\nExiting... Interrupt again to exit immediately." exit_unable_to_finish end end def runtime(existing_runtime) return Runtime.new(configuration) unless existing_runtime existing_runtime.tap { |runtime| runtime.configure(configuration) } end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/cli/options.rb
lib/cucumber/cli/options.rb
# frozen_string_literal: true require 'cucumber/cli/profile_loader' require 'cucumber/formatter/ansicolor' require 'cucumber/glue/registry_and_more' require 'cucumber/project_initializer' require 'cucumber/core/test/result' module Cucumber module Cli class Options CUCUMBER_PUBLISH_URL = ENV['CUCUMBER_PUBLISH_URL'] || 'https://messages.cucumber.io/api/reports -X GET' INDENT = ' ' * 53 BUILTIN_FORMATS = { 'pretty' => ['Cucumber::Formatter::Pretty', 'Prints the feature as is - in colours.'], 'progress' => ['Cucumber::Formatter::Progress', 'Prints one character per scenario.'], 'rerun' => ['Cucumber::Formatter::Rerun', 'Prints failing files with line numbers.'], 'usage' => ['Cucumber::Formatter::Usage', "Prints where step definitions are used.\n" \ "#{INDENT}The slowest step definitions (with duration) are\n" \ "#{INDENT}listed first. If --dry-run is used the duration\n" \ "#{INDENT}is not shown, and step definitions are sorted by\n" \ "#{INDENT}filename instead."], 'stepdefs' => ['Cucumber::Formatter::Stepdefs', "Prints All step definitions with their locations. Same as\n" \ "#{INDENT}the usage formatter, except that steps are not printed."], 'junit' => ['Cucumber::Formatter::Junit', "Generates a report similar to Ant+JUnit. Use\n" \ "#{INDENT}junit,fileattribute=true to include a file attribute."], 'json' => ['Cucumber::Formatter::Json', "Prints the feature as JSON.\n" \ "#{INDENT}The JSON format is in maintenance mode.\n" \ "#{INDENT}Please consider using the message formatter\n"\ "#{INDENT}with the standalone json-formatter\n" \ "#{INDENT}(https://github.com/cucumber/cucumber/tree/master/json-formatter)."], 'message' => ['Cucumber::Formatter::Message', 'Prints each message in NDJSON form, which can then be consumed by other tools.'], 'html' => ['Cucumber::Formatter::HTML', 'Outputs HTML report'], 'summary' => ['Cucumber::Formatter::Summary', 'Summary output of feature and scenarios'] }.freeze max = BUILTIN_FORMATS.keys.map(&:length).max FORMAT_HELP_MSG = [ 'Use --format rerun --out rerun.txt to write out failing', 'features. You can rerun them with cucumber @rerun.txt.', 'FORMAT can also be the fully qualified class name of', "your own custom formatter. If the class isn't loaded,", 'Cucumber will attempt to require a file with a relative', 'file name that is the underscore name of the class name.', 'Example: --format Foo::BarZap -> Cucumber will look for', 'foo/bar_zap.rb. You can place the file with this relative', 'path underneath your features/support directory or anywhere', "on Ruby's LOAD_PATH, for example in a Ruby gem." ].freeze FORMAT_HELP = (BUILTIN_FORMATS.keys.sort.map do |key| " #{key}#{' ' * (max - key.length)} : #{BUILTIN_FORMATS[key][1]}" end) + FORMAT_HELP_MSG PROFILE_SHORT_FLAG = '-p' NO_PROFILE_SHORT_FLAG = '-P' PROFILE_LONG_FLAG = '--profile' NO_PROFILE_LONG_FLAG = '--no-profile' FAIL_FAST_FLAG = '--fail-fast' RETRY_FLAG = '--retry' RETRY_TOTAL_FLAG = '--retry-total' OPTIONS_WITH_ARGS = [ '-r', '--require', '--i18n-keywords', '-f', '--format', '-o', '--out', '-t', '--tags', '-n', '--name', '-e', '--exclude', PROFILE_SHORT_FLAG, PROFILE_LONG_FLAG, RETRY_FLAG, RETRY_TOTAL_FLAG, '-l', '--lines', '--port', '-I', '--snippet-type' ].freeze ORDER_TYPES = %w[defined random].freeze TAG_LIMIT_MATCHER = /(?<tag_name>@\w+):(?<limit>\d+)/x.freeze def self.parse(args, out_stream, error_stream, options = {}) new(out_stream, error_stream, options).parse!(args) end def initialize(out_stream = $stdout, error_stream = $stderr, options = {}) @out_stream = out_stream @error_stream = error_stream @default_profile = options[:default_profile] @profiles = options[:profiles] || [] @overridden_paths = [] @options = default_options.merge(options) @profile_loader = options[:profile_loader] @options[:skip_profile_information] = options[:skip_profile_information] @disable_profile_loading = nil end def [](key) @options[key] end def []=(key, value) @options[key] = value end def parse!(args) @args = args @expanded_args = @args.dup @args.extend(::OptionParser::Arguable) @args.options do |opts| opts.banner = banner opts.on('--publish', 'Publish a report to https://reports.cucumber.io') do set_option :publish_enabled, true end opts.on('--publish-quiet', 'Don\'t print information banner about publishing reports') { set_option :publish_quiet } opts.on('-r LIBRARY|DIR', '--require LIBRARY|DIR', *require_files_msg) { |lib| require_files(lib) } opts.on('-j DIR', '--jars DIR', 'Load all the jars under DIR') { |jars| load_jars(jars) } if Cucumber::JRUBY opts.on("#{RETRY_FLAG} ATTEMPTS", *retry_msg) { |v| set_option :retry, v.to_i } opts.on("#{RETRY_TOTAL_FLAG} TESTS", *retry_total_msg) { |v| set_option :retry_total, v.to_i } opts.on('--i18n-languages', *i18n_languages_msg) { list_languages_and_exit } opts.on('--i18n-keywords LANG', *i18n_keywords_msg) { |lang| language lang } opts.on(FAIL_FAST_FLAG, 'Exit immediately following the first failing scenario') { set_option :fail_fast } opts.on('-f FORMAT', '--format FORMAT', *format_msg, *FORMAT_HELP) do |v| add_option :formats, [*parse_formats(v), @out_stream] end opts.on('--init', *init_msg) { initialize_project } opts.on('-o', '--out [FILE|DIR|URL]', *out_msg) { |v| out_stream v } opts.on('-t TAG_EXPRESSION', '--tags TAG_EXPRESSION', *tags_msg) { |v| add_tag(v) } opts.on('-n NAME', '--name NAME', *name_msg) { |v| add_option(:name_regexps, /#{v}/) } opts.on('-e', '--exclude PATTERN', *exclude_msg) { |v| add_option :excludes, Regexp.new(v) } opts.on(PROFILE_SHORT_FLAG, "#{PROFILE_LONG_FLAG} PROFILE", *profile_short_flag_msg) { |v| add_profile v } opts.on(NO_PROFILE_SHORT_FLAG, NO_PROFILE_LONG_FLAG, *no_profile_short_flag_msg) { |_v| disable_profile_loading } opts.on('-c', '--[no-]color', *color_msg) { |v| color v } opts.on('-d', '--dry-run', *dry_run_msg) { set_dry_run_and_duration } opts.on('-m', '--no-multiline', "Don't print multiline strings and tables under steps.") { set_option :no_multiline } opts.on('-s', '--no-source', "Don't print the file and line of the step definition with the steps.") { set_option :source, false } opts.on('-i', '--no-snippets', "Don't print snippets for pending steps.") { set_option :snippets, false } opts.on('-I', '--snippet-type TYPE', *snippet_type_msg) { |v| set_option :snippet_type, v.to_sym } opts.on('-q', '--quiet', 'Alias for --no-snippets --no-source --no-duration --publish-quiet.') { shut_up } opts.on('--no-duration', "Don't print the duration at the end of the summary") { set_option :duration, false } opts.on('-b', '--backtrace', 'Show full backtrace for all errors.') { Cucumber.use_full_backtrace = true } opts.on('-S', '--[no-]strict', *strict_msg) { |setting| set_strict(setting) } opts.on('--[no-]strict-undefined', 'Fail if there are any undefined results.') { |setting| set_strict(setting, :undefined) } opts.on('--[no-]strict-pending', 'Fail if there are any pending results.') { |setting| set_strict(setting, :pending) } opts.on('--[no-]strict-flaky', 'Fail if there are any flaky results.') { |setting| set_strict(setting, :flaky) } opts.on('-w', '--wip', 'Fail if there are any passing scenarios.') { set_option :wip } opts.on('-v', '--verbose', 'Show the files and features loaded.') { set_option :verbose } opts.on('-g', '--guess', 'Guess best match for Ambiguous steps.') { set_option :guess } opts.on('-l', '--lines LINES', *lines_msg) { |lines| set_option :lines, lines } opts.on('-x', '--expand', 'Expand Scenario Outline Tables in output.') { set_option :expand } opts.on('--order TYPE[:SEED]', 'Run examples in the specified order. Available types:', *<<~TEXT.split("\n")) do |order| [defined] Run scenarios in the order they were defined (default). [random] Shuffle scenarios before running. Specify SEED to reproduce the shuffling from a previous run. e.g. --order random:5738 TEXT @options[:order], @options[:seed] = *order.split(':') raise "'#{@options[:order]}' is not a recognised order type. Please use one of #{ORDER_TYPES.join(', ')}." unless ORDER_TYPES.include?(@options[:order]) end opts.on_tail('--version', 'Show version.') { exit_ok(Cucumber::VERSION) } opts.on_tail('-h', '--help', "You're looking at it.") { exit_ok(opts.help) } end.parse! process_publish_options @args.map! { |a| "#{a}:#{@options[:lines]}" } if @options[:lines] extract_environment_variables @options[:paths] = @args.dup # whatver is left over check_formatter_stream_conflicts merge_profiles self end def custom_profiles @profiles - [@default_profile] end def filters @options[:filters] ||= [] end def check_formatter_stream_conflicts streams = @options[:formats].uniq.map { |(_, _, stream)| stream } return if streams == streams.uniq raise 'All but one formatter must use --out, only one can print to each stream (or STDOUT)' end def to_hash Hash(@options) end protected attr_reader :options, :profiles, :expanded_args protected :options, :profiles, :expanded_args private def process_publish_options @options[:publish_enabled] = true if truthy_string?(ENV['CUCUMBER_PUBLISH_ENABLED']) || ENV['CUCUMBER_PUBLISH_TOKEN'] @options[:formats] << publisher if @options[:publish_enabled] @options[:publish_quiet] = true if truthy_string?(ENV['CUCUMBER_PUBLISH_QUIET']) end def truthy_string?(str) return false if str.nil? str !~ /^(false|no|0)$/i end def color_msg [ 'Whether or not to use ANSI color in the output. Cucumber decides', 'based on your platform and the output destination if not specified.' ] end def dry_run_msg ['Invokes formatters without executing the steps.'] end def exclude_msg ["Don't run feature files or require ruby files matching PATTERN"] end def format_msg ['How to format features (Default: pretty). Available formats:'] end def i18n_languages_msg [ 'List all available languages' ] end def i18n_keywords_msg [ 'List keywords for in a particular language', %(Run with "--i18n help" to see all languages) ] end def init_msg [ 'Initializes folder structure and generates conventional files for', 'a Cucumber project.' ] end def lines_msg ['Run given line numbers. Equivalent to FILE:LINE syntax'] end def no_profile_short_flag_msg [ "Disables all profile loading to avoid using the 'default' profile." ] end def profile_short_flag_msg [ 'Pull commandline arguments from cucumber.yml which can be defined as', "strings or arrays. When a 'default' profile is defined and no profile", 'is specified it is always used. (Unless disabled, see -P below.)', 'When feature files are defined in a profile and on the command line', 'then only the ones from the command line are used.' ] end def retry_msg ['Specify the number of times to retry failing tests (default: 0)'] end def retry_total_msg [ 'The total number of failing test after which retrying of tests is suspended.', 'Example: --retry-total 10 -> Will stop retrying tests after 10 failing tests.' ] end def name_msg [ 'Only execute the feature elements which match part of the given name.', 'If this option is given more than once, it will match against all the', 'given names.' ] end def strict_msg [ 'Fail if there are any strict affected results ', '(that is undefined, pending or flaky results).' ] end def parse_formats(value) formatter, *formatter_options = value.split(',') options_hash = Hash[formatter_options.map { |string| string.split('=') }] [formatter, options_hash] end def out_stream(value) @options[:formats] << ['pretty', {}, nil] if @options[:formats].empty? @options[:formats][-1][2] = value end def tags_msg [ 'Only execute the features or scenarios with tags matching TAG_EXPRESSION.', 'Scenarios inherit tags declared on the Feature level. The simplest', 'TAG_EXPRESSION is simply a tag. Example: --tags @dev. To represent', "boolean NOT preceed the tag with 'not '. Example: --tags 'not @dev'.", 'A tag expression can have several tags separated by an or which represents', "logical OR. Example: --tags '@dev or @wip'. The --tags option can be specified", 'A tag expression can have several tags separated by an and which represents', "logical AND. Example: --tags '@dev and @wip'. The --tags option can be specified", 'several times, and this also represents logical AND.', "Example: --tags '@foo or not @bar' --tags @zap. This represents the boolean", 'expression (@foo || !@bar) && @zap.', "\n", 'Beware that if you want to use several negative tags to exclude several tags', "you have to use logical AND: --tags 'not @fixme and not @buggy'.", "\n", 'Tags can be given a threshold to limit the number of occurrences.', 'Example: --tags @qa:3 will fail if there are more than 3 occurrences of the @qa tag.', 'This can be practical if you are practicing Kanban or CONWIP.' ] end def out_msg [ 'Write output to a file/directory/URL instead of STDOUT. This option', 'applies to the previously specified --format, or the', 'default format if no format is specified. Check the specific', "formatter's docs to see whether to pass a file, dir or URL.", "\n", 'When using a URL, the output of the formatter will be sent as the HTTP request body.', 'HTTP headers and request method can be set with cURL like options.', 'Example: --out "http://example.com -X POST -H Content-Type:text/json"' ] end def require_files_msg [ 'Require files before executing the features. If this', 'option is not specified, all *.rb files that are', 'siblings of or below the features will be loaded auto-', 'matically. Automatic loading is disabled when this', 'option is specified; all loading becomes explicit.', 'Files in directories named "support" are still always', 'loaded first when their parent directories are', 'required or if the "support" directories themselves are', 'explicitly required.', 'This option can be specified multiple times.' ] end def snippet_type_msg [ 'Use different snippet type (Default: cucumber_expression). Available types:', Cucumber::Glue::RegistryAndMore.cli_snippet_type_options ].flatten end def banner [ 'Usage: cucumber [options] [ [FILE|DIR|URL][:LINE[:LINE]*] ]+', '', 'Examples:', 'cucumber examples/i18n/en/features', 'cucumber @rerun.txt (See --format rerun)', 'cucumber examples/i18n/it/features/somma.feature:6:98:113', 'cucumber -s -i http://rubyurl.com/eeCl', '', '' ].join("\n") end def require_files(filenames) @options[:require] << filenames return unless Cucumber::JRUBY && File.directory?(filenames) require 'java' $CLASSPATH << filenames end def require_jars(jars) Dir["#{jars}/**/*.jar"].sort.each { |jar| require jar } end def publisher url = CUCUMBER_PUBLISH_URL url += %( -H "Authorization: Bearer #{ENV['CUCUMBER_PUBLISH_TOKEN']}") if ENV['CUCUMBER_PUBLISH_TOKEN'] ['message', {}, url] end def language(lang) require 'gherkin/dialect' return indicate_invalid_language_and_exit(lang) unless ::Gherkin::DIALECTS.key?(lang) list_keywords_and_exit(lang) end def disable_profile_loading @disable_profile_loading = true end def non_stdout_formats @options[:formats].reject { |_, _, output| output == @out_stream } end def add_option(option, value) @options[option] << value end def add_tag(value) raise("Found tags option '#{value}'. '~@tag' is no longer supported, use 'not @tag' instead.") if value.include?('~') raise("Found tags option '#{value}'. '@tag1,@tag2' is no longer supported, use '@tag or @tag2' instead.") if value.include?(',') @options[:tag_expressions] << value.gsub(/(@\w+)(:\d+)?/, '\1') add_tag_limits(value) end def add_tag_limits(value) value.split(/[, ]/).map { |part| TAG_LIMIT_MATCHER.match(part) }.compact.each do |matchdata| add_tag_limit(@options[:tag_limits], matchdata[:tag_name], matchdata[:limit].to_i) end end def add_tag_limit(tag_limits, tag_name, limit) raise "Inconsistent tag limits for #{tag_name}: #{tag_limits[tag_name]} and #{limit}" if tag_limits[tag_name] && tag_limits[tag_name] != limit tag_limits[tag_name] = limit end def color(color) Cucumber::Term::ANSIColor.coloring = color end def initialize_project ProjectInitializer.new.run && Kernel.exit(0) end def add_profile(profile) @profiles << profile end def set_option(option, value = nil) @options[option] = value.nil? ? true : value end def set_dry_run_and_duration @options[:dry_run] = true @options[:duration] = false end def exit_ok(text) @out_stream.puts(text) Kernel.exit(0) end def shut_up @options[:publish_quiet] = true @options[:snippets] = false @options[:source] = false @options[:duration] = false end def set_strict(setting, type = nil) @options[:strict].set_strict(setting, type) end def stdout_formats @options[:formats].select { |_, _, output| output == @out_stream } end def extract_environment_variables @args.delete_if do |arg| if arg =~ /^(\w+)=(.*)$/ @options[:env_vars][Regexp.last_match(1)] = Regexp.last_match(2) true end end end def merge_profiles return @out_stream.puts 'Disabling profiles...' if @disable_profile_loading @profiles << @default_profile if default_profile_should_be_used? @profiles.each { |profile| merge_with_profile(profile) } @options[:profiles] = @profiles end def merge_with_profile(profile) profile_args = profile_loader.args_from(profile) profile_options = Options.parse( profile_args, @out_stream, @error_stream, skip_profile_information: true, profile_loader: profile_loader ) reverse_merge(profile_options) end def default_profile_should_be_used? @profiles.empty? && profile_loader.cucumber_yml_defined? && profile_loader.profile?(@default_profile) end def profile_loader @profile_loader ||= ProfileLoader.new end def reverse_merge(other_options) @options = other_options.options.merge(@options) @options[:require] += other_options[:require] @options[:excludes] += other_options[:excludes] @options[:name_regexps] += other_options[:name_regexps] @options[:tag_expressions] += other_options[:tag_expressions] merge_tag_limits(@options[:tag_limits], other_options[:tag_limits]) @options[:env_vars] = other_options[:env_vars].merge(@options[:env_vars]) if @options[:paths].empty? @options[:paths] = other_options[:paths] else @overridden_paths += (other_options[:paths] - @options[:paths]) end @options[:source] &= other_options[:source] @options[:snippets] &= other_options[:snippets] @options[:duration] &= other_options[:duration] @options[:strict] = other_options[:strict].merge!(@options[:strict]) @options[:dry_run] |= other_options[:dry_run] @profiles += other_options.profiles @expanded_args += other_options.expanded_args if @options[:formats].empty? @options[:formats] = other_options[:formats] else @options[:formats] += other_options[:formats] @options[:formats] = stdout_formats[0..0] + non_stdout_formats end @options[:retry] = other_options[:retry] if @options[:retry].zero? @options[:retry_total] = other_options[:retry_total] if @options[:retry_total].infinite? self end def merge_tag_limits(option_limits, other_limits) other_limits.each { |key, value| add_tag_limit(option_limits, key, value) } end def indicate_invalid_language_and_exit(lang) @out_stream.write("Invalid language '#{lang}'. Available languages are:\n") list_languages_and_exit end def list_keywords_and_exit(lang) require 'gherkin/dialect' language = ::Gherkin::Dialect.for(lang) data = Cucumber::MultilineArgument::DataTable.from( [ ['feature', to_keywords_string(language.feature_keywords)], ['background', to_keywords_string(language.background_keywords)], ['scenario', to_keywords_string(language.scenario_keywords)], ['scenario_outline', to_keywords_string(language.scenario_outline_keywords)], ['examples', to_keywords_string(language.examples_keywords)], ['given', to_keywords_string(language.given_keywords)], ['when', to_keywords_string(language.when_keywords)], ['then', to_keywords_string(language.then_keywords)], ['and', to_keywords_string(language.and_keywords)], ['but', to_keywords_string(language.but_keywords)], ['given (code)', to_code_keywords_string(language.given_keywords)], ['when (code)', to_code_keywords_string(language.when_keywords)], ['then (code)', to_code_keywords_string(language.then_keywords)], ['and (code)', to_code_keywords_string(language.and_keywords)], ['but (code)', to_code_keywords_string(language.but_keywords)] ] ) @out_stream.write(data.to_s(color: false, prefixes: Hash.new(''))) Kernel.exit(0) end def list_languages_and_exit require 'gherkin/dialect' data = Cucumber::MultilineArgument::DataTable.from( ::Gherkin::DIALECTS.keys.map do |key| [key, ::Gherkin::DIALECTS[key].fetch('name'), ::Gherkin::DIALECTS[key].fetch('native')] end ) @out_stream.write(data.to_s(color: false, prefixes: Hash.new(''))) Kernel.exit(0) end def to_keywords_string(list) list.map { |item| "\"#{item}\"" }.join(', ') end def to_code_keywords_string(list) to_keywords_string(Cucumber::Gherkin::I18n.code_keywords_for(list)) end def default_options { strict: Cucumber::Core::Test::Result::StrictConfiguration.new, require: [], dry_run: false, formats: [], excludes: [], tag_expressions: [], tag_limits: {}, name_regexps: [], env_vars: {}, diff_enabled: true, snippets: true, source: true, duration: true, retry: 0, retry_total: Float::INFINITY } end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/cli/configuration.rb
lib/cucumber/cli/configuration.rb
# frozen_string_literal: true require 'logger' require 'cucumber/cli/options' require 'cucumber/cli/rerun_file' require 'cucumber/constantize' require 'cucumber' module Cucumber module Cli YmlLoadError = Class.new(StandardError) ProfilesNotDefinedError = Class.new(YmlLoadError) ProfileNotFound = Class.new(StandardError) class Configuration include Constantize attr_reader :out_stream def initialize(out_stream = $stdout, error_stream = $stderr) @out_stream = out_stream @error_stream = error_stream @options = Options.new(@out_stream, @error_stream, default_profile: 'default') end def parse!(args) @args = args @options.parse!(args) arrange_formats raise("You can't use both --strict and --wip") if strict.strict? && wip? set_environment_variables end def verbose? @options[:verbose] end def randomize? @options[:order] == 'random' end def seed Integer(@options[:seed] || rand(0xFFFF)) end def strict @options[:strict] end def wip? @options[:wip] end def guess? @options[:guess] end def dry_run? @options[:dry_run] end def expand? @options[:expand] end def fail_fast? @options[:fail_fast] end def retry_attempts @options[:retry] end def snippet_type @options[:snippet_type] || :cucumber_expression end def log logger = Logger.new(@out_stream) logger.formatter = LogFormatter.new logger.level = Logger::INFO logger.level = Logger::DEBUG if verbose? logger end def tag_limits @options[:tag_limits] end def tag_expressions @options[:tag_expressions] end def name_regexps @options[:name_regexps] end def filters @options.filters end def formats @options[:formats] end def paths @options[:paths] end def to_hash Hash(@options).merge(out_stream: @out_stream, error_stream: @error_stream, seed: seed) end private class LogFormatter < ::Logger::Formatter def call(_severity, _time, _progname, msg) msg end end def set_environment_variables @options[:env_vars].each do |var, value| ENV[var] = value end end def arrange_formats add_default_formatter if needs_default_formatter? @options[:formats] = @options[:formats].sort_by do |f| f[2] == @out_stream ? -1 : 1 end @options[:formats].uniq! @options.check_formatter_stream_conflicts end def add_default_formatter @options[:formats] << ['pretty', {}, @out_stream] end def needs_default_formatter? formatter_missing? || publish_only? end def formatter_missing? @options[:formats].empty? end def publish_only? @options[:formats] .uniq .map { |formatter, _, stream| [formatter, stream] } .uniq .reject { |formatter, stream| formatter == 'message' && stream != @out_stream } .empty? end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/cli/rerun_file.rb
lib/cucumber/cli/rerun_file.rb
# frozen_string_literal: true module Cucumber module Cli class RerunFile attr_reader :path def self.can_read?(path) path[0] == '@' && File.file?(real_path(path)) end def self.real_path(path) path[1..] end def initialize(path) @path = self.class.real_path(path) end def features lines.map { |l| l.scan(/(?:^| |)(.*?\.feature(?:(?::\d+)*))/) }.flatten end private def lines IO.read(@path).split("\n") end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/cli/profile_loader.rb
lib/cucumber/cli/profile_loader.rb
# frozen_string_literal: true require 'yaml' require 'erb' module Cucumber module Cli class ProfileLoader def initialize @cucumber_yml = nil end def args_from(profile) unless cucumber_yml.key?(profile) raise(ProfileNotFound, <<~ERROR_MESSAGE) Could not find profile: '#{profile}' Defined profiles in cucumber.yml: * #{cucumber_yml.keys.sort.join("\n * ")} ERROR_MESSAGE end args_from_yml = cucumber_yml[profile] || '' case args_from_yml when String if args_from_yml =~ /^\s*$/ raise YmlLoadError, "The '#{profile}' profile in cucumber.yml was blank." \ " Please define the command line arguments for the '#{profile}' profile in cucumber.yml.\n" end args_from_yml = processed_shellwords(args_from_yml) when Array raise YmlLoadError, "The '#{profile}' profile in cucumber.yml was empty. Please define the command line arguments for the '#{profile}' profile in cucumber.yml.\n" if args_from_yml.empty? else raise YmlLoadError, "The '#{profile}' profile in cucumber.yml was a #{args_from_yml.class}. It must be a String or Array" end args_from_yml end def profile?(profile) cucumber_yml.key?(profile) end def cucumber_yml_defined? cucumber_file && File.exist?(cucumber_file) end private # Loads the profile, processing it through ERB and YAML, and returns it as a hash. def cucumber_yml return @cucumber_yml if @cucumber_yml ensure_configuration_file_exists process_configuration_file_with_erb load_configuration unless @cucumber_yml.is_a?(Hash) raise(YmlLoadError, <<~ERROR_MESSAGE) cucumber.yml was found, but was blank or malformed. Please refer to cucumber's documentation on correct profile usage. Type 'cucumber --help' for usage. ERROR_MESSAGE end @cucumber_yml end def ensure_configuration_file_exists return if cucumber_yml_defined? raise(ProfilesNotDefinedError, <<~ERROR_MESSAGE) cucumber.yml was not found. Current directory is #{Dir.pwd}. Please refer to cucumber's documentation on defining profiles in cucumber.yml. You must define a 'default' profile to use the cucumber command without any arguments. Type 'cucumber --help' for usage. ERROR_MESSAGE end def process_configuration_file_with_erb @cucumber_erb = ERB.new(IO.read(cucumber_file), trim_mode: '%').result(binding) rescue StandardError raise(YmlLoadError, "cucumber.yml was found, but could not be parsed with ERB. Please refer to cucumber's documentation on correct profile usage.\n#{$ERROR_INFO.inspect}") end def load_configuration @cucumber_yml = YAML.load(@cucumber_erb) rescue StandardError raise(YmlLoadError, "cucumber.yml was found, but could not be parsed. Please refer to cucumber's documentation on correct profile usage.") end def cucumber_file @cucumber_file ||= Dir.glob('{,.config/,config/}cucumber{.yml,.yaml}').first end def processed_shellwords(args_from_yml) require 'shellwords' return Shellwords.shellwords(args_from_yml) unless Cucumber::WINDOWS # Shellwords treats backslash as an escape character so we have to mask it out temporarily placeholder = 'pseudo_unique_backslash_placeholder' sanitized_line = args_from_yml.gsub('\\', placeholder) Shellwords.shellwords(sanitized_line).collect { |argument| argument.gsub(placeholder, '\\') } end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/glue/snippet.rb
lib/cucumber/glue/snippet.rb
# frozen_string_literal: true module Cucumber module Glue module Snippet ARGUMENT_PATTERNS = ['"([^"]*)"', '(\d+)'].freeze class Generator def self.register_on(configuration) configuration.snippet_generators << new end def initialize(cucumber_expression_generator) @cucumber_expression_generator = cucumber_expression_generator end def call(code_keyword, step_name, multiline_arg, snippet_type) snippet_class = typed_snippet_class(snippet_type) snippet_class.new(@cucumber_expression_generator, code_keyword, step_name, multiline_arg).to_s end def typed_snippet_class(type) SNIPPET_TYPES.fetch(type || :cucumber_expression) end end class BaseSnippet def initialize(cucumber_expression_generator, code_keyword, step_name, multiline_argument) @number_of_arguments = 0 @code_keyword = code_keyword @pattern = replace_and_count_capturing_groups(step_name) @generated_expressions = cucumber_expression_generator.generate_expressions(step_name) @multiline_argument = MultilineArgumentSnippet.new(multiline_argument) end def to_s "#{step} #{do_block}" end def step "#{code_keyword}#{typed_pattern}" end def self.cli_option_string(type, cucumber_expression_generator) format('%<type>-7s: %<description>-28s e.g. %<example>s', type: type, description: description, example: example(cucumber_expression_generator)) end private attr_reader :code_keyword, :pattern, :generated_expressions, :multiline_argument, :number_of_arguments def replace_and_count_capturing_groups(pattern) modified_pattern = ::Regexp.escape(pattern).gsub('\ ', ' ').gsub('/', '\/') ARGUMENT_PATTERNS.each do |argument_pattern| modified_pattern.gsub!(::Regexp.new(argument_pattern), argument_pattern) @number_of_arguments += modified_pattern.scan(argument_pattern).length end modified_pattern end def do_block <<~DOC.chomp do#{parameters} #{multiline_argument.comment} end DOC end def parameters block_args = (0...number_of_arguments).map { |n| "arg#{n + 1}" } multiline_argument.append_block_parameter_to(block_args) block_args.empty? ? '' : " |#{block_args.join(', ')}|" end class << self private def example(cucumber_expression_generator) new(cucumber_expression_generator, 'Given', 'I have 2 cukes', MultilineArgument::None.new).step end end end class CucumberExpression < BaseSnippet def typed_pattern "(\"#{generated_expressions[0].source}\")" end def to_s header = generated_expressions.each_with_index.map do |expr, i| prefix = i.zero? ? '' : '# ' "#{prefix}#{code_keyword}('#{expr.source}') do#{parameters(expr)}" end.join("\n") body = <<~DOC.chomp #{multiline_argument.comment} end DOC "#{header}\n#{body}" end def parameters(expr) parameter_names = expr.parameter_names multiline_argument.append_block_parameter_to(parameter_names) parameter_names.empty? ? '' : " |#{parameter_names.join(', ')}|" end def self.description 'Cucumber Expressions' end end class Regexp < BaseSnippet def typed_pattern "(/^#{pattern}$/)" end def self.description 'Snippets with parentheses' end end class Classic < BaseSnippet def typed_pattern " /^#{pattern}$/" end def self.description 'Snippets without parentheses. Note that these cause a warning from modern versions of Ruby.' end end class Percent < BaseSnippet def typed_pattern " %r{^#{pattern}$}" end def self.description 'Snippets with percent regexp' end end SNIPPET_TYPES = { cucumber_expression: CucumberExpression, regexp: Regexp, classic: Classic, percent: Percent }.freeze module MultilineArgumentSnippet def self.new(multiline_argument) builder = Builder.new multiline_argument.describe_to(builder) builder.result end class Builder def doc_string(*_args) @result = DocString.new end def data_table(table, *_args) @result = DataTable.new(table) end def result @result || None.new end end class DocString def append_block_parameter_to(array) array << 'doc_string' end def comment 'pending # Write code here that turns the phrase above into concrete actions' end end class DataTable def initialize(table) @table = table end def append_block_parameter_to(array) array << 'table' end def comment <<~COMMENT.chomp # table is a #{Cucumber::MultilineArgument::DataTable} pending # Write code here that turns the phrase above into concrete actions COMMENT end end class None def append_block_parameter_to(array); end def comment 'pending # Write code here that turns the phrase above into concrete actions' end end end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/glue/proto_world.rb
lib/cucumber/glue/proto_world.rb
# frozen_string_literal: true require 'cucumber/gherkin/formatter/ansi_escapes' require 'cucumber/core/test/data_table' require 'mini_mime' module Cucumber module Glue # Defines the basic API methods available in all Cucumber step definitions. # # You can, and probably should, extend this API with your own methods that # make sense in your domain. For more on that, see {Cucumber::Glue::Dsl#World} module ProtoWorld # Run a single Gherkin step # @example Call another step # step "I am logged in" # @example Call a step with quotes in the name # step %{the user "Dave" is logged in} # @example Passing a table # step "the following users exist:", table(%{ # | name | email | # | Matt | matt@matt.com | # | Aslak | aslak@aslak.com | # }) # @example Passing a multiline string # step "the email should contain:", "Dear sir,\nYou've won a prize!\n" # @param [String] name The name of the step # @param [String, Cucumber::Test::DocString, Cucumber::Ast::Table] raw_multiline_arg def step(name, raw_multiline_arg = nil) super end # Run a snippet of Gherkin # @example # steps %{ # Given the user "Susan" exists # And I am logged in as "Susan" # } # @param [String] steps_text The Gherkin snippet to run def steps(steps_text) super end # Parse Gherkin into a {Cucumber::Ast::Table} object. # # Useful in conjunction with the #step method. # @example Create a table # users = table(%{ # | name | email | # | Matt | matt@matt.com | # | Aslak | aslak@aslak.com | # }) # @param [String] text_or_table The Gherkin string that represents the table # Returns a Cucumber::MultilineArgument::DataTable for +text_or_table+, which can either # be a String: # # table(%{ # | account | description | amount | # | INT-100 | Taxi | 114 | # | CUC-101 | Peeler | 22 | # }) # # or a 2D Array: # # table([ # %w{ account description amount }, # %w{ INT-100 Taxi 114 }, # %w{ CUC-101 Peeler 22 } # ]) # def table(text_or_table) MultilineArgument::DataTable.from(text_or_table) end # Pause the tests and ask the operator for input def ask(question, timeout_seconds = 60) super end def log(*messages) messages.each { |message| attach(message.to_s.dup, 'text/x.cucumber.log+plain') } end # Attach a file to the output # @param file [string|io] the file to attach. # It can be a string containing the file content itself, the file path, or an IO ready to be read. # @param media_type [string] the media type. # If file is a valid path, media_type can be omitted, it will then be inferred from the file name. # @param filename [string] the name of the file you wish to specify. # This is only needed in situations where you want to rename a PDF download e.t.c. - In most situations # you should not need to pass a filename def attach(file, media_type = nil, filename = nil) if File.file?(file) media_type = MiniMime.lookup_by_filename(file)&.content_type if media_type.nil? file = File.read(file, mode: 'rb') end super rescue StandardError super end # Mark the matched step as pending. def pending(message = 'TODO') raise Pending, message unless block_given? yield rescue Exception raise Pending, message end # Skips this step and the remaining steps in the scenario def skip_this_scenario(message = 'Scenario skipped') raise Core::Test::Result::Skipped, message end # Prints the list of modules that are included in the World def inspect super end # see {#inspect} def to_s inspect end # Dynamically generate the API module, closuring the dependencies def self.for(runtime, language) Module.new do def self.extended(object) # wrap the dynamically generated module so that we can document the methods # for yardoc, which doesn't like define_method. object.extend(ProtoWorld) end # TODO: pass these in when building the module, instead of mutating them later # Extend the World with user-defined modules def add_modules!(world_modules, namespaced_world_modules) add_world_modules!(world_modules) if world_modules.any? add_namespaced_modules!(namespaced_world_modules) if namespaced_world_modules.any? end define_method(:step) do |name, raw_multiline_arg = nil| location = Core::Test::Location.of_caller runtime.invoke_dynamic_step(name, MultilineArgument.from(raw_multiline_arg, location)) end define_method(:steps) do |steps_text| location = Core::Test::Location.of_caller runtime.invoke_dynamic_steps(steps_text, language, location) end define_method(:ask) do |question, timeout_seconds = 60| runtime.ask(question, timeout_seconds) end define_method(:attach) do |file, media_type, filename| runtime.attach(file, media_type, filename) end # Prints the list of modules that are included in the World def inspect modules = [self.class] (class << self; self; end).instance_eval do modules += included_modules end modules << stringify_namespaced_modules format('#<%<modules>s:0x%<object_id>x>', modules: modules.join('+'), object_id: object_id) end private def add_world_modules!(modules) modules.each do |world_module| extend(world_module) end end def add_namespaced_modules!(modules) @__namespaced_modules = modules modules.each do |namespace, world_modules| world_modules.each do |world_module| variable_name = "@__#{namespace}_world" inner_world = instance_variable_get(variable_name) || Object.new instance_variable_set( variable_name, inner_world.extend(world_module) ) self.class.send(:define_method, namespace) do instance_variable_get(variable_name) end end end end def stringify_namespaced_modules return '' if @__namespaced_modules.nil? @__namespaced_modules.map { |k, v| "#{v.join(',')} (as #{k})" }.join('+') end end end AnsiEscapes = Cucumber::Gherkin::Formatter::AnsiEscapes end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/glue/world_factory.rb
lib/cucumber/glue/world_factory.rb
# frozen_string_literal: true module Cucumber module Glue class WorldFactory def initialize(proc) @proc = proc || -> { Object.new } end def create_world @proc.call || raise_nil_world end def raise_nil_world raise NilWorld rescue NilWorld => e e.backtrace.clear e.backtrace.push(Glue.backtrace_line(@proc, 'World')) raise e end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/glue/invoke_in_world.rb
lib/cucumber/glue/invoke_in_world.rb
# frozen_string_literal: true require 'cucumber/platform' module Cucumber module Glue # Utility methods for executing step definitions with nice backtraces etc. # TODO: add unit tests # TODO: refactor for readability class InvokeInWorld def self.replace_instance_exec_invocation_line!(backtrace, instance_exec_invocation_line, pseudo_method) return if Cucumber.use_full_backtrace instance_exec_pos = backtrace.index(instance_exec_invocation_line) return unless instance_exec_pos replacement_line = instance_exec_pos + INSTANCE_EXEC_OFFSET if pseudo_method pattern = RUBY_VERSION >= '3.4' ? /'.*'/ : /`.*'/ backtrace[replacement_line].gsub!(pattern, "`#{pseudo_method}'") end depth = backtrace.count { |line| line == instance_exec_invocation_line } end_pos = depth > 1 ? instance_exec_pos : -1 backtrace[replacement_line + 1..end_pos] = nil backtrace.compact! end def self.cucumber_instance_exec_in(world, check_arity, pseudo_method, *args, &block) cucumber_run_with_backtrace_filtering(pseudo_method) do if check_arity && !cucumber_compatible_arity?(args, block) world.instance_exec do ari = block.arity ari = ari.negative? ? "#{ari.abs - 1}+" : ari s1 = ari == 1 ? '' : 's' s2 = args.length == 1 ? '' : 's' raise ArityMismatchError, "Your block takes #{ari} argument#{s1}, but the Regexp matched #{args.length} argument#{s2}." end else world.instance_exec(*args, &block) end end end def self.cucumber_compatible_arity?(args, block) return true if block.arity == args.length return true if block.arity.negative? && args.length >= (block.arity.abs - 1) false end def self.cucumber_run_with_backtrace_filtering(pseudo_method) yield rescue Exception => e yield_line_number = __LINE__ - 2 instance_exec_invocation_line = if RUBY_VERSION >= '3.4' "#{__FILE__}:#{yield_line_number}:in '#{name}.#{__method__}'" else "#{__FILE__}:#{yield_line_number}:in `#{__method__}'" end replace_instance_exec_invocation_line!((e.backtrace || []), instance_exec_invocation_line, pseudo_method) raise e end INSTANCE_EXEC_OFFSET = -3 end # Raised if the number of a StepDefinition's Regexp match groups # is different from the number of Proc arguments. class ArityMismatchError < StandardError end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/glue/registry_wrapper.rb
lib/cucumber/glue/registry_wrapper.rb
# frozen_string_literal: true module Cucumber module Glue ## # This class wraps some internals methods to expose them to external plugins. class RegistryWrapper def initialize(registry) @registry = registry end ## # Creates a new CucumberExpression from the given +string_or_regexp+. # # If +string_or_regexp+ is a string, it will return a new CucumberExpression::CucumberExpression # # If +string_or_regexp+ is a regexp, it will return a new CucumberExpressions::RegularExpression # # An ArgumentError is raised if +string_or_regexp+ is not a string or a regexp def create_expression(string_or_regexp) @registry.create_expression(string_or_regexp) end ## # Return the current execution environment - AKA an isntance of World def current_world @registry.current_world end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/glue/dsl.rb
lib/cucumber/glue/dsl.rb
# frozen_string_literal: true require 'cucumber/cucumber_expressions/parameter_type' module Cucumber module Glue # This module provides the methods the DSL you can use to define # steps, hooks, transforms etc. module Dsl class << self attr_writer :rb_language def alias_adverb(adverb) alias_method adverb, :register_rb_step_definition end def build_rb_world_factory(world_modules, namespaced_world_modules, proc) @rb_language.build_rb_world_factory(world_modules, namespaced_world_modules, proc) end def register_rb_hook(type, tag_names, proc, name: nil) @rb_language.register_rb_hook(type, tag_names, proc, name: name) end def define_parameter_type(parameter_type) @rb_language.define_parameter_type(parameter_type) end def register_rb_step_definition(regexp, proc_or_sym, options = {}) @rb_language.register_rb_step_definition(regexp, proc_or_sym, options) end end # Registers any number of +world_modules+ (Ruby Modules) and/or a Proc. # The +proc+ will be executed once before each scenario to create an # Object that the scenario's steps will run within. Any +world_modules+ # will be mixed into this Object (via Object#extend). # # By default the +world modules+ are added to a global namespace. It is # possible to create a namespaced World by using an hash, where the # symbols are the namespaces. # # This method is typically called from one or more Ruby scripts under # <tt>features/support</tt>. You can call this method as many times as you # like (to register more modules), but if you try to register more than # one Proc you will get an error. # # Cucumber will not yield anything to the +proc+. Examples: # # World do # MyClass.new # end # # World(MyModule) # # World(my_module: MyModule) # def World(*world_modules, **namespaced_world_modules, &proc) Dsl.build_rb_world_factory(world_modules, namespaced_world_modules, proc) end # Registers a proc that will run before each Scenario. You can register as many # as you want (typically from ruby scripts under <tt>support/hooks.rb</tt>). def Before(*tag_expressions, name: nil, &proc) Dsl.register_rb_hook('before', tag_expressions, proc, name: name) end # Registers a proc that will run after each Scenario. You can register as many # as you want (typically from ruby scripts under <tt>support/hooks.rb</tt>). def After(*tag_expressions, name: nil, &proc) Dsl.register_rb_hook('after', tag_expressions, proc, name: name) end # Registers a proc that will be wrapped around each scenario. The proc # should accept two arguments: two arguments: the scenario and a "block" # argument (but passed as a regular argument, since blocks cannot accept # blocks in 1.8), on which it should call the .call method. You can register # as many as you want (typically from ruby scripts under <tt>support/hooks.rb</tt>). def Around(*tag_expressions, name: nil, &proc) Dsl.register_rb_hook('around', tag_expressions, proc, name: name) end # Registers a proc that will run after each Step. You can register as # as you want (typically from ruby scripts under <tt>support/hooks.rb</tt>). def AfterStep(*tag_expressions, name: nil, &proc) Dsl.register_rb_hook('after_step', tag_expressions, proc, name: name) end def ParameterType(options) type = options[:type] || Object use_for_snippets = if_nil(options[:use_for_snippets], true) prefer_for_regexp_match = if_nil(options[:prefer_for_regexp_match], false) parameter_type = CucumberExpressions::ParameterType.new( options[:name], options[:regexp], type, options[:transformer], use_for_snippets, prefer_for_regexp_match ) Dsl.define_parameter_type(parameter_type) end def if_nil(value, default) value.nil? ? default : value end # Registers a proc that will run after Cucumber is configured in order to install an external plugin. def InstallPlugin(name: nil, &proc) Dsl.register_rb_hook('install_plugin', [], proc, name: name) end # Registers a proc that will run before the execution of the scenarios. # Use it for your final set-ups def BeforeAll(name: nil, &proc) Dsl.register_rb_hook('before_all', [], proc, name: name) end # Registers a proc that will run after the execution of the scenarios. # Use it for your final clean-ups def AfterAll(name: nil, &proc) Dsl.register_rb_hook('after_all', [], proc, name: name) end # Registers a new Ruby StepDefinition. This method is aliased # to <tt>Given</tt>, <tt>When</tt> and <tt>Then</tt>, and # also to the i18n translations whenever a feature of a # new language is loaded. # # If provided, the +symbol+ is sent to the <tt>World</tt> object # as defined by #World. A new <tt>World</tt> object is created # for each scenario and is shared across step definitions within # that scenario. If the +options+ hash contains an <tt>:on</tt> # key, the value for this is assumed to be a proc. This proc # will be executed in the context of the <tt>World</tt> object # and then sent the +symbol+. # # If no +symbol+ if provided then the +&proc+ gets executed in # the context of the <tt>World</tt> object. def register_rb_step_definition(regexp, symbol = nil, options = {}, &proc) proc_or_sym = symbol || proc Dsl.register_rb_step_definition(regexp, proc_or_sym, options) end end end end # rubocop:disable Style/MixinUsage # This "should" always be present, because it allows users to write `Before` and `After` # See. https://github.com/cucumber/cucumber-ruby/pull/1566#discussion_r683235396 extend(Cucumber::Glue::Dsl) # rubocop:enable Style/MixinUsage
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/glue/registry_and_more.rb
lib/cucumber/glue/registry_and_more.rb
# frozen_string_literal: true require 'cucumber/cucumber_expressions/parameter_type_registry' require 'cucumber/cucumber_expressions/cucumber_expression' require 'cucumber/cucumber_expressions/regular_expression' require 'cucumber/cucumber_expressions/cucumber_expression_generator' require 'cucumber/glue/dsl' require 'cucumber/glue/snippet' require 'cucumber/glue/hook' require 'cucumber/glue/proto_world' require 'cucumber/glue/step_definition' require 'cucumber/glue/world_factory' require 'cucumber/gherkin/i18n' require 'multi_test' require 'cucumber/step_match' require 'cucumber/step_definition_light' require 'cucumber/events/step_definition_registered' module Cucumber module Glue def self.backtrace_line(proc, name) location = Cucumber::Core::Test::Location.from_source_location(*proc.source_location) "#{location}:in `#{name}'" end # Raised if a World block returns Nil. class NilWorld < StandardError def initialize super('World procs should never return nil') end end # Raised if there are 2 or more World blocks. class MultipleWorld < StandardError def initialize(first_proc, second_proc) # TODO: [LH] - Just use a heredoc here to fix this up message = String.new message << "You can only pass a proc to #World once, but it's happening\n" message << "in 2 places:\n\n" message << Glue.backtrace_line(first_proc, 'World') << "\n" message << Glue.backtrace_line(second_proc, 'World') << "\n\n" message << "Use Ruby modules instead to extend your worlds. See the Cucumber::Glue::Dsl#World RDoc\n" message << "or http://wiki.github.com/cucumber/cucumber/a-whole-new-world.\n\n" super(message) end end # TODO: This class has too many responsibilities, split off class RegistryAndMore attr_reader :current_world, :step_definitions all_keywords = ::Gherkin::DIALECTS.keys.map do |dialect_name| dialect = ::Gherkin::Dialect.for(dialect_name) dialect.given_keywords + dialect.when_keywords + dialect.then_keywords + dialect.and_keywords + dialect.but_keywords end Cucumber::Gherkin::I18n.code_keywords_for(all_keywords.flatten.uniq.sort).each do |adverb| Glue::Dsl.alias_adverb(adverb.strip) end def self.cli_snippet_type_options registry = CucumberExpressions::ParameterTypeRegistry.new cucumber_expression_generator = CucumberExpressions::CucumberExpressionGenerator.new(registry) Snippet::SNIPPET_TYPES.keys.sort_by(&:to_s).map do |type| Snippet::SNIPPET_TYPES[type].cli_option_string(type, cucumber_expression_generator) end end def initialize(runtime, configuration) @runtime = runtime @configuration = configuration @step_definitions = [] Glue::Dsl.rb_language = self @world_proc = @world_modules = nil @parameter_type_registry = CucumberExpressions::ParameterTypeRegistry.new cucumber_expression_generator = CucumberExpressions::CucumberExpressionGenerator.new(@parameter_type_registry) @configuration.register_snippet_generator(Snippet::Generator.new(cucumber_expression_generator)) end def step_matches(name_to_match) @step_definitions.each_with_object([]) do |step_definition, result| if (arguments = step_definition.arguments_from(name_to_match)) result << StepMatch.new(step_definition, name_to_match, arguments) end end end def register_rb_hook(type, tag_expressions, proc, name: nil) hook = add_hook(type, Hook.new(@configuration.id_generator.new_id, self, tag_expressions, proc, name: name)) @configuration.notify(:envelope, hook.to_envelope(type)) hook end def define_parameter_type(parameter_type) @configuration.notify :envelope, parameter_type_envelope(parameter_type) @parameter_type_registry.define_parameter_type(parameter_type) end def register_rb_step_definition(string_or_regexp, proc_or_sym, options) step_definition = StepDefinition.new(@configuration.id_generator.new_id, self, string_or_regexp, proc_or_sym, options) @step_definitions << step_definition @configuration.notify :step_definition_registered, step_definition @configuration.notify :envelope, step_definition.to_envelope step_definition rescue Cucumber::CucumberExpressions::UndefinedParameterTypeError => e # TODO: add a way to extract the parameter type directly from the error. type_name = e.message.match(/^Undefined parameter type ['|{](.*)['|}].?$/)[1] @configuration.notify :undefined_parameter_type, type_name, string_or_regexp end def build_rb_world_factory(world_modules, namespaced_world_modules, proc) if proc raise MultipleWorld.new(@world_proc, proc) if @world_proc @world_proc = proc end @world_modules ||= [] @world_modules += world_modules @namespaced_world_modules ||= Hash.new { |h, k| h[k] = [] } namespaced_world_modules.each do |namespace, world_module| @namespaced_world_modules[namespace] << world_module unless @namespaced_world_modules[namespace].include?(world_module) end end def load_code_file(code_file) return unless File.extname(code_file) == '.rb' # This will cause self.add_step_definition, self.add_hook, and self.define_parameter_type to be called from Glue::Dsl if Cucumber.use_legacy_autoloader load File.expand_path(code_file) else require File.expand_path(code_file) end end def begin_scenario(test_case) @current_world = WorldFactory.new(@world_proc).create_world @current_world.extend(ProtoWorld.for(@runtime, test_case.language)) MultiTest.extend_with_best_assertion_library(@current_world) @current_world.add_modules!(@world_modules || [], @namespaced_world_modules || {}) end def end_scenario @current_world = nil end def install_plugin(configuration, registry) hooks[:install_plugin].each do |hook| hook.invoke('InstallPlugin', [configuration, registry]) end end def before_all hooks[:before_all].each do |hook| hook.invoke('BeforeAll', []) end end def after_all hooks[:after_all].each do |hook| hook.invoke('AfterAll', []) end end def add_hook(type, hook) hooks[type.to_sym] << hook hook end def clear_hooks @hooks = nil end def hooks_for(type, scenario) # :nodoc: hooks[type.to_sym].select { |hook| scenario.accept_hook?(hook) } end def create_expression(string_or_regexp) return CucumberExpressions::CucumberExpression.new(string_or_regexp, @parameter_type_registry) if string_or_regexp.is_a?(String) return CucumberExpressions::RegularExpression.new(string_or_regexp, @parameter_type_registry) if string_or_regexp.is_a?(Regexp) raise ArgumentError, 'Expression must be a String or Regexp' end private def parameter_type_envelope(parameter_type) # TODO: should this be moved to Cucumber::Expression::ParameterType#to_envelope ?? # Note: that would mean that cucumber-expression would depend on cucumber-messages Cucumber::Messages::Envelope.new( parameter_type: Cucumber::Messages::ParameterType.new( id: @configuration.id_generator.new_id, name: parameter_type.name, regular_expressions: parameter_type.regexps.map(&:to_s), prefer_for_regular_expression_match: parameter_type.prefer_for_regexp_match, use_for_snippets: parameter_type.use_for_snippets, source_reference: Cucumber::Messages::SourceReference.new( uri: parameter_type.transformer.source_location[0], location: Cucumber::Messages::Location.new(line: parameter_type.transformer.source_location[1]) ) ) ) end def hooks @hooks ||= Hash.new { |h, k| h[k] = [] } end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/glue/step_definition.rb
lib/cucumber/glue/step_definition.rb
# frozen_string_literal: true require 'cucumber/step_match' require 'cucumber/glue/invoke_in_world' module Cucumber module Glue # A Step Definition holds a Regexp pattern and a Proc, and is # typically created by calling {Dsl#register_rb_step_definition Given, When or Then} # in the step_definitions Ruby files. # # Example: # # Given /I have (\d+) cucumbers in my belly/ do # # some code here # end # class StepDefinition class MissingProc < StandardError def message 'Step definitions must always have a proc or symbol' end end class << self def new(id, registry, string_or_regexp, proc_or_sym, options) raise MissingProc if proc_or_sym.nil? super id, registry, registry.create_expression(string_or_regexp), create_proc(proc_or_sym, options) end private def create_proc(proc_or_sym, options) return proc_or_sym if proc_or_sym.is_a?(Proc) raise ArgumentError unless proc_or_sym.is_a?(Symbol) message = proc_or_sym target_proc = parse_target_proc_from(options) patch_location_onto lambda { |*args| target = instance_exec(&target_proc) target.send(message, *args) } end def patch_location_onto(block) location = Core::Test::Location.of_caller(5) block.define_singleton_method(:source_location) { [location.file, location.line] } block end def parse_target_proc_from(options) return -> { self } unless options.key?(:on) target = options[:on] case target when Proc target when Symbol -> { send(target) } else -> { raise ArgumentError, 'Target must be a symbol or a proc' } end end end attr_reader :id, :expression, :registry def initialize(id, registry, expression, proc) raise 'No regexp' if expression.is_a?(Regexp) @id = id @registry = registry @expression = expression @proc = proc end def to_envelope Cucumber::Messages::Envelope.new( step_definition: Cucumber::Messages::StepDefinition.new( id: id, pattern: Cucumber::Messages::StepDefinitionPattern.new( source: expression.source.to_s, type: expression_type ), source_reference: Cucumber::Messages::SourceReference.new( uri: location.file, location: Cucumber::Messages::Location.new( line: location.lines.first ) ) ) ) end def expression_type return Cucumber::Messages::StepDefinitionPatternType::CUCUMBER_EXPRESSION if expression.is_a?(CucumberExpressions::CucumberExpression) Cucumber::Messages::StepDefinitionPatternType::REGULAR_EXPRESSION end # @api private def to_hash type = expression.is_a?(CucumberExpressions::RegularExpression) ? 'regular expression' : 'cucumber expression' regexp = expression.regexp flags = '' flags += 'm' if (regexp.options & Regexp::MULTILINE) != 0 flags += 'i' if (regexp.options & Regexp::IGNORECASE) != 0 flags += 'x' if (regexp.options & Regexp::EXTENDED) != 0 { source: { type: type, expression: expression.source }, regexp: { source: regexp.source, flags: flags } } end # @api private def ==(other) expression.source == other.expression.source end # @api private def arguments_from(step_name) @expression.match(step_name) end # @api private # TODO: inline this and step definition just be a value object def invoke(args) InvokeInWorld.cucumber_instance_exec_in(@registry.current_world, true, @expression.to_s, *args, &@proc) rescue ArityMismatchError => e e.backtrace.unshift(backtrace_line) raise e end # @api private def backtrace_line "#{location}:in `#{@expression}'" end # @api private def file_colon_line case @proc when Proc location.to_s when Symbol ":#{@proc}" end end # The source location where the step definition can be found def location @location ||= Cucumber::Core::Test::Location.from_source_location(*@proc.source_location) end # @api private def file @file ||= location.file end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/lib/cucumber/glue/hook.rb
lib/cucumber/glue/hook.rb
# frozen_string_literal: true require 'cucumber/glue/invoke_in_world' module Cucumber module Glue # TODO: Kill pointless wrapper for Before, After and AfterStep hooks with fire class Hook attr_reader :id, :tag_expressions, :location, :name def initialize(id, registry, tag_expressions, proc, name: nil) @id = id @registry = registry @name = name @tag_expressions = tag_expressions @proc = proc @location = Cucumber::Core::Test::Location.from_source_location(*@proc.source_location) end def invoke(pseudo_method, arguments, &block) check_arity = false InvokeInWorld.cucumber_instance_exec_in( @registry.current_world, check_arity, pseudo_method, *[arguments, block].flatten.compact, &@proc ) end def to_envelope(type) Cucumber::Messages::Envelope.new( hook: Cucumber::Messages::Hook.new( id: id, name: name, tag_expression: tag_expressions.empty? ? nil : tag_expressions.join(' '), type: hook_type_to_enum_value[type.to_sym], source_reference: Cucumber::Messages::SourceReference.new( uri: location.file, location: Cucumber::Messages::Location.new( line: location.lines.first ) ) ) ) end private def hook_type_to_enum_value { before: 'BEFORE_TEST_CASE', after: 'AFTER_TEST_CASE', around: nil, # This needs deleting and removing from cucumber-ruby in v11 after_step: 'AFTER_TEST_STEP', install_plugin: 'BEFORE_TEST_RUN', before_all: 'BEFORE_TEST_RUN', after_all: 'AFTER_TEST_RUN' } end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/cck_spec.rb
compatibility/cck_spec.rb
# frozen_string_literal: true require_relative 'support/shared_examples' require_relative 'support/cck/examples' require 'cck/examples' # This is the implementation of the CCK testing for cucumber-ruby # It will run each example from the CCK that is of type "gherkin" (As "markdown" examples aren't implemented in ruby) # # All step definition and required supporting logic is contained here, the CCK gem proper contains the source of truth # of the "golden" NDJSON files and attachments / miscellaneous files describe CCK, :cck do let(:cucumber_command) { 'bundle exec cucumber --publish-quiet --profile none --format message' } CCK::Examples.gherkin.each do |example_name| describe "'#{example_name}' example" do include_examples 'cucumber compatibility kit' do let(:example) { example_name } let(:extra_args) { example == 'retry' ? '--retry 2' : '' } let(:support_code_path) { CCK::Examples.supporting_code_for(example) } let(:messages) { `#{cucumber_command} #{extra_args} --require #{support_code_path} #{cck_path}` } end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/support/shared_examples.rb
compatibility/support/shared_examples.rb
# frozen_string_literal: true require 'json' require 'rspec' require 'cucumber/messages' require_relative 'cck/helpers' require_relative 'cck/messages_comparator' RSpec.shared_examples 'cucumber compatibility kit' do include CCK::Helpers let(:cck_path) { CCK::Examples.feature_code_for(example) } let(:parsed_original) { parse_ndjson_file("#{cck_path}/#{example}.ndjson") } let(:parsed_generated) { parse_ndjson(messages) } let(:original_messages_types) { parsed_original.map { |msg| message_type(msg) } } let(:generated_messages_types) { parsed_generated.map { |msg| message_type(msg) } } it 'generates valid message types' do expect(generated_messages_types).to contain_exactly(*original_messages_types) end it 'generates valid message structure' do comparator = CCK::MessagesComparator.new(parsed_generated, parsed_original) expect(comparator.errors).to be_empty, "There were comparison errors: #{comparator.errors}" end it 'ensures a consistent `testRunStartedId` across the entire test run' do test_run_started_id = parsed_generated.detect { |msg| message_type(msg) == :test_run_started }.test_run_started.id ids = parsed_generated.filter_map do |msg| # These two types of message are the only ones containing the testRunStartedId attribute msg.send(message_type(msg)).test_run_started_id if %i[test_case test_run_finished].include?(message_type(msg)) end expect(ids).to all eq(test_run_started_id) end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/support/cck/keys_checker.rb
compatibility/support/cck/keys_checker.rb
# frozen_string_literal: true module CCK class KeysChecker def self.compare(detected, expected) new(detected, expected).compare end attr_reader :detected, :expected def initialize(detected, expected) @detected = detected @expected = expected end def compare return if identical_keys? return "Detected extra keys in message #{message_name}: #{extra_keys}" if extra_keys.any? "Missing keys in message #{message_name}: #{missing_keys}" if missing_keys.any? rescue StandardError => e ["Unexpected error: #{e.message}"] end private def identical_keys? detected_keys == expected_keys end def detected_keys @detected_keys ||= ordered_uniq_hash_keys(detected) end def expected_keys @expected_keys ||= ordered_uniq_hash_keys(expected) end def ordered_uniq_hash_keys(object) object.to_h(reject_nil_values: true).keys.sort end def extra_keys (detected_keys - expected_keys).reject { |key| meta_message? && key == :ci } end def missing_keys (expected_keys - detected_keys).reject { |key| meta_message? && key == :ci } end def meta_message? detected.instance_of?(Cucumber::Messages::Meta) end def message_name detected.class.name end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/support/cck/helpers.rb
compatibility/support/cck/helpers.rb
# frozen_string_literal: true module CCK module Helpers def message_type(message) message.to_h.each do |key, value| return key unless value.nil? end end def parse_ndjson_file(path) parse_ndjson(File.read(path)) end def parse_ndjson(ndjson) Cucumber::Messages::Helpers::NdjsonToMessageEnumerator.new(ndjson) end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/support/cck/messages_comparator.rb
compatibility/support/cck/messages_comparator.rb
# frozen_string_literal: true require_relative 'keys_checker' require_relative 'helpers' module CCK class MessagesComparator include Helpers def initialize(detected, expected) compare(detected, expected) end def errors all_errors.compact end private def compare(detected, expected) detected_by_type = messages_by_type(detected) expected_by_type = messages_by_type(expected) detected_by_type.each_key do |type| compare_list(detected_by_type[type], expected_by_type[type]) rescue StandardError => e all_errors << "Error while comparing #{type}: #{e.message}" end end def messages_by_type(messages) by_type = Hash.new { |h, k| h[k] = [] } messages.each do |msg| by_type[message_type(msg)] << remove_envelope(msg) end by_type end def remove_envelope(message) message.send(message_type(message)) end def compare_list(detected, expected) detected.each_with_index do |message, index| compare_message(message, expected[index]) end end def compare_message(detected, expected) return if not_message?(detected) return if ignorable?(detected) return if incomparable?(detected) all_errors << CCK::KeysChecker.compare(detected, expected) compare_sub_messages(detected, expected) end def not_message?(detected) !detected.is_a?(Cucumber::Messages::Message) end # These messages need to be ignored because they are too large, or they feature timestamps which will be different def ignorable?(detected) too_large_message?(detected) || time_message?(detected) end def too_large_message?(detected) detected.is_a?(Cucumber::Messages::GherkinDocument) || detected.is_a?(Cucumber::Messages::Pickle) end def time_message?(detected) detected.is_a?(Cucumber::Messages::Timestamp) || detected.is_a?(Cucumber::Messages::Duration) end # These messages need to be ignored because they are often not of identical shape def incomparable?(detected) detected.is_a?(Cucumber::Messages::Ci) || detected.is_a?(Cucumber::Messages::Git) end def compare_sub_messages(detected, expected) return unless expected.respond_to? :to_h expected.to_h.each_key do |key| value = expected.send(key) if value.is_a?(Array) compare_list(detected.send(key), value) else compare_message(detected.send(key), value) end end end def all_errors @all_errors ||= [] end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/support/cck/examples.rb
compatibility/support/cck/examples.rb
# frozen_string_literal: true module CCK module Examples class << self def supporting_code_for(example_name) path = File.join(local_features_folder_location, example_name) return path if File.directory?(path) raise ArgumentError, "No supporting code directory found locally for CCK example: #{example_name}" end private def local_features_folder_location File.expand_path("#{File.dirname(__FILE__)}/../../features/") end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/empty/empty_steps.rb
compatibility/features/empty/empty_steps.rb
# frozen_string_literal: true # The empty CCK scenario does not contain any executable steps. It contains just one scenario # which will be "ran" and only produce a single pickle for the name of the scenario (No pickles for steps)
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/undefined/undefined_steps.rb
compatibility/features/undefined/undefined_steps.rb
# frozen_string_literal: true Given('an implemented step') do # no-op end Given('a step that will be skipped') do # no-op end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/hooks-conditional/hooks-conditional_steps.rb
compatibility/features/hooks-conditional/hooks-conditional_steps.rb
# frozen_string_literal: true Before('@passing-hook') do # no-op end Before('@fail-before') do raise 'Exception in conditional hook' end When('a step passes') do # no-op end After('@passing-hook') do # no-op end After('@fail-after') do raise 'Exception in conditional hook' end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/skipped/skipped_steps.rb
compatibility/features/skipped/skipped_steps.rb
# frozen_string_literal: true Before('@skip') do skip_this_scenario('') end Given('a step that does not skip') do # no-op end Given('a step that is skipped') do # no-op end Given('I skip a step') do skip_this_scenario('') end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/hooks-named/hooks-named_steps.rb
compatibility/features/hooks-named/hooks-named_steps.rb
# frozen_string_literal: true Before(name: 'A named before hook') do # no-op end When('a step passes') do # no-op end After(name: 'A named after hook') do # no-op end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/examples-tables/examples-tables_steps.rb
compatibility/features/examples-tables/examples-tables_steps.rb
# frozen_string_literal: true Given('there are {int} cucumbers') do |initial_count| @count = initial_count end Given('there are {int} friends') do |initial_friends| @friends = initial_friends end When('I eat {int} cucumbers') do |eat_count| @count -= eat_count end Then('I should have {int} cucumbers') do |expected_count| expect(@count).to eq(expected_count) end Then('each person can eat {int} cucumbers') do |expected_share| share = (@count / (1 + @friends)).floor expect(share).to eq(expected_share) end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/examples-tables-attachment/examples-tables-attachment_steps.rb
compatibility/features/examples-tables-attachment/examples-tables-attachment_steps.rb
# frozen_string_literal: true def cck_asset_path "#{Gem.loaded_specs['cucumber-compatibility-kit'].full_gem_path}/features/examples-tables-attachment" end When('a JPEG image is attached') do attach(File.open("#{cck_asset_path}/cucumber.jpeg"), 'image/jpeg') end When('a PNG image is attached') do attach(File.open("#{cck_asset_path}/cucumber.png"), 'image/png') end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/parameter-types/parameter-types_steps.rb
compatibility/features/parameter-types/parameter-types_steps.rb
# frozen_string_literal: true class Flight attr_reader :from, :to def initialize(from, to) @from = from @to = to end end ParameterType( name: 'flight', regexp: /([A-Z]{3})-([A-Z]{3})/, transformer: ->(from, to) { Flight.new(from, to) } ) Given('{flight} has been delayed') do |flight| expect(flight.from).to eq('LHR') expect(flight.to).to eq('CDG') end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/hooks-attachment/hooks-attachment_steps.rb
compatibility/features/hooks-attachment/hooks-attachment_steps.rb
# frozen_string_literal: true def cck_asset_path "#{Gem.loaded_specs['cucumber-compatibility-kit'].full_gem_path}/features/hooks-attachment" end Before do attach(File.open("#{cck_asset_path}/cucumber.svg"), 'image/svg+xml') end After do attach(File.open("#{cck_asset_path}/cucumber.svg"), 'image/svg+xml') end When('a step passes') do # no-op end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/data-tables/data-tables_steps.rb
compatibility/features/data-tables/data-tables_steps.rb
# frozen_string_literal: true When('the following table is transposed:') do |table| @transposed = table.transpose end Then('it should be:') do |expected| @transposed.diff!(expected) end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/unknown-parameter-type/unknown-parameter-type_steps.rb
compatibility/features/unknown-parameter-type/unknown-parameter-type_steps.rb
# frozen_string_literal: true Given('{airport} is closed because of a strike') do |_airport| raise 'Should not be called because airport parameter type has not been defined' end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/hooks/hooks_steps.rb
compatibility/features/hooks/hooks_steps.rb
# frozen_string_literal: true Before do # no-op end When('a step passes') do # no-op end When('a step fails') do raise 'Exception in step' end After do # no-op end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/rules/rules_steps.rb
compatibility/features/rules/rules_steps.rb
# frozen_string_literal: true Given('the customer has {int} cents') do |money| @money = money end Given('there are chocolate bars in stock') do @stock = ['Mars'] end Given('there are no chocolate bars in stock') do @stock = [] end When('the customer tries to buy a {int} cent chocolate bar') do |price| @chocolate = @stock.pop if @money >= price end Then('the sale should not happen') do expect(@chocolate).to be_nil end Then('the sale should happen') do expect(@chocolate).not_to be_nil end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/retry/retry_steps.rb
compatibility/features/retry/retry_steps.rb
# frozen_string_literal: true Given('a step that always passes') do # no-op end second_time_pass = 0 Given('a step that passes the second time') do second_time_pass += 1 raise 'Exception in step' if second_time_pass < 2 end third_time_pass = 0 Given('a step that passes the third time') do third_time_pass += 1 raise 'Exception in step' if third_time_pass < 3 end Given('a step that always fails') do raise 'Exception in step' end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/minimal/minimal_steps.rb
compatibility/features/minimal/minimal_steps.rb
# frozen_string_literal: true Given('I have {int} cukes in my belly') do |_cuke_count| # no-op end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/stack-traces/stack-traces_steps.rb
compatibility/features/stack-traces/stack-traces_steps.rb
# frozen_string_literal: true When('a step throws an exception') do raise 'BOOM' end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/cdata/cdata_steps.rb
compatibility/features/cdata/cdata_steps.rb
# frozen_string_literal: true Given('I have {int} <![CDATA[cukes]]> in my belly') do |_cuke_count| # no-op end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/pending/pending_steps.rb
compatibility/features/pending/pending_steps.rb
# frozen_string_literal: true Given('an implemented non-pending step') do # no-op end Given('an implemented step that is skipped') do # no-op end Given('an unimplemented pending step') do pending('') end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/features/attachments/attachments_steps.rb
compatibility/features/attachments/attachments_steps.rb
# frozen_string_literal: true def cck_asset_path "#{Gem.loaded_specs['cucumber-compatibility-kit'].full_gem_path}/features/attachments" end When('the string {string} is attached as {string}') do |text, media_type| attach(text, media_type) end When('the string {string} is logged') do |text| log(text) end When('text with ANSI escapes is logged') do log("This displays a \x1b[31mr\x1b[0m\x1b[91ma\x1b[0m\x1b[33mi\x1b[0m\x1b[32mn\x1b[0m\x1b[34mb\x1b[0m\x1b[95mo\x1b[0m\x1b[35mw\x1b[0m") end When('the following string is attached as {string}:') do |media_type, doc_string| attach(doc_string, media_type) end When('an array with {int} bytes is attached as {string}') do |size, media_type| data = (0..size - 1).map { |i| [i].pack('C') }.join attach(data, media_type) end When('a PDF document is attached and renamed') do attach(File.open("#{cck_asset_path}/document.pdf"), 'application/pdf', 'renamed.pdf') end When('a link to {string} is attached') do |link| attach(link, 'text/uri-list') end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/spec/cck/keys_checker_spec.rb
compatibility/spec/cck/keys_checker_spec.rb
# frozen_string_literal: true require 'rspec' require 'cucumber/messages' require_relative '../../support/cck/keys_checker' describe CCK::KeysChecker do describe '#compare' do let(:expected_kvps) { Cucumber::Messages::Attachment.new(url: 'https://foo.com', file_name: 'file.extension', test_step_id: 123_456) } let(:missing_kvps) { Cucumber::Messages::Attachment.new(url: 'https://foo.com') } let(:extra_kvps) { Cucumber::Messages::Attachment.new(url: 'https://foo.com', file_name: 'file.extension', test_step_id: 123_456, source: '1') } let(:missing_and_extra_kvps) { Cucumber::Messages::Attachment.new(file_name: 'file.extension', test_step_id: 123_456, test_run_started_id: 123_456) } let(:wrong_values) { Cucumber::Messages::Attachment.new(url: 'https://otherfoo.com', file_name: 'file.other', test_step_id: 456_789) } it 'finds missing keys' do expect(described_class.compare(missing_kvps, expected_kvps)).to eq( 'Missing keys in message Cucumber::Messages::Attachment: [:file_name, :test_step_id]' ) end it 'finds extra keys' do expect(described_class.compare(extra_kvps, expected_kvps)).to eq( 'Detected extra keys in message Cucumber::Messages::Attachment: [:source]' ) end it 'finds the extra keys first' do expect(described_class.compare(missing_and_extra_kvps, expected_kvps)).to eq( 'Detected extra keys in message Cucumber::Messages::Attachment: [:test_run_started_id]' ) end it 'does not care about the values' do expect(described_class.compare(expected_kvps, wrong_values)).to be_nil end context 'when default values are omitted' do let(:default_set) { Cucumber::Messages::Duration.new(seconds: 0, nanos: 12) } let(:default_not_set) { Cucumber::Messages::Duration.new(nanos: 12) } it 'does not raise an exception' do expect(described_class.compare(default_set, default_not_set)).to be_nil end end context 'when executed as part of a CI' do before { allow(ENV).to receive(:[]).with('CI').and_return(true) } it 'ignores actual CI related messages' do detected = Cucumber::Messages::Meta.new(ci: Cucumber::Messages::Ci.new(name: 'Some CI')) expected = Cucumber::Messages::Meta.new expect(described_class.compare(detected, expected)).to be_nil end end context 'when an unexpected error occurs' do it 'does not raise error' do expect { described_class.compare(nil, nil) }.not_to raise_error end it 'returns the error to be debugged' do expect(described_class.compare(nil, nil)).to include(/wrong number of arguments \(given 1, expected 0\)/) end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/spec/cck/messages_comparator_spec.rb
compatibility/spec/cck/messages_comparator_spec.rb
# frozen_string_literal: true require 'rspec' require 'cucumber/messages' require_relative '../../support/cck/messages_comparator' describe CCK::MessagesComparator do describe '#errors' do context 'when executed as part of a CI' do before { allow(ENV).to receive(:[]).with('CI').and_return(true) } let(:ci_message) { Cucumber::Messages::Ci.new(name: 'Some CI') } let(:blank_meta_message) { Cucumber::Messages::Meta.new } let(:filled_meta_message) { Cucumber::Messages::Meta.new(ci: ci_message) } let(:ci_message_envelope) { Cucumber::Messages::Envelope.new(meta: filled_meta_message) } let(:meta_message_envelope) { Cucumber::Messages::Envelope.new(meta: blank_meta_message) } it 'ignores any detected CI messages' do comparator = described_class.new([ci_message_envelope], [meta_message_envelope]) expect(comparator.errors).to be_empty end it 'ignores any expected CI messages' do comparator = described_class.new([meta_message_envelope], [ci_message_envelope]) expect(comparator.errors).to be_empty end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
cucumber/cucumber-ruby
https://github.com/cucumber/cucumber-ruby/blob/50c37055b0e5e74de50a026756ca915f0f7b7820/compatibility/spec/cck/examples_spec.rb
compatibility/spec/cck/examples_spec.rb
# frozen_string_literal: true require_relative '../../support/cck/examples' describe CCK::Examples do let(:features_path) { File.expand_path("#{File.dirname(__FILE__)}/../../features") } describe '#supporting_code_for' do context 'with an example that exists' do it 'returns the path of the folder containing the supporting code for the example' do expect(described_class.supporting_code_for('hooks')).to eq("#{features_path}/hooks") end end context 'with an example that does not exist' do it 'raises ArgumentError' do expect { described_class.supporting_code_for('nonexistent-example') }.to raise_error(ArgumentError) end end end end
ruby
MIT
50c37055b0e5e74de50a026756ca915f0f7b7820
2026-01-04T15:43:43.142161Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/spec_helper.rb
spec/spec_helper.rb
require 'active_record' require 'fast_jsonapi' require 'rspec-benchmark' require 'byebug' require 'active_model_serializers' require 'oj' require 'jsonapi/serializable' require 'jsonapi-serializers' Dir[File.dirname(__FILE__) + '/shared/contexts/*.rb'].each {|file| require file } Dir[File.dirname(__FILE__) + '/shared/examples/*.rb'].each {|file| require file } RSpec.configure do |config| config.include RSpec::Benchmark::Matchers if ENV['TRAVIS'] == 'true' || ENV['TRAVIS'] == true config.filter_run_excluding performance: true end end Oj.optimize_rails ActiveModel::Serializer.config.adapter = :json_api ActiveModel::Serializer.config.key_transform = :underscore ActiveModelSerializers.logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new('/dev/null'))
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/object_serializer_spec.rb
spec/lib/object_serializer_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do include_context 'movie class' include_context 'group class' context 'when testing instance methods of object serializer' do it 'returns correct hash when serializable_hash is called' do options = {} options[:meta] = { total: 2 } options[:links] = { self: 'self' } options[:include] = [:actors] serializable_hash = MovieSerializer.new([movie, movie], options).serializable_hash expect(serializable_hash[:data].length).to eq 2 expect(serializable_hash[:data][0][:relationships].length).to eq 4 expect(serializable_hash[:data][0][:attributes].length).to eq 2 expect(serializable_hash[:meta]).to be_instance_of(Hash) expect(serializable_hash[:links]).to be_instance_of(Hash) expect(serializable_hash[:included]).to be_instance_of(Array) expect(serializable_hash[:included][0]).to be_instance_of(Hash) expect(serializable_hash[:included].length).to eq 3 serializable_hash = MovieSerializer.new(movie).serializable_hash expect(serializable_hash[:data]).to be_instance_of(Hash) expect(serializable_hash[:meta]).to be nil expect(serializable_hash[:links]).to be nil expect(serializable_hash[:included]).to be nil end it 'returns correct nested includes when serializable_hash is called' do # 3 actors, 3 agencies include_object_total = 6 options = {} options[:include] = [:actors, :'actors.agency'] serializable_hash = MovieSerializer.new([movie], options).serializable_hash expect(serializable_hash[:included]).to be_instance_of(Array) expect(serializable_hash[:included].length).to eq include_object_total (0..include_object_total-1).each do |include| expect(serializable_hash[:included][include]).to be_instance_of(Hash) end options[:include] = [:'actors.agency'] serializable_hash = MovieSerializer.new([movie], options).serializable_hash expect(serializable_hash[:included]).to be_instance_of(Array) expect(serializable_hash[:included].length).to eq include_object_total (0..include_object_total-1).each do |include| expect(serializable_hash[:included][include]).to be_instance_of(Hash) end end it 'returns correct number of records when serialized_json is called for an array' do options = {} options[:meta] = { total: 2 } json = MovieSerializer.new([movie, movie], options).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data'].length).to eq 2 expect(serializable_hash['meta']).to be_instance_of(Hash) end it 'returns correct id when serialized_json is called for a single object' do json = MovieSerializer.new(movie).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']['id']).to eq movie.id.to_s end it 'returns correct json when serializing nil' do json = MovieSerializer.new(nil).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']).to eq nil end it 'returns correct json when record id is nil' do movie.id = nil json = MovieSerializer.new(movie).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']['id']).to be nil end it 'returns correct json when has_many returns []' do movie.actor_ids = [] json = MovieSerializer.new(movie).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']['relationships']['actors']['data'].length).to eq 0 end it 'returns correct json when belongs_to returns nil' do movie.owner_id = nil json = MovieSerializer.new(movie).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']['relationships']['owner']['data']).to be nil end it 'returns correct json when belongs_to returns nil and there is a block for the relationship' do movie.owner_id = nil json = MovieSerializer.new(movie, {include: [:owner]}).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']['relationships']['owner']['data']).to be nil end it 'returns correct json when has_one returns nil' do supplier.account_id = nil json = SupplierSerializer.new(supplier).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']['relationships']['account']['data']).to be nil end it 'returns correct json when serializing []' do json = MovieSerializer.new([]).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']).to eq [] end describe '#as_json' do it 'returns a json hash' do json_hash = MovieSerializer.new(movie).as_json expect(json_hash['data']['id']).to eq movie.id.to_s end it 'returns multiple records' do json_hash = MovieSerializer.new([movie, movie]).as_json expect(json_hash['data'].length).to eq 2 end it 'removes non-relevant attributes' do movie.director = 'steven spielberg' json_hash = MovieSerializer.new(movie).as_json expect(json_hash['data']['director']).to eq(nil) end end it 'returns errors when serializing with non-existent includes key' do options = {} options[:meta] = { total: 2 } options[:include] = [:blah_blah] expect { MovieSerializer.new([movie, movie], options).serializable_hash }.to raise_error(ArgumentError) end it 'does not throw an error with non-empty string array includes key' do options = {} options[:include] = ['actors'] expect { MovieSerializer.new(movie, options) }.not_to raise_error end it 'returns keys when serializing with empty string/nil array includes key' do options = {} options[:meta] = { total: 2 } options[:include] = [''] expect(MovieSerializer.new([movie, movie], options).serializable_hash.keys).to eq [:data, :meta] options[:include] = [nil] expect(MovieSerializer.new([movie, movie], options).serializable_hash.keys).to eq [:data, :meta] end end context 'id attribute is the same for actors and not a primary key' do before do ActorSerializer.set_id :email movie.actor_ids = [0, 0, 0] class << movie def actors super.each_with_index { |actor, i| actor.email = "actor#{i}@email.com" } end end end after { ActorSerializer.set_id nil } let(:options) { { include: ['actors'] } } subject { MovieSerializer.new(movie, options).serializable_hash } it 'returns all actors in includes' do expect( subject[:included].select { |i| i[:type] == :actor }.map { |i| i[:id] } ).to eq( movie.actors.map(&:email) ) end end context 'nested includes' do it 'has_many to belongs_to: returns correct nested includes when serializable_hash is called' do # 3 actors, 3 agencies include_object_total = 6 options = {} options[:include] = [:actors, :'actors.agency'] serializable_hash = MovieSerializer.new([movie], options).serializable_hash expect(serializable_hash[:included]).to be_instance_of(Array) expect(serializable_hash[:included].length).to eq include_object_total (0..include_object_total-1).each do |include| expect(serializable_hash[:included][include]).to be_instance_of(Hash) end options[:include] = [:'actors.agency'] serializable_hash = MovieSerializer.new([movie], options).serializable_hash expect(serializable_hash[:included]).to be_instance_of(Array) expect(serializable_hash[:included].length).to eq include_object_total (0..include_object_total-1).each do |include| expect(serializable_hash[:included][include]).to be_instance_of(Hash) end end it '`has_many` to `belongs_to` to `belongs_to` - returns correct nested includes when serializable_hash is called' do # 3 actors, 3 agencies, 1 state include_object_total = 7 options = {} options[:include] = [:actors, :'actors.agency', :'actors.agency.state'] serializable_hash = MovieSerializer.new([movie], options).serializable_hash expect(serializable_hash[:included]).to be_instance_of(Array) expect(serializable_hash[:included].length).to eq include_object_total actors_serialized = serializable_hash[:included].find_all { |included| included[:type] == :actor }.map { |included| included[:id].to_i } agencies_serialized = serializable_hash[:included].find_all { |included| included[:type] == :agency }.map { |included| included[:id].to_i } states_serialized = serializable_hash[:included].find_all { |included| included[:type] == :state }.map { |included| included[:id].to_i } movie.actors.each do |actor| expect(actors_serialized).to include(actor.id) end agencies = movie.actors.map(&:agency).uniq agencies.each do |agency| expect(agencies_serialized).to include(agency.id) end states = agencies.map(&:state).uniq states.each do |state| expect(states_serialized).to include(state.id) end end it 'has_many => has_one returns correct nested includes when serializable_hash is called' do options = {} options[:include] = [:movies, :'movies.advertising_campaign'] serializable_hash = MovieTypeSerializer.new([movie_type], options).serializable_hash movies_serialized = serializable_hash[:included].find_all { |included| included[:type] == :movie }.map { |included| included[:id].to_i } advertising_campaigns_serialized = serializable_hash[:included].find_all { |included| included[:type] == :advertising_campaign }.map { |included| included[:id].to_i } movies = movie_type.movies movies.each do |movie| expect(movies_serialized).to include(movie.id) end advertising_campaigns = movies.map(&:advertising_campaign) advertising_campaigns.each do |advertising_campaign| expect(advertising_campaigns_serialized).to include(advertising_campaign.id) end end it 'belongs_to: returns correct nested includes when nested attributes are nil when serializable_hash is called' do class Movie def advertising_campaign nil end end options = {} options[:include] = [:movies, :'movies.advertising_campaign'] serializable_hash = MovieTypeSerializer.new([movie_type], options).serializable_hash movies_serialized = serializable_hash[:included].find_all { |included| included[:type] == :movie }.map { |included| included[:id].to_i } movies = movie_type.movies movies.each do |movie| expect(movies_serialized).to include(movie.id) end end it 'polymorphic has_many: returns correct nested includes when serializable_hash is called' do options = {} options[:include] = [:groupees] serializable_hash = GroupSerializer.new([group], options).serializable_hash persons_serialized = serializable_hash[:included].find_all { |included| included[:type] == :person }.map { |included| included[:id].to_i } groups_serialized = serializable_hash[:included].find_all { |included| included[:type] == :group }.map { |included| included[:id].to_i } persons = group.groupees.find_all { |groupee| groupee.is_a?(Person) } persons.each do |person| expect(persons_serialized).to include(person.id) end groups = group.groupees.find_all { |groupee| groupee.is_a?(Group) } groups.each do |group| expect(groups_serialized).to include(group.id) end end end context 'when testing included do block of object serializer' do it 'should set default_type based on serializer class name' do class BlahSerializer include FastJsonapi::ObjectSerializer end expect(BlahSerializer.record_type).to be :blah end it 'should set default_type for a multi word class name' do class BlahBlahSerializer include FastJsonapi::ObjectSerializer end expect(BlahBlahSerializer.record_type).to be :blah_blah end it 'shouldnt set default_type for a serializer that doesnt follow convention' do class BlahBlahSerializerBuilder include FastJsonapi::ObjectSerializer end expect(BlahBlahSerializerBuilder.record_type).to be_nil end it 'should set default_type for a namespaced serializer' do module V1 class BlahSerializer include FastJsonapi::ObjectSerializer end end expect(V1::BlahSerializer.record_type).to be :blah end end context 'when serializing included, serialize any links' do before do ActorSerializer.link(:self) do |actor_object| actor_object.url end end subject(:serializable_hash) do options = {} options[:include] = [:actors] MovieSerializer.new(movie, options).serializable_hash end let(:actor) { movie.actors.first } let(:url) { "http://movies.com/actors/#{actor.id}" } it 'returns correct hash when serializable_hash is called' do expect(serializable_hash[:included][0][:links][:self]).to eq url end end context 'when serializing included, params should be available in any serializer' do subject(:serializable_hash) do options = {} options[:include] = [:"actors.awards"] options[:params] = { include_award_year: true } MovieSerializer.new(movie, options).serializable_hash end let(:actor) { movie.actors.first } let(:award) { actor.awards.first } let(:year) { award.year } it 'passes params to deeply nested includes' do expect(year).to_not be_blank expect(serializable_hash[:included][0][:attributes][:year]).to eq year end end context 'when is_collection option present' do subject { MovieSerializer.new(resource, is_collection_options).serializable_hash } context 'autodetect' do let(:is_collection_options) { {} } context 'collection if no option present' do let(:resource) { [movie] } it { expect(subject[:data]).to be_a(Array) } end context 'single if no option present' do let(:resource) { movie } it { expect(subject[:data]).to be_a(Hash) } end end context 'force is_collection to true' do let(:is_collection_options) { { is_collection: true } } context 'collection will pass' do let(:resource) { [movie] } it { expect(subject[:data]).to be_a(Array) } end context 'single will raise error' do let(:resource) { movie } it { expect { subject }.to raise_error(NoMethodError, /method(.*)each/) } end end context 'force is_collection to false' do let(:is_collection_options) { { is_collection: false } } context 'collection will fail without id' do let(:resource) { [movie] } it { expect { subject }.to raise_error(FastJsonapi::MandatoryField, /id is a mandatory field/) } end context 'single will pass' do let(:resource) { movie } it { expect(subject[:data]).to be_a(Hash) } end end end context 'when optional attributes are determined by record data' do it 'returns optional attribute when attribute is included' do movie.release_year = 2001 json = MovieOptionalRecordDataSerializer.new(movie).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']['attributes']['release_year']).to eq movie.release_year end it "doesn't return optional attribute when attribute is not included" do movie.release_year = 1970 json = MovieOptionalRecordDataSerializer.new(movie).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']['attributes'].has_key?('release_year')).to be_falsey end end context 'when optional attributes are determined by params data' do it 'returns optional attribute when attribute is included' do movie.director = 'steven spielberg' json = MovieOptionalParamsDataSerializer.new(movie, { params: { admin: true }}).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']['attributes']['director']).to eq 'steven spielberg' end it "doesn't return optional attribute when attribute is not included" do movie.director = 'steven spielberg' json = MovieOptionalParamsDataSerializer.new(movie, { params: { admin: false }}).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']['attributes'].has_key?('director')).to be_falsey end end context 'when optional relationships are determined by record data' do it 'returns optional relationship when relationship is included' do json = MovieOptionalRelationshipSerializer.new(movie).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']['relationships'].has_key?('actors')).to be_truthy end context "when relationship is not included" do let(:json) { MovieOptionalRelationshipSerializer.new(movie, options).serialized_json } let(:options) { {} } let(:serializable_hash) { JSON.parse(json) } it "doesn't return optional relationship" do movie.actor_ids = [] expect(serializable_hash['data']['relationships'].has_key?('actors')).to be_falsey end it "doesn't include optional relationship" do movie.actor_ids = [] options[:include] = [:actors] expect(serializable_hash['included']).to be_blank end end end context 'when optional relationships are determined by params data' do it 'returns optional relationship when relationship is included' do json = MovieOptionalRelationshipWithParamsSerializer.new(movie, { params: { admin: true }}).serialized_json serializable_hash = JSON.parse(json) expect(serializable_hash['data']['relationships'].has_key?('owner')).to be_truthy end context "when relationship is not included" do let(:json) { MovieOptionalRelationshipWithParamsSerializer.new(movie, options).serialized_json } let(:options) { { params: { admin: false }} } let(:serializable_hash) { JSON.parse(json) } it "doesn't return optional relationship" do expect(serializable_hash['data']['relationships'].has_key?('owner')).to be_falsey end it "doesn't include optional relationship" do options[:include] = [:owner] expect(serializable_hash['included']).to be_blank end end end context 'when attribute contents are determined by params data' do it 'does not throw an error with no params are passed' do expect { MovieOptionalAttributeContentsWithParamsSerializer.new(movie).serialized_json }.not_to raise_error end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/object_serializer_attribute_param_spec.rb
spec/lib/object_serializer_attribute_param_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do include_context 'movie class' context "params option" do let(:hash) { serializer.serializable_hash } before(:context) do class Movie def viewed?(user) user.viewed.include?(id) end end class MovieSerializer attribute :viewed do |movie, params| params[:user] ? movie.viewed?(params[:user]) : false end attribute :no_param_attribute do |movie| "no-param-attribute" end end User = Struct.new(:viewed) end after(:context) do Object.send(:remove_const, User) if Object.constants.include?(User) end context "enforces a hash only params" do let(:params) { User.new([]) } it "fails when creating a serializer with an object as params" do expect(-> { MovieSerializer.new(movie, {params: User.new([])}) }).to raise_error(ArgumentError) end it "succeeds creating a serializer with a hash" do expect(-> { MovieSerializer.new(movie, {params: {current_user: User.new([])}}) }).not_to raise_error end end context "passing params to the serializer" do let(:params) { {user: User.new([movie.id])} } let(:options_with_params) { {params: params} } context "with a single record" do let(:serializer) { MovieSerializer.new(movie, options_with_params) } it "handles attributes that use params" do expect(hash[:data][:attributes][:viewed]).to eq(true) end it "handles attributes that don't use params" do expect(hash[:data][:attributes][:no_param_attribute]).to eq("no-param-attribute") end end context "with a list of records" do let(:movies) { build_movies(3) } let(:user) { User.new(movies.map { |m| [true, false].sample ? m.id : nil }.compact) } let(:params) { {user: user} } let(:serializer) { MovieSerializer.new(movies, options_with_params) } it "has 3 items" do hash[:data].length == 3 end it "handles passing params to a list of resources" do param_attribute_values = hash[:data].map { |data| [data[:id], data[:attributes][:viewed]] } expected_values = movies.map { |m| [m.id.to_s, user.viewed.include?(m.id)] } expect(param_attribute_values).to eq(expected_values) end it "handles attributes without params" do no_param_attribute_values = hash[:data].map { |data| data[:attributes][:no_param_attribute] } expected_values = (1..3).map { "no-param-attribute" } expect(no_param_attribute_values).to eq(expected_values) end end end context "without passing params to the serializer" do context "with a single movie" do let(:serializer) { MovieSerializer.new(movie) } it "handles param attributes" do expect(hash[:data][:attributes][:viewed]).to eq(false) end it "handles attributes that don't use params" do expect(hash[:data][:attributes][:no_param_attribute]).to eq("no-param-attribute") end end context "with multiple movies" do let(:serializer) { MovieSerializer.new(build_movies(3)) } it "handles attributes with params" do param_attribute_values = hash[:data].map { |data| data[:attributes][:viewed] } expect(param_attribute_values).to eq([false, false, false]) end it "handles attributes that don't use params" do no_param_attribute_values = hash[:data].map { |data| data[:attributes][:no_param_attribute] } expected_attribute_values = (1..3).map { "no-param-attribute" } expect(no_param_attribute_values).to eq(expected_attribute_values) end end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/object_serializer_fields_spec.rb
spec/lib/object_serializer_fields_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do include_context 'movie class' let(:fields) do { movie: %i[name actors advertising_campaign], actor: %i[name agency] } end it 'only returns specified fields' do hash = MovieSerializer.new(movie, fields: fields).serializable_hash expect(hash[:data][:attributes].keys.sort).to eq %i[name] end it 'only returns specified relationships' do hash = MovieSerializer.new(movie, fields: fields).serializable_hash expect(hash[:data][:relationships].keys.sort).to eq %i[actors advertising_campaign] end it 'only returns specified fields for included relationships' do hash = MovieSerializer.new(movie, fields: fields, include: %i[actors]).serializable_hash expect(hash[:included].first[:attributes].keys.sort).to eq %i[name] end it 'only returns specified relationships for included relationships' do hash = MovieSerializer.new(movie, fields: fields, include: %i[actors advertising_campaign]).serializable_hash expect(hash[:included].first[:relationships].keys.sort).to eq %i[agency] end it 'returns all fields for included relationships when no explicit fields have been specified' do hash = MovieSerializer.new(movie, fields: fields, include: %i[actors advertising_campaign]).serializable_hash expect(hash[:included][3][:attributes].keys.sort).to eq %i[id name] end it 'returns all fields for included relationships when no explicit fields have been specified' do hash = MovieSerializer.new(movie, fields: fields, include: %i[actors advertising_campaign]).serializable_hash expect(hash[:included][3][:relationships].keys.sort).to eq %i[movie] end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/object_serializer_caching_spec.rb
spec/lib/object_serializer_caching_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do include_context 'movie class' context 'when caching has_many' do before(:each) do rails = OpenStruct.new rails.cache = ActiveSupport::Cache::MemoryStore.new stub_const('Rails', rails) end it 'returns correct hash when serializable_hash is called' do options = {} options[:meta] = { total: 2 } options[:links] = { self: 'self' } options[:include] = [:actors] serializable_hash = CachingMovieSerializer.new([movie, movie], options).serializable_hash expect(serializable_hash[:data].length).to eq 2 expect(serializable_hash[:data][0][:relationships].length).to eq 3 expect(serializable_hash[:data][0][:attributes].length).to eq 2 expect(serializable_hash[:meta]).to be_instance_of(Hash) expect(serializable_hash[:links]).to be_instance_of(Hash) expect(serializable_hash[:included]).to be_instance_of(Array) expect(serializable_hash[:included][0]).to be_instance_of(Hash) expect(serializable_hash[:included].length).to eq 3 serializable_hash = CachingMovieSerializer.new(movie).serializable_hash expect(serializable_hash[:data]).to be_instance_of(Hash) expect(serializable_hash[:meta]).to be nil expect(serializable_hash[:links]).to be nil expect(serializable_hash[:included]).to be nil end it 'uses cached values for the record' do previous_name = movie.name previous_actors = movie.actors CachingMovieSerializer.new(movie).serializable_hash movie.name = 'should not match' allow(movie).to receive(:actor_ids).and_return([99]) expect(previous_name).not_to eq(movie.name) expect(previous_actors).not_to eq(movie.actors) serializable_hash = CachingMovieSerializer.new(movie).serializable_hash expect(serializable_hash[:data][:attributes][:name]).to eq(previous_name) expect(serializable_hash[:data][:relationships][:actors][:data].length).to eq movie.actors.length end it 'uses cached values for has many as specified' do previous_name = movie.name previous_actors = movie.actors CachingMovieWithHasManySerializer.new(movie).serializable_hash movie.name = 'should not match' allow(movie).to receive(:actor_ids).and_return([99]) expect(previous_name).not_to eq(movie.name) expect(previous_actors).not_to eq(movie.actors) serializable_hash = CachingMovieWithHasManySerializer.new(movie).serializable_hash expect(serializable_hash[:data][:attributes][:name]).to eq(previous_name) expect(serializable_hash[:data][:relationships][:actors][:data].length).to eq previous_actors.length end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/object_serializer_performance_spec.rb
spec/lib/object_serializer_performance_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer, performance: true do include_context 'movie class' include_context 'ams movie class' include_context 'jsonapi movie class' include_context 'jsonapi-serializers movie class' include_context 'group class' include_context 'ams group class' include_context 'jsonapi group class' include_context 'jsonapi-serializers group class' before(:all) { GC.disable } after(:all) { GC.enable } SERIALIZERS = { fast_jsonapi: { name: 'Fast Serializer', hash_method: :serializable_hash, json_method: :serialized_json }, ams: { name: 'AMS serializer', speed_factor: 25, hash_method: :as_json }, jsonapi: { name: 'jsonapi-rb serializer' }, jsonapis: { name: 'jsonapi-serializers' } } context 'when testing performance of serialization' do it 'should create a hash of 1000 records in less than 50 ms' do movies = 1000.times.map { |_i| movie } expect { MovieSerializer.new(movies).serializable_hash }.to perform_under(50).ms end it 'should serialize 1000 records to jsonapi in less than 60 ms' do movies = 1000.times.map { |_i| movie } expect { MovieSerializer.new(movies).serialized_json }.to perform_under(60).ms end it 'should create a hash of 1000 records with includes and meta in less than 75 ms' do count = 1000 movies = count.times.map { |_i| movie } options = {} options[:meta] = { total: count } options[:include] = [:actors] expect { MovieSerializer.new(movies, options).serializable_hash }.to perform_under(75).ms end it 'should serialize 1000 records to jsonapi with includes and meta in less than 75 ms' do count = 1000 movies = count.times.map { |_i| movie } options = {} options[:meta] = { total: count } options[:include] = [:actors] expect { MovieSerializer.new(movies, options).serialized_json }.to perform_under(75).ms end end def print_stats(message, count, data) puts puts message name_length = SERIALIZERS.collect { |s| s[1].fetch(:name, s[0]).length }.max puts format("%-#{name_length+1}s %-10s %-10s %s", 'Serializer', 'Records', 'Time', 'Speed Up') report_format = "%-#{name_length+1}s %-10s %-10s" fast_jsonapi_time = data[:fast_jsonapi][:time] puts format(report_format, 'Fast serializer', count, fast_jsonapi_time.round(2).to_s + ' ms') data.reject { |k,v| k == :fast_jsonapi }.each_pair do |k,v| t = v[:time] factor = t / fast_jsonapi_time speed_factor = SERIALIZERS[k].fetch(:speed_factor, 1) result = factor >= speed_factor ? '✔' : '✘' puts format("%-#{name_length+1}s %-10s %-10s %sx %s", SERIALIZERS[k][:name], count, t.round(2).to_s + ' ms', factor.round(2), result) end end def run_hash_benchmark(message, movie_count, serializers) data = Hash[serializers.keys.collect { |k| [ k, { hash: nil, time: nil, speed_factor: nil }] }] serializers.each_pair do |k,v| hash_method = SERIALIZERS[k].key?(:hash_method) ? SERIALIZERS[k][:hash_method] : :to_hash data[k][:time] = Benchmark.measure { data[k][:hash] = v.send(hash_method) }.real * 1000 end print_stats(message, movie_count, data) data end def run_json_benchmark(message, movie_count, serializers) data = Hash[serializers.keys.collect { |k| [ k, { json: nil, time: nil, speed_factor: nil }] }] serializers.each_pair do |k,v| ams_json = nil json_method = SERIALIZERS[k].key?(:json_method) ? SERIALIZERS[k][:json_method] : :to_json data[k][:time] = Benchmark.measure { data[k][:json] = v.send(json_method) }.real * 1000 end print_stats(message, movie_count, data) data end context 'when comparing with AMS 0.10.x' do [1, 25, 250, 1000].each do |movie_count| it "should serialize #{movie_count} records atleast #{SERIALIZERS[:ams][:speed_factor]} times faster than AMS" do ams_movies = build_ams_movies(movie_count) movies = build_movies(movie_count) jsonapi_movies = build_jsonapi_movies(movie_count) jsonapis_movies = build_js_movies(movie_count) serializers = { fast_jsonapi: MovieSerializer.new(movies), ams: ActiveModelSerializers::SerializableResource.new(ams_movies), jsonapi: JSONAPISerializer.new(jsonapi_movies), jsonapis: JSONAPISSerializer.new(jsonapis_movies) } message = "Serialize to JSON string #{movie_count} records" json_benchmarks = run_json_benchmark(message, movie_count, serializers) message = "Serialize to Ruby Hash #{movie_count} records" hash_benchmarks = run_hash_benchmark(message, movie_count, serializers) # json expect(json_benchmarks[:fast_jsonapi][:json].length).to eq json_benchmarks[:ams][:json].length json_speed_up = json_benchmarks[:ams][:time] / json_benchmarks[:fast_jsonapi][:time] # hash hash_speed_up = hash_benchmarks[:ams][:time] / hash_benchmarks[:fast_jsonapi][:time] expect(hash_speed_up).to be >= SERIALIZERS[:ams][:speed_factor] end end end context 'when comparing with AMS 0.10.x and with includes and meta' do [1, 25, 250, 1000].each do |movie_count| it "should serialize #{movie_count} records atleast #{SERIALIZERS[:ams][:speed_factor]} times faster than AMS" do ams_movies = build_ams_movies(movie_count) movies = build_movies(movie_count) jsonapi_movies = build_jsonapi_movies(movie_count) jsonapis_movies = build_js_movies(movie_count) options = {} options[:meta] = { total: movie_count } options[:include] = [:actors, :movie_type] serializers = { fast_jsonapi: MovieSerializer.new(movies, options), ams: ActiveModelSerializers::SerializableResource.new(ams_movies, include: options[:include], meta: options[:meta]), jsonapi: JSONAPISerializer.new(jsonapi_movies, include: options[:include], meta: options[:meta]), jsonapis: JSONAPISSerializer.new(jsonapis_movies, include: options[:include].map { |i| i.to_s.dasherize }, meta: options[:meta]) } message = "Serialize to JSON string #{movie_count} with includes and meta" json_benchmarks = run_json_benchmark(message, movie_count, serializers) message = "Serialize to Ruby Hash #{movie_count} with includes and meta" hash_benchmarks = run_hash_benchmark(message, movie_count, serializers) # json expect(json_benchmarks[:fast_jsonapi][:json].length).to eq json_benchmarks[:ams][:json].length json_speed_up = json_benchmarks[:ams][:time] / json_benchmarks[:fast_jsonapi][:time] # hash hash_speed_up = hash_benchmarks[:ams][:time] / hash_benchmarks[:fast_jsonapi][:time] expect(hash_speed_up).to be >= SERIALIZERS[:ams][:speed_factor] end end end context 'when comparing with AMS 0.10.x and with polymorphic has_many' do [1, 25, 250, 1000].each do |group_count| it "should serialize #{group_count} records at least #{SERIALIZERS[:ams][:speed_factor]} times faster than AMS" do ams_groups = build_ams_groups(group_count) groups = build_groups(group_count) jsonapi_groups = build_jsonapi_groups(group_count) jsonapis_groups = build_jsonapis_groups(group_count) options = {} serializers = { fast_jsonapi: GroupSerializer.new(groups, options), ams: ActiveModelSerializers::SerializableResource.new(ams_groups), jsonapi: JSONAPISerializerB.new(jsonapi_groups), jsonapis: JSONAPISSerializerB.new(jsonapis_groups) } message = "Serialize to JSON string #{group_count} with polymorphic has_many" json_benchmarks = run_json_benchmark(message, group_count, serializers) message = "Serialize to Ruby Hash #{group_count} with polymorphic has_many" hash_benchmarks = run_hash_benchmark(message, group_count, serializers) # json expect(json_benchmarks[:fast_jsonapi][:json].length).to eq json_benchmarks[:ams][:json].length json_speed_up = json_benchmarks[:ams][:time] / json_benchmarks[:fast_jsonapi][:time] # hash hash_speed_up = hash_benchmarks[:ams][:time] / hash_benchmarks[:fast_jsonapi][:time] expect(hash_speed_up).to be >= SERIALIZERS[:ams][:speed_factor] end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/serialization_core_spec.rb
spec/lib/serialization_core_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do include_context "movie class" include_context 'group class' context 'when testing class methods of serialization core' do it 'returns correct hash when id_hash is called' do inputs = [{id: 23, record_type: :movie}, {id: 'x', record_type: 'person'}] inputs.each do |hash| result_hash = MovieSerializer.send(:id_hash, hash[:id], hash[:record_type]) expect(result_hash[:id]).to eq hash[:id].to_s expect(result_hash[:type]).to eq hash[:record_type] end result_hash = MovieSerializer.send(:id_hash, nil, 'movie') expect(result_hash).to be nil end it 'returns correct hash when attributes_hash is called' do attributes_hash = MovieSerializer.send(:attributes_hash, movie) attribute_names = attributes_hash.keys.sort expect(attribute_names).to eq MovieSerializer.attributes_to_serialize.keys.sort MovieSerializer.attributes_to_serialize.each do |key, attribute| value = attributes_hash[key] expect(value).to eq movie.send(attribute.method) end end it 'returns the correct empty result when relationships_hash is called' do movie.actor_ids = [] movie.owner_id = nil relationships_hash = MovieSerializer.send(:relationships_hash, movie) expect(relationships_hash[:actors][:data]).to eq([]) expect(relationships_hash[:owner][:data]).to eq(nil) end it 'returns correct keys when relationships_hash is called' do relationships_hash = MovieSerializer.send(:relationships_hash, movie) relationship_names = relationships_hash.keys.sort relationships_hashes = MovieSerializer.relationships_to_serialize.values expected_names = relationships_hashes.map{|relationship| relationship.key}.sort expect(relationship_names).to eq expected_names end it 'returns correct values when relationships_hash is called' do relationships_hash = MovieSerializer.relationships_hash(movie) actors_hash = movie.actor_ids.map { |id| {id: id.to_s, type: :actor} } owner_hash = {id: movie.owner_id.to_s, type: :user} expect(relationships_hash[:actors][:data]).to match_array actors_hash expect(relationships_hash[:owner][:data]).to eq owner_hash end it 'returns correct hash when record_hash is called' do record_hash = MovieSerializer.send(:record_hash, movie, nil) expect(record_hash[:id]).to eq movie.id.to_s expect(record_hash[:type]).to eq MovieSerializer.record_type expect(record_hash).to have_key(:attributes) if MovieSerializer.attributes_to_serialize.present? expect(record_hash).to have_key(:relationships) if MovieSerializer.relationships_to_serialize.present? end it 'serializes known included records only once' do includes_list = [:actors] known_included_objects = {} included_records = [] [movie, movie].each do |record| included_records.concat MovieSerializer.send(:get_included_records, record, includes_list, known_included_objects, {}, nil) end expect(included_records.size).to eq 3 end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/object_serializer_relationship_param_spec.rb
spec/lib/object_serializer_relationship_param_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do include_context 'movie class' context "params option" do let(:hash) { serializer.serializable_hash } before(:context) do class MovieSerializer has_many :agencies do |movie, params| movie.actors.map(&:agency) if params[:authorized] end belongs_to :primary_agency do |movie, params| movie.actors.map(&:agency)[0] if params[:authorized] end belongs_to :secondary_agency do |movie| movie.actors.map(&:agency)[1] end end end context "passing params to the serializer" do let(:params) { {authorized: true} } let(:options_with_params) { {params: params} } context "with a single record" do let(:serializer) { MovieSerializer.new(movie, options_with_params) } it "handles relationships that use params" do ids = hash[:data][:relationships][:agencies][:data].map{|a| a[:id]} ids.map!(&:to_i) expect(ids).to eq [0,1,2] end it "handles relationships that don't use params" do expect(hash[:data][:relationships][:secondary_agency][:data]).to include({id: 1.to_s}) end end context "with a list of records" do let(:movies) { build_movies(3) } let(:params) { {authorized: true} } let(:serializer) { MovieSerializer.new(movies, options_with_params) } it "handles relationship params when passing params to a list of resources" do relationships_hashes = hash[:data].map{|a| a[:relationships][:agencies][:data]}.uniq.flatten expect(relationships_hashes.map{|a| a[:id].to_i}).to contain_exactly 0,1,2 uniq_count = hash[:data].map{|a| a[:relationships][:primary_agency] }.uniq.count expect(uniq_count).to eq 1 end it "handles relationships without params" do uniq_count = hash[:data].map{|a| a[:relationships][:secondary_agency] }.uniq.count expect(uniq_count).to eq 1 end end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/object_serializer_inheritance_spec.rb
spec/lib/object_serializer_inheritance_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do after(:all) do classes_to_remove = %i[ User UserSerializer Country CountrySerializer Employee EmployeeSerializer Photo PhotoSerializer EmployeeAccount ] classes_to_remove.each do |klass_name| Object.send(:remove_const, klass_name) if Object.constants.include?(klass_name) end end class User attr_accessor :id, :first_name, :last_name attr_accessor :address_ids, :country_id def photo p = Photo.new p.id = 1 p.user_id = id p end def photo_id 1 end end class UserSerializer include FastJsonapi::ObjectSerializer set_type :user attributes :first_name, :last_name attribute :full_name do |user, params| "#{user.first_name} #{user.last_name}" end has_many :addresses, cached: true belongs_to :country has_one :photo end class Photo attr_accessor :id, :user_id end class PhotoSerializer include FastJsonapi::ObjectSerializer attributes :id, :name end class Country attr_accessor :id, :name end class CountrySerializer include FastJsonapi::ObjectSerializer attributes :name end class EmployeeAccount attr_accessor :id, :employee_id end class Employee < User attr_accessor :id, :location, :compensation def account a = EmployeeAccount.new a.id = 1 a.employee_id = id a end def account_id 1 end end class EmployeeSerializer < UserSerializer include FastJsonapi::ObjectSerializer attributes :location attributes :compensation has_one :account end it 'sets the correct record type' do expect(EmployeeSerializer.reflected_record_type).to eq :employee expect(EmployeeSerializer.record_type).to eq :employee end context 'when testing inheritance of attributes' do it 'includes parent attributes' do subclass_attributes = EmployeeSerializer.attributes_to_serialize superclass_attributes = UserSerializer.attributes_to_serialize expect(subclass_attributes).to include(superclass_attributes) end it 'returns inherited attribute with a block correctly' do e = Employee.new e.id = 1 e.first_name = 'S' e.last_name = 'K' attributes_hash = EmployeeSerializer.new(e).serializable_hash[:data][:attributes] expect(attributes_hash).to include(full_name: 'S K') end it 'includes child attributes' do expect(EmployeeSerializer.attributes_to_serialize[:location].method).to eq(:location) end it 'doesnt change parent class attributes' do EmployeeSerializer expect(UserSerializer.attributes_to_serialize).not_to have_key(:location) end end context 'when testing inheritance of relationship' do it 'includes parent relationships' do subclass_relationships = EmployeeSerializer.relationships_to_serialize superclass_relationships = UserSerializer.relationships_to_serialize expect(subclass_relationships).to include(superclass_relationships) end it 'returns inherited relationship correctly' do e = Employee.new e.country_id = 1 relationships_hash = EmployeeSerializer.new(e).serializable_hash[:data][:relationships][:country] expect(relationships_hash).to include(data: { id: "1", type: :country }) end it 'includes child relationships' do expect(EmployeeSerializer.relationships_to_serialize.keys).to include(:account) end it 'doesnt change parent class attributes' do EmployeeSerializer expect(UserSerializer.relationships_to_serialize.keys).not_to include(:account) end it 'includes parent cached relationships' do subclass_relationships = EmployeeSerializer.cachable_relationships_to_serialize superclass_relationships = UserSerializer.cachable_relationships_to_serialize expect(subclass_relationships).to include(superclass_relationships) end end context 'when test inheritence of other attributes' do it 'inherits the tranform method' do EmployeeSerializer expect(UserSerializer.transform_method).to eq EmployeeSerializer.transform_method end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/object_serializer_class_methods_spec.rb
spec/lib/object_serializer_class_methods_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do include_context 'movie class' describe '#has_many' do subject(:relationship) { serializer.relationships_to_serialize[:roles] } before do serializer.has_many *children end after do serializer.relationships_to_serialize = {} end context 'with namespace' do let(:serializer) { AppName::V1::MovieSerializer } let(:children) { [:roles] } context 'with overrides' do let(:children) { [:roles, id_method_name: :roles_only_ids, record_type: :super_role] } it_behaves_like 'returning correct relationship hash', :'AppName::V1::RoleSerializer', :roles_only_ids, :super_role end context 'without overrides' do let(:children) { [:roles] } it_behaves_like 'returning correct relationship hash', :'AppName::V1::RoleSerializer', :role_ids, :role end end context 'without namespace' do let(:serializer) { MovieSerializer } context 'with overrides' do let(:children) { [:roles, id_method_name: :roles_only_ids, record_type: :super_role] } it_behaves_like 'returning correct relationship hash', :'RoleSerializer', :roles_only_ids, :super_role end context 'without overrides' do let(:children) { [:roles] } it_behaves_like 'returning correct relationship hash', :'RoleSerializer', :role_ids, :role end end end describe '#has_many with block' do before do MovieSerializer.has_many :awards do |movie| movie.actors.map(&:awards).flatten end end after do MovieSerializer.relationships_to_serialize.delete(:awards) end context 'awards is not included' do subject(:hash) { MovieSerializer.new(movie).serializable_hash } it 'returns correct hash' do expect(hash[:data][:relationships][:awards][:data].length).to eq(6) expect(hash[:data][:relationships][:awards][:data][0]).to eq({ id: '9', type: :award }) expect(hash[:data][:relationships][:awards][:data][-1]).to eq({ id: '28', type: :award }) end end context 'state is included' do subject(:hash) { MovieSerializer.new(movie, include: [:awards]).serializable_hash } it 'returns correct hash' do expect(hash[:included].length).to eq 6 expect(hash[:included][0][:id]).to eq '9' expect(hash[:included][0][:type]).to eq :award expect(hash[:included][0][:attributes]).to eq({ id: 9, title: 'Test Award 9' }) expect(hash[:included][0][:relationships]).to eq({ actor: { data: { id: '1', type: :actor } } }) expect(hash[:included][-1][:id]).to eq '28' expect(hash[:included][-1][:type]).to eq :award expect(hash[:included][-1][:attributes]).to eq({ id: 28, title: 'Test Award 28' }) expect(hash[:included][-1][:relationships]).to eq({ actor: { data: { id: '3', type: :actor } } }) end end end describe '#has_many with block and id_method_name' do before do MovieSerializer.has_many(:awards, id_method_name: :imdb_award_id) do |movie| movie.actors.map(&:awards).flatten end end after do MovieSerializer.relationships_to_serialize.delete(:awards) end context 'awards is not included' do subject(:hash) { MovieSerializer.new(movie).serializable_hash } it 'returns correct hash where id is obtained from the method specified via `id_method_name`' do expected_award_data = movie.actors.map(&:awards).flatten.map do |actor| { id: actor.imdb_award_id.to_s, type: actor.class.name.downcase.to_sym } end serialized_award_data = hash[:data][:relationships][:awards][:data] expect(serialized_award_data).to eq(expected_award_data) end end end describe '#belongs_to' do subject(:relationship) { MovieSerializer.relationships_to_serialize[:area] } before do MovieSerializer.belongs_to *parent end after do MovieSerializer.relationships_to_serialize = {} end context 'with overrides' do let(:parent) { [:area, id_method_name: :blah_id, record_type: :awesome_area, serializer: :my_area] } it_behaves_like 'returning correct relationship hash', :'MyAreaSerializer', :blah_id, :awesome_area end context 'without overrides' do let(:parent) { [:area] } it_behaves_like 'returning correct relationship hash', :'AreaSerializer', :area_id, :area end end describe '#belongs_to with block' do before do ActorSerializer.belongs_to :state do |actor| actor.agency.state end end after do ActorSerializer.relationships_to_serialize.delete(:actorc) end context 'state is not included' do subject(:hash) { ActorSerializer.new(actor).serializable_hash } it 'returns correct hash' do expect(hash[:data][:relationships][:state][:data]).to eq({ id: '1', type: :state }) end end context 'state is included' do subject(:hash) { ActorSerializer.new(actor, include: [:state]).serializable_hash } it 'returns correct hash' do expect(hash[:included].length).to eq 1 expect(hash[:included][0][:id]).to eq '1' expect(hash[:included][0][:type]).to eq :state expect(hash[:included][0][:attributes]).to eq({ id: 1, name: 'Test State 1' }) expect(hash[:included][0][:relationships]).to eq({ agency: { data: [{ id: '432', type: :agency }] } }) end end end describe '#has_one' do subject(:relationship) { MovieSerializer.relationships_to_serialize[:area] } before do MovieSerializer.has_one *partner end after do MovieSerializer.relationships_to_serialize = {} end context 'with overrides' do let(:partner) { [:area, id_method_name: :blah_id, record_type: :awesome_area, serializer: :my_area] } it_behaves_like 'returning correct relationship hash', :'MyAreaSerializer', :blah_id, :awesome_area end context 'without overrides' do let(:partner) { [:area] } it_behaves_like 'returning correct relationship hash', :'AreaSerializer', :area_id, :area end end describe '#set_id' do subject(:serializable_hash) { MovieSerializer.new(resource).serializable_hash } context 'method name' do before do MovieSerializer.set_id :owner_id end after do MovieSerializer.set_id nil end context 'when one record is given' do let(:resource) { movie } it 'returns correct hash which id equals owner_id' do expect(serializable_hash[:data][:id].to_i).to eq movie.owner_id end end context 'when an array of records is given' do let(:resource) { [movie, movie] } it 'returns correct hash which id equals owner_id' do expect(serializable_hash[:data][0][:id].to_i).to eq movie.owner_id expect(serializable_hash[:data][1][:id].to_i).to eq movie.owner_id end end end context 'with block' do before do MovieSerializer.set_id { |record| "movie-#{record.owner_id}" } end after do MovieSerializer.set_id nil end context 'when one record is given' do let(:resource) { movie } it 'returns correct hash which id equals movie-id' do expect(serializable_hash[:data][:id]).to eq "movie-#{movie.owner_id}" end end context 'when an array of records is given' do let(:resource) { [movie, movie] } it 'returns correct hash which id equals movie-id' do expect(serializable_hash[:data][0][:id]).to eq "movie-#{movie.owner_id}" expect(serializable_hash[:data][1][:id]).to eq "movie-#{movie.owner_id}" end end end end describe '#use_hyphen' do subject { MovieSerializer.use_hyphen } after do MovieSerializer.transform_method = nil end it 'sets the correct transform_method when use_hyphen is used' do warning_message = "DEPRECATION WARNING: use_hyphen is deprecated and will be removed from fast_jsonapi 2.0 use (set_key_transform :dash) instead\n" expect { subject }.to output(warning_message).to_stderr expect(MovieSerializer.instance_variable_get(:@transform_method)).to eq :dasherize end end describe '#attribute' do subject(:serializable_hash) { MovieSerializer.new(movie).serializable_hash } context 'with block' do before do movie.release_year = 2008 MovieSerializer.attribute :title_with_year do |record| "#{record.name} (#{record.release_year})" end end after do MovieSerializer.attributes_to_serialize.delete(:title_with_year) end it 'returns correct hash when serializable_hash is called' do expect(serializable_hash[:data][:attributes][:name]).to eq movie.name expect(serializable_hash[:data][:attributes][:title_with_year]).to eq "#{movie.name} (#{movie.release_year})" end end context 'with &:proc' do before do movie.release_year = 2008 MovieSerializer.attribute :released_in_year, &:release_year MovieSerializer.attribute :name, &:local_name end after do MovieSerializer.attributes_to_serialize.delete(:released_in_year) end it 'returns correct hash when serializable_hash is called' do expect(serializable_hash[:data][:attributes][:name]).to eq "english #{movie.name}" expect(serializable_hash[:data][:attributes][:released_in_year]).to eq movie.release_year end end end describe '#meta' do subject(:serializable_hash) { MovieSerializer.new(movie).serializable_hash } before do movie.release_year = 2008 MovieSerializer.meta do |movie| { years_since_release: year_since_release_calculator(movie.release_year) } end end after do movie.release_year = nil MovieSerializer.meta_to_serialize = nil end it 'returns correct hash when serializable_hash is called' do expect(serializable_hash[:data][:meta]).to eq ({ years_since_release: year_since_release_calculator(movie.release_year) }) end private def year_since_release_calculator(release_year) Date.current.year - release_year end end describe '#link' do subject(:serializable_hash) { MovieSerializer.new(movie).serializable_hash } after do MovieSerializer.data_links = {} ActorSerializer.data_links = {} end context 'with block calling instance method on serializer' do before do MovieSerializer.link(:self) do |movie_object| movie_object.url end end let(:url) { "http://movies.com/#{movie.id}" } it 'returns correct hash when serializable_hash is called' do expect(serializable_hash[:data][:links][:self]).to eq url end end context 'with block and param' do before do MovieSerializer.link(:public_url) do |movie_object| "http://movies.com/#{movie_object.id}" end end let(:url) { "http://movies.com/#{movie.id}" } it 'returns correct hash when serializable_hash is called' do expect(serializable_hash[:data][:links][:public_url]).to eq url end end context 'with method' do before do MovieSerializer.link(:object_id, :id) end it 'returns correct hash when serializable_hash is called' do expect(serializable_hash[:data][:links][:object_id]).to eq movie.id end end context 'with method and convention' do before do MovieSerializer.link(:url) end it 'returns correct hash when serializable_hash is called' do expect(serializable_hash[:data][:links][:url]).to eq movie.url end end context 'when inheriting from a parent serializer' do before do MovieSerializer.link(:url) do |movie_object| "http://movies.com/#{movie_object.id}" end end subject(:action_serializable_hash) { ActionMovieSerializer.new(movie).serializable_hash } subject(:horror_serializable_hash) { HorrorMovieSerializer.new(movie).serializable_hash } let(:url) { "http://movies.com/#{movie.id}" } it 'returns the link for the correct sub-class' do expect(action_serializable_hash[:data][:links][:url]).to eq "/action-movie/#{movie.id}" end end end describe '#key_transform' do subject(:hash) { movie_serializer_class.new([movie, movie], include: [:movie_type]).serializable_hash } let(:movie_serializer_class) { "#{key_transform}_movie_serializer".classify.constantize } before(:context) do [:dash, :camel, :camel_lower, :underscore].each do |key_transform| movie_serializer_name = "#{key_transform}_movie_serializer".classify movie_type_serializer_name = "#{key_transform}_movie_type_serializer".classify # https://stackoverflow.com/questions/4113479/dynamic-class-definition-with-a-class-name movie_serializer_class = Object.const_set(movie_serializer_name, Class.new) # https://rubymonk.com/learning/books/5-metaprogramming-ruby-ascent/chapters/24-eval/lessons/67-instance-eval movie_serializer_class.instance_eval do include FastJsonapi::ObjectSerializer set_type :movie set_key_transform key_transform attributes :name, :release_year has_many :actors belongs_to :owner, record_type: :user belongs_to :movie_type, serializer: "#{key_transform}_movie_type".to_sym end movie_type_serializer_class = Object.const_set(movie_type_serializer_name, Class.new) movie_type_serializer_class.instance_eval do include FastJsonapi::ObjectSerializer set_key_transform key_transform attributes :name end end end context 'when key_transform is dash' do let(:key_transform) { :dash } it_behaves_like 'returning key transformed hash', :'movie-type', :'dash-movie-type', :'release-year' end context 'when key_transform is camel' do let(:key_transform) { :camel } it_behaves_like 'returning key transformed hash', :MovieType, :CamelMovieType, :ReleaseYear end context 'when key_transform is camel_lower' do let(:key_transform) { :camel_lower } it_behaves_like 'returning key transformed hash', :movieType, :camelLowerMovieType, :releaseYear end context 'when key_transform is underscore' do let(:key_transform) { :underscore } it_behaves_like 'returning key transformed hash', :movie_type, :underscore_movie_type, :release_year end end describe '#set_key_transform after #set_type' do subject(:serializable_hash) { MovieSerializer.new(movie).serializable_hash } before do MovieSerializer.set_type type_name MovieSerializer.set_key_transform :camel end after do MovieSerializer.transform_method = nil MovieSerializer.set_type :movie end context 'when sets singular type name' do let(:type_name) { :film } it 'returns correct hash which type equals transformed set_type value' do expect(serializable_hash[:data][:type]).to eq :Film end end context 'when sets plural type name' do let(:type_name) { :films } it 'returns correct hash which type equals transformed set_type value' do expect(serializable_hash[:data][:type]).to eq :Films end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/object_serializer_polymorphic_spec.rb
spec/lib/object_serializer_polymorphic_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do class List attr_accessor :id, :name, :items end class ChecklistItem attr_accessor :id, :name end class Car attr_accessor :id, :model, :year end class ListSerializer include FastJsonapi::ObjectSerializer set_type :list attributes :name set_key_transform :dash has_many :items, polymorphic: true end let(:car) do car = Car.new car.id = 1 car.model = 'Toyota Corolla' car.year = 1987 car end let(:checklist_item) do checklist_item = ChecklistItem.new checklist_item.id = 2 checklist_item.name = 'Do this action!' checklist_item end context 'when serializing id and type of polymorphic relationships' do it 'should return correct type when transform_method is specified' do list = List.new list.id = 1 list.items = [checklist_item, car] list_hash = ListSerializer.new(list).to_hash record_type = list_hash[:data][:relationships][:items][:data][0][:type] expect(record_type).to eq 'checklist-item'.to_sym record_type = list_hash[:data][:relationships][:items][:data][1][:type] expect(record_type).to eq 'car'.to_sym end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/object_serializer_relationship_links_spec.rb
spec/lib/object_serializer_relationship_links_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do include_context 'movie class' context "params option" do let(:hash) { serializer.serializable_hash } context "generating links for a serializer relationship" do let(:params) { { } } let(:options_with_params) { { params: params } } let(:relationship_url) { "http://movies.com/#{movie.id}/relationships/actors" } let(:related_url) { "http://movies.com/movies/#{movie.name.parameterize}/actors/" } before(:context) do class MovieSerializer has_many :actors, lazy_load_data: false, links: { self: :actors_relationship_url, related: -> (object, params = {}) { "#{params.has_key?(:secure) ? "https" : "http"}://movies.com/movies/#{object.name.parameterize}/actors/" } } end end context "with a single record" do let(:serializer) { MovieSerializer.new(movie, options_with_params) } let(:links) { hash[:data][:relationships][:actors][:links] } it "handles relationship links that call a method" do expect(links).to be_present expect(links[:self]).to eq(relationship_url) end it "handles relationship links that call a proc" do expect(links).to be_present expect(links[:related]).to eq(related_url) end context "with serializer params" do let(:params) { { secure: true } } let(:secure_related_url) { related_url.gsub("http", "https") } it "passes the params to the link serializer correctly" do expect(links).to be_present expect(links[:related]).to eq(secure_related_url) end end end end context "lazy loading relationship data" do before(:context) do class LazyLoadingMovieSerializer < MovieSerializer has_many :actors, lazy_load_data: true, links: { related: :actors_relationship_url } end end let(:serializer) { LazyLoadingMovieSerializer.new(movie) } let(:actor_hash) { hash[:data][:relationships][:actors] } it "does not include the :data key" do expect(actor_hash).to be_present expect(actor_hash).not_to have_key(:data) end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/object_serializer_struct_spec.rb
spec/lib/object_serializer_struct_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do include_context 'movie class' context 'when testing object serializer with ruby struct' do it 'returns correct hash when serializable_hash is called' do options = {} options[:meta] = { total: 2 } options[:links] = { self: 'self' } options[:include] = [:actors] serializable_hash = MovieSerializer.new([movie_struct, movie_struct], options).serializable_hash expect(serializable_hash[:data].length).to eq 2 expect(serializable_hash[:data][0][:relationships].length).to eq 4 expect(serializable_hash[:data][0][:attributes].length).to eq 2 expect(serializable_hash[:meta]).to be_instance_of(Hash) expect(serializable_hash[:links]).to be_instance_of(Hash) expect(serializable_hash[:included]).to be_instance_of(Array) expect(serializable_hash[:included][0]).to be_instance_of(Hash) expect(serializable_hash[:included].length).to eq 3 serializable_hash = MovieSerializer.new(movie_struct).serializable_hash expect(serializable_hash[:data]).to be_instance_of(Hash) expect(serializable_hash[:meta]).to be nil expect(serializable_hash[:links]).to be nil expect(serializable_hash[:included]).to be nil expect(serializable_hash[:data][:id]).to eq movie_struct.id.to_s end context 'struct without id' do it 'returns correct hash when serializable_hash is called' do serializer = MovieWithoutIdStructSerializer.new(movie_struct_without_id) expect { serializer.serializable_hash }.to raise_error(FastJsonapi::MandatoryField) end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/multi_to_json/result_spec.rb
spec/lib/multi_to_json/result_spec.rb
require 'spec_helper' module FastJsonapi module MultiToJson describe Result do it 'supports chaining of rescues' do expect do Result.new(LoadError) do require '1' end.rescue do require '2' end.rescue do require '3' end.rescue do '4' end end.not_to raise_error end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/extensions/active_record_spec.rb
spec/lib/extensions/active_record_spec.rb
require 'spec_helper' require 'active_record' require 'sqlite3' describe 'active record' do # Setup DB before(:all) do @db_file = "test.db" # Open a database db = SQLite3::Database.new @db_file # Create tables db.execute_batch <<-SQL create table suppliers ( name varchar(30), id int primary key ); create table accounts ( name varchar(30), id int primary key, supplier_id int, FOREIGN KEY (supplier_id) REFERENCES suppliers(id) ); SQL # Insert records @account_id = 2 @supplier_id = 1 @supplier_id_without_account = 3 db.execute_batch <<-SQL insert into suppliers values ('Supplier1', #{@supplier_id}), ('SupplierWithoutAccount', #{@supplier_id_without_account}); insert into accounts values ('Dollar Account', #{@account_id}, #{@supplier_id}); SQL end # Setup Active Record before(:all) do class Supplier < ActiveRecord::Base has_one :account end class Account < ActiveRecord::Base belongs_to :supplier end ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => @db_file ) end context 'has one patch' do it 'has account_id method for a supplier' do expect(Supplier.first.respond_to?(:account_id)).to be true expect(Supplier.first.account_id).to eq @account_id end it 'has account_id method return nil if account not present' do expect(Supplier.find(@supplier_id_without_account).account_id).to eq nil end end # Clean up DB after(:all) do File.delete(@db_file) if File.exist?(@db_file) end end describe 'active record has_one through' do # Setup DB before(:all) do @db_file = "test_two.db" # Open a database db = SQLite3::Database.new @db_file # Create tables db.execute_batch <<-SQL create table forests ( id int primary key, name varchar(30) ); create table trees ( id int primary key, forest_id int, name varchar(30), FOREIGN KEY (forest_id) REFERENCES forests(id) ); create table fruits ( id int primary key, tree_id int, name varchar(30), FOREIGN KEY (tree_id) REFERENCES trees(id) ); SQL # Insert records db.execute_batch <<-SQL insert into forests values (1, 'sherwood'); insert into trees values (2, 1,'pine'); insert into fruits values (3, 2, 'pine nut'); insert into fruits(id,name) values (4,'apple'); SQL end # Setup Active Record before(:all) do class Forest < ActiveRecord::Base has_many :trees end class Tree < ActiveRecord::Base belongs_to :forest end class Fruit < ActiveRecord::Base belongs_to :tree has_one :forest, through: :tree end ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => @db_file ) end context 'revenue' do it 'has an forest_id' do expect(Fruit.find(3).respond_to?(:forest_id)).to be true expect(Fruit.find(3).forest_id).to eq 1 expect(Fruit.find(3).forest.name).to eq "sherwood" end it 'has nil if tree id not available' do expect(Fruit.find(4).respond_to?(:tree_id)).to be true expect(Fruit.find(4).forest_id).to eq nil end end # Clean up DB after(:all) do File.delete(@db_file) if File.exist?(@db_file) end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/instrumentation/as_notifications_spec.rb
spec/lib/instrumentation/as_notifications_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do include_context 'movie class' context 'instrument' do before(:all) do require 'fast_jsonapi/instrumentation' end after(:all) do [ :serialized_json, :serializable_hash ].each do |m| alias_command = "alias_method :#{m}, :#{m}_without_instrumentation" FastJsonapi::ObjectSerializer.class_eval(alias_command) remove_command = "remove_method :#{m}_without_instrumentation" FastJsonapi::ObjectSerializer.class_eval(remove_command) end end before(:each) do options = {} options[:meta] = { total: 2 } options[:include] = [:actors] @serializer = MovieSerializer.new([movie, movie], options) end context 'serializable_hash' do it 'should send notifications' do events = [] ActiveSupport::Notifications.subscribe(FastJsonapi::ObjectSerializer::SERIALIZABLE_HASH_NOTIFICATION) do |*args| events << ActiveSupport::Notifications::Event.new(*args) end serialized_hash = @serializer.serializable_hash expect(events.length).to eq(1) event = events.first expect(event.duration).to be > 0 expect(event.payload).to eq({ name: 'MovieSerializer' }) expect(event.name).to eq(FastJsonapi::ObjectSerializer::SERIALIZABLE_HASH_NOTIFICATION) expect(serialized_hash.key?(:data)).to eq(true) expect(serialized_hash.key?(:meta)).to eq(true) expect(serialized_hash.key?(:included)).to eq(true) end end context 'serialized_json' do it 'should send notifications' do events = [] ActiveSupport::Notifications.subscribe(FastJsonapi::ObjectSerializer::SERIALIZED_JSON_NOTIFICATION) do |*args| events << ActiveSupport::Notifications::Event.new(*args) end json = @serializer.serialized_json expect(events.length).to eq(1) event = events.first expect(event.duration).to be > 0 expect(event.payload).to eq({ name: 'MovieSerializer' }) expect(event.name).to eq(FastJsonapi::ObjectSerializer::SERIALIZED_JSON_NOTIFICATION) expect(json.length).to be > 50 end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/instrumentation/as_notifications_negative_spec.rb
spec/lib/instrumentation/as_notifications_negative_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do include_context 'movie class' context 'instrument' do before(:each) do options = {} options[:meta] = { total: 2 } options[:include] = [:actors] @serializer = MovieSerializer.new([movie, movie], options) end context 'serializable_hash' do it 'should send not notifications' do events = [] ActiveSupport::Notifications.subscribe(FastJsonapi::ObjectSerializer::SERIALIZABLE_HASH_NOTIFICATION) do |*args| events << ActiveSupport::Notifications::Event.new(*args) end serialized_hash = @serializer.serializable_hash expect(events.length).to eq(0) expect(serialized_hash.key?(:data)).to eq(true) expect(serialized_hash.key?(:meta)).to eq(true) expect(serialized_hash.key?(:included)).to eq(true) end end context 'serialized_json' do it 'should send not notifications' do events = [] ActiveSupport::Notifications.subscribe(FastJsonapi::ObjectSerializer::SERIALIZED_JSON_NOTIFICATION) do |*args| events << ActiveSupport::Notifications::Event.new(*args) end json = @serializer.serialized_json expect(events.length).to eq(0) expect(json.length).to be > 50 end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/lib/instrumentation/skylight/normalizers_require_spec.rb
spec/lib/instrumentation/skylight/normalizers_require_spec.rb
require 'spec_helper' describe FastJsonapi::ObjectSerializer do context 'instrument' do context 'skylight' do # skip for normal runs because this could alter some # other test by insterting the instrumentation xit 'make sure requiring skylight normalizers works' do require 'fast_jsonapi/instrumentation/skylight' end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/shared/examples/object_serializer_class_methods_examples.rb
spec/shared/examples/object_serializer_class_methods_examples.rb
RSpec.shared_examples 'returning correct relationship hash' do |serializer, id_method_name, record_type| it 'returns correct relationship hash' do expect(relationship).to be_instance_of(FastJsonapi::Relationship) # expect(relationship.keys).to all(be_instance_of(Symbol)) expect(relationship.serializer).to be serializer expect(relationship.id_method_name).to be id_method_name expect(relationship.record_type).to be record_type end end RSpec.shared_examples 'returning key transformed hash' do |movie_type, serializer_type, release_year| it 'returns correctly transformed hash' do expect(hash[:data][0][:attributes]).to have_key(release_year) expect(hash[:data][0][:relationships]).to have_key(movie_type) expect(hash[:data][0][:relationships][movie_type][:data][:type]).to eq(movie_type) expect(hash[:included][0][:type]).to eq(serializer_type) end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/shared/contexts/jsonapi_context.rb
spec/shared/contexts/jsonapi_context.rb
RSpec.shared_context 'jsonapi movie class' do before(:context) do # models class JSONAPIMovie attr_accessor :id, :name, :release_year, :actors, :owner, :movie_type end class JSONAPIActor attr_accessor :id, :name, :email end class JSONAPIUser attr_accessor :id, :name end class JSONAPIMovieType attr_accessor :id, :name end # serializers class JSONAPIMovieSerializer < JSONAPI::Serializable::Resource type 'movie' attributes :name, :release_year has_many :actors has_one :owner belongs_to :movie_type end class JSONAPIActorSerializer < JSONAPI::Serializable::Resource type 'actor' attributes :name, :email end class JSONAPIUserSerializer < JSONAPI::Serializable::Resource type 'user' attributes :name end class JSONAPIMovieTypeSerializer < JSONAPI::Serializable::Resource type 'movie_type' attributes :name end class JSONAPISerializer def initialize(data, options = {}) @serializer = JSONAPI::Serializable::Renderer.new @options = options.merge(class: { JSONAPIMovie: JSONAPIMovieSerializer, JSONAPIActor: JSONAPIActorSerializer, JSONAPIUser: JSONAPIUserSerializer, JSONAPIMovieType: JSONAPIMovieTypeSerializer }) @data = data end def to_json @serializer.render(@data, @options).to_json end def to_hash @serializer.render(@data, @options) end end end after :context do classes_to_remove = %i[ JSONAPIMovie JSONAPIActor JSONAPIUser JSONAPIMovieType JSONAPIMovieSerializer JSONAPIActorSerializer JSONAPIUserSerializer JSONAPIMovieTypeSerializer] classes_to_remove.each do |klass_name| Object.send(:remove_const, klass_name) if Object.constants.include?(klass_name) end end let(:jsonapi_actors) do 3.times.map do |i| j = JSONAPIActor.new j.id = i + 1 j.name = "Test #{j.id}" j.email = "test#{j.id}@test.com" j end end let(:jsonapi_user) do jsonapi_user = JSONAPIUser.new jsonapi_user.id = 3 jsonapi_user end let(:jsonapi_movie_type) do jsonapi_movie_type = JSONAPIMovieType.new jsonapi_movie_type.id = 1 jsonapi_movie_type.name = 'episode' jsonapi_movie_type end def build_jsonapi_movies(count) count.times.map do |i| m = JSONAPIMovie.new m.id = i + 1 m.name = 'test movie' m.actors = jsonapi_actors m.owner = jsonapi_user m.movie_type = jsonapi_movie_type m end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/shared/contexts/group_context.rb
spec/shared/contexts/group_context.rb
RSpec.shared_context 'group class' do # Person, Group Classes and serializers before(:context) do # models class Person attr_accessor :id, :first_name, :last_name end class Group attr_accessor :id, :name, :groupees # Let's assume groupees can be Person or Group objects end # serializers class PersonSerializer include FastJsonapi::ObjectSerializer set_type :person attributes :first_name, :last_name end class GroupSerializer include FastJsonapi::ObjectSerializer set_type :group attributes :name has_many :groupees, polymorphic: true end end # Person and Group struct before(:context) do PersonStruct = Struct.new( :id, :first_name, :last_name ) GroupStruct = Struct.new( :id, :name, :groupees, :groupee_ids ) end after(:context) do classes_to_remove = %i[ Person PersonSerializer Group GroupSerializer PersonStruct GroupStruct ] classes_to_remove.each do |klass_name| Object.send(:remove_const, klass_name) if Object.constants.include?(klass_name) end end let(:group) do group = Group.new group.id = 1 group.name = 'Group 1' person = Person.new person.id = 1 person.last_name = "Last Name 1" person.first_name = "First Name 1" child_group = Group.new child_group.id = 2 child_group.name = 'Group 2' group.groupees = [person, child_group] group end def build_groups(count) group_count = 0 person_count = 0 count.times.map do |i| group = Group.new group.id = group_count + 1 group.name = "Test Group #{group.id}" group_count = group.id person = Person.new person.id = person_count + 1 person.last_name = "Last Name #{person.id}" person.first_name = "First Name #{person.id}" person_count = person.id child_group = Group.new child_group.id = group_count + 1 child_group.name = "Test Group #{child_group.id}" group_count = child_group.id group.groupees = [person, child_group] group end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/shared/contexts/js_context.rb
spec/shared/contexts/js_context.rb
RSpec.shared_context 'jsonapi-serializers movie class' do before(:context) do # models class JSMovie attr_accessor :id, :name, :release_year, :actors, :owner, :movie_type end class JSActor attr_accessor :id, :name, :email end class JSUser attr_accessor :id, :name end class JSMovieType attr_accessor :id, :name end # serializers class JSActorSerializer include JSONAPI::Serializer attributes :name, :email def type 'actor' end end class JSUserSerializer include JSONAPI::Serializer attributes :name def type 'user' end end class JSMovieTypeSerializer include JSONAPI::Serializer attributes :name def type 'movie_type' end end class JSMovieSerializer include JSONAPI::Serializer attributes :name, :release_year has_many :actors has_one :owner has_one :movie_type def type 'movie' end end class JSONAPISSerializer def initialize(data, options = {}) @options = options.merge(is_collection: true) @data = data end def to_json JSONAPI::Serializer.serialize(@data, @options).to_json end def to_hash JSONAPI::Serializer.serialize(@data, @options) end end end after(:context) do classes_to_remove = %i[ JSMovie JSActor JSUser JSMovieType JSONAPISSerializer JSActorSerializer JSUserSerializer JSMovieTypeSerializer JSMovieSerializer] classes_to_remove.each do |klass_name| Object.send(:remove_const, klass_name) if Object.constants.include?(klass_name) end end let(:js_actors) do 3.times.map do |i| a = JSActor.new a.id = i + 1 a.name = "Test #{a.id}" a.email = "test#{a.id}@test.com" a end end let(:js_user) do ams_user = JSUser.new ams_user.id = 3 ams_user end let(:js_movie_type) do ams_movie_type = JSMovieType.new ams_movie_type.id = 1 ams_movie_type.name = 'episode' ams_movie_type end def build_js_movies(count) count.times.map do |i| m = JSMovie.new m.id = i + 1 m.name = 'test movie' m.actors = js_actors m.owner = js_user m.movie_type = js_movie_type m end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/shared/contexts/jsonapi_group_context.rb
spec/shared/contexts/jsonapi_group_context.rb
RSpec.shared_context 'jsonapi group class' do # Person, Group Classes and serializers before(:context) do # models class JSONAPIPerson attr_accessor :id, :first_name, :last_name end class JSONAPIGroup attr_accessor :id, :name, :groupees # Let's assume groupees can be Person or Group objects end # serializers class JSONAPIPersonSerializer < JSONAPI::Serializable::Resource type 'person' attributes :first_name, :last_name end class JSONAPIGroupSerializer < JSONAPI::Serializable::Resource type 'group' attributes :name has_many :groupees end class JSONAPISerializerB def initialize(data, options = {}) @serializer = JSONAPI::Serializable::Renderer.new @options = options.merge(class: { JSONAPIPerson: JSONAPIPersonSerializer, JSONAPIGroup: JSONAPIGroupSerializer }) @data = data end def to_json @serializer.render(@data, @options).to_json end def to_hash @serializer.render(@data, @options) end end end after :context do classes_to_remove = %i[ JSONAPIPerson JSONAPIGroup JSONAPIPersonSerializer JSONAPIGroupSerializer] classes_to_remove.each do |klass_name| Object.send(:remove_const, klass_name) if Object.constants.include?(klass_name) end end let(:jsonapi_groups) do group_count = 0 person_count = 0 3.times.map do |i| group = JSONAPIGroup.new group.id = group_count + 1 group.name = "Test Group #{group.id}" group_count = group.id person = JSONAPIPerson.new person.id = person_count + 1 person.last_name = "Last Name #{person.id}" person.first_name = "First Name #{person.id}" person_count = person.id child_group = JSONAPIGroup.new child_group.id = group_count + 1 child_group.name = "Test Group #{child_group.id}" group_count = child_group.id group.groupees = [person, child_group] group end end let(:jsonapi_person) do person = JSONAPIPerson.new person.id = 3 person end def build_jsonapi_groups(count) group_count = 0 person_count = 0 count.times.map do |i| group = JSONAPIGroup.new group.id = group_count + 1 group.name = "Test Group #{group.id}" group_count = group.id person = JSONAPIPerson.new person.id = person_count + 1 person.last_name = "Last Name #{person.id}" person.first_name = "First Name #{person.id}" person_count = person.id child_group = JSONAPIGroup.new child_group.id = group_count + 1 child_group.name = "Test Group #{child_group.id}" group_count = child_group.id group.groupees = [person, child_group] group end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/shared/contexts/movie_context.rb
spec/shared/contexts/movie_context.rb
RSpec.shared_context 'movie class' do # Movie, Actor Classes and serializers before(:context) do # models class Movie attr_accessor :id, :name, :release_year, :director, :actor_ids, :owner_id, :movie_type_id def actors actor_ids.map.with_index do |id, i| a = Actor.new a.id = id a.name = "Test #{a.id}" a.email = "test#{a.id}@test.com" a.agency_id = i a end end def movie_type mt = MovieType.new mt.id = movie_type_id mt.name = 'Episode' mt.movie_ids = [id] mt end def advertising_campaign_id 1 end def advertising_campaign ac = AdvertisingCampaign.new ac.id = 1 ac.movie_id = id ac.name = "Movie #{name} is incredible!!" ac end def owner return unless owner_id ow = Owner.new ow.id = owner_id ow end def cache_key "#{id}" end def local_name(locale = :english) "#{locale} #{name}" end def url "http://movies.com/#{id}" end def actors_relationship_url "#{url}/relationships/actors" end end class Actor attr_accessor :id, :name, :email, :agency_id def agency Agency.new.tap do |a| a.id = agency_id a.name = "Test Agency #{agency_id}" a.state_id = 1 end end def awards award_ids.map do |i| Award.new.tap do |a| a.id = i a.title = "Test Award #{i}" a.actor_id = id a.imdb_award_id = i * 10 a.year = 1990 + i end end end def award_ids [id * 9, id * 9 + 1] end def url "http://movies.com/actors/#{id}" end end class AdvertisingCampaign attr_accessor :id, :name, :movie_id end class Agency attr_accessor :id, :name, :state_id def state State.new.tap do |s| s.id = state_id s.name = "Test State #{state_id}" s.agency_ids = [id] end end end class Award attr_accessor :id, :title, :actor_id, :year, :imdb_award_id end class State attr_accessor :id, :name, :agency_ids end class MovieType attr_accessor :id, :name, :movie_ids def movies movie_ids.map.with_index do |id, i| m = Movie.new m.id = 232 m.name = 'test movie' m.actor_ids = [1, 2, 3] m.owner_id = 3 m.movie_type_id = 1 m end end end class Agency attr_accessor :id, :name, :actor_ids end class Agency attr_accessor :id, :name, :actor_ids end class Supplier attr_accessor :id, :account_id def account if account_id a = Account.new a.id = account_id a end end end class Account attr_accessor :id end class Owner attr_accessor :id end class OwnerSerializer include FastJsonapi::ObjectSerializer end # serializers class MovieSerializer include FastJsonapi::ObjectSerializer set_type :movie # director attr is not mentioned intentionally attributes :name, :release_year has_many :actors belongs_to :owner, record_type: :user do |object, params| object.owner end belongs_to :movie_type has_one :advertising_campaign end class GenreMovieSerializer < MovieSerializer link(:something) { '/something/' } end class ActionMovieSerializer < GenreMovieSerializer link(:url) { |object| "/action-movie/#{object.id}" } end class HorrorMovieSerializer < GenreMovieSerializer link(:url) { |object| "/horror-movie/#{object.id}" } end class MovieWithoutIdStructSerializer include FastJsonapi::ObjectSerializer attributes :name, :release_year end class CachingMovieSerializer include FastJsonapi::ObjectSerializer set_type :movie attributes :name, :release_year has_many :actors belongs_to :owner, record_type: :user belongs_to :movie_type cache_options enabled: true end class CachingMovieWithHasManySerializer include FastJsonapi::ObjectSerializer set_type :movie attributes :name, :release_year has_many :actors, cached: true belongs_to :owner, record_type: :user belongs_to :movie_type cache_options enabled: true end class ActorSerializer include FastJsonapi::ObjectSerializer set_type :actor attributes :name, :email belongs_to :agency has_many :awards belongs_to :agency end class AgencySerializer include FastJsonapi::ObjectSerializer attributes :id, :name belongs_to :state has_many :actors end class AwardSerializer include FastJsonapi::ObjectSerializer attributes :id, :title attribute :year, if: Proc.new { |record, params| params[:include_award_year].present? ? params[:include_award_year] : false } belongs_to :actor end class StateSerializer include FastJsonapi::ObjectSerializer attributes :id, :name has_many :agency end class AdvertisingCampaignSerializer include FastJsonapi::ObjectSerializer attributes :id, :name belongs_to :movie end class MovieTypeSerializer include FastJsonapi::ObjectSerializer set_type :movie_type attributes :name has_many :movies end class MovieSerializerWithAttributeBlock include FastJsonapi::ObjectSerializer set_type :movie attributes :name, :release_year attribute :title_with_year do |record| "#{record.name} (#{record.release_year})" end end class MovieSerializerWithAttributeBlock include FastJsonapi::ObjectSerializer set_type :movie attributes :name, :release_year attribute :title_with_year do |record| "#{record.name} (#{record.release_year})" end end class AgencySerializer include FastJsonapi::ObjectSerializer attributes :id, :name has_many :actors end class SupplierSerializer include FastJsonapi::ObjectSerializer set_type :supplier has_one :account end class AccountSerializer include FastJsonapi::ObjectSerializer set_type :account belongs_to :supplier end class MovieOptionalRecordDataSerializer include FastJsonapi::ObjectSerializer set_type :movie attributes :name attribute :release_year, if: Proc.new { |record| record.release_year >= 2000 } end class MovieOptionalParamsDataSerializer include FastJsonapi::ObjectSerializer set_type :movie attributes :name attribute :director, if: Proc.new { |record, params| params[:admin] == true } end class MovieOptionalRelationshipSerializer include FastJsonapi::ObjectSerializer set_type :movie attributes :name has_many :actors, if: Proc.new { |record| record.actors.any? } end class MovieOptionalRelationshipWithParamsSerializer include FastJsonapi::ObjectSerializer set_type :movie attributes :name belongs_to :owner, record_type: :user, if: Proc.new { |record, params| params[:admin] == true } end class MovieOptionalAttributeContentsWithParamsSerializer include FastJsonapi::ObjectSerializer set_type :movie attributes :name attribute :director do |record, params| data = {} data[:first_name] = 'steven' data[:last_name] = 'spielberg' if params[:admin] data end end end # Namespaced MovieSerializer before(:context) do # namespaced model stub module AppName module V1 class MovieSerializer include FastJsonapi::ObjectSerializer # to test if compute_serializer_name works end end end end # Movie and Actor struct before(:context) do MovieStruct = Struct.new( :id, :name, :release_year, :actor_ids, :actors, :owner_id, :owner, :movie_type_id, :advertising_campaign_id ) ActorStruct = Struct.new(:id, :name, :email, :agency_id, :award_ids) MovieWithoutIdStruct = Struct.new(:name, :release_year) AgencyStruct = Struct.new(:id, :name, :actor_ids) end after(:context) do classes_to_remove = %i[ ActionMovieSerializer GenreMovieSerializer HorrorMovieSerializer Movie MovieSerializer Actor ActorSerializer MovieType MovieTypeSerializer AppName::V1::MovieSerializer MovieStruct ActorStruct MovieWithoutIdStruct HyphenMovieSerializer MovieWithoutIdStructSerializer Agency AgencyStruct AgencySerializer AdvertisingCampaign AdvertisingCampaignSerializer ] classes_to_remove.each do |klass_name| Object.send(:remove_const, klass_name) if Object.constants.include?(klass_name) end end let(:movie_struct) do agency = AgencyStruct actors = [] 3.times.each do |id| actors << ActorStruct.new(id, id.to_s, id.to_s, id, [id]) end m = MovieStruct.new m[:id] = 23 m[:name] = 'struct movie' m[:release_year] = 1987 m[:actor_ids] = [1,2,3] m[:owner_id] = 3 m[:movie_type_id] = 2 m[:actors] = actors m end let(:movie_struct_without_id) do MovieWithoutIdStruct.new('struct without id', 2018) end let(:movie) do m = Movie.new m.id = 232 m.name = 'test movie' m.actor_ids = [1, 2, 3] m.owner_id = 3 m.movie_type_id = 1 m end let(:actor) do Actor.new.tap do |a| a.id = 234 a.name = 'test actor' a.email = 'test@test.com' a.agency_id = 432 end end let(:movie_type) do movie mt = MovieType.new mt.id = movie.movie_type_id mt.name = 'Foreign Thriller' mt.movie_ids = [movie.id] mt end let(:supplier) do s = Supplier.new s.id = 1 s.account_id = 1 s end def build_movies(count) count.times.map do |i| m = Movie.new m.id = i + 1 m.name = 'test movie' m.actor_ids = [1, 2, 3] m.owner_id = 3 m.movie_type_id = 1 m end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/shared/contexts/ams_group_context.rb
spec/shared/contexts/ams_group_context.rb
RSpec.shared_context 'ams group class' do before(:context) do # models class AMSPerson < ActiveModelSerializers::Model attr_accessor :id, :first_name, :last_name end class AMSGroup < ActiveModelSerializers::Model attr_accessor :id, :name, :groupees end # serializers class AMSPersonSerializer < ActiveModel::Serializer type 'person' attributes :first_name, :last_name end class AMSGroupSerializer < ActiveModel::Serializer type 'group' attributes :name has_many :groupees end end after(:context) do classes_to_remove = %i[AMSPerson AMSGroup AMSPersonSerializer AMSGroupSerializer] classes_to_remove.each do |klass_name| Object.send(:remove_const, klass_name) if Object.constants.include?(klass_name) end end let(:ams_groups) do group_count = 0 person_count = 0 3.times.map do |i| group = AMSGroup.new group.id = group_count + 1 group.name = "Test Group #{group.id}" group_count = group.id person = AMSPerson.new person.id = person_count + 1 person.last_name = "Last Name #{person.id}" person.first_name = "First Name #{person.id}" person_count = person.id child_group = AMSGroup.new child_group.id = group_count + 1 child_group.name = "Test Group #{child_group.id}" group_count = child_group.id group.groupees = [person, child_group] group end end let(:ams_person) do ams_person = AMSPerson.new ams_person.id = 3 ams_person end def build_ams_groups(count) group_count = 0 person_count = 0 count.times.map do |i| group = AMSGroup.new group.id = group_count + 1 group.name = "Test Group #{group.id}" group_count = group.id person = AMSPerson.new person.id = person_count + 1 person.last_name = "Last Name #{person.id}" person.first_name = "First Name #{person.id}" person_count = person.id child_group = AMSGroup.new child_group.id = group_count + 1 child_group.name = "Test Group #{child_group.id}" group_count = child_group.id group.groupees = [person, child_group] group end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/shared/contexts/js_group_context.rb
spec/shared/contexts/js_group_context.rb
RSpec.shared_context 'jsonapi-serializers group class' do # Person, Group Classes and serializers before(:context) do # models class JSPerson attr_accessor :id, :first_name, :last_name end class JSGroup attr_accessor :id, :name, :groupees # Let's assume groupees can be Person or Group objects end # serializers class JSPersonSerializer include JSONAPI::Serializer attributes :first_name, :last_name def type 'person' end end class JSGroupSerializer include JSONAPI::Serializer attributes :name has_many :groupees def type 'group' end end class JSONAPISSerializerB def initialize(data, options = {}) @options = options.merge(is_collection: true) @data = data end def to_json JSON.fast_generate(to_hash) end def to_hash JSONAPI::Serializer.serialize(@data, @options) end end end after :context do classes_to_remove = %i[ JSPerson JSGroup JSPersonSerializer JSGroupSerializer] classes_to_remove.each do |klass_name| Object.send(:remove_const, klass_name) if Object.constants.include?(klass_name) end end let(:jsonapi_groups) do group_count = 0 person_count = 0 3.times.map do |i| group = JSGroup.new group.id = group_count + 1 group.name = "Test Group #{group.id}" group_count = group.id person = JSPerson.new person.id = person_count + 1 person.last_name = "Last Name #{person.id}" person.first_name = "First Name #{person.id}" person_count = person.id child_group = JSGroup.new child_group.id = group_count + 1 child_group.name = "Test Group #{child_group.id}" group_count = child_group.id group.groupees = [person, child_group] group end end let(:jsonapis_person) do person = JSPerson.new person.id = 3 person end def build_jsonapis_groups(count) group_count = 0 person_count = 0 count.times.map do |i| group = JSGroup.new group.id = group_count + 1 group.name = "Test Group #{group.id}" group_count = group.id person = JSPerson.new person.id = person_count + 1 person.last_name = "Last Name #{person.id}" person.first_name = "First Name #{person.id}" person_count = person.id child_group = JSGroup.new child_group.id = group_count + 1 child_group.name = "Test Group #{child_group.id}" group_count = child_group.id group.groupees = [person, child_group] group end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/spec/shared/contexts/ams_context.rb
spec/shared/contexts/ams_context.rb
RSpec.shared_context 'ams movie class' do before(:context) do # models class AMSModel < ActiveModelSerializers::Model derive_attributes_from_names_and_fix_accessors end class AMSMovieType < AMSModel attributes :id, :name, :movies end class AMSMovie < AMSModel attributes :id, :name, :release_year, :actors, :owner, :movie_type, :advertising_campaign def movie_type mt = AMSMovieType.new mt.id = 1 mt.name = 'Episode' mt.movies = [self] mt end end class AMSAdvertisingCampaign < AMSModel attributes :id, :name, :movie end class AMSAward < AMSModel attributes :id, :title, :actor end class AMSAgency < AMSModel attributes :id, :name, :actors end class AMSActor < AMSModel attributes :id, :name, :email, :agency, :awards, :agency_id def agency AMSAgency.new.tap do |a| a.id = agency_id a.name = "Test Agency #{agency_id}" end end def award_ids [id * 9, id * 9 + 1] end def awards award_ids.map do |i| AMSAward.new.tap do |a| a.id = i a.title = "Test Award #{i}" end end end end class AMSUser < AMSModel attributes :id, :name end class AMSMovieType < AMSModel attributes :id, :name end # serializers class AMSAwardSerializer < ActiveModel::Serializer type 'award' attributes :id, :title belongs_to :actor end class AMSAgencySerializer < ActiveModel::Serializer type 'agency' attributes :id, :name belongs_to :state has_many :actors end class AMSActorSerializer < ActiveModel::Serializer type 'actor' attributes :name, :email belongs_to :agency, serializer: ::AMSAgencySerializer has_many :awards, serializer: ::AMSAwardSerializer end class AMSUserSerializer < ActiveModel::Serializer type 'user' attributes :name end class AMSMovieTypeSerializer < ActiveModel::Serializer type 'movie_type' attributes :name has_many :movies end class AMSAdvertisingCampaignSerializer < ActiveModel::Serializer type 'advertising_campaign' attributes :name end class AMSMovieSerializer < ActiveModel::Serializer type 'movie' attributes :name, :release_year has_many :actors has_one :owner belongs_to :movie_type has_one :advertising_campaign end end after(:context) do classes_to_remove = %i[AMSMovie AMSMovieSerializer] classes_to_remove.each do |klass_name| Object.send(:remove_const, klass_name) if Object.constants.include?(klass_name) end end let(:ams_actors) do 3.times.map do |i| a = AMSActor.new a.id = i + 1 a.name = "Test #{a.id}" a.email = "test#{a.id}@test.com" a.agency_id = i a end end let(:ams_user) do ams_user = AMSUser.new ams_user.id = 3 ams_user end let(:ams_movie_type) do ams_movie_type = AMSMovieType.new ams_movie_type.id = 1 ams_movie_type.name = 'episode' ams_movie_type end let(:ams_advertising_campaign) do campaign = AMSAdvertisingCampaign.new campaign.id = 1 campaign.name = "Movie is incredible!!" campaign end def build_ams_movies(count) count.times.map do |i| m = AMSMovie.new m.id = i + 1 m.name = 'test movie' m.actors = ams_actors m.owner = ams_user m.movie_type = ams_movie_type m.advertising_campaign = ams_advertising_campaign m end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi.rb
lib/fast_jsonapi.rb
# frozen_string_literal: true module FastJsonapi require 'fast_jsonapi/object_serializer' if defined?(::Rails) require 'fast_jsonapi/railtie' elsif defined?(::ActiveRecord) require 'extensions/has_one' end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/version.rb
lib/fast_jsonapi/version.rb
module FastJsonapi VERSION = "1.5" end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/relationship.rb
lib/fast_jsonapi/relationship.rb
module FastJsonapi class Relationship attr_reader :key, :name, :id_method_name, :record_type, :object_method_name, :object_block, :serializer, :relationship_type, :cached, :polymorphic, :conditional_proc, :transform_method, :links, :lazy_load_data def initialize( key:, name:, id_method_name:, record_type:, object_method_name:, object_block:, serializer:, relationship_type:, cached: false, polymorphic:, conditional_proc:, transform_method:, links:, lazy_load_data: false ) @key = key @name = name @id_method_name = id_method_name @record_type = record_type @object_method_name = object_method_name @object_block = object_block @serializer = serializer @relationship_type = relationship_type @cached = cached @polymorphic = polymorphic @conditional_proc = conditional_proc @transform_method = transform_method @links = links || {} @lazy_load_data = lazy_load_data end def serialize(record, serialization_params, output_hash) if include_relationship?(record, serialization_params) empty_case = relationship_type == :has_many ? [] : nil output_hash[key] = {} unless lazy_load_data output_hash[key][:data] = ids_hash_from_record_and_relationship(record, serialization_params) || empty_case end add_links_hash(record, serialization_params, output_hash) if links.present? end end def fetch_associated_object(record, params) return object_block.call(record, params) unless object_block.nil? record.send(object_method_name) end def include_relationship?(record, serialization_params) if conditional_proc.present? conditional_proc.call(record, serialization_params) else true end end private def ids_hash_from_record_and_relationship(record, params = {}) return ids_hash( fetch_id(record, params) ) unless polymorphic return unless associated_object = fetch_associated_object(record, params) return associated_object.map do |object| id_hash_from_record object, polymorphic end if associated_object.respond_to? :map id_hash_from_record associated_object, polymorphic end def id_hash_from_record(record, record_types) # memoize the record type within the record_types dictionary, then assigning to record_type: associated_record_type = record_types[record.class] ||= run_key_transform(record.class.name.demodulize.underscore) id_hash(record.id, associated_record_type) end def ids_hash(ids) return ids.map { |id| id_hash(id, record_type) } if ids.respond_to? :map id_hash(ids, record_type) # ids variable is just a single id here end def id_hash(id, record_type, default_return=false) if id.present? { id: id.to_s, type: record_type } else default_return ? { id: nil, type: record_type } : nil end end def fetch_id(record, params) if object_block.present? object = object_block.call(record, params) return object.map { |item| item.public_send(id_method_name) } if object.respond_to? :map return object.try(id_method_name) end record.public_send(id_method_name) end def add_links_hash(record, params, output_hash) output_hash[key][:links] = links.each_with_object({}) do |(key, method), hash| Link.new(key: key, method: method).serialize(record, params, hash)\ end end def run_key_transform(input) if self.transform_method.present? input.to_s.send(*self.transform_method).to_sym else input.to_sym end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/attribute.rb
lib/fast_jsonapi/attribute.rb
module FastJsonapi class Attribute attr_reader :key, :method, :conditional_proc def initialize(key:, method:, options: {}) @key = key @method = method @conditional_proc = options[:if] end def serialize(record, serialization_params, output_hash) if include_attribute?(record, serialization_params) output_hash[key] = if method.is_a?(Proc) method.arity.abs == 1 ? method.call(record) : method.call(record, serialization_params) else record.public_send(method) end end end def include_attribute?(record, serialization_params) if conditional_proc.present? conditional_proc.call(record, serialization_params) else true end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/serialization_core.rb
lib/fast_jsonapi/serialization_core.rb
# frozen_string_literal: true require 'active_support/concern' require 'fast_jsonapi/multi_to_json' module FastJsonapi MandatoryField = Class.new(StandardError) module SerializationCore extend ActiveSupport::Concern included do class << self attr_accessor :attributes_to_serialize, :relationships_to_serialize, :cachable_relationships_to_serialize, :uncachable_relationships_to_serialize, :transform_method, :record_type, :record_id, :cache_length, :race_condition_ttl, :cached, :data_links, :meta_to_serialize end end class_methods do def id_hash(id, record_type, default_return=false) if id.present? { id: id.to_s, type: record_type } else default_return ? { id: nil, type: record_type } : nil end end def links_hash(record, params = {}) data_links.each_with_object({}) do |(_k, link), hash| link.serialize(record, params, hash) end end def attributes_hash(record, fieldset = nil, params = {}) attributes = attributes_to_serialize attributes = attributes.slice(*fieldset) if fieldset.present? attributes.each_with_object({}) do |(_k, attribute), hash| attribute.serialize(record, params, hash) end end def relationships_hash(record, relationships = nil, fieldset = nil, params = {}) relationships = relationships_to_serialize if relationships.nil? relationships = relationships.slice(*fieldset) if fieldset.present? relationships.each_with_object({}) do |(_k, relationship), hash| relationship.serialize(record, params, hash) end end def meta_hash(record, params = {}) meta_to_serialize.call(record, params) end def record_hash(record, fieldset, params = {}) if cached record_hash = Rails.cache.fetch(record.cache_key, expires_in: cache_length, race_condition_ttl: race_condition_ttl) do temp_hash = id_hash(id_from_record(record), record_type, true) temp_hash[:attributes] = attributes_hash(record, fieldset, params) if attributes_to_serialize.present? temp_hash[:relationships] = {} temp_hash[:relationships] = relationships_hash(record, cachable_relationships_to_serialize, fieldset, params) if cachable_relationships_to_serialize.present? temp_hash[:links] = links_hash(record, params) if data_links.present? temp_hash end record_hash[:relationships] = record_hash[:relationships].merge(relationships_hash(record, uncachable_relationships_to_serialize, fieldset, params)) if uncachable_relationships_to_serialize.present? record_hash[:meta] = meta_hash(record, params) if meta_to_serialize.present? record_hash else record_hash = id_hash(id_from_record(record), record_type, true) record_hash[:attributes] = attributes_hash(record, fieldset, params) if attributes_to_serialize.present? record_hash[:relationships] = relationships_hash(record, nil, fieldset, params) if relationships_to_serialize.present? record_hash[:links] = links_hash(record, params) if data_links.present? record_hash[:meta] = meta_hash(record, params) if meta_to_serialize.present? record_hash end end def id_from_record(record) return record_id.call(record) if record_id.is_a?(Proc) return record.send(record_id) if record_id raise MandatoryField, 'id is a mandatory field in the jsonapi spec' unless record.respond_to?(:id) record.id end # Override #to_json for alternative implementation def to_json(payload) FastJsonapi::MultiToJson.to_json(payload) if payload.present? end def parse_include_item(include_item) return [include_item.to_sym] unless include_item.to_s.include?('.') include_item.to_s.split('.').map { |item| item.to_sym } end def remaining_items(items) return unless items.size > 1 items_copy = items.dup items_copy.delete_at(0) [items_copy.join('.').to_sym] end # includes handler def get_included_records(record, includes_list, known_included_objects, fieldsets, params = {}) return unless includes_list.present? includes_list.sort.each_with_object([]) do |include_item, included_records| items = parse_include_item(include_item) items.each do |item| next unless relationships_to_serialize && relationships_to_serialize[item] relationship_item = relationships_to_serialize[item] next unless relationship_item.include_relationship?(record, params) unless relationship_item.polymorphic.is_a?(Hash) record_type = relationship_item.record_type serializer = relationship_item.serializer.to_s.constantize end relationship_type = relationship_item.relationship_type included_objects = relationship_item.fetch_associated_object(record, params) next if included_objects.blank? included_objects = [included_objects] unless relationship_type == :has_many included_objects.each do |inc_obj| if relationship_item.polymorphic.is_a?(Hash) record_type = inc_obj.class.name.demodulize.underscore serializer = self.compute_serializer_name(inc_obj.class.name.demodulize.to_sym).to_s.constantize end if remaining_items(items) serializer_records = serializer.get_included_records(inc_obj, remaining_items(items), known_included_objects, fieldsets, params) included_records.concat(serializer_records) unless serializer_records.empty? end code = "#{record_type}_#{serializer.id_from_record(inc_obj)}" next if known_included_objects.key?(code) known_included_objects[code] = inc_obj included_records << serializer.record_hash(inc_obj, fieldsets[serializer.record_type], params) end end end end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/multi_to_json.rb
lib/fast_jsonapi/multi_to_json.rb
# frozen_string_literal: true require 'logger' # Usage: # class Movie # def to_json(payload) # FastJsonapi::MultiToJson.to_json(payload) # end # end module FastJsonapi module MultiToJson # Result object pattern is from https://johnnunemaker.com/resilience-in-ruby/ # e.g. https://github.com/github/github-ds/blob/fbda5389711edfb4c10b6c6bad19311dfcb1bac1/lib/github/result.rb class Result def initialize(*rescued_exceptions) @rescued_exceptions = if rescued_exceptions.empty? [StandardError] else rescued_exceptions end @value = yield @error = nil rescue *rescued_exceptions => e @error = e end def ok? @error.nil? end def value! if ok? @value else raise @error end end def rescue return self if ok? Result.new(*@rescued_exceptions) { yield(@error) } end end def self.logger(device=nil) return @logger = Logger.new(device) if device @logger ||= Logger.new(IO::NULL) end # Encoder-compatible with default MultiJSON adapters and defaults def self.to_json_method encode_method = String.new(%(def _fast_to_json(object)\n )) encode_method << Result.new(LoadError) { require 'oj' %(::Oj.dump(object, mode: :compat, time_format: :ruby, use_to_json: true)) }.rescue { require 'yajl' %(::Yajl::Encoder.encode(object)) }.rescue { require 'jrjackson' unless defined?(::JrJackson) %(::JrJackson::Json.dump(object)) }.rescue { require 'json' %(JSON.fast_generate(object, create_additions: false, quirks_mode: true)) }.rescue { require 'gson' %(::Gson::Encoder.new({}).encode(object)) }.rescue { require 'active_support/json/encoding' %(::ActiveSupport::JSON.encode(object)) }.rescue { warn "No JSON encoder found. Falling back to `object.to_json`" %(object.to_json) }.value! encode_method << "\nend" end def self.to_json(object) _fast_to_json(object) rescue NameError define_to_json(FastJsonapi::MultiToJson) _fast_to_json(object) end def self.define_to_json(receiver) cl = caller_locations[0] method_body = to_json_method logger.debug { "Defining #{receiver}._fast_to_json as #{method_body.inspect}" } receiver.instance_eval method_body, cl.absolute_path, cl.lineno end def self.reset_to_json! undef :_fast_to_json if method_defined?(:_fast_to_json) logger.debug { "Undefining #{receiver}._fast_to_json" } end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/link.rb
lib/fast_jsonapi/link.rb
module FastJsonapi class Link attr_reader :key, :method def initialize(key:, method:) @key = key @method = method end def serialize(record, serialization_params, output_hash) output_hash[key] = if method.is_a?(Proc) method.arity == 1 ? method.call(record) : method.call(record, serialization_params) else record.public_send(method) end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/railtie.rb
lib/fast_jsonapi/railtie.rb
# frozen_string_literal: true require 'rails/railtie' class Railtie < Rails::Railtie initializer 'fast_jsonapi.active_record' do ActiveSupport.on_load :active_record do require 'extensions/has_one' end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/object_serializer.rb
lib/fast_jsonapi/object_serializer.rb
# frozen_string_literal: true require 'active_support/time' require 'active_support/json' require 'active_support/concern' require 'active_support/inflector' require 'active_support/core_ext/numeric/time' require 'fast_jsonapi/attribute' require 'fast_jsonapi/relationship' require 'fast_jsonapi/link' require 'fast_jsonapi/serialization_core' module FastJsonapi module ObjectSerializer extend ActiveSupport::Concern include SerializationCore SERIALIZABLE_HASH_NOTIFICATION = 'render.fast_jsonapi.serializable_hash' SERIALIZED_JSON_NOTIFICATION = 'render.fast_jsonapi.serialized_json' included do # Set record_type based on the name of the serializer class set_type(reflected_record_type) if reflected_record_type end def initialize(resource, options = {}) process_options(options) @resource = resource end def serializable_hash return hash_for_collection if is_collection?(@resource, @is_collection) hash_for_one_record end alias_method :to_hash, :serializable_hash def hash_for_one_record serializable_hash = { data: nil } serializable_hash[:meta] = @meta if @meta.present? serializable_hash[:links] = @links if @links.present? return serializable_hash unless @resource serializable_hash[:data] = self.class.record_hash(@resource, @fieldsets[self.class.record_type.to_sym], @params) serializable_hash[:included] = self.class.get_included_records(@resource, @includes, @known_included_objects, @fieldsets, @params) if @includes.present? serializable_hash end def hash_for_collection serializable_hash = {} data = [] included = [] fieldset = @fieldsets[self.class.record_type.to_sym] @resource.each do |record| data << self.class.record_hash(record, fieldset, @params) included.concat self.class.get_included_records(record, @includes, @known_included_objects, @fieldsets, @params) if @includes.present? end serializable_hash[:data] = data serializable_hash[:included] = included if @includes.present? serializable_hash[:meta] = @meta if @meta.present? serializable_hash[:links] = @links if @links.present? serializable_hash end def serialized_json ActiveSupport::JSON.encode(serializable_hash) end private def process_options(options) @fieldsets = deep_symbolize(options[:fields].presence || {}) @params = {} return if options.blank? @known_included_objects = {} @meta = options[:meta] @links = options[:links] @is_collection = options[:is_collection] @params = options[:params] || {} raise ArgumentError.new("`params` option passed to serializer must be a hash") unless @params.is_a?(Hash) if options[:include].present? @includes = options[:include].delete_if(&:blank?).map(&:to_sym) self.class.validate_includes!(@includes) end end def deep_symbolize(collection) if collection.is_a? Hash Hash[collection.map do |k, v| [k.to_sym, deep_symbolize(v)] end] elsif collection.is_a? Array collection.map { |i| deep_symbolize(i) } else collection.to_sym end end def is_collection?(resource, force_is_collection = nil) return force_is_collection unless force_is_collection.nil? resource.respond_to?(:size) && !resource.respond_to?(:each_pair) end class_methods do def inherited(subclass) super(subclass) subclass.attributes_to_serialize = attributes_to_serialize.dup if attributes_to_serialize.present? subclass.relationships_to_serialize = relationships_to_serialize.dup if relationships_to_serialize.present? subclass.cachable_relationships_to_serialize = cachable_relationships_to_serialize.dup if cachable_relationships_to_serialize.present? subclass.uncachable_relationships_to_serialize = uncachable_relationships_to_serialize.dup if uncachable_relationships_to_serialize.present? subclass.transform_method = transform_method subclass.cache_length = cache_length subclass.race_condition_ttl = race_condition_ttl subclass.data_links = data_links.dup if data_links.present? subclass.cached = cached subclass.set_type(subclass.reflected_record_type) if subclass.reflected_record_type subclass.meta_to_serialize = meta_to_serialize end def reflected_record_type return @reflected_record_type if defined?(@reflected_record_type) @reflected_record_type ||= begin if self.name.end_with?('Serializer') self.name.split('::').last.chomp('Serializer').underscore.to_sym end end end def set_key_transform(transform_name) mapping = { camel: :camelize, camel_lower: [:camelize, :lower], dash: :dasherize, underscore: :underscore } self.transform_method = mapping[transform_name.to_sym] # ensure that the record type is correctly transformed if record_type set_type(record_type) elsif reflected_record_type set_type(reflected_record_type) end end def run_key_transform(input) if self.transform_method.present? input.to_s.send(*@transform_method).to_sym else input.to_sym end end def use_hyphen warn('DEPRECATION WARNING: use_hyphen is deprecated and will be removed from fast_jsonapi 2.0 use (set_key_transform :dash) instead') set_key_transform :dash end def set_type(type_name) self.record_type = run_key_transform(type_name) end def set_id(id_name = nil, &block) self.record_id = block || id_name end def cache_options(cache_options) self.cached = cache_options[:enabled] || false self.cache_length = cache_options[:cache_length] || 5.minutes self.race_condition_ttl = cache_options[:race_condition_ttl] || 5.seconds end def attributes(*attributes_list, &block) attributes_list = attributes_list.first if attributes_list.first.class.is_a?(Array) options = attributes_list.last.is_a?(Hash) ? attributes_list.pop : {} self.attributes_to_serialize = {} if self.attributes_to_serialize.nil? attributes_list.each do |attr_name| method_name = attr_name key = run_key_transform(method_name) attributes_to_serialize[key] = Attribute.new( key: key, method: block || method_name, options: options ) end end alias_method :attribute, :attributes def add_relationship(relationship) self.relationships_to_serialize = {} if relationships_to_serialize.nil? self.cachable_relationships_to_serialize = {} if cachable_relationships_to_serialize.nil? self.uncachable_relationships_to_serialize = {} if uncachable_relationships_to_serialize.nil? if !relationship.cached self.uncachable_relationships_to_serialize[relationship.name] = relationship else self.cachable_relationships_to_serialize[relationship.name] = relationship end self.relationships_to_serialize[relationship.name] = relationship end def has_many(relationship_name, options = {}, &block) relationship = create_relationship(relationship_name, :has_many, options, block) add_relationship(relationship) end def has_one(relationship_name, options = {}, &block) relationship = create_relationship(relationship_name, :has_one, options, block) add_relationship(relationship) end def belongs_to(relationship_name, options = {}, &block) relationship = create_relationship(relationship_name, :belongs_to, options, block) add_relationship(relationship) end def meta(&block) self.meta_to_serialize = block end def create_relationship(base_key, relationship_type, options, block) name = base_key.to_sym if relationship_type == :has_many base_serialization_key = base_key.to_s.singularize base_key_sym = base_serialization_key.to_sym id_postfix = '_ids' else base_serialization_key = base_key base_key_sym = name id_postfix = '_id' end Relationship.new( key: options[:key] || run_key_transform(base_key), name: name, id_method_name: compute_id_method_name( options[:id_method_name], "#{base_serialization_key}#{id_postfix}".to_sym, block ), record_type: options[:record_type] || run_key_transform(base_key_sym), object_method_name: options[:object_method_name] || name, object_block: block, serializer: compute_serializer_name(options[:serializer] || base_key_sym), relationship_type: relationship_type, cached: options[:cached], polymorphic: fetch_polymorphic_option(options), conditional_proc: options[:if], transform_method: @transform_method, links: options[:links], lazy_load_data: options[:lazy_load_data] ) end def compute_id_method_name(custom_id_method_name, id_method_name_from_relationship, block) if block.present? custom_id_method_name || :id else custom_id_method_name || id_method_name_from_relationship end end def compute_serializer_name(serializer_key) return serializer_key unless serializer_key.is_a? Symbol namespace = self.name.gsub(/()?\w+Serializer$/, '') serializer_name = serializer_key.to_s.classify + 'Serializer' (namespace + serializer_name).to_sym end def fetch_polymorphic_option(options) option = options[:polymorphic] return false unless option.present? return option if option.respond_to? :keys {} end def link(link_name, link_method_name = nil, &block) self.data_links = {} if self.data_links.nil? link_method_name = link_name if link_method_name.nil? key = run_key_transform(link_name) self.data_links[key] = Link.new( key: key, method: block || link_method_name ) end def validate_includes!(includes) return if includes.blank? includes.detect do |include_item| klass = self parse_include_item(include_item).each do |parsed_include| relationships_to_serialize = klass.relationships_to_serialize || {} relationship_to_include = relationships_to_serialize[parsed_include] raise ArgumentError, "#{parsed_include} is not specified as a relationship on #{klass.name}" unless relationship_to_include klass = relationship_to_include.serializer.to_s.constantize unless relationship_to_include.polymorphic.is_a?(Hash) end end end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/instrumentation.rb
lib/fast_jsonapi/instrumentation.rb
require 'fast_jsonapi/instrumentation/serializable_hash' require 'fast_jsonapi/instrumentation/serialized_json'
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/instrumentation/skylight.rb
lib/fast_jsonapi/instrumentation/skylight.rb
require 'fast_jsonapi/instrumentation/skylight/normalizers/serializable_hash' require 'fast_jsonapi/instrumentation/skylight/normalizers/serialized_json'
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/instrumentation/serialized_json.rb
lib/fast_jsonapi/instrumentation/serialized_json.rb
require 'active_support/notifications' module FastJsonapi module ObjectSerializer alias_method :serialized_json_without_instrumentation, :serialized_json def serialized_json ActiveSupport::Notifications.instrument(SERIALIZED_JSON_NOTIFICATION, { name: self.class.name }) do serialized_json_without_instrumentation end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/instrumentation/serializable_hash.rb
lib/fast_jsonapi/instrumentation/serializable_hash.rb
require 'active_support/notifications' module FastJsonapi module ObjectSerializer alias_method :serializable_hash_without_instrumentation, :serializable_hash def serializable_hash ActiveSupport::Notifications.instrument(SERIALIZABLE_HASH_NOTIFICATION, { name: self.class.name }) do serializable_hash_without_instrumentation end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false
Netflix/fast_jsonapi
https://github.com/Netflix/fast_jsonapi/blob/68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7/lib/fast_jsonapi/instrumentation/skylight/normalizers/serialized_json.rb
lib/fast_jsonapi/instrumentation/skylight/normalizers/serialized_json.rb
require 'fast_jsonapi/instrumentation/skylight/normalizers/base' require 'fast_jsonapi/instrumentation/serializable_hash' module FastJsonapi module Instrumentation module Skylight module Normalizers class SerializedJson < SKYLIGHT_NORMALIZER_BASE_CLASS register FastJsonapi::ObjectSerializer::SERIALIZED_JSON_NOTIFICATION CAT = "view.#{FastJsonapi::ObjectSerializer::SERIALIZED_JSON_NOTIFICATION}".freeze def normalize(trace, name, payload) [ CAT, payload[:name], nil ] end end end end end end
ruby
Apache-2.0
68a5515bb33c6ba4f1df4d4f7b51d33eb2bcf3a7
2026-01-04T15:44:27.122992Z
false