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 |
|---|---|---|---|---|---|---|---|---|
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/db/seeds.rb | ruby/sentry-rails/rails-7.0/db/seeds.rb | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: "Star Wars" }, { name: "Lord of the Rings" }])
# Character.create(name: "Luke", movie: movies.first)
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/db/schema.rb | ruby/sentry-rails/rails-7.0/db/schema.rb | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.0].define(version: 2022_04_03_110436) do
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/db/migrate/20220403110436_create_posts.rb | ruby/sentry-rails/rails-7.0/db/migrate/20220403110436_create_posts.rb | class CreatePosts < ActiveRecord::Migration[7.0]
def change
create_table :posts do |t|
t.string :title
t.text :content
t.timestamps
end
end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/test/application_system_test_case.rb | ruby/sentry-rails/rails-7.0/test/application_system_test_case.rb | require "test_helper"
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium, using: :chrome, screen_size: [1400, 1400]
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/test/test_helper.rb | ruby/sentry-rails/rails-7.0/test/test_helper.rb | ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"
class ActiveSupport::TestCase
# Run tests in parallel with specified workers
parallelize(workers: :number_of_processors)
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/test/channels/application_cable/connection_test.rb | ruby/sentry-rails/rails-7.0/test/channels/application_cable/connection_test.rb | require "test_helper"
class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase
# test "connects with cookies" do
# cookies.signed[:user_id] = 42
#
# connect
#
# assert_equal connection.user_id, "42"
# end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/spec/rails_helper.rb | ruby/sentry-rails/rails-7.0/spec/rails_helper.rb | # This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'sentry/test_helper'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
config.include Sentry::TestHelper
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# You can uncomment this line to turn off ActiveRecord support entirely.
# config.use_active_record = false
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, type: :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/spec/spec_helper.rb | ruby/sentry-rails/rails-7.0/spec/spec_helper.rb | # This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# https://relishapp.com/rspec/rspec-core/docs/configuration/zero-monkey-patching-mode
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/spec/requests/welcomes_spec.rb | ruby/sentry-rails/rails-7.0/spec/requests/welcomes_spec.rb | require 'rails_helper'
RSpec.describe "Welcomes", type: :request do
before do
setup_sentry_test
end
after do
teardown_sentry_test
end
describe "GET /" do
it "captures and sends exception to Sentry" do
get "/"
expect(response).to have_http_status(500)
expect(sentry_events.count).to eq(2)
error_event = sentry_events.first
expect(error_event.transaction).to eq("WelcomeController#index")
error = extract_sentry_exceptions(error_event).first
expect(error.type).to eq("ZeroDivisionError")
expect(error_event.tags).to match(counter: 1, request_id: anything)
transaction_event = sentry_events.last
expect(transaction_event.spans.count).to eq(3)
end
end
describe "GET /view_error" do
it "captures and sends exception to Sentry" do
get "/view_error"
expect(response).to have_http_status(500)
expect(sentry_events.count).to eq(2)
error_event = sentry_events.first
expect(error_event.transaction).to eq("WelcomeController#view_error")
error = extract_sentry_exceptions(error_event).first
expect(error.type).to eq("NameError")
expect(error_event.tags).to match(counter: 1, request_id: anything)
transaction_event = sentry_events.last
expect(transaction_event.spans.count).to eq(4)
end
end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/application.rb | ruby/sentry-rails/rails-7.0/config/application.rb | require_relative "boot"
require "rails/all"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module ExampleApp
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 7.0
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/environment.rb | ruby/sentry-rails/rails-7.0/config/environment.rb | # Load the Rails application.
require_relative "application"
# Initialize the Rails application.
Rails.application.initialize!
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/puma.rb | ruby/sentry-rails/rails-7.0/config/puma.rb | # Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers: a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count }
threads min_threads_count, max_threads_count
# Specifies the `worker_timeout` threshold that Puma will use to wait before
# terminating a worker in development environments.
#
worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development"
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT") { 3000 }
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
# Specifies the `pidfile` that Puma will use.
pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked web server processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory.
#
# preload_app!
# Allow puma to be restarted by `bin/rails restart` command.
plugin :tmp_restart
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/routes.rb | ruby/sentry-rails/rails-7.0/config/routes.rb | require "resque/server"
Rails.application.routes.draw do
resources :posts
get '500', to: 'welcome#report_demo'
root to: "welcome#index"
get 'appearance', to: 'welcome#appearance'
get 'connect_trace', to: 'welcome#connect_trace'
get 'view_error', to: 'welcome#view_error'
get 'sidekiq_error', to: 'welcome#sidekiq_error'
get 'resque_error', to: 'welcome#resque_error'
get 'delayed_job_error', to: 'welcome#delayed_job_error'
get 'job_error', to: 'welcome#job_error'
require 'sidekiq/web'
mount Sidekiq::Web => '/sidekiq'
mount Resque::Server.new, at: "/resque"
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/boot.rb | ruby/sentry-rails/rails-7.0/config/boot.rb | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)
require "bundler/setup" # Set up gems listed in the Gemfile.
require "bootsnap/setup" # Speed up boot time by caching expensive operations.
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/initializers/content_security_policy.rb | ruby/sentry-rails/rails-7.0/config/initializers/content_security_policy.rb | # Be sure to restart your server when you modify this file.
# Define an application-wide content security policy
# For further information see the following documentation
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
# Rails.application.configure do
# config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# policy.style_src :self, :https
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
# end
#
# # Generate session nonces for permitted importmap and inline scripts
# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s }
# config.content_security_policy_nonce_directives = %w(script-src)
#
# # Report CSP violations to a specified URI. See:
# # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
# # config.content_security_policy_report_only = true
# end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/initializers/filter_parameter_logging.rb | ruby/sentry-rails/rails-7.0/config/initializers/filter_parameter_logging.rb | # Be sure to restart your server when you modify this file.
# Configure parameters to be filtered from the log file. Use this to limit dissemination of
# sensitive information. See the ActiveSupport::ParameterFilter documentation for supported
# notations and behaviors.
Rails.application.config.filter_parameters += [
:passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn
]
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/initializers/inflections.rb | ruby/sentry-rails/rails-7.0/config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, "\\1en"
# inflect.singular /^(ox)en/i, "\\1"
# inflect.irregular "person", "people"
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym "RESTful"
# end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/initializers/permissions_policy.rb | ruby/sentry-rails/rails-7.0/config/initializers/permissions_policy.rb | # Define an application-wide HTTP permissions policy. For further
# information see https://developers.google.com/web/updates/2018/06/feature-policy
#
# Rails.application.config.permissions_policy do |f|
# f.camera :none
# f.gyroscope :none
# f.microphone :none
# f.usb :none
# f.fullscreen :self
# f.payment :self, "https://secure.example.com"
# end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/initializers/assets.rb | ruby/sentry-rails/rails-7.0/config/initializers/assets.rb | # Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = "1.0"
# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in the app/assets
# folder are already added.
# Rails.application.config.assets.precompile += %w( admin.js admin.css )
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/initializers/sentry.rb | ruby/sentry-rails/rails-7.0/config/initializers/sentry.rb | Sentry.init do |config|
config.breadcrumbs_logger = [:active_support_logger]
config.background_worker_threads = 0
config.send_default_pii = true
config.traces_sample_rate = 1.0 # set a float between 0.0 and 1.0 to enable performance monitoring
config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472'
config.release = `git branch --show-current`
config.include_local_variables = true
# you can use the pre-defined job for the async callback
#
# config.async = lambda do |event, hint|
# Sentry::SendEventJob.perform_later(event, hint)
# end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/environments/test.rb | ruby/sentry-rails/rails-7.0/config/environments/test.rb | require "active_support/core_ext/integer/time"
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Turn false under Spring and add config.action_view.cache_template_loading = true.
config.cache_classes = true
# Eager loading loads your whole application. When running a single test locally,
# this probably isn't necessary. It's a good idea to do in a continuous integration
# system, or in some way before deploying your code.
config.eager_load = ENV["CI"].present?
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=#{1.hour.to_i}"
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.cache_store = :null_store
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = true
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Store uploaded files on the local file system in a temporary directory.
config.active_storage.service = :test
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raise exceptions for disallowed deprecations.
config.active_support.disallowed_deprecation = :raise
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Raises error for missing translations.
# config.i18n.raise_on_missing_translations = true
# Annotate rendered view with file names.
# config.action_view.annotate_rendered_view_with_filenames = true
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/environments/development.rb | ruby/sentry-rails/rails-7.0/config/environments/development.rb | require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded any time
# it changes. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable server timing
config.server_timing = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join("tmp/caching-dev.txt").exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise exceptions for disallowed deprecations.
config.active_support.disallowed_deprecation = :raise
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.i18n.raise_on_missing_translations = true
# Annotate rendered view with file names.
# config.action_view.annotate_rendered_view_with_filenames = true
# Uncomment if you wish to allow Action Cable access from any origin.
# config.action_cable.disable_request_forgery_protection = true
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-7.0/config/environments/production.rb | ruby/sentry-rails/rails-7.0/config/environments/production.rb | require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.asset_host = "http://assets.example.com"
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache
# config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = "wss://example.com/cable"
# config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Include generic and useful information about system operation, but avoid logging too much
# information to avoid inadvertent exposure of personally identifiable information (PII).
config.log_level = :info
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "example_app_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Don't log any deprecations.
config.active_support.report_deprecations = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require "syslog/logger"
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new "app-name")
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/minimum-rails/app.rb | ruby/sentry-rails/minimum-rails/app.rb | require "bundler/inline"
gemfile(true) do
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '> 2.6'
gem 'sentry-rails', path: "../../"
gem 'railties', '~> 6.0.0'
end
require "action_view/railtie"
require "action_controller/railtie"
require 'sentry-rails'
Sentry.init do |config|
config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472'
config.sdk_logger = Logger.new($stdout)
end
ActiveSupport::Deprecation.silenced = true
class TestApp < Rails::Application
end
class TestController < ActionController::Base
include Rails.application.routes.url_helpers
def exception
raise "foo"
end
end
def app
return @app if @app
app = Class.new(TestApp) do
def self.name
"RailsTestApp"
end
end
app.config.root = __dir__
app.config.hosts = nil
app.config.consider_all_requests_local = false
app.config.logger = Logger.new($stdout)
app.config.log_level = :debug
Rails.logger = app.config.logger
app.routes.append do
get "/exception" => "test#exception"
end
app.initialize!
Rails.application = app
@app = app
app
end
require "rack/test"
include Rack::Test::Methods
get "/exception"
sleep(2) # wait for the background_worker
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/app/jobs/application_job.rb | ruby/sentry-rails/rails-8.0/app/jobs/application_job.rb | class ApplicationJob < ActiveJob::Base
# Automatically retry jobs that encountered a deadlock
# retry_on ActiveRecord::Deadlocked
# Most jobs are safe to ignore if the underlying records are no longer available
# discard_on ActiveJob::DeserializationError
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/app/jobs/error_job.rb | ruby/sentry-rails/rails-8.0/app/jobs/error_job.rb | class ErrorJob < ApplicationJob
queue_as :default
def perform(*args)
foo
end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/app/helpers/application_helper.rb | ruby/sentry-rails/rails-8.0/app/helpers/application_helper.rb | module ApplicationHelper
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/app/controllers/application_controller.rb | ruby/sentry-rails/rails-8.0/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
# Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has.
allow_browser versions: :modern
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/app/models/application_record.rb | ruby/sentry-rails/rails-8.0/app/models/application_record.rb | class ApplicationRecord < ActiveRecord::Base
primary_abstract_class
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/app/mailers/application_mailer.rb | ruby/sentry-rails/rails-8.0/app/mailers/application_mailer.rb | class ApplicationMailer < ActionMailer::Base
default from: "from@example.com"
layout "mailer"
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/db/seeds.rb | ruby/sentry-rails/rails-8.0/db/seeds.rb | # This file should ensure the existence of records required to run the application in every environment (production,
# development, test). The code here should be idempotent so that it can be executed at any point in every environment.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Example:
#
# ["Action", "Comedy", "Drama", "Horror"].each do |genre_name|
# MovieGenre.find_or_create_by!(name: genre_name)
# end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/db/queue_schema.rb | ruby/sentry-rails/rails-8.0/db/queue_schema.rb | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.0].define(version: 1) do
create_table "solid_queue_blocked_executions", force: :cascade do |t|
t.bigint "job_id", null: false
t.string "queue_name", null: false
t.integer "priority", default: 0, null: false
t.string "concurrency_key", null: false
t.datetime "expires_at", null: false
t.datetime "created_at", null: false
t.index ["concurrency_key", "priority", "job_id"], name: "index_solid_queue_blocked_executions_for_release"
t.index ["expires_at", "concurrency_key"], name: "index_solid_queue_blocked_executions_for_maintenance"
t.index ["job_id"], name: "index_solid_queue_blocked_executions_on_job_id", unique: true
end
create_table "solid_queue_claimed_executions", force: :cascade do |t|
t.bigint "job_id", null: false
t.bigint "process_id"
t.datetime "created_at", null: false
t.index ["job_id"], name: "index_solid_queue_claimed_executions_on_job_id", unique: true
t.index ["process_id", "job_id"], name: "index_solid_queue_claimed_executions_on_process_id_and_job_id"
end
create_table "solid_queue_failed_executions", force: :cascade do |t|
t.bigint "job_id", null: false
t.text "error"
t.datetime "created_at", null: false
t.index ["job_id"], name: "index_solid_queue_failed_executions_on_job_id", unique: true
end
create_table "solid_queue_jobs", force: :cascade do |t|
t.string "queue_name", null: false
t.string "class_name", null: false
t.text "arguments"
t.integer "priority", default: 0, null: false
t.string "active_job_id"
t.datetime "scheduled_at"
t.datetime "finished_at"
t.string "concurrency_key"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["active_job_id"], name: "index_solid_queue_jobs_on_active_job_id"
t.index ["class_name"], name: "index_solid_queue_jobs_on_class_name"
t.index ["finished_at"], name: "index_solid_queue_jobs_on_finished_at"
t.index ["queue_name", "finished_at"], name: "index_solid_queue_jobs_for_filtering"
t.index ["scheduled_at", "finished_at"], name: "index_solid_queue_jobs_for_alerting"
end
create_table "solid_queue_pauses", force: :cascade do |t|
t.string "queue_name", null: false
t.datetime "created_at", null: false
t.index ["queue_name"], name: "index_solid_queue_pauses_on_queue_name", unique: true
end
create_table "solid_queue_processes", force: :cascade do |t|
t.string "kind", null: false
t.datetime "last_heartbeat_at", null: false
t.bigint "supervisor_id"
t.integer "pid", null: false
t.string "hostname"
t.text "metadata"
t.datetime "created_at", null: false
t.string "name", null: false
t.index ["last_heartbeat_at"], name: "index_solid_queue_processes_on_last_heartbeat_at"
t.index ["name", "supervisor_id"], name: "index_solid_queue_processes_on_name_and_supervisor_id", unique: true
t.index ["supervisor_id"], name: "index_solid_queue_processes_on_supervisor_id"
end
create_table "solid_queue_ready_executions", force: :cascade do |t|
t.bigint "job_id", null: false
t.string "queue_name", null: false
t.integer "priority", default: 0, null: false
t.datetime "created_at", null: false
t.index ["job_id"], name: "index_solid_queue_ready_executions_on_job_id", unique: true
t.index ["priority", "job_id"], name: "index_solid_queue_poll_all"
t.index ["queue_name", "priority", "job_id"], name: "index_solid_queue_poll_by_queue"
end
create_table "solid_queue_recurring_executions", force: :cascade do |t|
t.bigint "job_id", null: false
t.string "task_key", null: false
t.datetime "run_at", null: false
t.datetime "created_at", null: false
t.index ["job_id"], name: "index_solid_queue_recurring_executions_on_job_id", unique: true
t.index ["task_key", "run_at"], name: "index_solid_queue_recurring_executions_on_task_key_and_run_at", unique: true
end
create_table "solid_queue_recurring_tasks", force: :cascade do |t|
t.string "key", null: false
t.string "schedule", null: false
t.string "command", limit: 2048
t.string "class_name"
t.text "arguments"
t.string "queue_name"
t.integer "priority", default: 0
t.boolean "static", default: true, null: false
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["key"], name: "index_solid_queue_recurring_tasks_on_key", unique: true
t.index ["static"], name: "index_solid_queue_recurring_tasks_on_static"
end
create_table "solid_queue_scheduled_executions", force: :cascade do |t|
t.bigint "job_id", null: false
t.string "queue_name", null: false
t.integer "priority", default: 0, null: false
t.datetime "scheduled_at", null: false
t.datetime "created_at", null: false
t.index ["job_id"], name: "index_solid_queue_scheduled_executions_on_job_id", unique: true
t.index ["scheduled_at", "priority", "job_id"], name: "index_solid_queue_dispatch_all"
end
create_table "solid_queue_semaphores", force: :cascade do |t|
t.string "key", null: false
t.integer "value", default: 1, null: false
t.datetime "expires_at", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["expires_at"], name: "index_solid_queue_semaphores_on_expires_at"
t.index ["key", "value"], name: "index_solid_queue_semaphores_on_key_and_value"
t.index ["key"], name: "index_solid_queue_semaphores_on_key", unique: true
end
add_foreign_key "solid_queue_blocked_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_claimed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_failed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_ready_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_recurring_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_scheduled_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/db/cache_schema.rb | ruby/sentry-rails/rails-8.0/db/cache_schema.rb | # frozen_string_literal: true
ActiveRecord::Schema[7.2].define(version: 1) do
create_table "solid_cache_entries", force: :cascade do |t|
t.binary "key", limit: 1024, null: false
t.binary "value", limit: 536870912, null: false
t.datetime "created_at", null: false
t.integer "key_hash", limit: 8, null: false
t.integer "byte_size", limit: 4, null: false
t.index ["byte_size"], name: "index_solid_cache_entries_on_byte_size"
t.index ["key_hash", "byte_size"], name: "index_solid_cache_entries_on_key_hash_and_byte_size"
t.index ["key_hash"], name: "index_solid_cache_entries_on_key_hash", unique: true
end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/db/schema.rb | ruby/sentry-rails/rails-8.0/db/schema.rb | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.0].define(version: 0) do
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/db/cable_schema.rb | ruby/sentry-rails/rails-8.0/db/cable_schema.rb | ActiveRecord::Schema[7.1].define(version: 1) do
create_table "solid_cable_messages", force: :cascade do |t|
t.binary "channel", limit: 1024, null: false
t.binary "payload", limit: 536870912, null: false
t.datetime "created_at", null: false
t.integer "channel_hash", limit: 8, null: false
t.index ["channel"], name: "index_solid_cable_messages_on_channel"
t.index ["channel_hash"], name: "index_solid_cable_messages_on_channel_hash"
t.index ["created_at"], name: "index_solid_cable_messages_on_created_at"
end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/test/application_system_test_case.rb | ruby/sentry-rails/rails-8.0/test/application_system_test_case.rb | require "test_helper"
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
driven_by :selenium, using: :headless_chrome, screen_size: [ 1400, 1400 ]
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/test/test_helper.rb | ruby/sentry-rails/rails-8.0/test/test_helper.rb | ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"
module ActiveSupport
class TestCase
# Run tests in parallel with specified workers
parallelize(workers: :number_of_processors)
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/test/jobs/error_job_test.rb | ruby/sentry-rails/rails-8.0/test/jobs/error_job_test.rb | require "test_helper"
class ErrorJobTest < ActiveJob::TestCase
# test "the truth" do
# assert true
# end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/application.rb | ruby/sentry-rails/rails-8.0/config/application.rb | require_relative "boot"
require "rails/all"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Rails80
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 8.0
# Please, add to the `ignore` list any other `lib` subdirectories that do
# not contain `.rb` files, or that should not be reloaded or eager loaded.
# Common ones are `templates`, `generators`, or `middleware`, for example.
config.autoload_lib(ignore: %w[assets tasks])
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
end
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/environment.rb | ruby/sentry-rails/rails-8.0/config/environment.rb | # Load the Rails application.
require_relative "application"
# Initialize the Rails application.
Rails.application.initialize!
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/puma.rb | ruby/sentry-rails/rails-8.0/config/puma.rb | # This configuration file will be evaluated by Puma. The top-level methods that
# are invoked here are part of Puma's configuration DSL. For more information
# about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html.
#
# Puma starts a configurable number of processes (workers) and each process
# serves each request in a thread from an internal thread pool.
#
# You can control the number of workers using ENV["WEB_CONCURRENCY"]. You
# should only set this value when you want to run 2 or more workers. The
# default is already 1.
#
# The ideal number of threads per worker depends both on how much time the
# application spends waiting for IO operations and on how much you wish to
# prioritize throughput over latency.
#
# As a rule of thumb, increasing the number of threads will increase how much
# traffic a given process can handle (throughput), but due to CRuby's
# Global VM Lock (GVL) it has diminishing returns and will degrade the
# response time (latency) of the application.
#
# The default is set to 3 threads as it's deemed a decent compromise between
# throughput and latency for the average Rails application.
#
# Any libraries that use a connection pool or another resource pool should
# be configured to provide at least as many connections as the number of
# threads. This includes Active Record's `pool` parameter in `database.yml`.
threads_count = ENV.fetch("RAILS_MAX_THREADS", 3)
threads threads_count, threads_count
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
port ENV.fetch("PORT", 3000)
# Allow puma to be restarted by `bin/rails restart` command.
plugin :tmp_restart
# Run the Solid Queue supervisor inside of Puma for single-server deployments
plugin :solid_queue if ENV["SOLID_QUEUE_IN_PUMA"]
# Specify the PID file. Defaults to tmp/pids/server.pid in development.
# In other environments, only set the PID file if requested.
pidfile ENV["PIDFILE"] if ENV["PIDFILE"]
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/routes.rb | ruby/sentry-rails/rails-8.0/config/routes.rb | Rails.application.routes.draw do
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
# Can be used by load balancers and uptime monitors to verify that the app is live.
get "up" => "rails/health#show", as: :rails_health_check
# Render dynamic PWA files from app/views/pwa/* (remember to link manifest in application.html.erb)
# get "manifest" => "rails/pwa#manifest", as: :pwa_manifest
# get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker
# Defines the root path route ("/")
# root "posts#index"
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/importmap.rb | ruby/sentry-rails/rails-8.0/config/importmap.rb | # Pin npm packages by running ./bin/importmap
pin "application"
pin "@hotwired/turbo-rails", to: "turbo.min.js"
pin "@hotwired/stimulus", to: "stimulus.min.js"
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js"
pin_all_from "app/javascript/controllers", under: "controllers"
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/boot.rb | ruby/sentry-rails/rails-8.0/config/boot.rb | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)
require "bundler/setup" # Set up gems listed in the Gemfile.
require "bootsnap/setup" # Speed up boot time by caching expensive operations.
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/initializers/content_security_policy.rb | ruby/sentry-rails/rails-8.0/config/initializers/content_security_policy.rb | # Be sure to restart your server when you modify this file.
# Define an application-wide content security policy.
# See the Securing Rails Applications Guide for more information:
# https://guides.rubyonrails.org/security.html#content-security-policy-header
# Rails.application.configure do
# config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# policy.style_src :self, :https
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
# end
#
# # Generate session nonces for permitted importmap, inline scripts, and inline styles.
# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s }
# config.content_security_policy_nonce_directives = %w(script-src style-src)
#
# # Report violations without enforcing the policy.
# # config.content_security_policy_report_only = true
# end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/initializers/filter_parameter_logging.rb | ruby/sentry-rails/rails-8.0/config/initializers/filter_parameter_logging.rb | # Be sure to restart your server when you modify this file.
# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file.
# Use this to limit dissemination of sensitive information.
# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors.
Rails.application.config.filter_parameters += [
:passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc
]
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/initializers/inflections.rb | ruby/sentry-rails/rails-8.0/config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, "\\1en"
# inflect.singular /^(ox)en/i, "\\1"
# inflect.irregular "person", "people"
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym "RESTful"
# end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/initializers/assets.rb | ruby/sentry-rails/rails-8.0/config/initializers/assets.rb | # Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = "1.0"
# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/initializers/sentry.rb | ruby/sentry-rails/rails-8.0/config/initializers/sentry.rb | Sentry.init do |config|
config.breadcrumbs_logger = [:active_support_logger]
config.background_worker_threads = 0
config.send_default_pii = true
config.traces_sample_rate = 1.0 # set a float between 0.0 and 1.0 to enable performance monitoring
config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472'
config.release = `git branch --show-current`
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/environments/development.rb | ruby/sentry-rails/rails-8.0/config/environments/development.rb | require "active_support/core_ext/integer/time"
Rails.application.configure do
config.active_job.queue_adapter = :solid_queue
config.solid_queue.connects_to = { database: { writing: :queue } }
# Settings specified here will take precedence over those in config/application.rb.
# Make code changes take effect immediately without server restart.
config.enable_reloading = true
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable server timing.
config.server_timing = true
# Enable/disable Action Controller caching. By default Action Controller caching is disabled.
# Run rails dev:cache to toggle Action Controller caching.
if Rails.root.join("tmp/caching-dev.txt").exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.public_file_server.headers = { "cache-control" => "public, max-age=#{2.days.to_i}" }
else
config.action_controller.perform_caching = false
end
# Change to :null_store to avoid any caching.
config.cache_store = :memory_store
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Make template changes take effect immediately.
config.action_mailer.perform_caching = false
# Set localhost to be used by links generated in mailer templates.
config.action_mailer.default_url_options = { host: "localhost", port: 3000 }
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Append comments with runtime information tags to SQL queries in logs.
config.active_record.query_log_tags_enabled = true
# Highlight code that enqueued background job in logs.
config.active_job.verbose_enqueue_logs = true
# Raises error for missing translations.
# config.i18n.raise_on_missing_translations = true
# Annotate rendered view with file names.
config.action_view.annotate_rendered_view_with_filenames = true
# Uncomment if you wish to allow Action Cable access from any origin.
# config.action_cable.disable_request_forgery_protection = true
# Raise error when a before_action's only/except options reference missing actions.
config.action_controller.raise_on_missing_callback_actions = true
# Apply autocorrection by RuboCop to files generated by `bin/rails generate`.
# config.generators.apply_rubocop_autocorrect_after_generate!
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-rails/rails-8.0/config/environments/production.rb | ruby/sentry-rails/rails-8.0/config/environments/production.rb | require "active_support/core_ext/integer/time"
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.enable_reloading = false
# Eager load code on boot for better performance and memory savings (ignored by Rake tasks).
config.eager_load = true
# Full error reports are disabled.
config.consider_all_requests_local = false
# Turn on fragment caching in view templates.
config.action_controller.perform_caching = true
# Cache assets for far-future expiry since they are all digest stamped.
config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" }
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.asset_host = "http://assets.example.com"
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Assume all access to the app is happening through a SSL-terminating reverse proxy.
config.assume_ssl = true
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Skip http-to-https redirect for the default health check endpoint.
# config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } }
# Log to STDOUT with the current request id as a default log tag.
config.log_tags = [ :request_id ]
config.logger = ActiveSupport::TaggedLogging.logger(STDOUT)
# Change to "debug" to log everything (including potentially personally-identifiable information!)
config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info")
# Prevent health checks from clogging up the logs.
config.silence_healthcheck_path = "/up"
# Don't log any deprecations.
config.active_support.report_deprecations = false
# Replace the default in-process memory cache store with a durable alternative.
config.cache_store = :solid_cache_store
# Replace the default in-process and non-durable queuing backend for Active Job.
config.active_job.queue_adapter = :solid_queue
config.solid_queue.connects_to = { database: { writing: :queue } }
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Set host to be used by links generated in mailer templates.
config.action_mailer.default_url_options = { host: "example.com" }
# Specify outgoing SMTP server. Remember to add smtp/* credentials via rails credentials:edit.
# config.action_mailer.smtp_settings = {
# user_name: Rails.application.credentials.dig(:smtp, :user_name),
# password: Rails.application.credentials.dig(:smtp, :password),
# address: "smtp.example.com",
# port: 587,
# authentication: :plain
# }
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Only use :id for inspections in production.
config.active_record.attributes_for_inspect = [ :id ]
# Enable DNS rebinding protection and other `Host` header attacks.
# config.hosts = [
# "example.com", # Allow requests from example.com
# /.*\.example\.com/ # Allow requests from subdomains like `www.example.com`
# ]
#
# Skip DNS rebinding protection for the default health check endpoint.
# config.host_authorization = { exclude: ->(request) { request.path == "/up" } }
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
dewski/itunes | https://github.com/dewski/itunes/blob/55bfe21926c60b01665dd4b9fecb6ec57279e9cb/spec/itunes_spec.rb | spec/itunes_spec.rb | require File.expand_path('../spec_helper', __FILE__)
describe ITunes do
after do
ITunes.reset
end
use_vcr_cassette :record => :new_episodes, :match_requests_on => [:uri, :method]
context "when delegating to a client" do
it "should return the same results as a client" do
ITunes.music('Jose James').should == ITunes::Client.new.music('Jose James')
end
end
describe '.client' do
it 'should return and ITunes::Client' do
ITunes.client.should be_a ITunes::Client
end
end
describe '.respond_to?' do
it "should take an optional argument" do
ITunes.respond_to?(:new, true).should be_true
end
end
describe ".new" do
it "should return an ITunes::Client" do
ITunes.new.should be_a ITunes::Client
end
end
describe ".limit" do
it 'should return the default limit' do
ITunes.limit.should == ITunes::Configuration::DEFAULT_LIMIT
end
end
describe ".limit=" do
it "should set the limit" do
ITunes.limit = 5
ITunes.limit.should == 5
end
end
describe ".adapter" do
it "should instantiate with the default adapter" do
ITunes.adapter.should == Faraday.default_adapter
end
end
describe ".adapter=" do
it "should set the adapter" do
ITunes.adapter = :typhoeus
ITunes.adapter.should == :typhoeus
end
end
describe ".configure" do
ITunes::Configuration::VALID_OPTIONS_KEYS.each do |key|
it "should set the #{key}" do
ITunes.configure do |config|
config.send("#{key}=", key)
ITunes.send(key).should == key
end
end
end
end
end | ruby | MIT | 55bfe21926c60b01665dd4b9fecb6ec57279e9cb | 2026-01-04T17:58:16.478853Z | false |
dewski/itunes | https://github.com/dewski/itunes/blob/55bfe21926c60b01665dd4b9fecb6ec57279e9cb/spec/spec_helper.rb | spec/spec_helper.rb | require 'simplecov'
SimpleCov.start do
add_group 'ITunes', 'lib/itunes'
add_group 'Faraday Middleware', 'lib/faraday'
add_group 'Specs', 'spec'
end
require File.expand_path('../../lib/itunes', __FILE__)
require 'rspec'
require 'vcr'
RSpec.configure do |c|
c.extend VCR::RSpec::Macros
end
VCR.config do |c|
c.cassette_library_dir = 'spec/fixtures'
c.stub_with :webmock
end
| ruby | MIT | 55bfe21926c60b01665dd4b9fecb6ec57279e9cb | 2026-01-04T17:58:16.478853Z | false |
dewski/itunes | https://github.com/dewski/itunes/blob/55bfe21926c60b01665dd4b9fecb6ec57279e9cb/spec/itunes/client_spec.rb | spec/itunes/client_spec.rb | require 'spec_helper'
describe ITunes::Client do
before(:each) do
@client = ITunes::Client.new
end
use_vcr_cassette :record => :new_episodes, :match_requests_on => [:uri, :method]
describe ".lookup" do
it "should return results for valid ids" do
item = @client.lookup('396405320')
item.results.first.collection_name.should == 'Hold it Down - Single'
item.results.first.primary_genre_name == 'Dance'
end
describe "when passing an id_type other than amg or upc" do
it "should raise an error" do
lambda {
@client.lookup('1235', :id_type => :lastfm)
}.should raise_error
end
end
end
describe '.amg_artist' do
it "should return a valid item when passed a single id" do
items = @client.amg_artist('792844')
items.result_count.should == 1
end
it "should return results when passed a comma separated string of ids" do
items = @client.amg_artist('468749,5723')
items.result_count.should == 2
end
it "should return results when passed an array of ids" do
items = @client.amg_artist(['468749','5723'])
items.result_count.should == 2
end
it 'should be aliased as amg_artists' do
@client.amg_artist(['468749','5723']).should == @client.amg_artists(['468749','5723'])
end
end
describe '.amg_album' do
it "should return a valid item when passed a single id" do
items = @client.amg_album('15197')
items.results.first.artist_name.should == 'Wilson Pickett'
end
it "should return results when passed a comma separated string of ids" do
items = @client.amg_album('15197,15198')
items.results.first.artist_name.should == 'Wilson Pickett'
end
it "should return results when passed an array of ids" do
items = @client.amg_album(['15197','15198'])
items.results.first.artist_name.should == 'Wilson Pickett'
end
it 'should be aliased as amg_albums' do
@client.amg_album(['15197','15198']).should == @client.amg_albums(['15197','15198'])
end
end
describe '.upc' do
it "should return a valid item when passed a single id" do
item = @client.upc('5024545486520')
item.results.first.collection_name.should == 'Untrue'
item.results.first.artist_name.should == 'Burial'
end
end
describe '.isbn' do
it 'should return a valid item when passed a single id' do
item = @client.isbn('9780316069359')
item.results.first.kind.should == 'ebook'
item.results.first.track_name.should == 'The Fifth Witness'
end
end
describe "search" do
describe ".all" do
it "should raise an ArgumentError when passed a nil search term" do
lambda {
@client.all(nil)
}.should raise_error
end
it "should raise an ArgumentError when passed an empty string as a search term" do
lambda {
@client.all('')
}.should raise_error
end
it "should accept a limit option" do
response = @client.all('Michael Jackson', :limit => 2)
response.result_count.should == 2
end
it "should ignore the limit when set to 0" do
@client.limit = 0
response = @client.all('Michael Jackson')
response.result_count.should > 0
end
end
describe ".music" do
it "should return music results" do
response = @client.music('Jose James')
response.results.each do |result|
['music-artist', 'music-track', 'album', 'music-video', 'mix', 'song'].should include(result.kind)
end
end
end
describe ".podcast" do
it "should return podcast results" do
response = @client.podcast('Beyondjazz')
response.results.each do |result|
result.kind.should == 'podcast'
end
end
end
describe ".movie" do
it "should return movie results" do
response = @client.movie('Blade Runner')
response.results.each do |result|
result.kind.should == 'feature-movie'
end
end
end
describe ".music_video" do
it "should return music video results" do
response = @client.music_video('Sabotage')
response.results.each do |result|
result.kind.should == 'music-video'
end
end
end
describe ".audiobook" do
it "should return audiobook results" do
response = @client.audiobook('Ernest Hemingway')
response.results.each do |result|
result.wrapper_type.should == 'audiobook'
end
end
end
describe ".short_film" do
it "should return short film results" do
response = @client.short_film('Pixar')
response.results.each do |result|
result.kind.should == 'feature-movie'
end
end
end
describe ".tv_show" do
it "should return tv show results" do
response = @client.tv_show('Lost')
response.results.each do |result|
result.kind.should == 'tv-episode'
end
end
end
describe ".software" do
it "should return tv show results" do
response = @client.software('Doodle Jump')
response.results.each do |result|
['software', 'iPadSoftware', 'macSoftware'].should include(result.kind)
end
end
end
describe ".ebook" do
it "should return ebook results" do
response = @client.ebook('Alice in Wonderland')
response.results.each do |result|
result.kind.should == 'ebook'
end
end
end
end
end | ruby | MIT | 55bfe21926c60b01665dd4b9fecb6ec57279e9cb | 2026-01-04T17:58:16.478853Z | false |
dewski/itunes | https://github.com/dewski/itunes/blob/55bfe21926c60b01665dd4b9fecb6ec57279e9cb/lib/itunes.rb | lib/itunes.rb | require 'faraday_middleware'
require 'itunes/configuration'
require 'itunes/client'
module ITunes
extend Configuration
# Alias for ITunes::Client.new
#
# @return [ITunes::Client]
def self.client(options={})
ITunes::Client.new(options)
end
# Alias for ITunes::Client.new
#
# @return [ITunes::Client]
def self.new(options={})
ITunes::Client.new(options)
end
# Delegate to ITunes::Client
def self.method_missing(method, *args, &block)
return super unless new.respond_to?(method)
new.send(method, *args, &block)
end
def self.respond_to?(method, include_private = false)
new.respond_to?(method, include_private) || super(method, include_private)
end
end
| ruby | MIT | 55bfe21926c60b01665dd4b9fecb6ec57279e9cb | 2026-01-04T17:58:16.478853Z | false |
dewski/itunes | https://github.com/dewski/itunes/blob/55bfe21926c60b01665dd4b9fecb6ec57279e9cb/lib/itunes/version.rb | lib/itunes/version.rb | module ITunes
VERSION = '0.7.0'
end
| ruby | MIT | 55bfe21926c60b01665dd4b9fecb6ec57279e9cb | 2026-01-04T17:58:16.478853Z | false |
dewski/itunes | https://github.com/dewski/itunes/blob/55bfe21926c60b01665dd4b9fecb6ec57279e9cb/lib/itunes/configuration.rb | lib/itunes/configuration.rb | require 'faraday'
require File.expand_path('../version', __FILE__)
module ITunes
# Defines constants and methods related to configuration
module Configuration
# An array of valid keys in the options hash when configuring
VALID_OPTIONS_KEYS = [:adapter, :endpoint, :limit, :user_agent, :request_options].freeze
# The adapter that will be used to connect if none is set
#
# @note The default faraday adapter is Net::HTTP.
DEFAULT_ADAPTER = Faraday.default_adapter
# The endpoint that will be used to connect if none is set
DEFAULT_ENDPOINT = 'https://itunes.apple.com'.freeze
# The user agent that will be sent to the API endpoint if none is set
DEFAULT_USER_AGENT = "ITunes Ruby Gem #{ITunes::VERSION}".freeze
# The default number of results to return from the API
#
# @note The default limit from iTunes is 100.
DEFAULT_LIMIT = nil
# The default request options for Faraday
DEFAULT_REQUEST_OPTIONS = {
:timeout => 5,
:open_timeout => 5
}
# @private
attr_accessor *VALID_OPTIONS_KEYS
# When this module is extended, set all configuration options to their default values
def self.extended(base)
base.reset
end
# Convenience method to allow configuration options to be set in a block
def configure
yield self
end
# Create a hash of options and their values
def options
VALID_OPTIONS_KEYS.inject({}) do |option, key|
option.merge!(key => send(key))
end
end
# Reset all configuration options to defaults
def reset
self.adapter = DEFAULT_ADAPTER
self.endpoint = DEFAULT_ENDPOINT
self.limit = DEFAULT_LIMIT
self.user_agent = DEFAULT_USER_AGENT
self.request_options = nil
self
end
end
end
| ruby | MIT | 55bfe21926c60b01665dd4b9fecb6ec57279e9cb | 2026-01-04T17:58:16.478853Z | false |
dewski/itunes | https://github.com/dewski/itunes/blob/55bfe21926c60b01665dd4b9fecb6ec57279e9cb/lib/itunes/client.rb | lib/itunes/client.rb | require File.expand_path('../request', __FILE__)
module ITunes
class Client
# @private
attr_accessor *Configuration::VALID_OPTIONS_KEYS
# Creates a new Client
def initialize(options={})
options = ITunes.options.merge(options)
Configuration::VALID_OPTIONS_KEYS.each do |key|
send("#{key}=", options[key])
end
end
Dir[File.expand_path('../client/*.rb', __FILE__)].each{|f| require f}
alias :api_endpoint :endpoint
include Request
include Search
include Lookup
end
end
| ruby | MIT | 55bfe21926c60b01665dd4b9fecb6ec57279e9cb | 2026-01-04T17:58:16.478853Z | false |
dewski/itunes | https://github.com/dewski/itunes/blob/55bfe21926c60b01665dd4b9fecb6ec57279e9cb/lib/itunes/request.rb | lib/itunes/request.rb | module ITunes
module Request
# @private
private
# Perform an HTTP GET request
def request(request_type, params)
url = '/WebObjects/MZStoreServices.woa/wa/ws' + request_type
response = connection.get do |req|
req.url url, params
req.options.timeout = Configuration::DEFAULT_REQUEST_OPTIONS[:timeout]
req.options.open_timeout = Configuration::DEFAULT_REQUEST_OPTIONS[:open_timeout]
end
response.body
end
def connection
options = {
:headers => {'Accept' => 'application/json', 'User-Agent' => user_agent},
:url => api_endpoint,
}
Faraday.new(options) do |builder|
builder.use Faraday::Response::Rashify
builder.use Faraday::Response::ParseJson
builder.adapter(adapter)
end
end
end
end
| ruby | MIT | 55bfe21926c60b01665dd4b9fecb6ec57279e9cb | 2026-01-04T17:58:16.478853Z | false |
dewski/itunes | https://github.com/dewski/itunes/blob/55bfe21926c60b01665dd4b9fecb6ec57279e9cb/lib/itunes/client/search.rb | lib/itunes/client/search.rb | module ITunes
module Search
# Performs a music search
# @param [String] term The search term
# @option options [Symbol]
def music(term, options={})
search(term, 'music', options)
end
# Performs a movie search
# @param [String] term The search term
# @option options [Symbol]
def movie(term, options={})
search(term, 'movie', options)
end
# Performs a podcast search
# @param [String] term The search term
# @option options [Symbol]
def podcast(term, options={})
search(term, 'podcast', options)
end
# Performs a music video search
# @param [String] term The search term
# @option options [Symbol]
def music_video(term, options={})
search(term, 'musicVideo', options)
end
# Performs an audiobook search
# @param [String] term The search term
# @option options [Symbol]
def audiobook(term, options={})
search(term, 'audiobook', options)
end
# Performs a short film search
# @param [String] term The search term
# @option options [Symbol]
def short_film(term, options={})
search(term, 'shortFilm', options)
end
# Performs a tv show search
# @param [String] term The search term
# @option options [Symbol]
def tv_show(term, options={})
search(term, 'tvShow', options)
end
# Performs a software search
# @param [String] term The search term
# @option options [Symbol]
def software(term, options={})
search(term, 'software', options)
end
# Performs a ebook search
# @param [String] term The search term
# @option options [Symbol]
def ebook(term, options={})
search(term, 'ebook', options)
end
# Performs a search on all itunes content
# @param [String] term The search term
# @option options [Symbol]
def all(term, options={})
search(term, 'all', options)
end
private
def search(term, media='all', options={})
raise ArgumentError, 'you need to search for something, provide a term.' if term.nil? || term.length == 0
params = { :term => term, :media => media }
if options.has_key?(:limit)
params.merge!(:limit => options.delete(:limit))
elsif limit
params.merge!({ :limit => limit })
end
params.delete(:limit) if params[:limit] && params[:limit] == 0
params.merge!(options)
# clear empty key/value pairs
params.reject! { |key, value| value.nil? }
request('Search', params)
end
end
end | ruby | MIT | 55bfe21926c60b01665dd4b9fecb6ec57279e9cb | 2026-01-04T17:58:16.478853Z | false |
dewski/itunes | https://github.com/dewski/itunes/blob/55bfe21926c60b01665dd4b9fecb6ec57279e9cb/lib/itunes/client/lookup.rb | lib/itunes/client/lookup.rb | module ITunes
module Lookup
ID_TYPES = { :amg_artist => 'amgArtistId', :id => 'id', :amg_album => 'amgAlbumId', :upc => 'upc' }
# Performs a lookup request based on iTunes IDs, UPCs/ EANs, and All Music Guide (AMG) IDs
# @param [String] id
# @option options [Symbol] :id_type used to specify the option type being passed, valid types are: id, upc, amg_artist, amg_album
# @raise [ArgumentError] If an invalid id_type is specified in options
def lookup(id, options={})
id_type = options.delete(:id_type) || :id
raise ArgumentError, 'invalid id_type.' unless ID_TYPES.keys.include?(id_type.to_sym)
warn "#{Kernel.caller.first}: [DEPRECATION] id_type option is deprecated and will be permanently removed in the next major version. Please use ITunes::Lookup methods (amg_artist, amg_album, and upc) instead." unless id_type == :id
perform_lookup(ID_TYPES[id_type.to_sym], id, options)
end
# Performs a lookup request based on an All Music Guide (AMG) Artist ID
# @param [String] id
# @option options [Symbol]
def amg_artist(id, options={})
perform_lookup('amgArtistId', id, options)
end
alias :amg_artists :amg_artist
# Performs a lookup request based on an All Music Guide (AMG) Album ID
# @param [String] id
# @option options [Symbol]
def amg_album(id, options={})
perform_lookup('amgAlbumId', id, options)
end
alias :amg_albums :amg_album
# Performs a lookup request based on a UPC
# @param [String] id
# @option options [Symbol]
def upc(id, options={})
perform_lookup('upc', id, options)
end
# Performs a lookup request based on an ISBN
# @param [String] id
# @option options [Symbol]
def isbn(id, options={})
perform_lookup('isbn', id, options)
end
private
def perform_lookup(id_type, id, options)
id = id.split(',') if id.kind_of?(String)
options.merge!(id_type => id.join(','))
request('Lookup', options)
end
end
end | ruby | MIT | 55bfe21926c60b01665dd4b9fecb6ec57279e9cb | 2026-01-04T17:58:16.478853Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/spec/spec_helper.rb | spec/spec_helper.rb | require 'simplecov'
require 'jsonapi/rspec'
SimpleCov.start do
add_filter '/spec/'
end
SimpleCov.minimum_coverage 90
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.order = :random
config.shared_context_metadata_behavior = :apply_to_host_groups
Kernel.srand config.seed
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/spec/jsonapi/id_spec.rb | spec/jsonapi/id_spec.rb | require 'spec_helper'
RSpec.describe JSONAPI::RSpec, '#have_id' do
it 'succeeds when id matches' do
expect('id' => 'foo').to have_id('foo')
end
it 'fails when id mismatches' do
expect('id' => 'foo').not_to have_id('bar')
end
it 'fails when id is absent' do
expect({}).not_to have_id('foo')
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/spec/jsonapi/type_spec.rb | spec/jsonapi/type_spec.rb | require 'spec_helper'
RSpec.describe JSONAPI::RSpec, '#have_type' do
it 'succeeds when type matches' do
expect('type' => 'foo').to have_type('foo')
end
it 'succeeds when expectation is symbol' do
expect('type' => 'foo').to have_type(:foo)
end
it 'succeeds when type is a symbol' do
expect('type' => :foo).to have_type('foo')
end
it 'fails when type mismatches' do
expect('type' => 'foo').not_to have_type('bar')
end
it 'fails when type is absent' do
expect({}).not_to have_type('foo')
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/spec/jsonapi/relationships_spec.rb | spec/jsonapi/relationships_spec.rb | require 'spec_helper'
RSpec.describe JSONAPI::RSpec, '#have_relationship(s)' do
let(:doc) do
{
'relationships' => {
'user' => {
'data' => { 'id' => '1', 'type' => 'user' }
},
'comments' => {
'data' => [
{ 'id' => '1', 'type' => 'comment' },
{ 'id' => '2', 'type' => 'comment' }
]
}
}
}
end
it { expect(doc).not_to have_relationships('user', 'comments', 'authors') }
it { expect(doc).to have_relationships('user', 'comments') }
it { expect(doc).not_to have_relationship('authors') }
it { expect(doc).to have_relationship('user') }
it { expect(doc).to have_relationships('user', 'comments').exactly }
it { expect(doc).not_to have_relationships('comments').exactly }
it do
expect(doc).to have_relationship('user').with_data(
{ 'id' => '1', 'type' => 'user' }
)
end
it do
expect(doc).to have_relationship('comments').with_data(
[
{ 'id' => '1', 'type' => 'comment' },
{ 'id' => '2', 'type' => 'comment' }
]
)
end
context 'with jsonapi indifferent hash enabled' do
before(:all) { RSpec.configuration.jsonapi_indifferent_hash = true }
after(:all) { RSpec.configuration.jsonapi_indifferent_hash = false }
it { expect(doc).to have_relationships(:user, :comments) }
it do
expect(doc).to have_relationship('user').with_data(id: '1', type: :user)
end
it do
expect(doc).to have_relationship('comments').with_data(
[
{ id: '1', type: 'comment' },
{ id: '2', type: 'comment' }
]
)
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/spec/jsonapi/rspec_spec.rb | spec/jsonapi/rspec_spec.rb | require 'securerandom'
require 'spec_helper'
RSpec.describe JSONAPI::RSpec, '#as_indifferent_hash' do
let(:doc) do
{
id: SecureRandom.uuid,
list: [
{ one: 1, 'one + one' => :two }
],
hash: { key: :value, 'another key' => 'another value' }
}
end
it do
expect(JSONAPI::RSpec.as_indifferent_hash(doc)).not_to eq(
JSON.parse(JSON.generate(doc))
)
end
context 'with jsonapi indifferent hash enabled' do
before(:all) { RSpec.configuration.jsonapi_indifferent_hash = true }
after(:all) { RSpec.configuration.jsonapi_indifferent_hash = false }
it do
expect(JSONAPI::RSpec.as_indifferent_hash(doc)).to eq(
JSON.parse(JSON.generate(doc))
)
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/spec/jsonapi/links_spec.rb | spec/jsonapi/links_spec.rb | require 'spec_helper'
RSpec.describe JSONAPI::RSpec do
let(:doc) do
{
'links' => {
'self' => 'self_link',
'related' => 'related_link'
}
}
end
context '#have_link' do
it { expect(doc).to have_link(:self) }
it { expect(doc).to have_link(:self).with_value('self_link') }
it { expect(doc).not_to have_link(:self).with_value('any_link') }
it { expect(doc).not_to have_link(:any) }
end
context '#have_links' do
it { expect(doc).to have_links(:self, :related) }
it { expect(doc).not_to have_links(:self, :other) }
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/spec/jsonapi/attributes_spec.rb | spec/jsonapi/attributes_spec.rb | require 'spec_helper'
RSpec.describe JSONAPI::RSpec do
let(:doc) do
{
'attributes' => {
'one' => 1,
'two' => 2,
'four' => 3,
'six' => { foo: 'bar' }
}
}
end
describe '#have_attribute' do
it { expect(doc).to have_attribute(:one) }
it { expect(doc).not_to have_attribute(:five) }
it { expect(doc).to have_attribute(:one).with_value(1) }
it { expect(doc).not_to have_attribute(:one).with_value(2) }
it { expect(doc).to have_attribute(:six).with_value(foo: 'bar') }
it 'rejects with an appropriate failure message' do
expect { expect(doc).to have_attribute(:three) }
.to raise_error(
RSpec::Expectations::ExpectationNotMetError,
'expected attributes to include `three`. ' \
'Actual attributes were ["one", "two", "four", "six"]'
)
end
it 'fails with a failure message for chained with_value' do
expect { expect(doc).to have_attribute(:one).with_value(2) }
.to raise_error(
RSpec::Expectations::ExpectationNotMetError,
/expected `one` attribute to have value `2` but was `1`/m
)
end
it 'fails with a failure message and diff for chained with_value' do
expect { expect(doc).to have_attribute(:six).with_value(bar: 'baz') }
.to raise_error(
RSpec::Expectations::ExpectationNotMetError,
/expected `six` .* `{:bar=>"baz"}` but was `{:foo=>"bar"}`.*Diff:/m
)
end
end
describe '#have_jsonapi_attributes' do
it { expect(doc).to have_jsonapi_attributes(:one, :two) }
it { expect(doc).not_to have_jsonapi_attributes(:two, :five) }
it { expect(doc).to have_jsonapi_attributes(:one, :two, :four, :six).exactly }
it { expect(doc).not_to have_jsonapi_attributes(:one).exactly }
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/spec/jsonapi/jsonapi_object_spec.rb | spec/jsonapi/jsonapi_object_spec.rb | require 'spec_helper'
RSpec.describe JSONAPI::RSpec, '#have_jsonapi_object' do
context 'when providing no value' do
it 'succeeds when jsonapi object is present' do
expect('jsonapi' => { 'version' => '1.0' }).to have_jsonapi_object
end
it 'fails when jsonapi object is absent' do
expect({}).not_to have_jsonapi_object
end
end
context 'when providing a value' do
context 'with jsonapi indifferent hash enabled' do
before(:all) { RSpec.configuration.jsonapi_indifferent_hash = true }
after(:all) { RSpec.configuration.jsonapi_indifferent_hash = false }
it do
expect('jsonapi' => { 'version' => '1.0' })
.to have_jsonapi_object(version: '1.0')
end
end
it 'succeeds when jsonapi object matches' do
expect('jsonapi' => { 'version' => '1.0' })
.to have_jsonapi_object('version' => '1.0')
end
it 'fails when jsonapi object mismatches' do
expect('jsonapi' => { 'version' => '2.0' })
.not_to have_jsonapi_object('version' => '1.0')
end
it 'fails when jsonapi object is absent' do
expect({}).not_to have_jsonapi_object('version' => '1.0')
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/spec/jsonapi/meta_spec.rb | spec/jsonapi/meta_spec.rb | require 'spec_helper'
RSpec.describe JSONAPI::RSpec, '#have_meta' do
let(:doc) do
{
'meta' => {
'one' => 'I',
'two' => 'II',
'three' => 'III'
}
}
end
context 'when providing no value' do
it 'succeeds when meta is present' do
expect(doc).to have_meta
end
it 'fails when meta is absent' do
expect({}).not_to have_meta
end
end
context 'when providing a value' do
context 'with jsonapi indifferent hash enabled' do
before(:all) { RSpec.configuration.jsonapi_indifferent_hash = true }
after(:all) { RSpec.configuration.jsonapi_indifferent_hash = false }
it do
expect(doc).to have_meta(one: 'I')
end
end
it 'succeeds when meta includes the value' do
expect(doc).to have_meta('one' => 'I')
end
it 'fails when meta does not include the value' do
expect(doc).not_to have_meta('one' => 'II')
end
it 'succeeds when meta exactly matches the value' do
expect(doc).to have_meta({ 'one' => 'I', 'two' => 'II', 'three' => 'III' }).exactly
end
it 'succeeds when meta does not exactly match the value' do
expect(doc).not_to have_meta({ 'one' => 'foo', 'two' => 'II', 'three' => 'III' }).exactly
end
it 'fails when meta is absent' do
expect({}).not_to have_meta(foo: 'bar')
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/spec/jsonapi/errors_spec.rb | spec/jsonapi/errors_spec.rb | require 'spec_helper'
RSpec.describe JSONAPI::RSpec, '#have_error' do
let(:doc) do
{
'errors' => [
{
'status' => '422',
'source' => { 'pointer' => '/data/attributes/firstName' },
'title' => 'Invalid Attribute',
'detail' => 'First name must contain at least three characters.'
}
]
}
end
context 'when providing no value' do
it 'succeeds when errors are present' do
expect(doc).to have_error
end
it 'fails when errors are missing' do
expect({}).not_to have_error
expect({ 'errors' => [] }).not_to have_error
end
end
context 'when providing a value' do
it do
expect(doc).to have_error(
'status' => '422',
'source' => { 'pointer' => '/data/attributes/firstName' }
)
end
it 'fails when meta is absent' do
expect(doc).not_to have_error({ 'status' => '500' })
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/lib/jsonapi/rspec.rb | lib/jsonapi/rspec.rb | require 'json'
require 'rspec/matchers'
require 'rspec/core'
require 'jsonapi/rspec/id'
require 'jsonapi/rspec/type'
require 'jsonapi/rspec/attributes'
require 'jsonapi/rspec/relationships'
require 'jsonapi/rspec/links'
require 'jsonapi/rspec/meta'
require 'jsonapi/rspec/jsonapi_object'
require 'jsonapi/rspec/errors'
RSpec.configure do |c|
c.add_setting :jsonapi_indifferent_hash, default: false
end
module JSONAPI
module RSpec
include Id
include Type
include Attributes
include Relationships
include Links
include Meta
include JsonapiObject
def self.as_indifferent_hash(doc)
return doc unless ::RSpec.configuration.jsonapi_indifferent_hash
if doc.respond_to?(:with_indifferent_access)
return doc.with_indifferent_access
end
JSON.parse(JSON.generate(doc))
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/lib/jsonapi/rspec/attributes.rb | lib/jsonapi/rspec/attributes.rb | module JSONAPI
module RSpec
module Attributes
::RSpec::Matchers.define :have_attribute do |attr_name|
match do |doc|
doc = JSONAPI::RSpec.as_indifferent_hash(doc)
attributes_node = doc['attributes']
return false unless attributes_node
@existing_attributes = attributes_node.keys
@has_attribute = attributes_node.key?(attr_name.to_s)
@actual = attributes_node[attr_name.to_s]
return @actual == @expected if @has_attribute && @should_match_value
@has_attribute
end
chain :with_value do |expected_value|
@should_match_value = true
@expected = expected_value
end
description do
result = "have attribute #{attr_name.inspect}"
result << " with value #{@expected.inspect}" if @should_match_value
result
end
failure_message do |_doc|
if @has_attribute
"expected `#{attr_name}` attribute " \
"to have value `#{@expected}` but was `#{@actual}`"
else
"expected attributes to include `#{attr_name}`. " \
"Actual attributes were #{@existing_attributes}"
end
end
diffable
end
::RSpec::Matchers.define :have_jsonapi_attributes do |*attrs|
match do |actual|
actual = JSONAPI::RSpec.as_indifferent_hash(actual)
return false unless actual.key?('attributes')
counted = (attrs.size == actual['attributes'].size) if @exactly
(attrs.map(&:to_s) - actual['attributes'].keys).empty? &&
(counted == @exactly)
end
chain :exactly do
@exactly = true
end
end
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/lib/jsonapi/rspec/relationships.rb | lib/jsonapi/rspec/relationships.rb | module JSONAPI
module RSpec
module Relationships
::RSpec::Matchers.define :have_relationship do |rel|
match do |actual|
actual = JSONAPI::RSpec.as_indifferent_hash(actual)
return false unless (actual['relationships'] || {}).key?(rel.to_s)
!@data_set || actual['relationships'][rel.to_s]['data'] == @data_val
end
chain :with_data do |val|
@data_set = true
@data_val = JSONAPI::RSpec.as_indifferent_hash(val)
end
failure_message do |actual|
if (actual['relationships'] || {}).key?(rel.to_s)
"expected #{actual['relationships'][rel.to_s]} " \
"to have data #{@data_val}"
else
"expected #{actual} to have relationship #{rel}"
end
end
end
::RSpec::Matchers.define :have_relationships do |*rels|
match do |actual|
actual = JSONAPI::RSpec.as_indifferent_hash(actual)
return false unless actual.key?('relationships')
counted = (rels.size == actual['relationships'].keys.size) if @exactly
rels.map(&:to_s).all? { |rel| actual['relationships'].key?(rel) } \
&& (counted == @exactly)
end
chain :exactly do
@exactly = true
end
end
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/lib/jsonapi/rspec/meta.rb | lib/jsonapi/rspec/meta.rb | module JSONAPI
module RSpec
module Meta
::RSpec::Matchers.define :have_meta do |val|
match do |actual|
actual = JSONAPI::RSpec.as_indifferent_hash(actual)
return false unless actual.key?('meta')
return true unless val
val = JSONAPI::RSpec.as_indifferent_hash(val)
return false unless val <= actual['meta']
!@exactly || (@exactly && val.size == actual['meta'].size)
end
chain :exactly do
@exactly = true
end
end
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/lib/jsonapi/rspec/errors.rb | lib/jsonapi/rspec/errors.rb | module JSONAPI
module RSpec
module Meta
::RSpec::Matchers.define :have_error do |error|
match do |actual|
actual = JSONAPI::RSpec.as_indifferent_hash(actual)
return false unless actual.key?('errors')
return false unless actual['errors'].is_a?(Array)
return true if actual['errors'].any? && error.nil?
error = JSONAPI::RSpec.as_indifferent_hash(error)
actual['errors'].any? { |actual_error| error <= actual_error }
end
end
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/lib/jsonapi/rspec/type.rb | lib/jsonapi/rspec/type.rb | module JSONAPI
module RSpec
module Type
::RSpec::Matchers.define :have_type do |expected|
match do |actual|
JSONAPI::RSpec.as_indifferent_hash(actual)['type'].to_s == expected.to_s
end
end
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/lib/jsonapi/rspec/id.rb | lib/jsonapi/rspec/id.rb | module JSONAPI
module RSpec
module Id
::RSpec::Matchers.define :have_id do |expected|
match do |actual|
JSONAPI::RSpec.as_indifferent_hash(actual)['id'] == expected
end
end
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/lib/jsonapi/rspec/jsonapi_object.rb | lib/jsonapi/rspec/jsonapi_object.rb | module JSONAPI
module RSpec
module JsonapiObject
::RSpec::Matchers.define :have_jsonapi_object do |val|
match do |actual|
actual = JSONAPI::RSpec.as_indifferent_hash(actual)
val = JSONAPI::RSpec.as_indifferent_hash(val)
actual.key?('jsonapi') && (!val || actual['jsonapi'] == val)
end
end
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
jsonapi-rb/jsonapi-rspec | https://github.com/jsonapi-rb/jsonapi-rspec/blob/f3af9a8e2f4e5ae149760e14222b79b8a530f774/lib/jsonapi/rspec/links.rb | lib/jsonapi/rspec/links.rb | module JSONAPI
module RSpec
module Links
::RSpec::Matchers.define :have_link do |link|
match do |actual|
actual = JSONAPI::RSpec.as_indifferent_hash(actual)
actual.key?('links') && actual['links'].key?(link.to_s) &&
(!@val_set || actual['links'][link.to_s] == @val)
end
chain :with_value do |val|
@val_set = true
@val = val
end
end
::RSpec::Matchers.define :have_links do |*links|
match do |actual|
actual = JSONAPI::RSpec.as_indifferent_hash(actual)
return false unless actual.key?('links')
links.all? { |link| actual['links'].key?(link.to_s) }
end
end
end
end
end
| ruby | MIT | f3af9a8e2f4e5ae149760e14222b79b8a530f774 | 2026-01-04T17:58:16.857566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/spec/dare_spec.rb | spec/dare_spec.rb | require 'spec_helper'
describe Dare do
it 'does stuff' do
expect(1).to eq 1
end
end
| ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/spec/spec_helper.rb | spec/spec_helper.rb | #require 'coveralls'
#Coveralls.wear!
require 'jquery'
require 'dare'
| ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/spec/dare/window_spec.rb | spec/dare/window_spec.rb | require 'spec_helper'
describe Dare::Window do
let(:canvas) {double()}
let(:clock) {double()}
let(:window_without_defaults) {Dare::Window.new(clock: clock, canvas: canvas, no_mouse: true)}
let(:window_with_defaults) {Dare::Window.new(width: 200, height: 100, clock: clock, canvas: canvas, no_mouse: true)}
before do
allow(canvas).to receive(:context)
allow(canvas).to receive(:id)
allow(canvas).to receive(:canvas)
allow(clock).to receive(:start)
end
it "has a default width" do
expect(window_without_defaults.width).to eq 640
end
it "has a default height" do
expect(window_without_defaults.height).to eq 480
end
it "can be passed a width" do
expect(window_with_defaults.width).to eq 200
end
it "can be passed a height" do
expect(window_with_defaults.height).to eq 100
end
describe "#update" do
it "runs once per update interval" do
#window = Dare::Window.new(update_interval: 16.666)
#window.run!
#sleep 0.5
#window.stop!
#expect(window.ticks).to be > 10
end
end
describe "#draw" do
it "is run after each update" do
end
end
end
| ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/examples/tutorial/tutorial.rb | examples/tutorial/tutorial.rb | require 'dare'
class Star
attr_reader :x, :y
def initialize(animation)
@animation = animation
@creation_time = Dare.ms
@x = rand 640
@y = rand 480
end
def draw
img = @animation[((Dare.ms-@creation_time)/100).to_i % @animation.size]
img.draw_rot(@x, @y)
end
def update
end
end
class Player
def initialize
@image = Dare::Image.new('assets/Starfighter.png')
@grab_star_beep = Dare::Sound.new('assets/Beep.wav', overlap: 10)
@x = @y = @vel_x = @vel_y = 0.0
@angle = 90.0
@score = 0
end
def warp(x, y)
@x, @y = x, y
end
def turn_left
@angle += 4.5
end
def turn_right
@angle -= 4.5
end
def accelerate
@vel_x += Dare.offset_x(@angle, 0.5)
@vel_y += Dare.offset_y(@angle, 0.5)
end
def move
@x += @vel_x
@y += @vel_y
@x %= 640
@y %= 480
@vel_x *= 0.95
@vel_y *= 0.95
end
def draw
@image.draw_rot(@x, @y, @angle)
end
def score
@score
end
def collect_stars(stars)
if stars.reject! {|star| Dare.distance(@x, @y, star.x, star.y) < 35 }
@score += 1
@grab_star_beep.play
end
end
end
class Game < Dare::Window
def initialize
super width: 640, height: 480, border: true
self.caption = "Dare Tutorial Game"
@background_image = Dare::Image.new('assets/Space.png')
@player = Player.new
@player.warp 320, 240
@star_animation = Dare::Image.load_tiles('assets/Star.png', width: 25)
@stars = []
@font = Dare::Font.new(font: "Arial", size: 20, color: 'yellow')
end
def draw
@background_image.draw
@player.draw
@stars.each(&:draw)
@font.draw("Score: #{@player.score}", 20, 20)
end
def update
if button_down? Dare::KbLeft
@player.turn_left
end
if button_down? Dare::KbRight
@player.turn_right
end
if button_down? Dare::KbUp
@player.accelerate
end
@stars.each(&:update)
@player.move
@player.collect_stars(@stars)
if rand(100) < 4 and @stars.size < 25
@stars << Star.new(@star_animation)
end
end
end
Game.new.run! | ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/examples/pong/pong.rb | examples/pong/pong.rb | require 'dare'
class Paddle
attr_reader :x, :y, :width, :height
def initialize(game, side)
@game = game
@side = side
@x = 20
@y = Game::HEIGHT/2
@width = 30
@height = 80
end
def draw
@game.draw_rect(
top_left: [@x,@y-@height/2],
width: @width,
height: @height,
color: 'red'
)
end
def update
@y = @game.mouse_y || Game::HEIGHT/2
if @y < @height/2
@y = @height/2
end
if @y > Game::HEIGHT - @height/2
@y = Game::HEIGHT - @height/2
end
end
end
class Ball
def initialize(game)
reset!
@size = 10
@game = game
end
def draw
@game.draw_rect(
top_left: [@x-@size,@y-@size],
width: 2*@size,
height: 2*@size,
color: 'red'
)
end
def update
check_bounds
if overlapped_with(@game.paddles[0])
@angle = (180.0-@angle)
@game.boops[:paddle].play
end
travel_distance = @speed*(Dare.ms-@birth)/16.666666
@x += Dare.offset_x(@angle, travel_distance)
@y += Dare.offset_y(@angle, travel_distance)
@birth = Dare.ms
end
def check_bounds
if (@x > Game::WIDTH)
@game.score += 1
reset!
end
if (@x < 0)
reset!
end
if (@y > Game::HEIGHT-@size) || (@y < 0+@size)
@angle = 360.0-@angle
@game.boops[:wall].play
end
end
def overlapped_with(paddle)
left_side_of_ball_past_right_side_of_paddle(paddle) &&
right_side_of_ball_past_left_side_of_paddle(paddle) &&
top_of_ball_past_bottom_of_paddle(paddle) &&
bottom_of_ball_past_top_of_paddle(paddle)
end
def left_side_of_ball_past_right_side_of_paddle(paddle)
(@x-@size) < (paddle.x+paddle.width)
end
def right_side_of_ball_past_left_side_of_paddle(paddle)
(@x+@size) > (paddle.x-paddle.width)
end
def top_of_ball_past_bottom_of_paddle(paddle)
(@y+@size) < paddle.y+paddle.height/2
end
def bottom_of_ball_past_top_of_paddle(paddle)
(@y-@size) > paddle.y-paddle.height/2
end
def reset!
@x = Game::WIDTH/2.0
@y = Game::HEIGHT/2.0+5
@angle = 90.0*rand - 45.0
@angle = @angle+180.0 if rand > 0.5
@birth = Dare.ms
@speed = 10.0
end
end
class Game < Dare::Window
WIDTH = 1024
HEIGHT = 768
attr_reader :paddles, :boops
attr_accessor :score
def initialize
super width: WIDTH, height: HEIGHT, border: true
@ball = Ball.new(self)
@paddles = []
@paddles[0] = Paddle.new(self, :left)
@paddles[1] = Paddle.new(self, :right)
@boops = {}
@boops[:paddle] = Dare::Sound.new('assets/pong_bounce.mp3', volume: 0.3)
@boops[:wall] = Dare::Sound.new('assets/wall_bounce.mp3', volume: 0.3)
@score_font = Dare::Font.new
@score = 10
end
def draw
@ball.draw
@paddles[0].draw
@score_font.draw(@score)
end
def update
@ball.update
@paddles[0].update
end
end
Game.new.run! | ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/examples/mario/mario.rb | examples/mario/mario.rb | require 'dare'
require 'json'
class Level
attr_reader :background_color, :images
def initialize(path, window = Dare.default_canvas)
@data = JSON.parse("{\n \"id\":\"level1\",\n \"background_color\":\"#6f84ff\",\n \"tiles\":{\n \"bricks\":{\n \"ground\":[[0,12,16,12],[0,13,14,13]],\n \"question_mark\":[[8,16]]\n },\n \"background\":{\n \"hill_5\":[[0,8]],\n \"shrub_5\":[[11,10]],\n \"hill_3\":[[16,9]]\n }\n }\n}")
@background_color = @data["background_color"]
@tiles = @data["tiles"]
@window = window
load_images
end
def load_images
@images = {}
@images[:block_ground] = Dare::Image.new('assets/block_ground.png')
@images[:bg_hill_5] = Dare::Image.new('assets/bg_hill_5.png')
@images[:bg_shrub_5] = Dare::Image.new('assets/bg_shrub_5.png')
end
end
class Camera
attr_accessor :x
def initialize(window = Dare.default_canvas)
@window = window
@x = 0
end
def update
if @window.button_down? Dare::KbRight
@x += 2
end
if @window.button_down? Dare::KbLeft
@x -= 2
end
if @x < 0
@x = 0
end
end
end
class Game < Dare::Window
WIDTH = 256
HEIGHT = 224
TILE_WIDTH = 16
def initialize
super width: WIDTH, height: HEIGHT, border: true
Dare.default_canvas = self
@level = Level.new('level1.json')
@camera = Camera.new
@font = Dare::Font.new("16px Arial")
@mario = Dare::Sprite.new
@mario.state[:stand_right] << Dare::Image.new("assets/mario_stand_right.png")
@mario.state[:stop_right] << Dare::Image.new("assets/mario_stand_left.png")
@mario.state[:stop_right].next = @mario.state[:walk_left]
@mario.state[:walk_right] << Dare::Image.new("assets/mario_walk_right_1.png")
@mario.state[:walk_right] << Dare::Image.new("assets/mario_walk_right_2.png")
@mario.state[:walk_right] << Dare::Image.new("assets/mario_walk_right_3.png")
end
def draw
draw_background
draw_tiles
@mario.draw(TILE_WIDTH*3, TILE_WIDTH*11)
end
def update
@camera.update
@mario.update
end
def draw_background
draw_rect(top_left: [0,0], width: WIDTH, height: HEIGHT, color: @level.background_color)
end
def draw_tiles
@level.images[:bg_hill_5].draw(TILE_WIDTH*0-@camera.x,TILE_WIDTH*9)
@level.images[:bg_shrub_5].draw(TILE_WIDTH*11-@camera.x,TILE_WIDTH*11)
(0..16).each do |x|
@level.images[:block_ground].draw(TILE_WIDTH*x-@camera.x, TILE_WIDTH*12)
@level.images[:block_ground].draw(TILE_WIDTH*x-@camera.x, TILE_WIDTH*13)
end
end
end
Game.new.run!
| ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare.rb | lib/dare.rb | require 'opal' #this will be removed when 0.7.0 is released
require 'opal-jquery'
require_tree 'dare'
module Dare
# returns the current version of this gem
VERSION = "0.2.0"
# returns the magnitude of the horizontal component of a vector
# at some angle and some magnitude where the angle is in degrees
# starting on the unit circle pointing to the right and going
# counterclockwise
# e.g.
# Dare.offset_x(90, 10) # returns 0
# Dare.offset_x(45, 10) # returns 10 times the square root of 2
#
def self.offset_x(angle, magnitude)
`#{magnitude}*Math.cos(-#{angle}*Math.PI/180.0)`
end
# returns the magnitude of the vertical component of a vector
# at some angle and some magnitude where the angle is in degrees
# starting on the unit circle pointing to the right and going
# counterclockwise
# e.g.
# Dare.offset_y(90, 10) # returns 10
# Dare.offset_y(45, 10) # returns 10 times the square root of 2
#
def self.offset_y(angle, magnitude)
`#{magnitude}*Math.sin(-#{angle}*Math.PI/180.0)`
end
# returns the number of milliseconds since the Unix epoch
# useful for delta physics
#
def self.ms
`(new Date()).getTime()`
end
def self.distance(x1, y1, x2, y2)
`Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))`
end
class << self
attr_accessor :default_canvas
end
end | ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare/clock.rb | lib/dare/clock.rb | module Dare
class Clock
def initialize(opts = {})
opts[:update_interval] ||= 16.666
@update_interval = opts[:update_interval]
end
def start(&block)
@interval = `setInterval(function(){#{block.call}}, #{@update_interval})`
end
def stop
`clearInterval(#@interval)`
end
end
end | ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare/canvas.rb | lib/dare/canvas.rb | module Dare
class Canvas
attr_reader :id, :canvas
def initialize(opts = {})
opts[:width] ||= 640
opts[:height] ||= 480
opts[:border] ||= false
`var my_canvas = document.createElement("canvas")`
@id = rand(36**8).to_s(36)
`my_canvas.setAttribute('id', #{@id})`
`my_canvas.width = #{opts[:width]}`
`my_canvas.height = #{opts[:height]}`
`my_canvas.style.border = "solid 1px black"` if opts[:border]
`document.body.appendChild(my_canvas)`
@canvas = `my_canvas`
end
def context
`#{@canvas}.getContext('2d')`
end
end
end | ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare/window.rb | lib/dare/window.rb | module Dare
class Color
attr_accessor :red, :green, :blue
def initialize(color)
end
end
class Window
attr_reader :width, :height, :ticks, :mouse_x, :mouse_y, :canvas, :key, :update_interval
# Creates a new window object to hold all your game goodness
# @param [Hash] opts the options to create a window.
# @option opts [Integer] :width (640) sets default canvas to a particular width in pixels
# @option opts [Integer] :height (480) sets default canvas to a particular height in pixels
# @option opts [Float] :update_interval (16.666666) sets the update interval in milliseconds between updates
# @option opts [Boolean] :border (false) draws a border around the default canvas
# @option opts [Dare::Canvas] :canvas (Dare.default_canvas) a canvas to refer to when drawing.
# @option opts [Boolean] :mouse (true) turn off mouse event listeners by setting to false
#
def initialize(opts = {})
opts[:width] ||= 640
opts[:height] ||= 480
opts[:update_interval] ||= 16.666666
opts[:border] ||= false
opts[:canvas] ||= Canvas.new(width: opts[:width], height: opts[:height], border: opts[:border])
opts[:mouse] ||= true
@width = opts[:width]
@height = opts[:height]
@update_interval = opts[:update_interval]
@clock = opts[:clock]
@canvas = opts[:canvas]
Dare.default_canvas ||= @canvas
@keys = []
add_mouse_event_listener if opts[:mouse]
add_keyboard_event_listeners
end
# starts the game loop for the window.
def run!
%x{
function update_loop() {
#{update};
}
function anim_loop() {
requestAnimationFrame(anim_loop);
#{@canvas.canvas}.width = #{@canvas.canvas}.width;
#{draw};
}
setInterval(update_loop, #{@update_interval});
requestAnimationFrame(anim_loop);
}
end
# gets run every frame of animation
# override this in your subclass of Dare::Window
def draw
end
# gets run every update_interval if it can
# override this in your subclass of Dare::Window
def update
end
# adds mousemove event listener to main canvas
def add_mouse_event_listener
Element.find("##{@canvas.id}").on :mousemove do |event|
coords = get_cursor_position(event)
@mouse_x = coords.x[:x]
@mouse_y = coords.x[:y]
end
end
# adds keyboard event listeners to entire page
def add_keyboard_event_listeners
Element.find("html").on :keydown do |event|
@keys[get_key_id(event)] = true
end
Element.find("html").on :keyup do |event|
@keys[get_key_id(event)] = false
end
::Window.on :blur do |event|
@keys.fill false
end
end
# checks to see if button passed is currently being pressed
def button_down?(button)
@keys[button]
end
# sets mouse_x and mouse_y to current mouse positions relative
# to the main canvas
def get_cursor_position(event)
if (event.page_x && event.page_y)
x = event.page_x
y = event.page_y
else
doc = Opal.Document[0]
x = event[:clientX] + doc.scrollLeft +
doc.documentElement.scrollLeft
y = event[:clientY] + doc.body.scrollTop +
doc.documentElement.scrollTop
end
x -= `#{@canvas.canvas}.offsetLeft`
y -= `#{@canvas.canvas}.offsetTop`
Coordinates.new(x: x, y: y)
end
# retrieves key code of current pressed key for keydown or keyup event
def get_key_id(event)
event[:keyCode]
end
# draws a rectangle starting at (top_left[0], top_left[1])
# down to (top_left[0]+width, top_left[1]+height)
def draw_rect(opts = {})
x = opts[:top_left][0]
y = opts[:top_left][1]
width = opts[:width]
height = opts[:height]
color = opts[:color]
`#{@canvas.context}.fillStyle = #{color}`
`#{@canvas.context}.fillRect(#{x}, #{y}, #{width}, #{height})`
end
#works the same as Gosu::Window.draw_quad
def draw_quad(x1, y1, c1, x2, y2, c2, x3, y3, c3, x4, y4, c4, z)
%x{
var QUALITY = 256;
var canvas_colors = document.createElement( 'canvas' );
canvas_colors.width = 2;
canvas_colors.height = 2;
var context_colors = canvas_colors.getContext( '2d' );
context_colors.fillStyle = 'rgba(0,0,0,1)';
context_colors.fillRect( 0, 0, 2, 2 );
var image_colors = context_colors.getImageData( 0, 0, 2, 2 );
var data = image_colors.data;
var canvas_render = #{@canvas};
var context_render = #{@canvas.context};
context_render.translate( - QUALITY / 2, - QUALITY / 2 );
context_render.scale( QUALITY, QUALITY );
data[ 0 ] = 255; // Top-left, red component
data[ 5 ] = 255; // Top-right, green component
data[ 10 ] = 255; // Bottom-left, blue component
context_colors.putImageData( image_colors, 0, 0 );
context_render.drawImage( canvas_colors, 0, 0 );
}
end
# sets the caption/title of the window to the string passed
def caption=(title)
`document.getElementById('pageTitle').innerHTML = #{title}`
end
alias :title= :caption=
# checks if game is fullscreen. currently not implemented.
def fullscreen?
false
end
# this is here for Gosu API compatability
def text_input; end
end
class Coordinates < Struct.new(:x, :y); end
end | ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare/sound.rb | lib/dare/sound.rb | module Dare
# wrapper for JS Audio
# takes a path/uri as an argument
# e.g. song = Dare::Sound.new('my_song.mp3')
# song.play will then play the mp3 in the browser
#
class Sound
# loads an audio resource from a path
# Sound.new('http://www.google.com/song.mp3')
# Sound.new('local_song_in_same_directory_of_app_js_file.mp3')
# a predefined volume may be passed as an option
# Sound.new('file.mp3', volume: 0.5)
#
def initialize(path, opts = {})
opts[:overlap] ||= 1
opts[:volume] ||= 1
opts[:overlap] = 1 if opts[:overlap].to_i < 1
opts[:overlap] = 10 if opts[:overlap].to_i > 10
@overlap = opts[:overlap]
@sounds = []
@overlap.times do
`var snd = new Audio(#{path})`
`snd.volume = #{opts[:volume]}`
@sounds << `snd`
end
@sound = 0
end
# set the volume of the audio resource to value between 0 and 1
#
def volume=(vol)
`#{@sound}.volume = #{vol}`
end
# retrieve the current volume of the audio resource
#
def volume
`#{@sound}.volume`
end
# play the audio resource in the window/tab it was created in
# if resource was paused, it will start playing from where it left off
#
def play
@sound += 1
@sound %= @overlap
`#{@sounds[@sound]}.play()`
end
# pause the audio resource, halting playback
#
def pause
`#{@sound}.pause()`
end
# seek to particular time in playback. Time passed is in seconds.
#
def time=(time)
`#{@sound}.currentTime = #{time}`
end
end
end | ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare/font.rb | lib/dare/font.rb | module Dare
class Font
def initialize(opts = {})
opts[:font] ||= "Arial"
opts[:canvas] ||= Dare.default_canvas
opts[:size] ||= 30
opts[:color] ||= "black"
@font = opts[:size].to_s + "px" + " " + opts[:font]
@canvas = opts[:canvas]
@color = opts[:color]
end
def draw(string = "", x = 0, y = 0, opts = {})
%x{
#{@canvas.context}.font = #{@font} ;
#{@canvas.context}.textAlign = 'left';
#{@canvas.context}.textBaseline = 'top';
#{@canvas.context}.fillStyle = #{@color};
#{@canvas.context}.fillText(#{string}, #{x}, #{y});
}
end
end
end | ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare/keyboard_constants.rb | lib/dare/keyboard_constants.rb | %x{
//set jquery vars if jquery migrate doesn't work for some reason
try{
$.browser.mozilla;
$.browser.webkit;
} catch(e) { $.browser = {'mozilla': false,'webkit': false}; }
}
module Dare
# These are the corresponding character keycodes for keyboard presses
# e.g.
# if button_down? Dare::KbDown
# player.crouch #or something
# end
#
# for convenience, you can "include Dare::Kb" at the top
# of your main app file (after require 'dare'), and then
# refer to these constants directly
# e.g.
# if button_down? KbI
# open_inventory
# end
#
Kb0 = 48
Kb1 = 49
Kb2 = 50
Kb3 = 51
Kb4 = 52
Kb5 = 53
Kb6 = 54
Kb7 = 55
Kb8 = 56
Kb9 = 57
KbA = 65
KbB = 66
KbC = 67
KbD = 68
KbE = 69
KbF = 70
KbG = 71
KbH = 72
KbI = 73
KbJ = 74
KbK = 75
KbL = 76
KbM = 77
KbN = 78
KbO = 79
KbP = 80
KbQ = 81
KbR = 82
KbS = 83
KbT = 84
KbU = 85
KbV = 86
KbW = 87
KbX = 88
KbY = 89
KbZ = 90
KbBackspace = 8
KbDelete = 46
KbDown = 40
KbEnd = 35
KbEnter = 13
KbReturn = 13
KbEscape = 27
KbF1 = 112
KbF2 = 113
KbF3 = 114
KbF4 = 115
KbF5 = 116
KbF6 = 117
KbF7 = 118
KbF8 = 119
KbF9 = 120
KbF10 = 121
KbF11 = 122
KbF12 = 123
KbSpace = 32
KbPageUp = 33
KbPageDown = 34
KbHome = 36
KbLeft = 37
KbUp = 38
KbRight = 39
KbInsert = 45
KbShift = 16
KbControl = 17
KbAlt = 18
KbCapsLock = 20
KbNumpad0 = 96
KbNumpad1 = 97
KbNumpad2 = 98
KbNumpad3 = 99
KbNumpad4 = 100
KbNumpad5 = 101
KbNumpad6 = 102
KbNumpad7 = 103
KbNumpad8 = 104
KbNumpad9 = 105
KbNumpadMultiply = 106
KbNumpadAdd = 107
KbNumpadSubtract = 109
KbNumpadDivide = 111
KbTab = 9
KbBacktick = 192
KbTilde = 192
KbGraveAccent = 192
KbMinus = 189
KbDash = 189
KbEqual = 187
KbBracketLeft = 219
KbBracketRight = 221
KbBackslash = 220
KbSemicolon = 186
KbApostrophe = 222
KbComma = 188
KbPeriod = 190
KbSlash = 191
kbCmd ||= %x{ (function(){
if($.browser.mozilla){
return 224;
} else if($.browser.webkit) {
return 91;
} else {
return 17;
}
})()
}
kbCmdRight ||= %x{ (function(){
if($.browser.webkit) {
return 93;
} else {
return 17;
}
})()
}
KbCmd = kbCmd
KbCmdLeft = KbCmd
KbCmdRight = kbCmdRight
module Kb
Kb0 = 48
Kb1 = 49
Kb2 = 50
Kb3 = 51
Kb4 = 52
Kb5 = 53
Kb6 = 54
Kb7 = 55
Kb8 = 56
Kb9 = 57
KbA = 65
KbB = 66
KbC = 67
KbD = 68
KbE = 69
KbF = 70
KbG = 71
KbH = 72
KbI = 73
KbJ = 74
KbK = 75
KbL = 76
KbM = 77
KbN = 78
KbO = 79
KbP = 80
KbQ = 81
KbR = 82
KbS = 83
KbT = 84
KbU = 85
KbV = 86
KbW = 87
KbX = 88
KbY = 89
KbZ = 90
KbBackspace = 8
KbDelete = 46
KbDown = 40
KbEnd = 35
KbEnter = 13
KbReturn = 13
KbEscape = 27
KbF1 = 112
KbF2 = 113
KbF3 = 114
KbF4 = 115
KbF5 = 116
KbF6 = 117
KbF7 = 118
KbF8 = 119
KbF9 = 120
KbF10 = 121
KbF11 = 122
KbF12 = 123
KbSpace = 32
KbPageUp = 33
KbPageDown = 34
KbHome = 36
KbLeft = 37
KbUp = 38
KbRight = 39
KbInsert = 45
KbShift = 16
KbControl = 17
KbAlt = 18
KbCapsLock = 20
KbNumpad0 = 96
KbNumpad1 = 97
KbNumpad2 = 98
KbNumpad3 = 99
KbNumpad4 = 100
KbNumpad5 = 101
KbNumpad6 = 102
KbNumpad7 = 103
KbNumpad8 = 104
KbNumpad9 = 105
KbNumpadMultiply = 106
KbNumpadAdd = 107
KbNumpadSubtract = 109
KbNumpadDivide = 111
KbTab = 9
KbBacktick = 192
KbTilde = 192
KbGraveAccent = 192
KbMinus = 189
KbDash = 189
KbEqual = 187
KbBracketLeft = 219
KbBracketRight = 221
KbBackslash = 220
KbSemicolon = 186
KbApostrophe = 222
KbComma = 188
KbPeriod = 190
KbSlash = 191
kbCmd ||= %x{ (function(){
if($.browser.mozilla){
return 224;
} else if($.browser.webkit) {
return 91;
} else {
return 17;
}
})()
}
kbCmdRight ||= %x{ (function(){
if($.browser.webkit) {
return 93;
} else {
return 17;
}
})()
}
KbCmd = kbCmd
KbCmdLeft = KbCmd
KbCmdRight = kbCmdRight
end
end
| ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare/sprite.rb | lib/dare/sprite.rb | module Dare
class Sprite
attr_accessor :images, :state
def initialize(window = Dare.default_canvas)
@window = window
@images = []
@state = Hash.new {|h,k| h[k] = Dare::AnimationState.new}
@current_image = 0
@ticks_on_current_image = 0
@x = 0
@y = 0
end
def draw(x = 0, y = 0)
@images[@current_image].draw(x, y)
end
def update
if @window.button_down? Dare::KbRight
walk
else
stand
end
end
def walk
if @current_image == 0
@current_image = 2
@ticks_on_current_image = 0
elsif @current_image == 2
if @ticks_on_current_image >= 5
@current_image = 3
@ticks_on_current_image = 0
else
@ticks_on_current_image += 1
end
elsif @current_image == 3
if @ticks_on_current_image >= 5
@current_image = 4
@ticks_on_current_image = 0
else
@ticks_on_current_image += 1
end
elsif @current_image == 4
if @ticks_on_current_image >= 5
@current_image = 2
@ticks_on_current_image = 0
else
@ticks_on_current_image += 1
end
end
end
def stand
@current_image = 0
@ticks_on_current_image = 0
end
end
end | ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
domgetter/dare | https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare/image.rb | lib/dare/image.rb | module Dare
# Represents an image which can be drawn to a canvas
#
class Image
# Loads a new image resource from an absolute URL or relative path
#
# @param [String] path ("") the path to the resource
# @param [Hash] opts ({}) the options to create an image.
# @option opts [Dare::Canvas] :canvas (Dare.default_canvas) a canvas to refer to when drawing.
#
# @example
# Dare::Image.new('some_image.png')
#
# @example
# Dare::Image.new('https://www.google.com/images/srpr/logo11w.png', canvas: Dare::Canvas.new)
#
def initialize(path = "", opts = {})
opts[:canvas] ||= Dare.default_canvas
@path = path
@img = `new Image()`
`#{@img}.src = #{path}`
@canvas = opts[:canvas]
end
# The path or URL of the image
#
# @return [String]
#
def path
@path
end
def img
@img
end
# The width of the image in pixels
#
# @return [Integer]
#
def width
`#{@img}.width`
end
# The height of the image in pixels
#
# @return [Integer]
#
def height
`#{@img}.height`
end
# Draws image to a canvas at an `x` and `y` position. `x` and `y` represent the top-left corner of the image
#
# @param [Integer] x (0) x coordinate of top-left of image
# @param [Integer] y (0) y coordinate of top-left of image
# @param [Hash] opts ({}) the options to draw an image.
# @option opts [Dare::Canvas] :canvas (Dare.default_canvas) a canvas to refer to when drawing.
#
# @example
# image.draw(100, 200)
#
# @example
# image.draw(10, 10, canvas: Dare::Canvas.new(width: 100, height: 100))
#
def draw(x = 0, y = 0, opts = {})
opts[:canvas] ||= @canvas
%x{
#{opts[:canvas].context}.drawImage(
#{@img},
#{x},
#{y}
);
}
end
# (see #draw)
# @note Used by Dare::ImageTile to draw a portion of an image to a canvas.
#
def draw_tile(x = 0, y = 0, opts = {})
opts[:canvas] ||= @canvas
opts[:sx] ||= 0
opts[:sy] ||= 0
opts[:swidth] ||= width - opts[:sx]
opts[:sheight] ||= height - opts[:sy]
opts[:dwidth] ||= opts[:swidth]
opts[:dheight] ||= opts[:sheight]
%x{
#{opts[:canvas].context}.drawImage(
#{@img},
#{opts[:sx]},
#{opts[:sy]},
#{opts[:swidth]},
#{opts[:sheight]},
#{x},
#{y},
#{opts[:dwidth]},
#{opts[:dheight]}
);
}
end
# Draws image to a canvas at an x and y position and rotated at some angle
# x and y represent the center of the image
# angle is in degrees starting by pointing to the right and increasing counterclockwise
#
# @param [Integer] x (0) x coordinate of center of image
# @param [Integer] y (0) y coordinate of center of image
# @param [Float] angle (90.0) angle of image
# @param [Hash] opts ({}) the options to draw an image.
# @option opts [Dare::Canvas] :canvas (Dare.default_canvas) a canvas to refer to when drawing.
#
# @example
# image.draw_rot(100, 200, 45) # this will point the top of the image up and to the right
#
# @example
# image.draw_rot(50, 75, 270, canvas: some_other_canvas)
#
def draw_rot(x = 0, y = 0, angle = 90, opts = {})
opts[:canvas] ||= @canvas
%x{
var context = #{opts[:canvas].context};
var width = #{@img}.width;
var height = #{@img}.height;
context.translate(#{x}, #{y});
context.rotate(-#{angle-90}*Math.PI/180.0);
context.drawImage(#{@img}, -width/2, -height/2, width, height);
context.rotate(#{angle-90}*Math.PI/180.0);
context.translate(-#{x}, -#{y});
}
end
# (see #draw_rot)
# @note Used by Dare::ImageTile to draw a portion of an image to a canvas at an angle.
#
def draw_tile_rot(x = 0, y = 0, angle = 90, opts = {})
opts[:canvas] ||= @canvas
opts[:sx] ||= 0
opts[:sy] ||= 0
opts[:swidth] ||= width - opts[:sx]
opts[:sheight] ||= height - opts[:sy]
opts[:dwidth] ||= opts[:swidth]
opts[:dheight] ||= opts[:sheight]
%x{
var context = #{opts[:canvas].context};
context.translate(#{x}, #{y});
context.rotate(-#{angle-90}*Math.PI/180.0);
context.drawImage(
#{@img},
#{opts[:sx]},
#{opts[:sy]},
#{opts[:swidth]},
#{opts[:sheight]},
-#{opts[:swidth]}/2,
-#{opts[:sheight]}/2,
#{opts[:swidth]},
#{opts[:sheight]});
context.rotate(#{angle-90}*Math.PI/180.0);
context.translate(-#{x}, -#{y});
}
end
# Loads image and cuts it into tiles
#
# @param [String] path ("") the path to the resource
# @param [Hash] opts ({}) the options to create an image.
# @option opts [Integer] :width (Image.new(path).width) width of a single tile from the image
# @option opts [Integer] :height (Image.new(path).height) height of a single tile from the image
#
# @return [Array] An array of images each of which are individual tiles of the original
#
def self.load_tiles(path = "", opts = {})
image = Image.new(path)
@tiles = []
%x{
#{image.img}.onload = function() {
#{opts[:width] ||= image.width};
#{opts[:height] ||= image.height};
#{columns = image.width/opts[:width]};
#{rows = image.height/opts[:height]};
#{rows.times do |row|
columns.times do |column|
@tiles << ImageTile.new(image, column*opts[:width].to_i, row*opts[:height].to_i, opts[:width].to_i, opts[:height].to_i)
end
end};
}
}
@tiles
end
end
class ImageTile
attr_reader :width, :height
def initialize(image = Image.new, x = 0, y = 0, width = 0, height = 0)
@image = image
@x = x
@y = y
@width = width
@height = height
end
def draw(x = 0, y = 0, opts = {})
@image.draw_tile(x, y, opts.merge({sx: @x, sy: @y, swidth: @width, sheight: @height}))
end
def draw_rot(x = 0, y = 0, angle = 90, opts = {})
@image.draw_tile_rot(x, y, angle, opts.merge({sx: @x, sy: @y, swidth: @width, sheight: @height}))
end
end
end | ruby | MIT | a017efd98275992912f016fefe45a17f00117fe5 | 2026-01-04T17:58:17.217566Z | false |
pinterest/it-cpe-cookbooks | https://github.com/pinterest/it-cpe-cookbooks/blob/f021bd5f53d40256ef902e168399c0c3c04f2a9f/cpe_helloit/metadata.rb | cpe_helloit/metadata.rb | # vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2
name 'cpe_helloit'
maintainer 'Pinterest'
maintainer_email 'itcpe@pinterest.com'
license 'Apache-2.0'
description 'Installs/Configures cpe_helloit'
version '0.1.0'
chef_version '>= 14.14'
supports 'mac_os_x'
depends 'cpe_launchd'
depends 'cpe_profiles'
depends 'cpe_remote'
depends 'uber_helpers'
| ruby | Apache-2.0 | f021bd5f53d40256ef902e168399c0c3c04f2a9f | 2026-01-04T17:58:20.108383Z | false |
pinterest/it-cpe-cookbooks | https://github.com/pinterest/it-cpe-cookbooks/blob/f021bd5f53d40256ef902e168399c0c3c04f2a9f/cpe_helloit/recipes/default.rb | cpe_helloit/recipes/default.rb | #
# Cookbook:: cpe_helloit
# Recipe:: default
#
# vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2
#
# Copyright:: (c) 2017-present, Pinterest, Inc.
# All rights reserved.
#
# This source code is licensed under the Apache 2.0 license found in the
# LICENSE file in the root directory of this source tree.
#
return unless macos?
cpe_helloit_install 'Install Hello-IT package'
if node.os_at_least_or_lower?('10.15.99')
cpe_helloit_profile 'Apply Hello-IT profile'
else
cpe_helloit_defaults 'Apply Hello-IT defaults'
end
cpe_helloit_la 'Manage Hello-IT LaunchAgent'
| ruby | Apache-2.0 | f021bd5f53d40256ef902e168399c0c3c04f2a9f | 2026-01-04T17:58:20.108383Z | false |
pinterest/it-cpe-cookbooks | https://github.com/pinterest/it-cpe-cookbooks/blob/f021bd5f53d40256ef902e168399c0c3c04f2a9f/cpe_helloit/attributes/default.rb | cpe_helloit/attributes/default.rb | #
# Cookbook:: cpe_helloit
# Attributes:: default
#
# vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2
#
# Copyright:: (c) 2017-present, Pinterest, Inc.
# All rights reserved.
#
# This source code is licensed under the Apache 2.0 license found in the
# LICENSE file in the root directory of this source tree.
#
default['cpe_helloit'] = {
'install' => false,
'uninstall' => false,
'config' => true,
'manage_la' => true,
'la' => {
'keep_alive' => true,
'program_arguments' => [
'/Applications/Utilities/Hello IT.app/Contents/MacOS/Hello IT',
],
'run_at_load' => true,
'type' => 'agent',
},
'prefs' => {
'contents' => nil, # Array of dictionaries.
},
'pkg' => {
'name' => 'helloit',
'checksum' =>
'3481810cc0a39ab1820c60e68bc89bee62790ec99a833cf11204c6748bfeeada',
'receipt' => 'com.github.ygini.hello-it',
'version' => '1.6.0',
'pkg_name' => nil,
'pkg_url' => nil,
},
}
| ruby | Apache-2.0 | f021bd5f53d40256ef902e168399c0c3c04f2a9f | 2026-01-04T17:58:20.108383Z | false |
pinterest/it-cpe-cookbooks | https://github.com/pinterest/it-cpe-cookbooks/blob/f021bd5f53d40256ef902e168399c0c3c04f2a9f/cpe_helloit/resources/cpe_helloit_defaults.rb | cpe_helloit/resources/cpe_helloit_defaults.rb | #
# Cookbook:: cpe_helloit
# Resource:: cpe_helloit_defaults
#
# vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2
#
# Copyright:: (c) 2022-present, Pinterest, Inc.
# All rights reserved.
#
# This source code is licensed under the Apache 2.0 license found in the
# LICENSE file in the root directory of this source tree.
#
unified_mode true
resource_name :cpe_helloit_defaults
provides :cpe_helloit_defaults, :os => 'darwin'
default_action :config
# Enforce HelloIT settings
action :config do
return unless node['cpe_helloit']['install']
return unless node['cpe_helloit']['config']
hit_prefs = node['cpe_helloit']['prefs'].compact
if hit_prefs.empty?
Chef::Log.info("#{cookbook_name}: No prefs found.")
return
end
if node.at_least_chef14? # Chef 14+ for macos_userdefaults
hit_prefs.each_key do |key|
next if hit_prefs[key].nil?
macos_userdefaults "Configure com.github.ygini.Hello-IT - #{key}" do
domain '/Library/Preferences/com.github.ygini.Hello-IT'
key key
value hit_prefs[key].to_array
host :all
user :all
end
end
end
end
| ruby | Apache-2.0 | f021bd5f53d40256ef902e168399c0c3c04f2a9f | 2026-01-04T17:58:20.108383Z | false |
pinterest/it-cpe-cookbooks | https://github.com/pinterest/it-cpe-cookbooks/blob/f021bd5f53d40256ef902e168399c0c3c04f2a9f/cpe_helloit/resources/cpe_helloit_install.rb | cpe_helloit/resources/cpe_helloit_install.rb | #
# Cookbook:: cpe_helloit
# Resources:: cpe_helloit_install
#
# vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2
#
# Copyright:: (c) 2017-present, Pinterest, Inc.
# All rights reserved.
#
# This source code is licensed under the Apache 2.0 license found in the
# LICENSE file in the root directory of this source tree.
#
unified_mode true
resource_name :cpe_helloit_install
provides :cpe_helloit_install, :os => 'darwin'
default_action :manage
action :manage do
validate_install
install if install? && !uninstall?
remove if uninstall?
end
action_class do
def install?
node['cpe_helloit']['install']
end
def uninstall?
node['cpe_helloit']['uninstall']
end
# Forget the helloit package receipt
def forget_helloit_pkg
pkg = node['cpe_helloit']['pkg']
execute "/usr/sbin/pkgutil --forget #{pkg['receipt']}" do
not_if do
shell_out("/usr/sbin/pkgutil --pkg-info #{pkg['receipt']}").error?
end
action :run
end
end
def helloit_installed?
helloit_path =
'/Applications/Utilities/Hello IT.app/Contents/MacOS/Hello IT'
::File.exist?(helloit_path)
end
def validate_install
forget_helloit_pkg if install? && !helloit_installed?
end
def install
pkg = node['cpe_helloit']['pkg']
# Install Hello-IT
cpe_remote_pkg 'helloit' do
version pkg['version']
checksum pkg['checksum']
receipt pkg['receipt']
pkg_name pkg['pkg_name'] if pkg['pkg_name']
pkg_url pkg['pkg_url'] if pkg['pkg_url']
end
end
def remove
# Delete Hello-IT directory
directory '/Library/Application Support/com.github.ygini.hello-it' do
action :delete
recursive true
end
# Delete default Hello-IT LaunchAgent
launchd 'com.github.ygini.hello-it' do
action :delete
end
forget_helloit_pkg
end
end
| ruby | Apache-2.0 | f021bd5f53d40256ef902e168399c0c3c04f2a9f | 2026-01-04T17:58:20.108383Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.