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
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/dev_server_runner.rb
lib/webpacker/dev_server_runner.rb
require "shellwords" require "socket" require "webpacker/configuration" require "webpacker/dev_server" require "webpacker/runner" module Webpacker class DevServerRunner < Webpacker::Runner def run load_config detect_unsupported_switches! detect_port! execute_cmd end private def load_config app_root = Pathname.new(@app_path) @config = Configuration.new( root_path: app_root, config_path: Pathname.new(@webpacker_config), env: ENV["RAILS_ENV"] ) dev_server = DevServer.new(@config) @hostname = dev_server.host @port = dev_server.port @pretty = dev_server.pretty? @https = dev_server.https? @hot = dev_server.hmr? rescue Errno::ENOENT, NoMethodError $stdout.puts "webpack dev_server configuration not found in #{@config.config_path}[#{ENV["RAILS_ENV"]}]." $stdout.puts "Please run bundle exec rails webpacker:install to install Webpacker" exit! end UNSUPPORTED_SWITCHES = %w[--host --port] private_constant :UNSUPPORTED_SWITCHES def detect_unsupported_switches! unsupported_switches = UNSUPPORTED_SWITCHES & @argv if unsupported_switches.any? $stdout.puts "The following CLI switches are not supported by Webpacker: #{unsupported_switches.join(' ')}. Please edit your command and try again." exit! end if @argv.include?("--https") && !@https $stdout.puts "Please set https: true in webpacker.yml to use the --https command line flag." exit! end end def detect_port! server = TCPServer.new(@hostname, @port) server.close rescue Errno::EADDRINUSE $stdout.puts "Another program is running on port #{@port}. Set a new port in #{@config.config_path} for dev_server" exit! end def execute_cmd env = Webpacker::Compiler.env env["WEBPACKER_CONFIG"] = @webpacker_config env["WEBPACK_SERVE"] = "true" cmd = if node_modules_bin_exist? ["#{@node_modules_bin_path}/webpack", "serve"] else ["yarn", "webpack", "serve"] end if @argv.include?("--debug-webpacker") cmd = [ "node", "--inspect-brk", "--trace-warnings" ] + cmd @argv.delete "--debug-webpacker" end cmd += ["--config", @webpack_config] cmd += ["--progress", "--color"] if @pretty cmd += ["--hot"] if @hot cmd += @argv Dir.chdir(@app_path) do Kernel.exec env, *cmd end end def node_modules_bin_exist? File.exist?("#{@node_modules_bin_path}/webpack-dev-server") end end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/version.rb
lib/webpacker/version.rb
module Webpacker # Change the version in package.json too, please! VERSION = "6.0.0.rc.6".freeze end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/manifest.rb
lib/webpacker/manifest.rb
# Singleton registry for accessing the packs path using a generated manifest. # This allows javascript_pack_tag, stylesheet_pack_tag, asset_pack_path to take a reference to, # say, "calendar.js" or "calendar.css" and turn it into "/packs/calendar-1016838bab065ae1e314.js" or # "/packs/calendar-1016838bab065ae1e314.css". # # When the configuration is set to on-demand compilation, with the `compile: true` option in # the webpacker.yml file, any lookups will be preceded by a compilation if one is needed. class Webpacker::Manifest class MissingEntryError < StandardError; end delegate :config, :compiler, :dev_server, to: :@webpacker def initialize(webpacker) @webpacker = webpacker end def refresh @data = load end def lookup_pack_with_chunks(name, pack_type = {}) compile if compiling? manifest_pack_type = manifest_type(pack_type[:type]) manifest_pack_name = manifest_name(name, manifest_pack_type) find("entrypoints")[manifest_pack_name]["assets"][manifest_pack_type] rescue NoMethodError nil end def lookup_pack_with_chunks!(name, pack_type = {}) lookup_pack_with_chunks(name, pack_type) || handle_missing_entry(name, pack_type) end # Computes the relative path for a given Webpacker asset using manifest.json. # If no asset is found, returns nil. # # Example: # # Webpacker.manifest.lookup('calendar.js') # => "/packs/calendar-1016838bab065ae1e122.js" def lookup(name, pack_type = {}) compile if compiling? find(full_pack_name(name, pack_type[:type])) end # Like lookup, except that if no asset is found, raises a Webpacker::Manifest::MissingEntryError. def lookup!(name, pack_type = {}) lookup(name, pack_type) || handle_missing_entry(name, pack_type) end private def compiling? config.compile? && !dev_server.running? end def compile Webpacker.logger.tagged("Webpacker") { compiler.compile } end def data if config.cache_manifest? @data ||= load else refresh end end def find(name) data[name.to_s].presence end def full_pack_name(name, pack_type) return name unless File.extname(name.to_s).empty? "#{name}.#{manifest_type(pack_type)}" end def handle_missing_entry(name, pack_type) raise Webpacker::Manifest::MissingEntryError, missing_file_from_manifest_error(full_pack_name(name, pack_type[:type])) end def load if config.public_manifest_path.exist? JSON.parse config.public_manifest_path.read else {} end end # The `manifest_name` method strips of the file extension of the name, because in the # manifest hash the entrypoints are defined by their pack name without the extension. # When the user provides a name with a file extension, we want to try to strip it off. def manifest_name(name, pack_type) name.chomp(".#{pack_type}") end def manifest_type(pack_type) case pack_type when :javascript then "js" when :stylesheet then "css" else pack_type.to_s end end def missing_file_from_manifest_error(bundle_name) <<-MSG Webpacker can't find #{bundle_name} in #{config.public_manifest_path}. Possible causes: 1. You forgot to install node packages (try `yarn install`) or are running an incompatible version of Node 2. Your app has code with a non-standard extension (like a `.jsx` file) but the extension is not in the `extensions` config in `config/webpacker.yml` 3. You have set compile: false (see `config/webpacker.yml`) for this environment (unless you are using the `bin/webpacker -w` or the `bin/webpacker-dev-server`, in which case maybe you aren't running the dev server in the background?) 4. webpack has not yet re-run to reflect updates. 5. You have misconfigured Webpacker's `config/webpacker.yml` file. 6. Your webpack configuration is not creating a manifest. Your manifest contains: #{JSON.pretty_generate(@data)} MSG end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/compiler.rb
lib/webpacker/compiler.rb
require "open3" require "digest/sha1" class Webpacker::Compiler # Additional paths that test compiler needs to watch # Webpacker::Compiler.watched_paths << 'bower_components' # # Deprecated. Use additional_paths in the YAML configuration instead. cattr_accessor(:watched_paths) { [] } # Additional environment variables that the compiler is being run with # Webpacker::Compiler.env['FRONTEND_API_KEY'] = 'your_secret_key' cattr_accessor(:env) { {} } delegate :config, :logger, to: :webpacker def initialize(webpacker) @webpacker = webpacker end def compile if stale? run_webpack.tap do |success| # We used to only record the digest on success # However, the output file is still written on error, meaning that the digest should still be updated. # If it's not, you can end up in a situation where a recompile doesn't take place when it should. # See https://github.com/rails/webpacker/issues/2113 record_compilation_digest end else logger.debug "Everything's up-to-date. Nothing to do" true end end # Returns true if all the compiled packs are up to date with the underlying asset files. def fresh? last_compilation_digest&.== watched_files_digest end # Returns true if the compiled packs are out of date with the underlying asset files. def stale? !fresh? end private attr_reader :webpacker def last_compilation_digest compilation_digest_path.read if compilation_digest_path.exist? && config.public_manifest_path.exist? rescue Errno::ENOENT, Errno::ENOTDIR end def watched_files_digest warn "Webpacker::Compiler.watched_paths has been deprecated. Set additional_paths in webpacker.yml instead." unless watched_paths.empty? Dir.chdir File.expand_path(config.root_path) do files = Dir[*default_watched_paths, *watched_paths].reject { |f| File.directory?(f) } file_ids = files.sort.map { |f| "#{File.basename(f)}/#{Digest::SHA1.file(f).hexdigest}" } Digest::SHA1.hexdigest(file_ids.join("/")) end end def record_compilation_digest config.cache_path.mkpath compilation_digest_path.write(watched_files_digest) end def optionalRubyRunner bin_webpack_path = config.root_path.join("bin/webpacker") first_line = File.readlines(bin_webpack_path).first.chomp /ruby/.match?(first_line) ? RbConfig.ruby : "" end def run_webpack logger.info "Compiling..." stdout, stderr, status = Open3.capture3( webpack_env, "#{optionalRubyRunner} ./bin/webpacker", chdir: File.expand_path(config.root_path) ) if status.success? logger.info "Compiled all packs in #{config.public_output_path}" logger.error "#{stderr}" unless stderr.empty? if config.webpack_compile_output? logger.info stdout end else non_empty_streams = [stdout, stderr].delete_if(&:empty?) logger.error "\nCOMPILATION FAILED:\nEXIT STATUS: #{status}\nOUTPUTS:\n#{non_empty_streams.join("\n\n")}" end status.success? end def default_watched_paths [ *config.additional_paths, "#{config.source_path}/**/*", "yarn.lock", "package.json", "config/webpack/**/*" ].freeze end def compilation_digest_path config.cache_path.join("last-compilation-digest-#{webpacker.env}") end def webpack_env return env unless defined?(ActionController::Base) env.merge("WEBPACKER_ASSET_HOST" => ENV.fetch("WEBPACKER_ASSET_HOST", ActionController::Base.helpers.compute_asset_host), "WEBPACKER_RELATIVE_URL_ROOT" => ENV.fetch("WEBPACKER_RELATIVE_URL_ROOT", ActionController::Base.relative_url_root), "WEBPACKER_CONFIG" => webpacker.config_path.to_s) end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/env.rb
lib/webpacker/env.rb
class Webpacker::Env DEFAULT = "production".freeze delegate :config_path, :logger, to: :@webpacker def self.inquire(webpacker) new(webpacker).inquire end def initialize(webpacker) @webpacker = webpacker end def inquire fallback_env_warning if config_path.exist? && !current current || DEFAULT.inquiry end private def current Rails.env.presence_in(available_environments) end def fallback_env_warning logger.info "RAILS_ENV=#{Rails.env} environment is not defined in config/webpacker.yml, falling back to #{DEFAULT} environment" end def available_environments if config_path.exist? begin YAML.load_file(config_path.to_s, aliases: true) rescue ArgumentError YAML.load_file(config_path.to_s) end else [].freeze end rescue Psych::SyntaxError => e raise "YAML syntax error occurred while parsing #{config_path}. " \ "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \ "Error: #{e.message}" end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/railtie.rb
lib/webpacker/railtie.rb
require "rails/railtie" require "webpacker/helper" require "webpacker/dev_server_proxy" class Webpacker::Engine < ::Rails::Engine # Allows Webpacker config values to be set via Rails env config files config.webpacker = ActiveSupport::OrderedOptions.new initializer "webpacker.proxy" do |app| if (Webpacker.config.dev_server.present? rescue nil) app.middleware.insert_before 0, Rails::VERSION::MAJOR >= 5 ? Webpacker::DevServerProxy : "Webpacker::DevServerProxy", ssl_verify_none: true end end initializer "webpacker.helper" do ActiveSupport.on_load :action_controller do ActionController::Base.helper Webpacker::Helper end ActiveSupport.on_load :action_view do include Webpacker::Helper end end initializer "webpacker.logger" do config.after_initialize do if ::Rails.logger.respond_to?(:tagged) Webpacker.logger = ::Rails.logger else Webpacker.logger = ActiveSupport::TaggedLogging.new(::Rails.logger) end end end initializer "webpacker.bootstrap" do if defined?(Rails::Server) || defined?(Rails::Console) Webpacker.bootstrap if defined?(Spring) require "spring/watcher" Spring.after_fork { Webpacker.bootstrap } Spring.watch(Webpacker.config.config_path) end end end initializer "webpacker.set_source" do |app| if Webpacker.config.config_path.exist? app.config.javascript_path = Webpacker.config.source_path.relative_path_from(Rails.root.join("app")).to_s end end initializer "webpacker.remove_app_packs_from_the_autoload_paths" do Rails.application.config.before_initialize do if Webpacker.config.config_path.exist? source_path = Webpacker.config.source_path.to_s ActiveSupport::Dependencies.autoload_paths.delete(source_path) end end end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/dev_server.rb
lib/webpacker/dev_server.rb
class Webpacker::DevServer DEFAULT_ENV_PREFIX = "WEBPACKER_DEV_SERVER".freeze # Configure dev server connection timeout (in seconds), default: 0.01 # Webpacker.dev_server.connect_timeout = 1 cattr_accessor(:connect_timeout) { 0.01 } attr_reader :config def initialize(config) @config = config end def running? if config.dev_server.present? Socket.tcp(host, port, connect_timeout: connect_timeout).close true else false end rescue false end def host fetch(:host) end def port fetch(:port) end def https? case fetch(:https) when true, "true", Hash true else false end end def protocol https? ? "https" : "http" end def host_with_port "#{host}:#{port}" end def pretty? fetch(:pretty) end def hmr? fetch(:hmr) end def env_prefix config.dev_server.fetch(:env_prefix, DEFAULT_ENV_PREFIX) end private def fetch(key) return nil unless config.dev_server.present? ENV["#{env_prefix}_#{key.upcase}"] || config.dev_server.fetch(key, defaults[key]) end def defaults config.send(:defaults)[:dev_server] || {} end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/configuration.rb
lib/webpacker/configuration.rb
require "yaml" require "active_support/core_ext/hash/keys" require "active_support/core_ext/hash/indifferent_access" class Webpacker::Configuration class << self attr_accessor :installing end attr_reader :root_path, :config_path, :env def initialize(root_path:, config_path:, env:) @root_path = root_path @config_path = config_path @env = env end def dev_server fetch(:dev_server) end def compile? fetch(:compile) end def source_path root_path.join(fetch(:source_path)) end def additional_paths fetch(:additional_paths) end def source_entry_path source_path.join(fetch(:source_entry_path)) end def public_path root_path.join(fetch(:public_root_path)) end def public_output_path public_path.join(fetch(:public_output_path)) end def public_manifest_path public_output_path.join("manifest.json") end def cache_manifest? fetch(:cache_manifest) end def cache_path root_path.join(fetch(:cache_path)) end def check_yarn_integrity=(value) warn <<~EOS Webpacker::Configuration#check_yarn_integrity=(value) is obsolete. The integrity check has been removed from Webpacker (https://github.com/rails/webpacker/pull/2518) so changing this setting will have no effect. EOS end def webpack_compile_output? fetch(:webpack_compile_output) end def fetch(key) data.fetch(key, defaults[key]) end private def data @data ||= load end def load config = begin YAML.load_file(config_path.to_s, aliases: true) rescue ArgumentError YAML.load_file(config_path.to_s) end config[env].deep_symbolize_keys rescue Errno::ENOENT => e if self.class.installing {} else raise "Webpacker configuration file not found #{config_path}. " \ "Please run rails webpacker:install " \ "Error: #{e.message}" end rescue Psych::SyntaxError => e raise "YAML syntax error occurred while parsing #{config_path}. " \ "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \ "Error: #{e.message}" end def defaults @defaults ||= begin path = File.expand_path("../../install/config/webpacker.yml", __FILE__) config = begin YAML.load_file(path, aliases: true) rescue ArgumentError YAML.load_file(path) end HashWithIndifferentAccess.new(config[env]) end end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/runner.rb
lib/webpacker/runner.rb
module Webpacker class Runner def self.run(argv) $stdout.sync = true new(argv).run end def initialize(argv) @argv = argv @app_path = File.expand_path(".", Dir.pwd) @node_modules_bin_path = ENV["WEBPACKER_NODE_MODULES_BIN_PATH"] || `yarn bin`.chomp @webpack_config = File.join(@app_path, "config/webpack/#{ENV["NODE_ENV"]}.js") @webpacker_config = ENV["WEBPACKER_CONFIG"] || File.join(@app_path, "config/webpacker.yml") unless File.exist?(@webpack_config) $stderr.puts "webpack config #{@webpack_config} not found, please run 'bundle exec rails webpacker:install' to install Webpacker with default configs or add the missing config file for your custom environment." exit! end end end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/webpack_runner.rb
lib/webpacker/webpack_runner.rb
require "shellwords" require "webpacker/runner" module Webpacker class WebpackRunner < Webpacker::Runner WEBPACK_COMMANDS = [ "help", "h", "--help", "-h", "version", "v", "--version", "-v", "info", "i" ].freeze def run env = Webpacker::Compiler.env env["WEBPACKER_CONFIG"] = @webpacker_config cmd = if node_modules_bin_exist? ["#{@node_modules_bin_path}/webpack"] else ["yarn", "webpack"] end if @argv.delete "--debug-webpacker" cmd = ["node", "--inspect-brk"] + cmd end if @argv.delete "--trace-deprecation" cmd = ["node", "--trace-deprecation"] + cmd end if @argv.delete "--no-deprecation" cmd = ["node", "--no-deprecation"] + cmd end # Webpack commands are not compatible with --config option. if (@argv & WEBPACK_COMMANDS).empty? cmd += ["--config", @webpack_config] end cmd += @argv Dir.chdir(@app_path) do Kernel.exec env, *cmd end end private def node_modules_bin_exist? File.exist?("#{@node_modules_bin_path}/webpack") end end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/commands.rb
lib/webpacker/commands.rb
class Webpacker::Commands delegate :config, :compiler, :manifest, :logger, to: :@webpacker def initialize(webpacker) @webpacker = webpacker end # Cleanup old assets in the compile directory. By default it will # keep the latest version, 2 backups created within the past hour. # # Examples # # To force only 1 backup to be kept, set count=1 and age=0. # # To only keep files created within the last 10 minutes, set count=0 and # age=600. # def clean(count = 2, age = 3600) if config.public_output_path.exist? && config.public_manifest_path.exist? packs .map do |paths| paths.map { |path| [Time.now - File.mtime(path), path] } .sort .reject.with_index do |(file_age, _), index| file_age < age || index < count end .map { |_, path| path } end .flatten .compact .each do |file| if File.file?(file) File.delete(file) logger.info "Removed #{file}" end end end true end def clobber config.public_output_path.rmtree if config.public_output_path.exist? config.cache_path.rmtree if config.cache_path.exist? end def bootstrap manifest.refresh end def compile compiler.compile.tap do |success| manifest.refresh if success end end private def packs all_files = Dir.glob("#{config.public_output_path}/**/*") manifest_config = Dir.glob("#{config.public_manifest_path}*") packs = all_files - manifest_config - current_version packs.reject { |file| File.directory?(file) }.group_by do |path| base, _, ext = File.basename(path).scan(/(.*)(-[\da-f]+)(\.\w+)/).flatten "#{File.dirname(path)}/#{base}#{ext}" end.values end def current_version packs = manifest.refresh.values.map do |value| value = value["src"] if value.is_a?(Hash) next unless value.is_a?(String) File.join(config.root_path, "public", "#{value}*") end.compact Dir.glob(packs).uniq end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/helper.rb
lib/webpacker/helper.rb
module Webpacker::Helper # Returns the current Webpacker instance. # Could be overridden to use multiple Webpacker # configurations within the same app (e.g. with engines). def current_webpacker_instance Webpacker.instance end # Computes the relative path for a given Webpacker asset. # Returns the relative path using manifest.json and passes it to path_to_asset helper. # This will use path_to_asset internally, so most of their behaviors will be the same. # # Example: # # <%= asset_pack_path 'calendar.css' %> # => "/packs/calendar-1016838bab065ae1e122.css" def asset_pack_path(name, **options) path_to_asset(current_webpacker_instance.manifest.lookup!(name), options) end # Computes the absolute path for a given Webpacker asset. # Returns the absolute path using manifest.json and passes it to url_to_asset helper. # This will use url_to_asset internally, so most of their behaviors will be the same. # # Example: # # <%= asset_pack_url 'calendar.css' %> # => "http://example.com/packs/calendar-1016838bab065ae1e122.css" def asset_pack_url(name, **options) url_to_asset(current_webpacker_instance.manifest.lookup!(name), options) end # Computes the relative path for a given Webpacker image with the same automated processing as image_pack_tag. # Returns the relative path using manifest.json and passes it to path_to_asset helper. # This will use path_to_asset internally, so most of their behaviors will be the same. def image_pack_path(name, **options) resolve_path_to_image(name, **options) end # Computes the absolute path for a given Webpacker image with the same automated # processing as image_pack_tag. Returns the relative path using manifest.json # and passes it to path_to_asset helper. This will use path_to_asset internally, # so most of their behaviors will be the same. def image_pack_url(name, **options) resolve_path_to_image(name, **options.merge(protocol: :request)) end # Creates an image tag that references the named pack file. # # Example: # # <%= image_pack_tag 'application.png', size: '16x10', alt: 'Edit Entry' %> # <img alt='Edit Entry' src='/packs/application-k344a6d59eef8632c9d1.png' width='16' height='10' /> # # <%= image_pack_tag 'picture.png', srcset: { 'picture-2x.png' => '2x' } %> # <img srcset= "/packs/picture-2x-7cca48e6cae66ec07b8e.png 2x" src="/packs/picture-c38deda30895059837cf.png" > def image_pack_tag(name, **options) if options[:srcset] && !options[:srcset].is_a?(String) options[:srcset] = options[:srcset].map do |src_name, size| "#{resolve_path_to_image(src_name)} #{size}" end.join(", ") end image_tag(resolve_path_to_image(name), options) end # Creates a link tag for a favicon that references the named pack file. # # Example: # # <%= favicon_pack_tag 'mb-icon.png', rel: 'apple-touch-icon', type: 'image/png' %> # <link href="/packs/mb-icon-k344a6d59eef8632c9d1.png" rel="apple-touch-icon" type="image/png" /> def favicon_pack_tag(name, **options) favicon_link_tag(resolve_path_to_image(name), options) end # Creates script tags that reference the js chunks from entrypoints when using split chunks API, # as compiled by webpack per the entries list in package/environments/base.js. # By default, this list is auto-generated to match everything in # app/packs/entrypoints/*.js and all the dependent chunks. In production mode, the digested reference is automatically looked up. # See: https://webpack.js.org/plugins/split-chunks-plugin/ # # Example: # # <%= javascript_pack_tag 'calendar', 'map', 'data-turbolinks-track': 'reload' %> # => # <script src="/packs/vendor-16838bab065ae1e314.chunk.js" data-turbolinks-track="reload" defer="true"></script> # <script src="/packs/calendar~runtime-16838bab065ae1e314.chunk.js" data-turbolinks-track="reload" defer="true"></script> # <script src="/packs/calendar-1016838bab065ae1e314.chunk.js" data-turbolinks-track="reload" defer="true"></script> # <script src="/packs/map~runtime-16838bab065ae1e314.chunk.js" data-turbolinks-track="reload" defer="true"></script> # <script src="/packs/map-16838bab065ae1e314.chunk.js" data-turbolinks-track="reload" defer="true"></script> # # DO: # # <%= javascript_pack_tag 'calendar', 'map' %> # # DON'T: # # <%= javascript_pack_tag 'calendar' %> # <%= javascript_pack_tag 'map' %> def javascript_pack_tag(*names, defer: true, **options) javascript_include_tag(*sources_from_manifest_entrypoints(names, type: :javascript), **options.tap { |o| o[:defer] = defer }) end # Creates a link tag, for preloading, that references a given Webpacker asset. # In production mode, the digested reference is automatically looked up. # See: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content # # Example: # # <%= preload_pack_asset 'fonts/fa-regular-400.woff2' %> # => # <link rel="preload" href="/packs/fonts/fa-regular-400-944fb546bd7018b07190a32244f67dc9.woff2" as="font" type="font/woff2" crossorigin="anonymous"> def preload_pack_asset(name, **options) if self.class.method_defined?(:preload_link_tag) preload_link_tag(current_webpacker_instance.manifest.lookup!(name), options) else raise "You need Rails >= 5.2 to use this tag." end end # Creates link tags that reference the css chunks from entrypoints when using split chunks API, # as compiled by webpack per the entries list in package/environments/base.js. # By default, this list is auto-generated to match everything in # app/packs/entrypoints/*.js and all the dependent chunks. In production mode, the digested reference is automatically looked up. # See: https://webpack.js.org/plugins/split-chunks-plugin/ # # Examples: # # <%= stylesheet_pack_tag 'calendar', 'map' %> # => # <link rel="stylesheet" media="screen" href="/packs/3-8c7ce31a.chunk.css" /> # <link rel="stylesheet" media="screen" href="/packs/calendar-8c7ce31a.chunk.css" /> # <link rel="stylesheet" media="screen" href="/packs/map-8c7ce31a.chunk.css" /> # # When using the webpack-dev-server, CSS is inlined so HMR can be turned on for CSS, # including CSS modules # <%= stylesheet_pack_tag 'calendar', 'map' %> # => nil # # DO: # # <%= stylesheet_pack_tag 'calendar', 'map' %> # # DON'T: # # <%= stylesheet_pack_tag 'calendar' %> # <%= stylesheet_pack_tag 'map' %> def stylesheet_pack_tag(*names, **options) return "" if Webpacker.inlining_css? stylesheet_link_tag(*sources_from_manifest_entrypoints(names, type: :stylesheet), **options) end private def sources_from_manifest_entrypoints(names, type:) names.map { |name| current_webpacker_instance.manifest.lookup_pack_with_chunks!(name.to_s, type: type) }.flatten.uniq end def resolve_path_to_image(name, **options) path = name.starts_with?("static/") ? name : "static/#{name}" path_to_asset(current_webpacker_instance.manifest.lookup!(path), options) rescue path_to_asset(current_webpacker_instance.manifest.lookup!(name), options) end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/instance.rb
lib/webpacker/instance.rb
class Webpacker::Instance cattr_accessor(:logger) { ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDOUT)) } attr_reader :root_path, :config_path def initialize(root_path: Rails.root, config_path: Rails.root.join("config/webpacker.yml")) @root_path, @config_path = root_path, config_path end def env @env ||= Webpacker::Env.inquire self end def config @config ||= Webpacker::Configuration.new( root_path: root_path, config_path: config_path, env: env ) end def compiler @compiler ||= Webpacker::Compiler.new self end def dev_server @dev_server ||= Webpacker::DevServer.new config end def manifest @manifest ||= Webpacker::Manifest.new self end def commands @commands ||= Webpacker::Commands.new self end def inlining_css? dev_server.hmr? && dev_server.running? end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker/dev_server_proxy.rb
lib/webpacker/dev_server_proxy.rb
require "rack/proxy" class Webpacker::DevServerProxy < Rack::Proxy delegate :config, :dev_server, to: :@webpacker def initialize(app = nil, opts = {}) @webpacker = opts.delete(:webpacker) || Webpacker.instance opts[:streaming] = false if Rails.env.test? && !opts.key?(:streaming) super end def perform_request(env) if env["PATH_INFO"].start_with?("/#{public_output_uri_path}") && dev_server.running? env["HTTP_HOST"] = env["HTTP_X_FORWARDED_HOST"] = dev_server.host env["HTTP_X_FORWARDED_SERVER"] = dev_server.host_with_port env["HTTP_PORT"] = env["HTTP_X_FORWARDED_PORT"] = dev_server.port.to_s env["HTTP_X_FORWARDED_PROTO"] = env["HTTP_X_FORWARDED_SCHEME"] = dev_server.protocol unless dev_server.https? env["HTTPS"] = env["HTTP_X_FORWARDED_SSL"] = "off" end env["SCRIPT_NAME"] = "" super(env) else @app.call(env) end end private def public_output_uri_path config.public_output_path.relative_path_from(config.public_path).to_s + "/" end end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/install/binstubs.rb
lib/install/binstubs.rb
say "Copying binstubs" directory "#{__dir__}/bin", "bin" chmod "bin", 0755 & ~File.umask, verbose: false
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
rails/webpacker
https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/install/template.rb
lib/install/template.rb
# Install Webpacker copy_file "#{__dir__}/config/webpacker.yml", "config/webpacker.yml" copy_file "#{__dir__}/package.json", "package.json" say "Copying webpack core config" directory "#{__dir__}/config/webpack", "config/webpack" if Dir.exist?(Webpacker.config.source_path) say "The packs app source directory already exists" else say "Creating packs app source directory" empty_directory "app/javascript" copy_file "#{__dir__}/application.js", "app/javascript/application.js" end apply "#{__dir__}/binstubs.rb" git_ignore_path = Rails.root.join(".gitignore") if File.exist?(git_ignore_path) append_to_file git_ignore_path do "\n" + "/public/packs\n" + "/public/packs-test\n" + "/node_modules\n" + "/yarn-error.log\n" + "yarn-debug.log*\n" + ".yarn-integrity\n" end end if (app_layout_path = Rails.root.join("app/views/layouts/application.html.erb")).exist? say "Add JavaScript include tag in application layout" insert_into_file app_layout_path.to_s, %(\n <%= javascript_pack_tag "application" %>), before: /\s*<\/head>/ else say "Default application.html.erb is missing!", :red say %( Add <%= javascript_pack_tag "application" %> within the <head> tag in your custom layout.) end if (setup_path = Rails.root.join("bin/setup")).exist? say "Run bin/yarn during bin/setup" insert_into_file setup_path.to_s, <<-RUBY, after: %( system("bundle check") || system!("bundle install")\n) # Install JavaScript dependencies system! "bin/yarn" RUBY end if (asset_config_path = Rails.root.join("config/initializers/assets.rb")).exist? say "Add node_modules to the asset load path" append_to_file asset_config_path, <<-RUBY # Add node_modules folder to the asset load path. Rails.application.config.assets.paths << Rails.root.join("node_modules") RUBY end if (csp_config_path = Rails.root.join("config/initializers/content_security_policy.rb")).exist? say "Make note of webpack-dev-server exemption needed to csp" insert_into_file csp_config_path, <<-RUBY, after: %(# Rails.application.config.content_security_policy do |policy|) # # If you are using webpack-dev-server then specify webpack-dev-server host # policy.connect_src :self, :https, "http://localhost:3035", "ws://localhost:3035" if Rails.env.development? RUBY end results = [] Dir.chdir(Rails.root) do if Webpacker::VERSION.match?(/^[0-9]+\.[0-9]+\.[0-9]+$/) say "Installing all JavaScript dependencies [#{Webpacker::VERSION}]" results << run("yarn add @rails/webpacker@#{Webpacker::VERSION}") else say "Installing all JavaScript dependencies [from prerelease rails/webpacker]" results << run("yarn add @rails/webpacker@next") end package_json = File.read("#{__dir__}/../../package.json") webpack_version = package_json.match(/"webpack": "(.*)"/)[1] webpack_cli_version = package_json.match(/"webpack-cli": "(.*)"/)[1] # needed for experimental Yarn 2 support and should not harm Yarn 1 say "Installing webpack and webpack-cli as direct dependencies" results << run("yarn add webpack@#{webpack_version} webpack-cli@#{webpack_cli_version}") say "Installing dev server for live reloading" results << run("yarn add --dev webpack-dev-server @webpack-cli/serve") end if Rails::VERSION::MAJOR == 5 && Rails::VERSION::MINOR > 1 say "You need to allow webpack-dev-server host as allowed origin for connect-src.", :yellow say "This can be done in Rails 5.2+ for development environment in the CSP initializer", :yellow say "config/initializers/content_security_policy.rb with a snippet like this:", :yellow say "policy.connect_src :self, :https, \"http://localhost:3035\", \"ws://localhost:3035\" if Rails.env.development?", :yellow end unless results.all? say "Webpacker installation failed 😭 See above for details.", :red exit 1 end
ruby
MIT
a715e055d937748c7cfd34b0450295348ca13ee6
2026-01-04T15:43:16.273438Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/spec/search_spec.rb
spec/search_spec.rb
# encoding: utf-8 require "helper" describe T::Search do before :all do Timecop.freeze(Time.utc(2011, 11, 24, 16, 20, 0)) T.utc_offset = "PST" end before do T::RCFile.instance.path = "#{fixture_path}/.trc" @search = described_class.new @search.options = @search.options.merge("color" => "always") @old_stderr = $stderr $stderr = StringIO.new @old_stdout = $stdout $stdout = StringIO.new end after do T::RCFile.instance.reset $stderr = @old_stderr $stdout = @old_stdout end after :all do T.utc_offset = nil Timecop.return end describe "#all" do before do stub_get("/1.1/search/tweets.json").with(query: {q: "twitter", count: "100", include_entities: "false"}).to_return(body: fixture("search.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.all("twitter") expect(a_get("/1.1/search/tweets.json").with(query: {q: "twitter", count: "100", include_entities: "false"})).to have_been_made end it "has the correct output" do @search.all("twitter") expect($stdout.string).to eq <<-EOS @amaliasafitri2 RT @heartCOBOYJR: @AlvaroMaldini1 :-) http://t.co/Oxce0Tob3n @BPDPipesDrums Here is a picture of us getting ready to Santa into @CITCBoston! #Boston http://t.co/INACljvLLC @yunistosun6034 RT @sevilayyaziyor: gerçekten @ademyavuza ?Nasıl elin vardı böyle bi twit atmaya?Yolsuzlukla olmadı terörle mi şantaj yaparız diyosunuz? http://t.co/YPtNVYhLxl @_KAIRYALS My birthday cake was bomb http://t.co/LquXc7JXj4 @frozenharryx RT @LouisTexts: whos tessa? http://t.co/7DJQlmCfuu @MIKEFANTASMA Pues nada, aquí armando mi regalo de navidad solo me falta la cara y ya hago mi pedido con santa!.. http://t.co/iDC7bE9o4M @EleManera RT @xmyband: La gente che si arrabbia perché Harry non ha fatto gli auguri a Lou su Twitter. Non vorrei smontarvi, ma esistono i cellulari e i messaggi. @BigAlFerguson “@IrishRace; Merry Christmas to all our friends and followers from all @IrishRaceRally have a good one! http://t.co/rXFsC2ncFo” @Danloi1 @goksantezgel RT @nederlandline: Tayyip bey evladımızı severiz Biz ona dua ediyoruz.Fitnelere SAKIN HA! Mahmud Efndi (ks) #BedduayaLanetDuayaDavet http://t.co/h6MUyHxr9x" @MaimounaLvb RT @sissokodiaro: Miss mali pa pour les moche mon ga http://t.co/4WnwzoLgAD @MrSilpy @MrKATANI http://t.co/psk7K8rcND @hunterdl19 RT @MadisonBertini: Jakes turnt http://t.co/P60gYZNL8z @jayjay42__ RT @SteveStfler: Megan Fox Naked >> http://t.co/hMKlUMydFp @Bs1972Bill RT @erorin691: おはよう♪ http://t.co/v5YIFriCW3 @naked_gypsy All my friends are here 😂 http://t.co/w66iG4XXpL @whoa_lashton @Ashton5SOS http://t.co/uhYwoRY0Iz @seyfullaharpaci RT @Dedekorkut11: Utanmadıktan sonra... #CamiayaİftiraYolsuzluğuÖrtmez http://t.co/sXPn17D2md @NNGrilli esperando la Navidad :D http://t.co/iwBL2Xj3g7 @omersafak74 RT @1903Rc: Ben Beşiktaşlıyım.. http://t.co/qnEpDJwI3b @bryony_thfc merry christmas you arse X http://t.co/yRiWFgqr7p EOS end context "--csv" do before do @search.options = @search.options.merge("csv" => true) end it "outputs in CSV format" do @search.all("twitter") expect($stdout.string).to eq <<~EOS ID,Posted at,Screen name,Text 415600159511158784,2013-12-24 21:49:34 +0000,amaliasafitri2,RT @heartCOBOYJR: @AlvaroMaldini1 :-) http://t.co/Oxce0Tob3n 415600159490580480,2013-12-24 21:49:34 +0000,BPDPipesDrums,Here is a picture of us getting ready to Santa into @CITCBoston! #Boston http://t.co/INACljvLLC 415600159486406656,2013-12-24 21:49:34 +0000,yunistosun6034,RT @sevilayyaziyor: gerçekten @ademyavuza ?Nasıl elin vardı böyle bi twit atmaya?Yolsuzlukla olmadı terörle mi şantaj yaparız diyosunuz? http://t.co/YPtNVYhLxl 415600159486005248,2013-12-24 21:49:34 +0000,_KAIRYALS,My birthday cake was bomb http://t.co/LquXc7JXj4 415600159456632832,2013-12-24 21:49:34 +0000,frozenharryx,RT @LouisTexts: whos tessa? http://t.co/7DJQlmCfuu 415600159452438528,2013-12-24 21:49:34 +0000,MIKEFANTASMA,"Pues nada, aquí armando mi regalo de navidad solo me falta la cara y ya hago mi pedido con santa!.. http://t.co/iDC7bE9o4M" 415600159444439040,2013-12-24 21:49:34 +0000,EleManera,"RT @xmyband: La gente che si arrabbia perché Harry non ha fatto gli auguri a Lou su Twitter. Non vorrei smontarvi, ma esistono i cellulari e i messaggi." 415600159444434944,2013-12-24 21:49:34 +0000,BigAlFerguson,“@IrishRace; Merry Christmas to all our friends and followers from all @IrishRaceRally have a good one! http://t.co/rXFsC2ncFo” @Danloi1 415600159436066816,2013-12-24 21:49:34 +0000,goksantezgel,"RT @nederlandline: Tayyip bey evladımızı severiz Biz ona dua ediyoruz.Fitnelere SAKIN HA! Mahmud Efndi (ks) #BedduayaLanetDuayaDavet http://t.co/h6MUyHxr9x""" 415600159427670016,2013-12-24 21:49:34 +0000,MaimounaLvb,RT @sissokodiaro: Miss mali pa pour les moche mon ga http://t.co/4WnwzoLgAD 415600159423483904,2013-12-24 21:49:34 +0000,MrSilpy,@MrKATANI http://t.co/psk7K8rcND 415600159423094784,2013-12-24 21:49:34 +0000,hunterdl19,RT @MadisonBertini: Jakes turnt http://t.co/P60gYZNL8z 415600159419277312,2013-12-24 21:49:34 +0000,jayjay42__,RT @SteveStfler: Megan Fox Naked >> http://t.co/hMKlUMydFp 415600159415103488,2013-12-24 21:49:34 +0000,Bs1972Bill,RT @erorin691: おはよう♪ http://t.co/v5YIFriCW3 415600159415091200,2013-12-24 21:49:34 +0000,naked_gypsy,All my friends are here 😂 http://t.co/w66iG4XXpL 415600159398313984,2013-12-24 21:49:34 +0000,whoa_lashton,@Ashton5SOS http://t.co/uhYwoRY0Iz 415600159389937664,2013-12-24 21:49:34 +0000,seyfullaharpaci,RT @Dedekorkut11: Utanmadıktan sonra... #CamiayaİftiraYolsuzluğuÖrtmez http://t.co/sXPn17D2md 415600159389519872,2013-12-24 21:49:34 +0000,NNGrilli,esperando la Navidad :D http://t.co/iwBL2Xj3g7 415600159373144064,2013-12-24 21:49:34 +0000,omersafak74,RT @1903Rc: Ben Beşiktaşlıyım.. http://t.co/qnEpDJwI3b 415600159372767232,2013-12-24 21:49:34 +0000,bryony_thfc,merry christmas you arse X http://t.co/yRiWFgqr7p EOS end end context "--long" do before do @search.options = @search.options.merge("long" => true) end it "outputs in long format" do @search.all("twitter") expect($stdout.string).to eq <<~EOS ID Posted at Screen name Text 415600159511158784 Dec 24 13:49 @amaliasafitri2 RT @heartCOBOYJR: @Alvaro... 415600159490580480 Dec 24 13:49 @BPDPipesDrums Here is a picture of us g... 415600159486406656 Dec 24 13:49 @yunistosun6034 RT @sevilayyaziyor: gerçe... 415600159486005248 Dec 24 13:49 @_KAIRYALS My birthday cake was bomb... 415600159456632832 Dec 24 13:49 @frozenharryx RT @LouisTexts: whos tess... 415600159452438528 Dec 24 13:49 @MIKEFANTASMA Pues nada, aquí armando m... 415600159444439040 Dec 24 13:49 @EleManera RT @xmyband: La gente che... 415600159444434944 Dec 24 13:49 @BigAlFerguson “@IrishRace; Merry Christ... 415600159436066816 Dec 24 13:49 @goksantezgel RT @nederlandline: Tayyip... 415600159427670016 Dec 24 13:49 @MaimounaLvb RT @sissokodiaro: Miss ma... 415600159423483904 Dec 24 13:49 @MrSilpy @MrKATANI http://t.co/psk... 415600159423094784 Dec 24 13:49 @hunterdl19 RT @MadisonBertini: Jakes... 415600159419277312 Dec 24 13:49 @jayjay42__ RT @SteveStfler: Megan Fo... 415600159415103488 Dec 24 13:49 @Bs1972Bill RT @erorin691: おはよう♪ http... 415600159415091200 Dec 24 13:49 @naked_gypsy All my friends are here 😂... 415600159398313984 Dec 24 13:49 @whoa_lashton @Ashton5SOS http://t.co/u... 415600159389937664 Dec 24 13:49 @seyfullaharpaci RT @Dedekorkut11: Utanmad... 415600159389519872 Dec 24 13:49 @NNGrilli esperando la Navidad :D h... 415600159373144064 Dec 24 13:49 @omersafak74 RT @1903Rc: Ben Beşiktaşl... 415600159372767232 Dec 24 13:49 @bryony_thfc merry christmas you arse ... EOS end end context "--number" do before do stub_get("/1.1/search/tweets.json").with(query: {q: "twitter", count: "1", include_entities: "false"}).to_return(body: fixture("search2.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/search/tweets.json").with(query: {q: "twitter", count: "100", include_entities: "false"}).to_return(body: fixture("search.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/search/tweets.json").with(query: {q: "twitter", count: "100", include_entities: "1", max_id: "415600158693675007"}).to_return(body: fixture("search2.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "limits the number of results to 1" do @search.options = @search.options.merge("number" => 1) @search.all("twitter") expect(a_get("/1.1/search/tweets.json").with(query: {q: "twitter", count: "100", include_entities: "false"})).to have_been_made end it "limits the number of results to 201" do @search.options = @search.options.merge("number" => 201) @search.all("twitter") expect(a_get("/1.1/search/tweets.json").with(query: {q: "twitter", count: "100", include_entities: "false"})).to have_been_made expect(a_get("/1.1/search/tweets.json").with(query: {q: "twitter", count: "100", include_entities: "1", max_id: "415600158693675007"})).to have_been_made end end end describe "#favorites" do before do stub_get("/1.1/favorites/list.json").with(query: {count: "200", include_entities: "false"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/favorites/list.json").with(query: {count: "200", max_id: "244099460672679937", include_entities: "false"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.favorites("twitter") expect(a_get("/1.1/favorites/list.json").with(query: {count: "200", include_entities: "false"})).to have_been_made expect(a_get("/1.1/favorites/list.json").with(query: {count: "200", max_id: "244099460672679937", include_entities: "false"})).to have_been_made end it "has the correct output" do @search.favorites("twitter") expect($stdout.string).to eq <<-EOS @sferik @episod @twitterapi now https://t.co/I17jUTu2 and https://t.co/deDu4Hgw seem to be missing "1.1" from the URL. @sferik @episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? EOS end context "--csv" do before do @search.options = @search.options.merge("csv" => true) end it "outputs in CSV format" do @search.favorites("twitter") expect($stdout.string).to eq <<~EOS ID,Posted at,Screen name,Text 244102209942458368,2012-09-07 15:57:56 +0000,sferik,"@episod @twitterapi now https://t.co/I17jUTu2 and https://t.co/deDu4Hgw seem to be missing ""1.1"" from the URL." 244100411563339777,2012-09-07 15:50:47 +0000,sferik,@episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? EOS end end context "--decode-uris" do before do @search.options = @search.options.merge("decode_uris" => true) stub_get("/1.1/favorites/list.json").with(query: {count: "200", include_entities: "true"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/favorites/list.json").with(query: {count: "200", include_entities: "true", max_id: "244099460672679937"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.favorites("twitter") expect(a_get("/1.1/favorites/list.json").with(query: {count: "200", include_entities: "true"})).to have_been_made expect(a_get("/1.1/favorites/list.json").with(query: {count: "200", include_entities: "true", max_id: "244099460672679937"})).to have_been_made end it "decodes URLs" do @search.favorites("twitter") expect($stdout.string).to include "https://twitter.com/sferik/status/243988000076337152" end end context "--long" do before do @search.options = @search.options.merge("long" => true) end it "outputs in long format" do @search.favorites("twitter") expect($stdout.string).to eq <<~EOS ID Posted at Screen name Text 244102209942458368 Sep 7 07:57 @sferik @episod @twitterapi now https:... 244100411563339777 Sep 7 07:50 @sferik @episod @twitterapi Did you ca... EOS end end context "Twitter is down" do it "retries 3 times and then raise an error" do stub_get("/1.1/favorites/list.json").with(query: {count: "200", include_entities: "false"}).to_return(status: 502, headers: {content_type: "application/json; charset=utf-8"}) expect do @search.favorites("twitter") end.to raise_error(Twitter::Error::BadGateway) expect(a_get("/1.1/favorites/list.json").with(query: {count: "200", include_entities: "false"})).to have_been_made.times(3) end end context "with a user passed" do before do stub_get("/1.1/favorites/list.json").with(query: {count: "200", screen_name: "sferik", include_entities: "false"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/favorites/list.json").with(query: {count: "200", max_id: "244099460672679937", screen_name: "sferik", include_entities: "false"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.favorites("sferik", "twitter") expect(a_get("/1.1/favorites/list.json").with(query: {count: "200", screen_name: "sferik", include_entities: "false"})).to have_been_made expect(a_get("/1.1/favorites/list.json").with(query: {count: "200", max_id: "244099460672679937", screen_name: "sferik", include_entities: "false"})).to have_been_made end it "has the correct output" do @search.favorites("sferik", "twitter") expect($stdout.string).to eq <<-EOS @sferik @episod @twitterapi now https://t.co/I17jUTu2 and https://t.co/deDu4Hgw seem to be missing "1.1" from the URL. @sferik @episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? EOS end context "--id" do before do @search.options = @search.options.merge("id" => true) stub_get("/1.1/favorites/list.json").with(query: {count: "200", user_id: "7505382", include_entities: "false"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/favorites/list.json").with(query: {count: "200", max_id: "244099460672679937", user_id: "7505382", include_entities: "false"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.favorites("7505382", "twitter") expect(a_get("/1.1/favorites/list.json").with(query: {count: "200", user_id: "7505382", include_entities: "false"})).to have_been_made expect(a_get("/1.1/favorites/list.json").with(query: {count: "200", max_id: "244099460672679937", user_id: "7505382", include_entities: "false"})).to have_been_made end it "has the correct output" do @search.favorites("7505382", "twitter") expect($stdout.string).to eq <<-EOS @sferik @episod @twitterapi now https://t.co/I17jUTu2 and https://t.co/deDu4Hgw seem to be missing "1.1" from the URL. @sferik @episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? EOS end end end end describe "#mentions" do before do stub_get("/1.1/statuses/mentions_timeline.json").with(query: {count: "200", include_entities: "false"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/statuses/mentions_timeline.json").with(query: {count: "200", max_id: "244099460672679937", include_entities: "false"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.mentions("twitter") expect(a_get("/1.1/statuses/mentions_timeline.json").with(query: {count: "200", include_entities: "false"})).to have_been_made expect(a_get("/1.1/statuses/mentions_timeline.json").with(query: {count: "200", max_id: "244099460672679937", include_entities: "false"})).to have_been_made end it "has the correct output" do @search.mentions("twitter") expect($stdout.string).to eq <<-EOS @sferik @episod @twitterapi now https://t.co/I17jUTu2 and https://t.co/deDu4Hgw seem to be missing "1.1" from the URL. @sferik @episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? EOS end context "--csv" do before do @search.options = @search.options.merge("csv" => true) end it "outputs in CSV format" do @search.mentions("twitter") expect($stdout.string).to eq <<~EOS ID,Posted at,Screen name,Text 244102209942458368,2012-09-07 15:57:56 +0000,sferik,"@episod @twitterapi now https://t.co/I17jUTu2 and https://t.co/deDu4Hgw seem to be missing ""1.1"" from the URL." 244100411563339777,2012-09-07 15:50:47 +0000,sferik,@episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? EOS end end context "--decode-uris" do before do @search.options = @search.options.merge("decode_uris" => true) stub_get("/1.1/statuses/mentions_timeline.json").with(query: {count: "200", include_entities: "true"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/statuses/mentions_timeline.json").with(query: {count: "200", include_entities: "true", max_id: "244099460672679937"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.mentions("twitter") expect(a_get("/1.1/statuses/mentions_timeline.json").with(query: {count: "200", include_entities: "true"})).to have_been_made expect(a_get("/1.1/statuses/mentions_timeline.json").with(query: {count: "200", include_entities: "true", max_id: "244099460672679937"})).to have_been_made end it "decodes URLs" do @search.mentions("twitter") expect($stdout.string).to include "https://twitter.com/sferik/status/243988000076337152" end end context "--long" do before do @search.options = @search.options.merge("long" => true) end it "outputs in long format" do @search.mentions("twitter") expect($stdout.string).to eq <<~EOS ID Posted at Screen name Text 244102209942458368 Sep 7 07:57 @sferik @episod @twitterapi now https:... 244100411563339777 Sep 7 07:50 @sferik @episod @twitterapi Did you ca... EOS end end context "Twitter is down" do it "retries 3 times and then raise an error" do stub_get("/1.1/statuses/mentions_timeline.json").with(query: {count: "200", include_entities: "false"}).to_return(status: 502, headers: {content_type: "application/json; charset=utf-8"}) expect do @search.mentions("twitter") end.to raise_error(Twitter::Error::BadGateway) expect(a_get("/1.1/statuses/mentions_timeline.json").with(query: {count: "200", include_entities: "false"})).to have_been_made.times(3) end end end describe "#list" do before do stub_get("/1.1/lists/statuses.json").with(query: {count: "200", owner_screen_name: "testcli", slug: "presidents", include_entities: "false"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/lists/statuses.json").with(query: {count: "200", max_id: "244099460672679937", owner_screen_name: "testcli", slug: "presidents", include_entities: "false"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.list("presidents", "twitter") expect(a_get("/1.1/lists/statuses.json").with(query: {count: "200", owner_screen_name: "testcli", slug: "presidents", include_entities: "false"})).to have_been_made expect(a_get("/1.1/lists/statuses.json").with(query: {count: "200", max_id: "244099460672679937", owner_screen_name: "testcli", slug: "presidents", include_entities: "false"})).to have_been_made end it "has the correct output" do @search.list("presidents", "twitter") expect($stdout.string).to eq <<-EOS @sferik @episod @twitterapi now https://t.co/I17jUTu2 and https://t.co/deDu4Hgw seem to be missing "1.1" from the URL. @sferik @episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? EOS end context "--csv" do before do @search.options = @search.options.merge("csv" => true) end it "outputs in CSV format" do @search.list("presidents", "twitter") expect($stdout.string).to eq <<~EOS ID,Posted at,Screen name,Text 244102209942458368,2012-09-07 15:57:56 +0000,sferik,"@episod @twitterapi now https://t.co/I17jUTu2 and https://t.co/deDu4Hgw seem to be missing ""1.1"" from the URL." 244100411563339777,2012-09-07 15:50:47 +0000,sferik,@episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? EOS end end context "--decode-uris" do before do @search.options = @search.options.merge("decode_uris" => true) stub_get("/1.1/lists/statuses.json").with(query: {count: "200", owner_screen_name: "testcli", slug: "presidents", include_entities: "true"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/lists/statuses.json").with(query: {count: "200", max_id: "244099460672679937", owner_screen_name: "testcli", slug: "presidents", include_entities: "true"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.list("presidents", "twitter") expect(a_get("/1.1/lists/statuses.json").with(query: {count: "200", owner_screen_name: "testcli", slug: "presidents", include_entities: "true"})).to have_been_made expect(a_get("/1.1/lists/statuses.json").with(query: {count: "200", max_id: "244099460672679937", owner_screen_name: "testcli", slug: "presidents", include_entities: "true"})).to have_been_made end it "decodes URLs" do @search.list("presidents", "twitter") expect($stdout.string).to include "https://dev.twitter.com/docs/api/post/direct_messages/destroy" end end context "--long" do before do @search.options = @search.options.merge("long" => true) end it "outputs in long format" do @search.list("presidents", "twitter") expect($stdout.string).to eq <<~EOS ID Posted at Screen name Text 244102209942458368 Sep 7 07:57 @sferik @episod @twitterapi now https:... 244100411563339777 Sep 7 07:50 @sferik @episod @twitterapi Did you ca... EOS end end context "with a user passed" do it "requests the correct resource" do @search.list("testcli/presidents", "twitter") expect(a_get("/1.1/lists/statuses.json").with(query: {count: "200", owner_screen_name: "testcli", slug: "presidents", include_entities: "false"})).to have_been_made end context "--id" do before do @search.options = @search.options.merge("id" => true) stub_get("/1.1/lists/statuses.json").with(query: {count: "200", owner_id: "7505382", slug: "presidents", include_entities: "false"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/lists/statuses.json").with(query: {count: "200", max_id: "244099460672679937", owner_id: "7505382", slug: "presidents", include_entities: "false"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.list("7505382/presidents", "twitter") expect(a_get("/1.1/lists/statuses.json").with(query: {count: "200", owner_id: "7505382", slug: "presidents", include_entities: "false"})).to have_been_made expect(a_get("/1.1/lists/statuses.json").with(query: {count: "200", max_id: "244099460672679937", owner_id: "7505382", slug: "presidents", include_entities: "false"})).to have_been_made end end end context "Twitter is down" do it "retries 3 times and then raise an error" do stub_get("/1.1/lists/statuses.json").with(query: {count: "200", owner_screen_name: "testcli", slug: "presidents", include_entities: "false"}).to_return(status: 502, headers: {content_type: "application/json; charset=utf-8"}) expect do @search.list("presidents", "twitter") end.to raise_error(Twitter::Error::BadGateway) expect(a_get("/1.1/lists/statuses.json").with(query: {count: "200", owner_screen_name: "testcli", slug: "presidents", include_entities: "false"})).to have_been_made.times(3) end end end describe "#retweets" do before do stub_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", include_entities: "false"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", max_id: "244102729860009983", include_entities: "false"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.retweets("mosaic") expect(a_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", include_entities: "false"})).to have_been_made expect(a_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", max_id: "244102729860009983", include_entities: "false"})).to have_been_made.times(2) end it "has the correct output" do @search.retweets("mosaic") expect($stdout.string).to eq <<-EOS @calebelston RT @olivercameron: Mosaic looks cool: http://t.co/A8013C9k EOS end context "--csv" do before do @search.options = @search.options.merge("csv" => true) end it "outputs in CSV format" do @search.retweets("mosaic") expect($stdout.string).to eq <<~EOS ID,Posted at,Screen name,Text 244108728834592770,2012-09-07 16:23:50 +0000,calebelston,RT @olivercameron: Mosaic looks cool: http://t.co/A8013C9k EOS end end context "--decode-uris" do before do @search.options = @search.options.merge("decode_uris" => true) stub_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", include_entities: "true"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", max_id: "244102729860009983", include_entities: "true"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.retweets("mosaic") expect(a_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", include_entities: "true"})).to have_been_made expect(a_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", max_id: "244102729860009983", include_entities: "true"})).to have_been_made.times(2) end it "decodes URLs" do @search.retweets("mosaic") expect($stdout.string).to include "http://heymosaic.com/i/1Z8ssK" end end context "--long" do before do @search.options = @search.options.merge("long" => true) end it "outputs in long format" do @search.retweets("mosaic") expect($stdout.string).to eq <<~EOS ID Posted at Screen name Text 244108728834592770 Sep 7 08:23 @calebelston RT @olivercameron: Mosaic loo... EOS end end context "Twitter is down" do it "retries 3 times and then raise an error" do stub_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", include_entities: "false"}).to_return(status: 502, headers: {content_type: "application/json; charset=utf-8"}) expect do @search.retweets("mosaic") end.to raise_error(Twitter::Error::BadGateway) expect(a_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", include_entities: "false"})).to have_been_made.times(3) end end context "with a user passed" do before do stub_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", screen_name: "sferik", include_entities: "false"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", screen_name: "sferik", max_id: "244102729860009983", include_entities: "false"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @search.retweets("sferik", "mosaic") expect(a_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", screen_name: "sferik", include_entities: "false"})).to have_been_made expect(a_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", screen_name: "sferik", max_id: "244102729860009983", include_entities: "false"})).to have_been_made.times(2) end it "has the correct output" do @search.retweets("sferik", "mosaic") expect($stdout.string).to eq <<-EOS @calebelston RT @olivercameron: Mosaic looks cool: http://t.co/A8013C9k EOS end context "--id" do before do @search.options = @search.options.merge("id" => true) stub_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", user_id: "7505382", include_entities: "false"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/statuses/user_timeline.json").with(query: {count: "200", include_rts: "true", user_id: "7505382", max_id: "244102729860009983", include_entities: "false"}).to_return(body: fixture("empty_array.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
true
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/spec/delete_spec.rb
spec/delete_spec.rb
# encoding: utf-8 require "helper" describe T::Delete do before do T::RCFile.instance.path = "#{fixture_path}/.trc" @delete = described_class.new @old_stderr = $stderr $stderr = StringIO.new @old_stdout = $stdout $stdout = StringIO.new end after do T::RCFile.instance.reset $stderr = @old_stderr $stdout = @old_stdout end describe "#block" do before do @delete.options = @delete.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/blocks/destroy.json").with(body: {screen_name: "sferik"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @delete.block("sferik") expect(a_post("/1.1/blocks/destroy.json").with(body: {screen_name: "sferik"})).to have_been_made end it "has the correct output" do @delete.block("sferik") expect($stdout.string).to match(/^@testcli unblocked 1 user\.$/) end context "--id" do before do @delete.options = @delete.options.merge("id" => true) stub_post("/1.1/blocks/destroy.json").with(body: {user_id: "7505382"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @delete.block("7505382") expect(a_post("/1.1/blocks/destroy.json").with(body: {user_id: "7505382"})).to have_been_made end end end describe "#dm" do before do @delete.options = @delete.options.merge("profile" => "#{fixture_path}/.trc") stub_get("/1.1/direct_messages/events/show.json").with(query: {id: "1773478249"}).to_return(body: fixture("direct_message_event.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_delete("/1.1/direct_messages/events/destroy.json").with(query: {id: "1773478249"}).to_return(body: fixture("direct_message_event.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/users/show.json").with(query: {user_id: "58983"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do expect(Readline).to receive(:readline).with('Are you sure you want to permanently delete the direct message to @sferik: "testing"? [y/N] ', false).and_return("yes") @delete.dm("1773478249") expect(a_get("/1.1/direct_messages/events/show.json").with(query: {id: "1773478249"})).to have_been_made expect(a_delete("/1.1/direct_messages/events/destroy.json").with(query: {id: "1773478249"})).to have_been_made expect(a_get("/1.1/users/show.json").with(query: {user_id: "58983"})).to have_been_made end context "yes" do it "has the correct output" do expect(Readline).to receive(:readline).with('Are you sure you want to permanently delete the direct message to @sferik: "testing"? [y/N] ', false).and_return("yes") @delete.dm("1773478249") expect($stdout.string.chomp).to eq '@testcli deleted the direct message sent to @sferik: "testing"' end end context "no" do it "has the correct output" do expect(Readline).to receive(:readline).with('Are you sure you want to permanently delete the direct message to @sferik: "testing"? [y/N] ', false).and_return("no") @delete.dm("1773478249") expect($stdout.string.chomp).to be_empty end end context "--force" do before do @delete.options = @delete.options.merge("force" => true) end it "requests the correct resource" do @delete.dm("1773478249") expect(a_delete("/1.1/direct_messages/events/destroy.json").with(query: {id: "1773478249"})).to have_been_made end it "has the correct output" do @delete.dm("1773478249") expect($stdout.string.chomp).to eq "@testcli deleted 1 direct message." end end end describe "#favorite" do before do @delete.options = @delete.options.merge("profile" => "#{fixture_path}/.trc") stub_get("/1.1/statuses/show/28439861609.json").with(query: {include_my_retweet: "false"}).to_return(body: fixture("status.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_post("/1.1/favorites/destroy.json").with(body: {id: "28439861609"}).to_return(body: fixture("status.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do expect(Readline).to receive(:readline).with("Are you sure you want to remove @sferik's status: \"The problem with your code is that it's doing exactly what you told it to do.\" from your favorites? [y/N] ", false).and_return("yes") @delete.favorite("28439861609") expect(a_get("/1.1/statuses/show/28439861609.json").with(query: {include_my_retweet: "false"})).to have_been_made expect(a_post("/1.1/favorites/destroy.json").with(body: {id: "28439861609"})).to have_been_made end context "yes" do it "has the correct output" do expect(Readline).to receive(:readline).with("Are you sure you want to remove @sferik's status: \"The problem with your code is that it's doing exactly what you told it to do.\" from your favorites? [y/N] ", false).and_return("yes") @delete.favorite("28439861609") expect($stdout.string).to match(/^@testcli unfavorited @sferik's status: "The problem with your code is that it's doing exactly what you told it to do\."$/) end end context "no" do it "has the correct output" do expect(Readline).to receive(:readline).with("Are you sure you want to remove @sferik's status: \"The problem with your code is that it's doing exactly what you told it to do.\" from your favorites? [y/N] ", false).and_return("no") @delete.favorite("28439861609") expect($stdout.string.chomp).to be_empty end end context "--force" do before do @delete.options = @delete.options.merge("force" => true) end it "requests the correct resource" do @delete.favorite("28439861609") expect(a_post("/1.1/favorites/destroy.json").with(body: {id: "28439861609"})).to have_been_made end it "has the correct output" do @delete.favorite("28439861609") expect($stdout.string).to match(/^@testcli unfavorited @sferik's status: "The problem with your code is that it's doing exactly what you told it to do\."$/) end end end describe "#list" do before do @delete.options = @delete.options.merge("profile" => "#{fixture_path}/.trc") stub_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/lists/show.json").with(query: {owner_id: "7505382", slug: "presidents"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_post("/1.1/lists/destroy.json").with(body: {owner_id: "7505382", list_id: "8863586"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do expect(Readline).to receive(:readline).with('Are you sure you want to permanently delete the list "presidents"? [y/N] ', false).and_return("yes") @delete.list("presidents") expect(a_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"})).to have_been_made expect(a_post("/1.1/lists/destroy.json").with(body: {owner_id: "7505382", list_id: "8863586"})).to have_been_made end context "yes" do it "has the correct output" do expect(Readline).to receive(:readline).with('Are you sure you want to permanently delete the list "presidents"? [y/N] ', false).and_return("yes") @delete.list("presidents") expect($stdout.string.chomp).to eq '@testcli deleted the list "presidents".' end end context "no" do it "has the correct output" do expect(Readline).to receive(:readline).with('Are you sure you want to permanently delete the list "presidents"? [y/N] ', false).and_return("no") @delete.list("presidents") expect($stdout.string.chomp).to be_empty end end context "--force" do before do @delete.options = @delete.options.merge("force" => true) end it "requests the correct resource" do @delete.list("presidents") expect(a_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"})).to have_been_made expect(a_post("/1.1/lists/destroy.json").with(body: {owner_id: "7505382", list_id: "8863586"})).to have_been_made end it "has the correct output" do @delete.list("presidents") expect($stdout.string.chomp).to eq '@testcli deleted the list "presidents".' end end context "--id" do before do @delete.options = @delete.options.merge("id" => true) stub_get("/1.1/lists/show.json").with(query: {owner_id: "7505382", list_id: "8863586"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do expect(Readline).to receive(:readline).with('Are you sure you want to permanently delete the list "presidents"? [y/N] ', false).and_return("yes") @delete.list("8863586") expect(a_get("/1.1/lists/show.json").with(query: {owner_id: "7505382", list_id: "8863586"})).to have_been_made expect(a_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"})).to have_been_made expect(a_post("/1.1/lists/destroy.json").with(body: {owner_id: "7505382", list_id: "8863586"})).to have_been_made end end end describe "#mute" do before do @delete.options = @delete.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/mutes/users/destroy.json").with(body: {screen_name: "sferik"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @delete.mute("sferik") expect(a_post("/1.1/mutes/users/destroy.json").with(body: {screen_name: "sferik"})).to have_been_made end it "has the correct output" do @delete.mute("sferik") expect($stdout.string).to match(/^@testcli unmuted 1 user\.$/) end context "--id" do before do @delete.options = @delete.options.merge("id" => true) stub_post("/1.1/mutes/users/destroy.json").with(body: {user_id: "7505382"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @delete.mute("7505382") expect(a_post("/1.1/mutes/users/destroy.json").with(body: {user_id: "7505382"})).to have_been_made end end end describe "#account" do before do @delete.options = @delete.options.merge("profile" => "#{fixture_path}/.trc") delete_cli = { "delete_cli" => { "dw123" => { "consumer_key" => "abc123", "secret" => "epzrjvxtumoc", "token" => "428004849-cebdct6bwobn", "username" => "deletecli", "consumer_secret" => "asdfasd223sd2", }, "dw1234" => { "consumer_key" => "abc1234", "secret" => "epzrjvxtumoc", "token" => "428004849-cebdct6bwobn", "username" => "deletecli", "consumer_secret" => "asdfasd223sd2", }, }, } rcfile = @delete.instance_variable_get(:@rcfile) rcfile.profiles.merge!(delete_cli) rcfile.send(:write) end after do rcfile = @delete.instance_variable_get(:@rcfile) rcfile.delete_profile("delete_cli") end it "deletes the key" do @delete.account("delete_cli", "dw1234") rcfile = @delete.instance_variable_get(:@rcfile) expect(rcfile.profiles["delete_cli"].key?("dw1234")).to be false end it "deletes the account" do @delete.account("delete_cli") rcfile = @delete.instance_variable_get(:@rcfile) expect(rcfile.profiles.key?("delete_cli")).to be false end end describe "#status" do before do @delete.options = @delete.options.merge("profile" => "#{fixture_path}/.trc") stub_get("/1.1/statuses/show/26755176471724032.json").with(query: {include_my_retweet: "false"}).to_return(body: fixture("status.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_post("/1.1/statuses/destroy/26755176471724032.json").with(body: {trim_user: "true"}).to_return(body: fixture("status.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do expect(Readline).to receive(:readline).with("Are you sure you want to permanently delete @sferik's status: \"The problem with your code is that it's doing exactly what you told it to do.\"? [y/N] ", false).and_return("yes") @delete.status("26755176471724032") expect(a_get("/1.1/statuses/show/26755176471724032.json").with(query: {include_my_retweet: "false"})).to have_been_made expect(a_post("/1.1/statuses/destroy/26755176471724032.json").with(body: {trim_user: "true"})).to have_been_made end context "yes" do it "has the correct output" do expect(Readline).to receive(:readline).with("Are you sure you want to permanently delete @sferik's status: \"The problem with your code is that it's doing exactly what you told it to do.\"? [y/N] ", false).and_return("yes") @delete.status("26755176471724032") expect($stdout.string.chomp).to eq "@testcli deleted the Tweet: \"The problem with your code is that it's doing exactly what you told it to do.\"" end end context "no" do it "has the correct output" do expect(Readline).to receive(:readline).with("Are you sure you want to permanently delete @sferik's status: \"The problem with your code is that it's doing exactly what you told it to do.\"? [y/N] ", false).and_return("no") @delete.status("26755176471724032") expect($stdout.string.chomp).to be_empty end end context "--force" do before do @delete.options = @delete.options.merge("force" => true) end it "requests the correct resource" do @delete.status("26755176471724032") expect(a_post("/1.1/statuses/destroy/26755176471724032.json").with(body: {trim_user: "true"})).to have_been_made end it "has the correct output" do @delete.status("26755176471724032") expect($stdout.string.chomp).to eq "@testcli deleted the Tweet: \"The problem with your code is that it's doing exactly what you told it to do.\"" end end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/spec/rcfile_spec.rb
spec/rcfile_spec.rb
# encoding: utf-8 require "helper" describe T::RCFile do after do described_class.instance.reset FileUtils.rm_f("#{project_path}/tmp/trc") end it "is a singleton" do expect(described_class).to be_a Class expect do described_class.new end.to raise_error(NoMethodError, /private method (`|')new' called/) end describe "#[]" do it "returns the profiles for a user" do rcfile = described_class.instance rcfile.path = "#{fixture_path}/.trc" expect(rcfile["testcli"].keys).to eq %w[abc123] end end describe "#[]=" do it "adds a profile for a user" do rcfile = described_class.instance rcfile.path = "#{project_path}/tmp/trc" rcfile["testcli"] = { "abc123" => { username: "testcli", consumer_key: "abc123", consumer_secret: "def456", token: "ghi789", secret: "jkl012", }, } expect(rcfile["testcli"].keys).to eq %w[abc123] end it "is not be world writable" do rcfile = described_class.instance rcfile.path = "#{project_path}/tmp/trc" rcfile["testcli"] = { "abc123" => { username: "testcli", consumer_key: "abc123", consumer_secret: "def456", token: "ghi789", secret: "jkl012", }, } expect(File.world_writable?(rcfile.path)).to be_nil end it "is not be world readable" do rcfile = described_class.instance rcfile.path = "#{project_path}/tmp/trc" rcfile["testcli"] = { "abc123" => { username: "testcli", consumer_key: "abc123", consumer_secret: "def456", token: "ghi789", secret: "jkl012", }, } expect(File.world_readable?(rcfile.path)).to be_nil end end describe "#configuration" do it "returns configuration" do rcfile = described_class.instance rcfile.path = "#{fixture_path}/.trc" expect(rcfile.configuration.keys).to eq %w[default_profile] end end describe "#active_consumer_key" do it "returns default consumer key" do rcfile = described_class.instance rcfile.path = "#{fixture_path}/.trc" expect(rcfile.active_consumer_key).to eq "abc123" end end describe "#active_consumer_secret" do it "returns default consumer secret" do rcfile = described_class.instance rcfile.path = "#{fixture_path}/.trc" expect(rcfile.active_consumer_secret).to eq "asdfasd223sd2" end end describe "#active_profile" do it "returns default profile" do rcfile = described_class.instance rcfile.path = "#{fixture_path}/.trc" expect(rcfile.active_profile).to eq %w[testcli abc123] end end describe "#active_profile=" do it "sets default profile" do rcfile = described_class.instance rcfile.path = "#{project_path}/tmp/trc" rcfile.active_profile = {"username" => "testcli", "consumer_key" => "abc123"} expect(rcfile.active_profile).to eq %w[testcli abc123] end end describe "#active_token" do it "returns default token" do rcfile = described_class.instance rcfile.path = "#{fixture_path}/.trc" expect(rcfile.active_token).to eq "428004849-cebdct6bwobn" end end describe "#active_secret" do it "returns default secret" do rcfile = described_class.instance rcfile.path = "#{fixture_path}/.trc" expect(rcfile.active_secret).to eq "epzrjvxtumoc" end end describe "#delete" do it "deletes the rcfile" do path = "#{project_path}/tmp/trc" File.write(path, YAML.dump({})) expect(File.exist?(path)).to be true rcfile = described_class.instance rcfile.path = path rcfile.delete expect(File.exist?(path)).to be false end end describe "#empty?" do context "when a non-empty file exists" do it "returns false" do rcfile = described_class.instance rcfile.path = "#{fixture_path}/.trc" expect(rcfile.empty?).to be false end end context "when file does not exist at path" do it "returns true" do rcfile = described_class.instance rcfile.path = File.expand_path("fixtures/foo", __dir__) expect(rcfile.empty?).to be true end end end describe "#load_file" do context "when file exists at path" do it "loads data from file" do rcfile = described_class.instance rcfile.path = "#{fixture_path}/.trc" expect(rcfile.load_file["profiles"]["testcli"]["abc123"]["username"]).to eq "testcli" end end context "when file does not exist at path" do it "loads default structure" do rcfile = described_class.instance rcfile.path = File.expand_path("fixtures/foo", __dir__) expect(rcfile.load_file.keys.sort).to eq %w[configuration profiles] end end end describe "#path" do it "defaults to ~/.trc" do expect(described_class.instance.path).to eq File.join(File.expand_path("~"), ".trc") end end describe "#path=" do it "overrides path" do rcfile = described_class.instance rcfile.path = "#{project_path}/tmp/trc" expect(rcfile.path).to eq "#{project_path}/tmp/trc" end it "reloads data" do rcfile = described_class.instance rcfile.path = "#{fixture_path}/.trc" expect(rcfile["testcli"]["abc123"]["username"]).to eq "testcli" end end describe "#profiles" do it "returns profiles" do rcfile = described_class.instance rcfile.path = "#{fixture_path}/.trc" expect(rcfile.profiles.keys).to eq %w[testcli] end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/spec/editor_spec.rb
spec/editor_spec.rb
# encoding: utf-8 require "helper" describe T::Editor do context "when editing a file" do before do allow(described_class).to receive(:edit) do |path| File.binwrite(path, "A tweet!!!!") end end it "fetches your tweet content without comments" do expect(described_class.gets).to eq("A tweet!!!!") end end context "when fetching the editor to write in" do context "no $VISUAL or $EDITOR set" do before do ENV["EDITOR"] = ENV["VISUAL"] = nil end context "host_os is Mac OSX" do it "returns the system editor" do RbConfig::CONFIG["host_os"] = "darwin12.2.0" expect(described_class.editor).to eq("vi") end end context "host_os is Linux" do it "returns the system editor" do RbConfig::CONFIG["host_os"] = "3.2.0-4-amd64" expect(described_class.editor).to eq("vi") end end context "host_os is Windows" do it "returns the system editor" do RbConfig::CONFIG["host_os"] = "mswin" expect(described_class.editor).to eq("notepad") end end end context "$VISUAL is set" do before do ENV["EDITOR"] = nil ENV["VISUAL"] = "/my/vim/install" end it "returns the system editor" do expect(described_class.editor).to eq("/my/vim/install") end end context "$EDITOR is set" do before do ENV["EDITOR"] = "/usr/bin/subl" ENV["VISUAL"] = nil end it "returns the system editor" do expect(described_class.editor).to eq("/usr/bin/subl") end end context "$VISUAL and $EDITOR are set" do before do ENV["EDITOR"] = "/my/vastly/superior/editor" ENV["VISUAL"] = "/usr/bin/emacs" end it "returns the system editor" do expect(described_class.editor).to eq("/usr/bin/emacs") end end end context "when fetching system editor" do context "on a mac" do before do RbConfig::CONFIG["host_os"] = "darwin12.2.0" end it "returns 'vi' on a unix machine" do expect(described_class.system_editor).to eq("vi") end end context "on a Windows POC" do before do RbConfig::CONFIG["host_os"] = "mswin" end it "returns 'notepad' on a windows box" do expect(described_class.system_editor).to eq("notepad") end end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/spec/utils_spec.rb
spec/utils_spec.rb
# encoding: utf-8 require "helper" class Test; end describe T::Utils do before :all do Timecop.freeze(Time.utc(2011, 11, 24, 16, 20, 0)) T.utc_offset = -28_800 end before do @test = Test.new @test.extend(described_class) end after :all do T.utc_offset = nil Timecop.return end describe "#distance_of_time_in_words" do it 'returns "a split second" if difference is less than a second' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 11, 24, 16, 20, 0))).to eq "a split second" end it 'returns "a second" if difference is a second' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 11, 24, 16, 20, 1))).to eq "a second" end it 'returns "2 seconds" if difference is 2 seconds' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 11, 24, 16, 20, 2))).to eq "2 seconds" end it 'returns "59 seconds" if difference is just shy of 1 minute' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 11, 24, 16, 20, 59.9))).to eq "59 seconds" end it 'returns "a minute" if difference is 1 minute' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 11, 24, 16, 21, 0))).to eq "a minute" end it 'returns "2 minutes" if difference is 2 minutes' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 11, 24, 16, 22, 0))).to eq "2 minutes" end it 'returns "59 minutes" if difference is just shy of 1 hour' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 11, 24, 17, 19, 59.9))).to eq "59 minutes" end it 'returns "an hour" if difference is 1 hour' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 11, 24, 17, 20, 0))).to eq "an hour" end it 'returns "2 hours" if difference is 2 hours' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 11, 24, 18, 20, 0))).to eq "2 hours" end it 'returns "23 hours" if difference is just shy of 23.5 hours' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 11, 25, 15, 49, 59.9))).to eq "23 hours" end it 'returns "a day" if difference is 23.5 hours' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 11, 25, 15, 50, 0))).to eq "a day" end it 'returns "2 days" if difference is 2 days' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 11, 26, 16, 20, 0))).to eq "2 days" end it 'returns "29 days" if difference is just shy of 29.5 days' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 12, 24, 4, 19, 59.9))).to eq "29 days" end it 'returns "a month" if difference is 29.5 days' do expect(@test.send(:distance_of_time_in_words, Time.utc(2011, 12, 24, 4, 20, 0))).to eq "a month" end it 'returns "2 months" if difference is 2 months' do expect(@test.send(:distance_of_time_in_words, Time.utc(2012, 1, 24, 16, 20, 0))).to eq "2 months" end it 'returns "11 months" if difference is just shy of 11.5 months' do expect(@test.send(:distance_of_time_in_words, Time.utc(2012, 11, 8, 11, 19, 59.9))).to eq "11 months" end it 'returns "a year" if difference is 11.5 months' do expect(@test.send(:distance_of_time_in_words, Time.utc(2012, 11, 8, 11, 20, 0))).to eq "a year" end it 'returns "2 years" if difference is 2 years' do expect(@test.send(:distance_of_time_in_words, Time.utc(2013, 11, 24, 16, 20, 0))).to eq "2 years" end end describe "#strip_tags" do it "returns string sans tags" do expect(@test.send(:strip_tags, '<a href="http://twitter.com/#!/download/iphone" rel="nofollow">Twitter for iPhone</a>')).to eq "Twitter for iPhone" end end describe "#number_with_delimiter" do it "returns number with delimiter" do expect(@test.send(:number_with_delimiter, 1_234_567_890)).to eq "1,234,567,890" end context "with custom delimiter" do it "returns number with custom delimiter" do expect(@test.send(:number_with_delimiter, 1_234_567_890, ".")).to eq "1.234.567.890" end end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/spec/cli_spec.rb
spec/cli_spec.rb
# encoding: utf-8 require "helper" describe T::CLI do before :all do Timecop.freeze(Time.utc(2011, 11, 24, 16, 20, 0)) T.utc_offset = "PST" end before do T::RCFile.instance.path = "#{fixture_path}/.trc" @cli = described_class.new @cli.options = @cli.options.merge("color" => "always") @old_stderr = $stderr $stderr = StringIO.new @old_stdout = $stdout $stdout = StringIO.new end after do T::RCFile.instance.reset $stderr = @old_stderr $stdout = @old_stdout end after :all do T.utc_offset = nil Timecop.return end describe "#account" do before do @cli.options = @cli.options.merge("profile" => "#{fixture_path}/.trc") end it "has the correct output" do @cli.accounts expect($stdout.string).to eq <<~EOS testcli abc123 (active) EOS end end describe "#authorize" do before do @cli.options = @cli.options.merge("profile" => "#{project_path}/tmp/authorize", "display-uri" => true) stub_post("/oauth/request_token").to_return(body: fixture("request_token")) stub_post("/oauth/access_token").to_return(body: fixture("access_token")) stub_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do expect(Readline).to receive(:readline).with("Press [Enter] to open the Twitter Developer site. ", true).and_return("\n") expect(Readline).to receive(:readline).with("Enter your API key: ", true).and_return("abc123") expect(Readline).to receive(:readline).with("Enter your API secret: ", true).and_return("asdfasd223sd2") expect(Readline).to receive(:readline).with("Press [Enter] to open the Twitter app authorization page. ", true).and_return("\n") expect(Readline).to receive(:readline).with("Enter the supplied PIN: ", true).and_return("1234567890") @cli.authorize expect(a_post("/oauth/request_token")).to have_been_made expect(a_post("/oauth/access_token")).to have_been_made expect(a_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"})).to have_been_made end it "does not raise error" do expect do expect(Readline).to receive(:readline).with("Press [Enter] to open the Twitter Developer site. ", true).and_return("\n") expect(Readline).to receive(:readline).with("Enter your API key: ", true).and_return("abc123") expect(Readline).to receive(:readline).with("Enter your API secret: ", true).and_return("asdfasd223sd2") expect(Readline).to receive(:readline).with("Press [Enter] to open the Twitter app authorization page. ", true).and_return("\n") expect(Readline).to receive(:readline).with("Enter the supplied PIN: ", true).and_return("1234567890") @cli.authorize end.not_to raise_error end context "empty RC file" do before do file_path = "#{project_path}/tmp/empty" @cli.options = @cli.options.merge("profile" => file_path, "display-uri" => true) end after do file_path = "#{project_path}/tmp/empty" FileUtils.rm_f(file_path) end it "requests the correct resource" do expect(Readline).to receive(:readline).with("Press [Enter] to open the Twitter Developer site. ", true).and_return("\n") expect(Readline).to receive(:readline).with("Enter your API key: ", true).and_return("abc123") expect(Readline).to receive(:readline).with("Enter your API secret: ", true).and_return("asdfasd223sd2") expect(Readline).to receive(:readline).with("Press [Enter] to open the Twitter app authorization page. ", true).and_return("\n") expect(Readline).to receive(:readline).with("Enter the supplied PIN: ", true).and_return("1234567890") @cli.authorize expect(a_post("/oauth/request_token")).to have_been_made expect(a_post("/oauth/access_token")).to have_been_made expect(a_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"})).to have_been_made end it "does not raise error" do expect do expect(Readline).to receive(:readline).with("Press [Enter] to open the Twitter Developer site. ", true).and_return("\n") expect(Readline).to receive(:readline).with("Enter your API key: ", true).and_return("abc123") expect(Readline).to receive(:readline).with("Enter your API secret: ", true).and_return("asdfasd223sd2") expect(Readline).to receive(:readline).with("Press [Enter] to open the Twitter app authorization page. ", true).and_return("\n") expect(Readline).to receive(:readline).with("Enter the supplied PIN: ", true).and_return("1234567890") @cli.authorize end.not_to raise_error end end end describe "#block" do before do @cli.options = @cli.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/blocks/create.json").with(body: {screen_name: "sferik"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.block("sferik") expect(a_post("/1.1/blocks/create.json").with(body: {screen_name: "sferik"})).to have_been_made end it "has the correct output" do @cli.block("sferik") expect($stdout.string).to match(/^@testcli blocked 1 user/) end context "--id" do before do @cli.options = @cli.options.merge("id" => true) stub_post("/1.1/blocks/create.json").with(body: {user_id: "7505382"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.block("7505382") expect(a_post("/1.1/blocks/create.json").with(body: {user_id: "7505382"})).to have_been_made end end end describe "#direct_messages" do before do stub_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", include_entities: "false"}).to_return(body: fixture("direct_message_events.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", include_entities: "false", max_id: "856477710595624962"}).to_return(body: fixture("empty_cursor.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/users/lookup.json").with(query: {user_id: "358486183,311650899,422190131,759849327200047104,73660881,328677087,4374876088,2924245126"}).to_return(body: fixture("direct_message_users.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.direct_messages expect(a_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", include_entities: "false"})).to have_been_made expect(a_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", include_entities: "false", max_id: "856477710595624962"})).to have_been_made expect(a_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"})).to have_been_made expect(a_get("/1.1/users/lookup.json").with(query: {user_id: "358486183,311650899,422190131,759849327200047104,73660881,328677087,4374876088,2924245126"})).to have_been_made end it "has the correct output" do @cli.direct_messages expect($stdout.string).to eq <<-EOS @ Thanks https://twitter.com/i/stickers/image/10011 @Araujoselmaa ❤️ @nederfariar 😍 @juliawerneckx obrigada!!! bj @ https://twitter.com/i/stickers/image/10011 @marlonscampos OBRIGADO MINHA LINDA SERÁ INCRÍVEL ASSISTIR O TEU SHOW, VOU FAZER O POSSÍVEL PARA TE PRESTIGIAR. SUCESSO @abcss_cesar Obrigado. Vou adquiri-lo. Muito sucesso! @nederfariar COM CERTEZA QDO ESTIVER EM SAO PAUÇO IREI COM O MAIOR PRAZER SUCESSO LINDA @Free7Freejac 😍 Música boa para seu espetáculo em São-Paulo com seu amigo @Free7Freejac Jardim urbano @Free7Freejac https://twitter.com/messages/media/856478621090942979 @Free7Freejac Os amantes em face a o mar @Free7Freejac https://twitter.com/messages/media/856477710595624963 EOS end context "--csv" do before do @cli.options = @cli.options.merge("csv" => true) end it "outputs in CSV format" do @cli.direct_messages expect($stdout.string).to eq <<~EOS ID,Posted at,Screen name,Text 856574281366605831,2017-04-24 18:23:17 +0000,,Thanks https://twitter.com/i/stickers/image/10011 856571192978927619,2017-04-24 18:11:01 +0000,Araujoselmaa,❤️ 856554872984018948,2017-04-24 17:06:10 +0000,nederfariar,😍 856538753409703939,2017-04-24 16:02:07 +0000,juliawerneckx,obrigada!!! bj 856533644445396996,2017-04-24 15:41:49 +0000,, https://twitter.com/i/stickers/image/10011 856526573545062407,2017-04-24 15:13:43 +0000,marlonscampos,"OBRIGADO MINHA LINDA SERÁ INCRÍVEL ASSISTIR O TEU SHOW, VOU FAZER O POSSÍVEL PARA TE PRESTIGIAR. SUCESSO" 856516885524951043,2017-04-24 14:35:13 +0000,abcss_cesar,Obrigado. Vou adquiri-lo. Muito sucesso! 856502352299405315,2017-04-24 13:37:28 +0000,nederfariar,COM CERTEZA QDO ESTIVER EM SAO PAUÇO IREI COM O MAIOR PRAZER SUCESSO LINDA 856480124421771268,2017-04-24 12:09:08 +0000,Free7Freejac,😍 Música boa para seu espetáculo em São-Paulo com seu amigo 856478933260410883,2017-04-24 12:04:24 +0000,Free7Freejac,Jardim urbano 856478621090942979,2017-04-24 12:03:10 +0000,Free7Freejac, https://twitter.com/messages/media/856478621090942979 856477958885834755,2017-04-24 12:00:32 +0000,Free7Freejac,Os amantes em face a o mar 856477710595624963,2017-04-24 11:59:33 +0000,Free7Freejac, https://twitter.com/messages/media/856477710595624963 EOS end end context "--decode-uris" do before do @cli.options = @cli.options.merge("decode_uris" => true) stub_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", include_entities: "true"}).to_return(body: fixture("direct_message_events.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", max_id: "856477710595624962", include_entities: "true"}).to_return(body: fixture("empty_cursor.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.direct_messages expect(a_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", include_entities: "true"})).to have_been_made expect(a_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", max_id: "856477710595624962", include_entities: "true"})).to have_been_made end end context "--long" do before do @cli.options = @cli.options.merge("long" => true) end it "outputs in long format" do @cli.direct_messages expect($stdout.string).to eq <<~EOS ID Posted at Screen name Text 856574281366605831 Apr 24 10:23 @ Thanks https://twitter.com/... 856571192978927619 Apr 24 10:11 @Araujoselmaa ❤️ 856554872984018948 Apr 24 09:06 @nederfariar 😍 856538753409703939 Apr 24 08:02 @juliawerneckx obrigada!!! bj 856533644445396996 Apr 24 07:41 @ https://twitter.com/i/stic... 856526573545062407 Apr 24 07:13 @marlonscampos OBRIGADO MINHA LINDA SERÁ I... 856516885524951043 Apr 24 06:35 @abcss_cesar Obrigado. Vou adquiri-lo. M... 856502352299405315 Apr 24 05:37 @nederfariar COM CERTEZA QDO ESTIVER EM ... 856480124421771268 Apr 24 04:09 @Free7Freejac 😍 Música boa para seu espet... 856478933260410883 Apr 24 04:04 @Free7Freejac Jardim urbano 856478621090942979 Apr 24 04:03 @Free7Freejac https://twitter.com/messag... 856477958885834755 Apr 24 04:00 @Free7Freejac Os amantes em face a o mar 856477710595624963 Apr 24 03:59 @Free7Freejac https://twitter.com/messag... EOS end end context "--number" do before do stub_get("/1.1/users/lookup.json").with(query: {user_id: "358486183"}).to_return(body: fixture("users.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "limits the number of results to 1" do @cli.options = @cli.options.merge("number" => 1) @cli.direct_messages expect(a_get("/1.1/users/lookup.json").with(query: {user_id: "358486183"})).to have_been_made end end context "--reverse" do before do @cli.options = @cli.options.merge("reverse" => true) end it "reverses the order of the sort" do @cli.direct_messages expect($stdout.string).to eq <<-EOS @Free7Freejac https://twitter.com/messages/media/856477710595624963 @Free7Freejac Os amantes em face a o mar @Free7Freejac https://twitter.com/messages/media/856478621090942979 @Free7Freejac Jardim urbano @Free7Freejac 😍 Música boa para seu espetáculo em São-Paulo com seu amigo @nederfariar COM CERTEZA QDO ESTIVER EM SAO PAUÇO IREI COM O MAIOR PRAZER SUCESSO LINDA @abcss_cesar Obrigado. Vou adquiri-lo. Muito sucesso! @marlonscampos OBRIGADO MINHA LINDA SERÁ INCRÍVEL ASSISTIR O TEU SHOW, VOU FAZER O POSSÍVEL PARA TE PRESTIGIAR. SUCESSO @ https://twitter.com/i/stickers/image/10011 @juliawerneckx obrigada!!! bj @nederfariar 😍 @Araujoselmaa ❤️ @ Thanks https://twitter.com/i/stickers/image/10011 EOS end end end describe "#direct_messages_sent" do before do stub_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", include_entities: "false"}).to_return(body: fixture("direct_message_events.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", max_id: "856480385957548034", include_entities: "false"}).to_return(body: fixture("empty_cursor.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.direct_messages_sent expect(a_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", include_entities: "false"})).to have_been_made end it "has the correct output" do @cli.direct_messages_sent expect($stdout.string).to eq <<-EOS @ https://twitter.com/i/stickers/image/10018 @ https://twitter.com/i/stickers/image/10017 @ Obrigada Jacques EOS end context "--csv" do before do @cli.options = @cli.options.merge("csv" => true) end it "outputs in CSV format" do @cli.direct_messages_sent expect($stdout.string).to eq <<~EOS ID,Posted at,Screen name,Text 856523843892129796,2017-04-24 15:02:52 +0000,, https://twitter.com/i/stickers/image/10018 856523768910544899,2017-04-24 15:02:34 +0000,, https://twitter.com/i/stickers/image/10017 856480385957548035,2017-04-24 12:10:11 +0000,,Obrigada Jacques EOS end end context "--decode-uris" do before do @cli.options = @cli.options.merge("decode_uris" => true) stub_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", include_entities: "true"}).to_return(body: fixture("direct_message_events.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", max_id: "856480385957548034", include_entities: "true"}).to_return(body: fixture("empty_cursor.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.direct_messages_sent expect(a_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", include_entities: "true"})).to have_been_made end end context "--long" do before do @cli.options = @cli.options.merge("long" => true) end it "outputs in long format" do @cli.direct_messages_sent expect($stdout.string).to eq <<~EOS ID Posted at Screen name Text 856523843892129796 Apr 24 07:02 @ https://twitter.com/i/sticker... 856523768910544899 Apr 24 07:02 @ https://twitter.com/i/sticker... 856480385957548035 Apr 24 04:10 @ Obrigada Jacques EOS end end context "--number" do it "limits the number of results 1" do @cli.options = @cli.options.merge("number" => 1) @cli.direct_messages_sent expect(a_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", include_entities: "false"})).to have_been_made end it "limits the number of results to 201" do @cli.options = @cli.options.merge("number" => 201) @cli.direct_messages_sent expect(a_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", include_entities: "false"})).to have_been_made expect(a_get("/1.1/direct_messages/events/list.json").with(query: {count: "50", max_id: "856480385957548034", include_entities: "false"})).to have_been_made end end context "--reverse" do before do @cli.options = @cli.options.merge("reverse" => true) end it "reverses the order of the sort" do @cli.direct_messages_sent expect($stdout.string).to eq <<-EOS @ Obrigada Jacques @ https://twitter.com/i/stickers/image/10017 @ https://twitter.com/i/stickers/image/10018 EOS end end end describe "#dm" do before do @cli.options = @cli.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/direct_messages/events/new.json").with(body: {event: {type: "message_create", message_create: {target: {recipient_id: 7_505_382}, message_data: {text: "Creating a fixture for the Twitter gem"}}}}).to_return(body: fixture("direct_message_event.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/users/show.json").with(query: {screen_name: "sferik"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.dm("sferik", "Creating a fixture for the Twitter gem") expect(a_post("/1.1/direct_messages/events/new.json").with(body: {event: {type: "message_create", message_create: {target: {recipient_id: 7_505_382}, message_data: {text: "Creating a fixture for the Twitter gem"}}}})).to have_been_made expect(a_get("/1.1/users/show.json").with(query: {screen_name: "sferik"})).to have_been_made end it "has the correct output" do @cli.dm("sferik", "Creating a fixture for the Twitter gem") expect($stdout.string.chomp).to eq "Direct Message sent from @testcli to @sferik." end context "--id" do before do @cli.options = @cli.options.merge("id" => true) stub_post("/1.1/direct_messages/events/new.json").with(body: {event: {type: "message_create", message_create: {target: {recipient_id: 7_505_382}, message_data: {text: "Creating a fixture for the Twitter gem"}}}}).to_return(body: fixture("direct_message_event.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/users/show.json").with(query: {user_id: "7505382"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.dm("7505382", "Creating a fixture for the Twitter gem") expect(a_post("/1.1/direct_messages/events/new.json").with(body: {event: {type: "message_create", message_create: {target: {recipient_id: 7_505_382}, message_data: {text: "Creating a fixture for the Twitter gem"}}}})).to have_been_made expect(a_get("/1.1/users/show.json").with(query: {user_id: "7505382"})).to have_been_made end it "has the correct output" do @cli.dm("7505382", "Creating a fixture for the Twitter gem") expect($stdout.string.chomp).to eq "Direct Message sent from @testcli to @sferik." end end end describe "#does_contain" do before do @cli.options = @cli.options.merge("profile" => "#{fixture_path}/.trc") stub_get("/1.1/lists/members/show.json").with(query: {owner_screen_name: "testcli", screen_name: "testcli", slug: "presidents"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.does_contain("presidents") expect(a_get("/1.1/lists/members/show.json").with(query: {owner_screen_name: "testcli", screen_name: "testcli", slug: "presidents"})).to have_been_made end it "has the correct output" do @cli.does_contain("presidents") expect($stdout.string.chomp).to eq "Yes, presidents contains @testcli." end context "--id" do before do @cli.options = @cli.options.merge("id" => true) stub_get("/1.1/users/show.json").with(query: {user_id: "7505382"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/lists/members/show.json").with(query: {owner_screen_name: "testcli", screen_name: "sferik", slug: "presidents"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.does_contain("presidents", "7505382") expect(a_get("/1.1/users/show.json").with(query: {user_id: "7505382"})).to have_been_made expect(a_get("/1.1/lists/members/show.json").with(query: {owner_screen_name: "testcli", screen_name: "sferik", slug: "presidents"})).to have_been_made end end context "with an owner passed" do it "has the correct output" do @cli.does_contain("testcli/presidents", "testcli") expect($stdout.string.chomp).to eq "Yes, presidents contains @testcli." end context "--id" do before do @cli.options = @cli.options.merge("id" => true) stub_get("/1.1/users/show.json").with(query: {user_id: "7505382"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/lists/members/show.json").with(query: {owner_id: "7505382", screen_name: "sferik", slug: "presidents"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.does_contain("7505382/presidents", "7505382") expect(a_get("/1.1/users/show.json").with(query: {user_id: "7505382"})).to have_been_made expect(a_get("/1.1/lists/members/show.json").with(query: {owner_id: "7505382", screen_name: "sferik", slug: "presidents"})).to have_been_made end end end context "with a user passed" do it "has the correct output" do @cli.does_contain("presidents", "testcli") expect($stdout.string.chomp).to eq "Yes, presidents contains @testcli." end end context "false" do before do stub_get("/1.1/lists/members/show.json").with(query: {owner_screen_name: "testcli", screen_name: "testcli", slug: "presidents"}).to_return(body: fixture("not_found.json"), status: 404, headers: {content_type: "application/json; charset=utf-8"}) end it "exits" do expect do @cli.does_contain("presidents") end.to raise_error(SystemExit) expect(a_get("/1.1/lists/members/show.json").with(query: {owner_screen_name: "testcli", screen_name: "testcli", slug: "presidents"})).to have_been_made end end end describe "#does_follow" do before do @cli.options = @cli.options.merge("profile" => "#{fixture_path}/.trc") stub_get("/1.1/friendships/show.json").with(query: {source_screen_name: "ev", target_screen_name: "testcli"}).to_return(body: fixture("following.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.does_follow("ev") expect(a_get("/1.1/friendships/show.json").with(query: {source_screen_name: "ev", target_screen_name: "testcli"})).to have_been_made end it "has the correct output" do @cli.does_follow("ev") expect($stdout.string.chomp).to eq "Yes, @ev follows @testcli." end context "--id" do before do @cli.options = @cli.options.merge("id" => true) stub_get("/1.1/users/show.json").with(query: {user_id: "20"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/friendships/show.json").with(query: {source_screen_name: "sferik", target_screen_name: "testcli"}).to_return(body: fixture("following.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.does_follow("20") expect(a_get("/1.1/users/show.json").with(query: {user_id: "20"})).to have_been_made expect(a_get("/1.1/friendships/show.json").with(query: {source_screen_name: "sferik", target_screen_name: "testcli"})).to have_been_made end it "has the correct output" do @cli.does_follow("20") expect($stdout.string.chomp).to eq "Yes, @sferik follows @testcli." end end context "with a user passed" do before do stub_get("/1.1/friendships/show.json").with(query: {source_screen_name: "ev", target_screen_name: "sferik"}).to_return(body: fixture("following.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.does_follow("ev", "sferik") expect(a_get("/1.1/friendships/show.json").with(query: {source_screen_name: "ev", target_screen_name: "sferik"})).to have_been_made end it "has the correct output" do @cli.does_follow("ev", "sferik") expect($stdout.string.chomp).to eq "Yes, @ev follows @sferik." end context "--id" do before do @cli.options = @cli.options.merge("id" => true) stub_get("/1.1/users/show.json").with(query: {user_id: "20"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/users/show.json").with(query: {user_id: "428004849"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_get("/1.1/friendships/show.json").with(query: {source_screen_name: "sferik", target_screen_name: "sferik"}).to_return(body: fixture("following.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.does_follow("20", "428004849") expect(a_get("/1.1/users/show.json").with(query: {user_id: "20"})).to have_been_made expect(a_get("/1.1/users/show.json").with(query: {user_id: "428004849"})).to have_been_made expect(a_get("/1.1/friendships/show.json").with(query: {source_screen_name: "sferik", target_screen_name: "sferik"})).to have_been_made end it "has the correct output" do @cli.does_follow("20", "428004849") expect($stdout.string.chomp).to eq "Yes, @sferik follows @sferik." end it "cannot follow yourself" do expect do @cli.does_follow "testcli" expect($stderr.string.chomp).to eq "No, you are not following yourself." end.to raise_error(SystemExit) end it "cannot check same account" do expect do @cli.does_follow("sferik", "sferik") expect($stderr.string.chomp).to eq "No, @sferik is not following themself." end.to raise_error(SystemExit) end end end context "false" do before do stub_get("/1.1/friendships/show.json").with(query: {source_screen_name: "ev", target_screen_name: "testcli"}).to_return(body: fixture("not_following.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "exits" do expect do @cli.does_follow("ev") end.to raise_error(SystemExit) expect(a_get("/1.1/friendships/show.json").with(query: {source_screen_name: "ev", target_screen_name: "testcli"})).to have_been_made end end end describe "#favorite" do before do @cli.options = @cli.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/favorites/create.json").with(body: {id: "26755176471724032"}).to_return(body: fixture("status.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.favorite("26755176471724032") expect(a_post("/1.1/favorites/create.json").with(body: {id: "26755176471724032"})).to have_been_made end it "has the correct output" do @cli.favorite("26755176471724032") expect($stdout.string).to match(/^@testcli favorited 1 tweet.$/) end end describe "#favorites" do before do stub_get("/1.1/favorites/list.json").with(query: {count: "20", include_entities: "false"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @cli.favorites expect(a_get("/1.1/favorites/list.json").with(query: {count: "20", include_entities: "false"})).to have_been_made end it "has the correct output" do @cli.favorites expect($stdout.string).to eq <<-EOS @mutgoff Happy Birthday @imdane. Watch out for those @rally pranksters! @ironicsans If you like good real-life stories, check out @NarrativelyNY's just-launched site http://t.co/wiUL07jE (and also visit http://t.co/ZoyQxqWA) @pat_shaughnessy Something else to vote for: "New Rails workshops to bring more women into the Boston software scene" http://t.co/eNBuckHc /cc @bostonrb @calebelston Pushing the button to launch the site. http://t.co/qLoEn5jG @calebelston RT @olivercameron: Mosaic looks cool: http://t.co/A8013C9k @fivethirtyeight The Weatherman is Not a Moron: http://t.co/ZwL5Gnq5. An excerpt from my book, THE SIGNAL AND THE NOISE (http://t.co/fNXj8vCE) @codeforamerica RT @randomhacks: Going to Code Across Austin II: Y'all Come Hack Now, Sat, Sep 8 http://t.co/Sk5BM7U3 We'll see y'all there! #rhok @codeforamerica @TheaClay @fbjork RT @jondot: Just published: "Pragmatic Concurrency With #Ruby" http://t.co/kGEykswZ /cc @JRuby @headius @mbostock If you are wondering how we computed the split bubbles: http://t.co/BcaqSs5u @FakeDorsey "Write drunk. Edit sober."—Ernest Hemingway @al3x RT @wcmaier: Better banking through better ops: build something new with us @Simplify (remote, PDX) http://t.co/8WgzKZH3 @calebelston We just announced Mosaic, what we've been working on since the Yobongo acquisition. My personal post, http://t.co/ELOyIRZU @heymosaic @BarackObama Donate $10 or more --> get your favorite car magnet: http://t.co/NfRhl2s2 #Obama2012 @JEG2 RT @tenderlove: If corporations are people, can we use them to drive in the carpool lane? @eveningedition LDN—Obama's nomination; Putin woos APEC; Bombs hit Damascus; Quakes shake China; Canada cuts Iran ties; weekend read: http://t.co/OFs6dVW4 @dhh RT @ggreenwald: Democrats parade Osama bin Laden's corpse as their proudest
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
true
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/spec/stream_spec.rb
spec/stream_spec.rb
require "helper" describe T::Stream do let(:t_class) do klass = Class.new allow(klass).to receive(:options=) allow(klass).to receive(:options).and_return({}) klass end before :all do @tweet = tweet_from_fixture("status.json") end before do T::RCFile.instance.path = "#{fixture_path}/.trc" @streaming_client = double("Twitter::Streaming::Client").as_null_object @stream = described_class.new allow(@stream).to receive(:streaming_client) { @streaming_client } allow(@stream).to receive(:say) allow(STDOUT).to receive(:tty?).and_return(true) end describe "#all" do before do allow(@streaming_client).to receive(:sample).and_yield(@tweet) end it "prints the tweet" do expect(@stream).to receive(:print_message) @stream.all end context "--csv" do before do @stream.options = @stream.options.merge("csv" => true) end it "outputs headings when the stream initializes" do allow(@streaming_client).to receive(:before_request).and_yield allow(@streaming_client).to receive(:sample) expect(@stream).to receive(:say).with("ID,Posted at,Screen name,Text\n") @stream.all end it "outputs in CSV format" do allow(@streaming_client).to receive(:before_request) allow(@streaming_client).to receive(:sample).and_yield(@tweet) expect(@stream).to receive(:print_csv_tweet).with(any_args) @stream.all end end context "--long" do before do @stream.options = @stream.options.merge("long" => true) end it "outputs headings when the stream initializes" do allow(@streaming_client).to receive(:before_request).and_yield allow(@streaming_client).to receive(:sample) expect(@stream).to receive(:print_table).with(any_args) @stream.all end it "outputs in long text format" do allow(@streaming_client).to receive(:before_request) allow(@streaming_client).to receive(:sample).and_yield(@tweet) expect(@stream).to receive(:print_table).with(any_args) @stream.all end end it "invokes Twitter::Streaming::Client#sample" do allow(@streaming_client).to receive(:before_request) allow(@streaming_client).to receive(:sample) expect(@streaming_client).to receive(:sample) @stream.all end end describe "#list" do before do stub_get("/1.1/lists/members.json").with(query: {cursor: "-1", owner_screen_name: "testcli", slug: "presidents"}).to_return(body: fixture("users_list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "prints the tweet" do expect(@stream).to receive(:print_message) allow(@streaming_client).to receive(:filter).and_yield(@tweet) @stream.list("presidents") end it "requests the correct resource" do @stream.list("presidents") expect(a_get("/1.1/lists/members.json").with(query: {cursor: "-1", owner_screen_name: "testcli", slug: "presidents"})).to have_been_made end context "--csv" do before do @stream.options = @stream.options.merge("csv" => true) end it "outputs in CSV format" do allow(@streaming_client).to receive(:before_request) allow(@streaming_client).to receive(:filter).and_yield(@tweet) expect(@stream).to receive(:print_csv_tweet).with(any_args) @stream.list("presidents") end it "requests the correct resource" do @stream.list("presidents") expect(a_get("/1.1/lists/members.json").with(query: {cursor: "-1", owner_screen_name: "testcli", slug: "presidents"})).to have_been_made end end context "--long" do before do @stream.options = @stream.options.merge("long" => true) end it "outputs in long text format" do allow(@streaming_client).to receive(:before_request) allow(@streaming_client).to receive(:filter).and_yield(@tweet) expect(@stream).to receive(:print_table).with(any_args) @stream.list("presidents") end it "requests the correct resource" do @stream.list("presidents") expect(a_get("/1.1/lists/members.json").with(query: {cursor: "-1", owner_screen_name: "testcli", slug: "presidents"})).to have_been_made end end it "performs a REST search when the stream initializes" do allow(@streaming_client).to receive(:before_request).and_yield allow(@streaming_client).to receive(:filter) allow(T::List).to receive(:new).and_return(t_class) expect(t_class).to receive(:timeline) @stream.list("presidents") end it "invokes Twitter::Streaming::Client#userstream" do allow(@streaming_client).to receive(:filter) expect(@streaming_client).to receive(:filter) @stream.list("presidents") end end describe "#matrix" do before do stub_get("/1.1/search/tweets.json").with(query: {q: "lang:ja", count: 100, include_entities: "false"}).to_return(body: fixture("empty_cursor.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "outputs the tweet" do allow(@streaming_client).to receive(:before_request) allow(@streaming_client).to receive(:sample).and_yield(@tweet) expect(@stream).to receive(:say).with(any_args) @stream.matrix end it "invokes Twitter::Streaming::Client#sample" do allow(@streaming_client).to receive(:before_request) allow(@streaming_client).to receive(:sample).and_yield(@tweet) expect(@streaming_client).to receive(:sample) @stream.matrix end it "requests the correct resource" do allow(@streaming_client).to receive(:before_request).and_yield @stream.matrix expect(a_get("/1.1/search/tweets.json").with(query: {q: "lang:ja", count: 100, include_entities: "false"})).to have_been_made end end describe "#search" do before do allow(@streaming_client).to receive(:filter).with(track: "twitter,gem").and_yield(@tweet) end it "prints the tweet" do expect(@stream).to receive(:print_message) @stream.search(%w[twitter gem]) end context "--csv" do before do @stream.options = @stream.options.merge("csv" => true) end it "outputs in CSV format" do allow(@streaming_client).to receive(:before_request) expect(@stream).to receive(:print_csv_tweet).with(any_args) @stream.search(%w[twitter gem]) end end context "--long" do before do @stream.options = @stream.options.merge("long" => true) end it "outputs in long text format" do allow(@streaming_client).to receive(:before_request) allow(@streaming_client).to receive(:filter).with(track: "twitter,gem").and_yield(@tweet) expect(@stream).to receive(:print_table).with(any_args) @stream.search(%w[twitter gem]) end end it "performs a REST search when the stream initializes" do allow(@streaming_client).to receive(:before_request).and_yield allow(@streaming_client).to receive(:filter) allow(T::Search).to receive(:new).and_return(t_class) expect(t_class).to receive(:all).with("t OR gem") @stream.search("t", "gem") end it "invokes Twitter::Streaming::Client#filter" do allow(@streaming_client).to receive(:filter) expect(@streaming_client).to receive(:filter).with(track: "twitter,gem") @stream.search(%w[twitter gem]) end end describe "#timeline" do before do allow(@streaming_client).to receive(:user).and_yield(@tweet) end it "prints the tweet" do expect(@stream).to receive(:print_message) @stream.timeline end context "--csv" do before do @stream.options = @stream.options.merge("csv" => true) end it "outputs in CSV format" do allow(@streaming_client).to receive(:before_request) expect(@stream).to receive(:print_csv_tweet).with(any_args) @stream.timeline end end context "--long" do before do @stream.options = @stream.options.merge("long" => true) end it "outputs in long text format" do allow(@streaming_client).to receive(:before_request) expect(@stream).to receive(:print_table).with(any_args) @stream.timeline end end it "performs a REST search when the stream initializes" do allow(@streaming_client).to receive(:before_request).and_yield allow(@streaming_client).to receive(:user) allow(T::CLI).to receive(:new).and_return(t_class) expect(t_class).to receive(:timeline) @stream.timeline end it "invokes Twitter::Streaming::Client#userstream" do allow(@streaming_client).to receive(:user) expect(@streaming_client).to receive(:user) @stream.timeline end end describe "#users" do before do allow(@streaming_client).to receive(:filter).and_yield(@tweet) end it "prints the tweet" do expect(@stream).to receive(:print_message) @stream.users("123") end context "--csv" do before do @stream.options = @stream.options.merge("csv" => true) end it "outputs headings when the stream initializes" do allow(@streaming_client).to receive(:before_request).and_yield allow(@streaming_client).to receive(:filter) expect(@stream).to receive(:say).with("ID,Posted at,Screen name,Text\n") @stream.users("123") end it "outputs in CSV format" do allow(@streaming_client).to receive(:before_request) expect(@stream).to receive(:print_csv_tweet).with(any_args) @stream.users("123") end end context "--long" do before do @stream.options = @stream.options.merge("long" => true) end it "outputs headings when the stream initializes" do allow(@streaming_client).to receive(:before_request).and_yield allow(@streaming_client).to receive(:filter) expect(@stream).to receive(:print_table).with(any_args) @stream.users("123") end it "outputs in long text format" do allow(@streaming_client).to receive(:before_request) allow(@streaming_client).to receive(:filter).and_yield(@tweet) expect(@stream).to receive(:print_table).with(any_args) @stream.users("123") end end it "invokes Twitter::Streaming::Client#follow" do allow(@streaming_client).to receive(:filter) expect(@streaming_client).to receive(:filter).with(follow: "123,456,789") @stream.users("123", "456", "789") end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/spec/set_spec.rb
spec/set_spec.rb
# encoding: utf-8 require "helper" describe T::Set do before do T::RCFile.instance.path = "#{fixture_path}/.trc" @set = described_class.new @old_stderr = $stderr $stderr = StringIO.new @old_stdout = $stdout $stdout = StringIO.new end after do T::RCFile.instance.reset $stderr = @old_stderr $stdout = @old_stdout end describe "#active" do before do @set.options = @set.options.merge("profile" => "#{fixture_path}/.trc_set") end it "has the correct output" do @set.active("testcli", "abc123") expect($stdout.string.chomp).to eq "Active account has been updated to testcli." end it "accepts an account name without a consumer key" do @set.active("testcli") expect($stdout.string.chomp).to eq "Active account has been updated to testcli." end it "is case insensitive" do @set.active("TestCLI", "abc123") expect($stdout.string.chomp).to eq "Active account has been updated to testcli." end it "raises an error if username is ambiguous" do expect do @set.active("test", "abc123") end.to raise_error(ArgumentError, /Username test is ambiguous/) end it "raises an error if the username is not found" do expect do @set.active("clitest") end.to raise_error(ArgumentError, /Username clitest is not found/) end end describe "#bio" do before do @set.options = @set.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/account/update_profile.json").with(body: {description: "Vagabond."}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @set.bio("Vagabond.") expect(a_post("/1.1/account/update_profile.json").with(body: {description: "Vagabond."})).to have_been_made end it "has the correct output" do @set.bio("Vagabond.") expect($stdout.string.chomp).to eq "@testcli's bio has been updated." end end describe "#language" do before do @set.options = @set.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/account/settings.json").with(body: {lang: "en"}).to_return(body: fixture("settings.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @set.language("en") expect(a_post("/1.1/account/settings.json").with(body: {lang: "en"})).to have_been_made end it "has the correct output" do @set.language("en") expect($stdout.string.chomp).to eq "@testcli's language has been updated." end end describe "#location" do before do @set.options = @set.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/account/update_profile.json").with(body: {location: "San Francisco"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @set.location("San Francisco") expect(a_post("/1.1/account/update_profile.json").with(body: {location: "San Francisco"})).to have_been_made end it "has the correct output" do @set.location("San Francisco") expect($stdout.string.chomp).to eq "@testcli's location has been updated." end end describe "#name" do before do @set.options = @set.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/account/update_profile.json").with(body: {name: "Erik Michaels-Ober"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @set.name("Erik Michaels-Ober") expect(a_post("/1.1/account/update_profile.json").with(body: {name: "Erik Michaels-Ober"})).to have_been_made end it "has the correct output" do @set.name("Erik Michaels-Ober") expect($stdout.string.chomp).to eq "@testcli's name has been updated." end end describe "#profile_background_image" do before do @set.options = @set.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/account/update_profile_background_image.json").to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @set.profile_background_image("#{fixture_path}/we_concept_bg2.png") expect(a_post("/1.1/account/update_profile_background_image.json")).to have_been_made end it "has the correct output" do @set.profile_background_image("#{fixture_path}/we_concept_bg2.png") expect($stdout.string.chomp).to eq "@testcli's background image has been updated." end end describe "#profile_image" do before do @set.options = @set.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/account/update_profile_image.json").to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @set.profile_image("#{fixture_path}/me.jpg") expect(a_post("/1.1/account/update_profile_image.json")).to have_been_made end it "has the correct output" do @set.profile_image("#{fixture_path}/me.jpg") expect($stdout.string.chomp).to eq "@testcli's image has been updated." end end describe "#website" do before do @set.options = @set.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/account/update_profile.json").with(body: {url: "https://github.com/sferik"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @set.website("https://github.com/sferik") expect(a_post("/1.1/account/update_profile.json").with(body: {url: "https://github.com/sferik"})).to have_been_made end it "has the correct output" do @set.website("https://github.com/sferik") expect($stdout.string.chomp).to eq "@testcli's website has been updated." end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/spec/list_spec.rb
spec/list_spec.rb
# encoding: utf-8 require "helper" describe T::List do before :all do Timecop.freeze(Time.utc(2011, 11, 24, 16, 20, 0)) T.utc_offset = "PST" end before do T::RCFile.instance.path = "#{fixture_path}/.trc" @list = described_class.new @old_stderr = $stderr $stderr = StringIO.new @old_stdout = $stdout $stdout = StringIO.new end after do T::RCFile.instance.reset $stderr = @old_stderr $stdout = @old_stdout end after :all do T.utc_offset = nil Timecop.return end describe "#add" do before do @list.options = @list.options.merge("profile" => "#{fixture_path}/.trc") stub_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) stub_post("/1.1/lists/members/create_all.json").with(body: {screen_name: "BarackObama", slug: "presidents", owner_id: "7505382"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @list.add("presidents", "BarackObama") expect(a_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"})).to have_been_made expect(a_post("/1.1/lists/members/create_all.json").with(body: {screen_name: "BarackObama", slug: "presidents", owner_id: "7505382"})).to have_been_made end it "has the correct output" do @list.add("presidents", "BarackObama") expect($stdout.string.split("\n").first).to eq '@testcli added 1 member to the list "presidents".' end context "--id" do before do @list.options = @list.options.merge("id" => true) stub_post("/1.1/lists/members/create_all.json").with(body: {user_id: "7505382", slug: "presidents", owner_id: "7505382"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @list.add("presidents", "7505382") expect(a_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"})).to have_been_made expect(a_post("/1.1/lists/members/create_all.json").with(body: {user_id: "7505382", slug: "presidents", owner_id: "7505382"})).to have_been_made end end context "Twitter is down" do it "retries 3 times and then raise an error" do stub_post("/1.1/lists/members/create_all.json").with(body: {screen_name: "BarackObama", slug: "presidents", owner_id: "7505382"}).to_return(status: 502, headers: {content_type: "application/json; charset=utf-8"}) expect do @list.add("presidents", "BarackObama") end.to raise_error(Twitter::Error::BadGateway) expect(a_post("/1.1/lists/members/create_all.json").with(body: {screen_name: "BarackObama", slug: "presidents", owner_id: "7505382"})).to have_been_made.times(3) end end end describe "#create" do before do @list.options = @list.options.merge("profile" => "#{fixture_path}/.trc") stub_post("/1.1/lists/create.json").with(body: {name: "presidents"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @list.create("presidents") expect(a_post("/1.1/lists/create.json").with(body: {name: "presidents"})).to have_been_made end it "has the correct output" do @list.create("presidents") expect($stdout.string.chomp).to eq '@testcli created the list "presidents".' end end describe "#information" do before do @list.options = @list.options.merge("profile" => "#{fixture_path}/.trc") stub_get("/1.1/lists/show.json").with(query: {owner_screen_name: "testcli", slug: "presidents"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @list.information("presidents") expect(a_get("/1.1/lists/show.json").with(query: {owner_screen_name: "testcli", slug: "presidents"})).to have_been_made end it "has the correct output" do @list.information("presidents") expect($stdout.string).to eq <<~EOS ID 8863586 Description Presidents of the United States of America Slug presidents Screen name @sferik Created at Mar 15 2010 (a year ago) Members 2 Subscribers 1 Status Not following Mode public URL https://twitter.com/sferik/presidents EOS end it "has the correct output with --relative-dates turned on" do @list.options = @list.options.merge("relative_dates" => true) @list.information("presidents") expect($stdout.string).to eq <<~EOS ID 8863586 Description Presidents of the United States of America Slug presidents Screen name @sferik Created at Mar 15 2010 (a year ago) Members 2 Subscribers 1 Status Not following Mode public URL https://twitter.com/sferik/presidents EOS end context "with a user passed" do it "requests the correct resource" do @list.information("testcli/presidents") expect(a_get("/1.1/lists/show.json").with(query: {owner_screen_name: "testcli", slug: "presidents"})).to have_been_made end context "--id" do before do @list.options = @list.options.merge("id" => true) stub_get("/1.1/lists/show.json").with(query: {owner_id: "7505382", slug: "presidents"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @list.information("7505382/presidents") expect(a_get("/1.1/lists/show.json").with(query: {owner_id: "7505382", slug: "presidents"})).to have_been_made end end end context "--csv" do before do @list.options = @list.options.merge("csv" => true) end it "has the correct output" do @list.information("presidents") expect($stdout.string).to eq <<~EOS ID,Description,Slug,Screen name,Created at,Members,Subscribers,Following,Mode,URL 8863586,Presidents of the United States of America,presidents,sferik,2010-03-15 12:10:13 +0000,2,1,false,public,https://twitter.com/sferik/presidents EOS end end end describe "#members" do before do stub_get("/1.1/lists/members.json").with(query: {cursor: "-1", owner_screen_name: "testcli", slug: "presidents"}).to_return(body: fixture("users_list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @list.members("presidents") expect(a_get("/1.1/lists/members.json").with(query: {cursor: "-1", owner_screen_name: "testcli", slug: "presidents"})).to have_been_made end it "has the correct output" do @list.members("presidents") expect($stdout.string.chomp).to eq "pengwynn sferik" end context "--csv" do before do @list.options = @list.options.merge("csv" => true) end it "outputs in CSV format" do @list.members("presidents") expect($stdout.string).to eq <<~EOS ID,Since,Last tweeted at,Tweets,Favorites,Listed,Following,Followers,Screen name,Name,Verified,Protected,Bio,Status,Location,URL 14100886,2008-03-08 16:34:22 +0000,2012-07-07 20:33:19 +0000,6940,192,358,3427,5457,pengwynn,Wynn Netherland,false,false,"Christian, husband, father, GitHubber, Co-host of @thechangelog, Co-author of Sass, Compass, #CSS book http://wynn.fm/sass-meap",@akosmasoftware Sass book! @hcatlin @nex3 are the brains behind Sass. :-),"Denton, TX",http://wynnnetherland.com 7505382,2007-07-16 12:59:01 +0000,2012-07-08 18:29:20 +0000,7890,3755,118,212,2262,sferik,Erik Michaels-Ober,false,false,Vagabond.,@goldman You're near my home town! Say hi to Woodstock for me.,San Francisco,https://github.com/sferik EOS end end context "--long" do before do @list.options = @list.options.merge("long" => true) end it "outputs in long format" do @list.members("presidents") expect($stdout.string).to eq <<~EOS ID Since Last tweeted at Tweets Favorites Listed Following... 14100886 Mar 8 2008 Jul 7 12:33 6940 192 358 3427... 7505382 Jul 16 2007 Jul 8 10:29 7890 3755 118 212... EOS end end context "--reverse" do before do @list.options = @list.options.merge("reverse" => true) end it "reverses the order of the sort" do @list.members("presidents") expect($stdout.string.chomp).to eq "sferik pengwynn" end end context "--sort=favorites" do before do @list.options = @list.options.merge("sort" => "favorites") end it "sorts by the number of favorites" do @list.members("presidents") expect($stdout.string.chomp).to eq "pengwynn sferik" end end context "--sort=followers" do before do @list.options = @list.options.merge("sort" => "followers") end it "sorts by the number of followers" do @list.members("presidents") expect($stdout.string.chomp).to eq "sferik pengwynn" end end context "--sort=friends" do before do @list.options = @list.options.merge("sort" => "friends") end it "sorts by the number of friends" do @list.members("presidents") expect($stdout.string.chomp).to eq "sferik pengwynn" end end context "--sort=listed" do before do @list.options = @list.options.merge("sort" => "listed") end it "sorts by the number of list memberships" do @list.members("presidents") expect($stdout.string.chomp).to eq "sferik pengwynn" end end context "--sort=since" do before do @list.options = @list.options.merge("sort" => "since") end it "sorts by the time when Twitter account was created" do @list.members("presidents") expect($stdout.string.chomp).to eq "sferik pengwynn" end end context "--sort=tweets" do before do @list.options = @list.options.merge("sort" => "tweets") end it "sorts by the number of Tweets" do @list.members("presidents") expect($stdout.string.chomp).to eq "pengwynn sferik" end end context "--sort=tweeted" do before do @list.options = @list.options.merge("sort" => "tweeted") end it "sorts by the time of the last Tweet" do @list.members("presidents") expect($stdout.string.chomp).to eq "pengwynn sferik" end end context "--unsorted" do before do @list.options = @list.options.merge("unsorted" => true) end it "is not sorted" do @list.members("presidents") expect($stdout.string.chomp).to eq "sferik pengwynn" end end context "with a user passed" do it "requests the correct resource" do @list.members("testcli/presidents") expect(a_get("/1.1/lists/members.json").with(query: {cursor: "-1", owner_screen_name: "testcli", slug: "presidents"})).to have_been_made end context "--id" do before do @list.options = @list.options.merge("id" => true) stub_get("/1.1/lists/members.json").with(query: {cursor: "-1", owner_id: "7505382", slug: "presidents"}).to_return(body: fixture("users_list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @list.members("7505382/presidents") expect(a_get("/1.1/lists/members.json").with(query: {cursor: "-1", owner_id: "7505382", slug: "presidents"})).to have_been_made end end end end describe "#remove" do before do @list.options = @list.options.merge("profile" => "#{fixture_path}/.trc") stub_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"}).to_return(body: fixture("sferik.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do stub_post("/1.1/lists/members/destroy_all.json").with(body: {screen_name: "BarackObama", slug: "presidents", owner_id: "7505382"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) @list.remove("presidents", "BarackObama") expect(a_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"})).to have_been_made expect(a_post("/1.1/lists/members/destroy_all.json").with(body: {screen_name: "BarackObama", slug: "presidents", owner_id: "7505382"})).to have_been_made end it "has the correct output" do stub_post("/1.1/lists/members/destroy_all.json").with(body: {screen_name: "BarackObama", slug: "presidents", owner_id: "7505382"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) @list.remove("presidents", "BarackObama") expect($stdout.string.split("\n").first).to eq '@testcli removed 1 member from the list "presidents".' end context "--id" do before do @list.options = @list.options.merge("id" => true) stub_post("/1.1/lists/members/destroy_all.json").with(body: {user_id: "7505382", slug: "presidents", owner_id: "7505382"}).to_return(body: fixture("list.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @list.remove("presidents", "7505382") expect(a_get("/1.1/account/verify_credentials.json").with(query: {skip_status: "true"})).to have_been_made expect(a_post("/1.1/lists/members/destroy_all.json").with(body: {user_id: "7505382", slug: "presidents", owner_id: "7505382"})).to have_been_made end end context "Twitter is down" do it "retries 3 times and then raise an error" do stub_post("/1.1/lists/members/destroy_all.json").with(body: {screen_name: "BarackObama", slug: "presidents", owner_id: "7505382"}).to_return(status: 502, headers: {content_type: "application/json; charset=utf-8"}) expect do @list.remove("presidents", "BarackObama") end.to raise_error(Twitter::Error::BadGateway) expect(a_post("/1.1/lists/members/destroy_all.json").with(body: {screen_name: "BarackObama", slug: "presidents", owner_id: "7505382"})).to have_been_made.times(3) end end end describe "#timeline" do before do @list.options = @list.options.merge("color" => "always") stub_get("/1.1/lists/statuses.json").with(query: {owner_screen_name: "testcli", count: "20", slug: "presidents", include_entities: "false"}).to_return(body: fixture("statuses.json"), headers: {content_type: "application/json; charset=utf-8"}) end it "requests the correct resource" do @list.timeline("presidents") expect(a_get("/1.1/lists/statuses.json").with(query: {owner_screen_name: "testcli", count: "20", slug: "presidents", include_entities: "false"})).to have_been_made end it "has the correct output" do @list.timeline("presidents") expect($stdout.string).to eq <<-EOS @mutgoff Happy Birthday @imdane. Watch out for those @rally pranksters! @ironicsans If you like good real-life stories, check out @NarrativelyNY's just-launched site http://t.co/wiUL07jE (and also visit http://t.co/ZoyQxqWA) @pat_shaughnessy Something else to vote for: "New Rails workshops to bring more women into the Boston software scene" http://t.co/eNBuckHc /cc @bostonrb @calebelston Pushing the button to launch the site. http://t.co/qLoEn5jG @calebelston RT @olivercameron: Mosaic looks cool: http://t.co/A8013C9k @fivethirtyeight The Weatherman is Not a Moron: http://t.co/ZwL5Gnq5. An excerpt from my book, THE SIGNAL AND THE NOISE (http://t.co/fNXj8vCE) @codeforamerica RT @randomhacks: Going to Code Across Austin II: Y'all Come Hack Now, Sat, Sep 8 http://t.co/Sk5BM7U3 We'll see y'all there! #rhok @codeforamerica @TheaClay @fbjork RT @jondot: Just published: "Pragmatic Concurrency With #Ruby" http://t.co/kGEykswZ /cc @JRuby @headius @mbostock If you are wondering how we computed the split bubbles: http://t.co/BcaqSs5u @FakeDorsey "Write drunk. Edit sober."—Ernest Hemingway @al3x RT @wcmaier: Better banking through better ops: build something new with us @Simplify (remote, PDX) http://t.co/8WgzKZH3 @calebelston We just announced Mosaic, what we've been working on since the Yobongo acquisition. My personal post, http://t.co/ELOyIRZU @heymosaic @BarackObama Donate $10 or more --> get your favorite car magnet: http://t.co/NfRhl2s2 #Obama2012 @JEG2 RT @tenderlove: If corporations are people, can we use them to drive in the carpool lane? @eveningedition LDN—Obama's nomination; Putin woos APEC; Bombs hit Damascus; Quakes shake China; Canada cuts Iran ties; weekend read: http://t.co/OFs6dVW4 @dhh RT @ggreenwald: Democrats parade Osama bin Laden's corpse as their proudest achievement: why this goulish jingoism is so warped http://t.co/kood278s @jasonfried The story of Mars Curiosity's gears, made by a factory in Rockford, IL: http://t.co/MwCRsHQg @sferik @episod @twitterapi now https://t.co/I17jUTu2 and https://t.co/deDu4Hgw seem to be missing "1.1" from the URL. @sferik @episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? @dwiskus Gentlemen, you can't fight in here! This is the war room! http://t.co/kMxMYyqF EOS end context "--color=never" do before do @list.options = @list.options.merge("color" => "never") end it "outputs without color" do @list.timeline("presidents") expect($stdout.string).to eq <<-EOS @mutgoff Happy Birthday @imdane. Watch out for those @rally pranksters! @ironicsans If you like good real-life stories, check out @NarrativelyNY's just-launched site http://t.co/wiUL07jE (and also visit http://t.co/ZoyQxqWA) @pat_shaughnessy Something else to vote for: "New Rails workshops to bring more women into the Boston software scene" http://t.co/eNBuckHc /cc @bostonrb @calebelston Pushing the button to launch the site. http://t.co/qLoEn5jG @calebelston RT @olivercameron: Mosaic looks cool: http://t.co/A8013C9k @fivethirtyeight The Weatherman is Not a Moron: http://t.co/ZwL5Gnq5. An excerpt from my book, THE SIGNAL AND THE NOISE (http://t.co/fNXj8vCE) @codeforamerica RT @randomhacks: Going to Code Across Austin II: Y'all Come Hack Now, Sat, Sep 8 http://t.co/Sk5BM7U3 We'll see y'all there! #rhok @codeforamerica @TheaClay @fbjork RT @jondot: Just published: "Pragmatic Concurrency With #Ruby" http://t.co/kGEykswZ /cc @JRuby @headius @mbostock If you are wondering how we computed the split bubbles: http://t.co/BcaqSs5u @FakeDorsey "Write drunk. Edit sober."—Ernest Hemingway @al3x RT @wcmaier: Better banking through better ops: build something new with us @Simplify (remote, PDX) http://t.co/8WgzKZH3 @calebelston We just announced Mosaic, what we've been working on since the Yobongo acquisition. My personal post, http://t.co/ELOyIRZU @heymosaic @BarackObama Donate $10 or more --> get your favorite car magnet: http://t.co/NfRhl2s2 #Obama2012 @JEG2 RT @tenderlove: If corporations are people, can we use them to drive in the carpool lane? @eveningedition LDN—Obama's nomination; Putin woos APEC; Bombs hit Damascus; Quakes shake China; Canada cuts Iran ties; weekend read: http://t.co/OFs6dVW4 @dhh RT @ggreenwald: Democrats parade Osama bin Laden's corpse as their proudest achievement: why this goulish jingoism is so warped http://t.co/kood278s @jasonfried The story of Mars Curiosity's gears, made by a factory in Rockford, IL: http://t.co/MwCRsHQg @sferik @episod @twitterapi now https://t.co/I17jUTu2 and https://t.co/deDu4Hgw seem to be missing "1.1" from the URL. @sferik @episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? @dwiskus Gentlemen, you can't fight in here! This is the war room! http://t.co/kMxMYyqF EOS end end context "--color=auto" do before do @list.options = @list.options.merge("color" => "auto") end it "outputs without color when stdout is not a tty" do @list.timeline("presidents") expect($stdout.string).to eq <<-EOS @mutgoff Happy Birthday @imdane. Watch out for those @rally pranksters! @ironicsans If you like good real-life stories, check out @NarrativelyNY's just-launched site http://t.co/wiUL07jE (and also visit http://t.co/ZoyQxqWA) @pat_shaughnessy Something else to vote for: "New Rails workshops to bring more women into the Boston software scene" http://t.co/eNBuckHc /cc @bostonrb @calebelston Pushing the button to launch the site. http://t.co/qLoEn5jG @calebelston RT @olivercameron: Mosaic looks cool: http://t.co/A8013C9k @fivethirtyeight The Weatherman is Not a Moron: http://t.co/ZwL5Gnq5. An excerpt from my book, THE SIGNAL AND THE NOISE (http://t.co/fNXj8vCE) @codeforamerica RT @randomhacks: Going to Code Across Austin II: Y'all Come Hack Now, Sat, Sep 8 http://t.co/Sk5BM7U3 We'll see y'all there! #rhok @codeforamerica @TheaClay @fbjork RT @jondot: Just published: "Pragmatic Concurrency With #Ruby" http://t.co/kGEykswZ /cc @JRuby @headius @mbostock If you are wondering how we computed the split bubbles: http://t.co/BcaqSs5u @FakeDorsey "Write drunk. Edit sober."—Ernest Hemingway @al3x RT @wcmaier: Better banking through better ops: build something new with us @Simplify (remote, PDX) http://t.co/8WgzKZH3 @calebelston We just announced Mosaic, what we've been working on since the Yobongo acquisition. My personal post, http://t.co/ELOyIRZU @heymosaic @BarackObama Donate $10 or more --> get your favorite car magnet: http://t.co/NfRhl2s2 #Obama2012 @JEG2 RT @tenderlove: If corporations are people, can we use them to drive in the carpool lane? @eveningedition LDN—Obama's nomination; Putin woos APEC; Bombs hit Damascus; Quakes shake China; Canada cuts Iran ties; weekend read: http://t.co/OFs6dVW4 @dhh RT @ggreenwald: Democrats parade Osama bin Laden's corpse as their proudest achievement: why this goulish jingoism is so warped http://t.co/kood278s @jasonfried The story of Mars Curiosity's gears, made by a factory in Rockford, IL: http://t.co/MwCRsHQg @sferik @episod @twitterapi now https://t.co/I17jUTu2 and https://t.co/deDu4Hgw seem to be missing "1.1" from the URL. @sferik @episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? @dwiskus Gentlemen, you can't fight in here! This is the war room! http://t.co/kMxMYyqF EOS end it "outputs with color when stdout is a tty" do allow($stdout).to receive(:tty?).and_return(true) @list.timeline("presidents") expect($stdout.string).to eq <<~EOS \e[1m\e[33m @mutgoff\e[0m Happy Birthday @imdane. Watch out for those @rally pranksters! \e[1m\e[33m @ironicsans\e[0m If you like good real-life stories, check out @NarrativelyNY's just-launched site http://t.co/wiUL07jE (and also visit http://t.co/ZoyQxqWA) \e[1m\e[33m @pat_shaughnessy\e[0m Something else to vote for: "New Rails workshops to bring more women into the Boston software scene" http://t.co/eNBuckHc /cc @bostonrb \e[1m\e[33m @calebelston\e[0m Pushing the button to launch the site. http://t.co/qLoEn5jG \e[1m\e[33m @calebelston\e[0m RT @olivercameron: Mosaic looks cool: http://t.co/A8013C9k \e[1m\e[33m @fivethirtyeight\e[0m The Weatherman is Not a Moron: http://t.co/ZwL5Gnq5. An excerpt from my book, THE SIGNAL AND THE NOISE (http://t.co/fNXj8vCE) \e[1m\e[33m @codeforamerica\e[0m RT @randomhacks: Going to Code Across Austin II: Y'all Come Hack Now, Sat, Sep 8 http://t.co/Sk5BM7U3 We'll see y'all there! #rhok @codeforamerica @TheaClay \e[1m\e[33m @fbjork\e[0m RT @jondot: Just published: "Pragmatic Concurrency With #Ruby" http://t.co/kGEykswZ /cc @JRuby @headius \e[1m\e[33m @mbostock\e[0m If you are wondering how we computed the split bubbles: http://t.co/BcaqSs5u \e[1m\e[33m @FakeDorsey\e[0m "Write drunk. Edit sober."—Ernest Hemingway \e[1m\e[33m @al3x\e[0m RT @wcmaier: Better banking through better ops: build something new with us @Simplify (remote, PDX) http://t.co/8WgzKZH3 \e[1m\e[33m @calebelston\e[0m We just announced Mosaic, what we've been working on since the Yobongo acquisition. My personal post, http://t.co/ELOyIRZU @heymosaic \e[1m\e[33m @BarackObama\e[0m Donate $10 or more --> get your favorite car magnet: http://t.co/NfRhl2s2 #Obama2012 \e[1m\e[33m @JEG2\e[0m RT @tenderlove: If corporations are people, can we use them to drive in the carpool lane? \e[1m\e[33m @eveningedition\e[0m LDN—Obama's nomination; Putin woos APEC; Bombs hit Damascus; Quakes shake China; Canada cuts Iran ties; weekend read: http://t.co/OFs6dVW4 \e[1m\e[33m @dhh\e[0m RT @ggreenwald: Democrats parade Osama bin Laden's corpse as their proudest achievement: why this goulish jingoism is so warped http://t.co/kood278s \e[1m\e[33m @jasonfried\e[0m The story of Mars Curiosity's gears, made by a factory in Rockford, IL: http://t.co/MwCRsHQg \e[1m\e[33m @sferik\e[0m @episod @twitterapi now https://t.co/I17jUTu2 and https://t.co/deDu4Hgw seem to be missing "1.1" from the URL. \e[1m\e[33m @sferik\e[0m @episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? \e[1m\e[33m @dwiskus\e[0m Gentlemen, you can't fight in here! This is the war room! http://t.co/kMxMYyqF EOS end end context "--color=icon" do before do @list.options = @list.options.merge("color" => "icon") end it "outputs with color when stdout is a tty" do allow($stdout).to receive(:tty?).and_return(true) @list.timeline("presidents") names = %w[mutgoff ironicsans pat_shaughnessy calebelston fivethirtyeight codeforamerica fbjork mbostock FakeDorsey al3x BarackObama JEG2 eveningedition dhh jasonfried sferik dwiskus] icons = names.inject({}) { |acc, elem| acc.update(elem.to_sym => T::Identicon.for_user_name(elem)) } expect($stdout.string).to eq <<-EOS #{icons[:mutgoff].lines[0]}\e[1m\e[33m @mutgoff\e[0m #{icons[:mutgoff].lines[1]} Happy Birthday @imdane. Watch out for those @rally pranksters! #{icons[:mutgoff].lines[2]} #{icons[:ironicsans].lines[0]}\e[1m\e[33m @ironicsans\e[0m #{icons[:ironicsans].lines[1]} If you like good real-life stories, check out @NarrativelyNY's #{icons[:ironicsans].lines[2]} just-launched site http://t.co/wiUL07jE (and also visit http://t.co/ZoyQxqWA) #{icons[:pat_shaughnessy].lines[0]}\e[1m\e[33m @pat_shaughnessy\e[0m #{icons[:pat_shaughnessy].lines[1]} Something else to vote for: "New Rails workshops to bring more women #{icons[:pat_shaughnessy].lines[2]} into the Boston software scene" http://t.co/eNBuckHc /cc @bostonrb #{icons[:calebelston].lines[0]}\e[1m\e[33m @calebelston\e[0m #{icons[:calebelston].lines[1]} Pushing the button to launch the site. http://t.co/qLoEn5jG #{icons[:calebelston].lines[2]} #{icons[:calebelston].lines[0]}\e[1m\e[33m @calebelston\e[0m #{icons[:calebelston].lines[1]} RT @olivercameron: Mosaic looks cool: http://t.co/A8013C9k #{icons[:calebelston].lines[2]} #{icons[:fivethirtyeight].lines[0]}\e[1m\e[33m @fivethirtyeight\e[0m #{icons[:fivethirtyeight].lines[1]} The Weatherman is Not a Moron: http://t.co/ZwL5Gnq5. An excerpt from #{icons[:fivethirtyeight].lines[2]} my book, THE SIGNAL AND THE NOISE (http://t.co/fNXj8vCE) #{icons[:codeforamerica].lines[0]}\e[1m\e[33m @codeforamerica\e[0m #{icons[:codeforamerica].lines[1]} RT @randomhacks: Going to Code Across Austin II: Y'all Come Hack Now, #{icons[:codeforamerica].lines[2]} Sat, Sep 8 http://t.co/Sk5BM7U3 We'll see y'all there! #rhok @codeforamerica @TheaClay #{icons[:fbjork].lines[0]}\e[1m\e[33m @fbjork\e[0m #{icons[:fbjork].lines[1]} RT @jondot: Just published: "Pragmatic Concurrency With #Ruby" #{icons[:fbjork].lines[2]} http://t.co/kGEykswZ /cc @JRuby @headius #{icons[:mbostock].lines[0]}\e[1m\e[33m @mbostock\e[0m #{icons[:mbostock].lines[1]} If you are wondering how we computed the split bubbles: #{icons[:mbostock].lines[2]} http://t.co/BcaqSs5u #{icons[:FakeDorsey].lines[0]}\e[1m\e[33m @FakeDorsey\e[0m #{icons[:FakeDorsey].lines[1]} "Write drunk. Edit sober."—Ernest Hemingway #{icons[:FakeDorsey].lines[2]} #{icons[:al3x].lines[0]}\e[1m\e[33m @al3x\e[0m #{icons[:al3x].lines[1]} RT @wcmaier: Better banking through better ops: build something new #{icons[:al3x].lines[2]} with us @Simplify (remote, PDX) http://t.co/8WgzKZH3 #{icons[:calebelston].lines[0]}\e[1m\e[33m @calebelston\e[0m #{icons[:calebelston].lines[1]} We just announced Mosaic, what we've been working on since the #{icons[:calebelston].lines[2]} Yobongo acquisition. My personal post, http://t.co/ELOyIRZU @heymosaic #{icons[:BarackObama].lines[0]}\e[1m\e[33m @BarackObama\e[0m #{icons[:BarackObama].lines[1]} Donate $10 or more --> get your favorite car magnet: #{icons[:BarackObama].lines[2]} http://t.co/NfRhl2s2 #Obama2012 #{icons[:JEG2].lines[0]}\e[1m\e[33m @JEG2\e[0m #{icons[:JEG2].lines[1]} RT @tenderlove: If corporations are people, can we use them to drive #{icons[:JEG2].lines[2]} in the carpool lane? #{icons[:eveningedition].lines[0]}\e[1m\e[33m @eveningedition\e[0m #{icons[:eveningedition].lines[1]} LDN—Obama's nomination; Putin woos APEC; Bombs hit Damascus; Quakes #{icons[:eveningedition].lines[2]} shake China; Canada cuts Iran ties; weekend read: http://t.co/OFs6dVW4 #{icons[:dhh].lines[0]}\e[1m\e[33m @dhh\e[0m #{icons[:dhh].lines[1]} RT @ggreenwald: Democrats parade Osama bin Laden's corpse as their #{icons[:dhh].lines[2]} proudest achievement: why this goulish jingoism is so warped http://t.co/kood278s #{icons[:jasonfried].lines[0]}\e[1m\e[33m @jasonfried\e[0m #{icons[:jasonfried].lines[1]} The story of Mars Curiosity's gears, made by a factory in Rockford, #{icons[:jasonfried].lines[2]} IL: http://t.co/MwCRsHQg #{icons[:sferik].lines[0]}\e[1m\e[33m @sferik\e[0m #{icons[:sferik].lines[1]} @episod @twitterapi now https://t.co/I17jUTu2 and #{icons[:sferik].lines[2]} https://t.co/deDu4Hgw seem to be missing "1.1" from the URL. #{icons[:sferik].lines[0]}\e[1m\e[33m @sferik\e[0m #{icons[:sferik].lines[1]} @episod @twitterapi Did you catch https://t.co/VHsQvZT0 as well? #{icons[:sferik].lines[2]} #{icons[:dwiskus].lines[0]}\e[1m\e[33m @dwiskus\e[0m #{icons[:dwiskus].lines[1]} Gentlemen, you can't fight in here! This is the war room! #{icons[:dwiskus].lines[2]} http://t.co/kMxMYyqF EOS end end context "--csv" do before do
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
true
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/spec/helper.rb
spec/helper.rb
ENV["THOR_COLUMNS"] = "80" require "simplecov" SimpleCov.start do add_filter "/spec" minimum_coverage(99.18) end require "t" require "json" require "readline" require "rspec" require "timecop" require "webmock/rspec" RSpec.configure do |config| config.expect_with :rspec do |c| c.syntax = :expect end config.before do stub_post("/oauth2/token").with(body: "grant_type=client_credentials").to_return(body: fixture("bearer_token.json"), headers: {content_type: "application/json; charset=utf-8"}) end end def a_delete(path, endpoint = "https://api.twitter.com") a_request(:delete, endpoint + path) end def a_get(path, endpoint = "https://api.twitter.com") a_request(:get, endpoint + path) end def a_post(path, endpoint = "https://api.twitter.com") a_request(:post, endpoint + path) end def a_put(path, endpoint = "https://api.twitter.com") a_request(:put, endpoint + path) end def stub_delete(path, endpoint = "https://api.twitter.com") stub_request(:delete, endpoint + path) end def stub_get(path, endpoint = "https://api.twitter.com") stub_request(:get, endpoint + path) end def stub_post(path, endpoint = "https://api.twitter.com") stub_request(:post, endpoint + path) end def stub_put(path, endpoint = "https://api.twitter.com") stub_request(:put, endpoint + path) end def project_path File.expand_path("..", __dir__) end def fixture_path File.expand_path("fixtures", __dir__) end def fixture(file) File.new("#{fixture_path}/#{file}") end def tweet_from_fixture(file) Twitter::Tweet.new(JSON.parse(fixture(file).read, symbolize_names: true)) end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t.rb
lib/t.rb
require "t/cli" require "time" module T class << self # Convert time to local time by applying the `utc_offset` setting. def local_time(time) time = time.dup utc_offset ? (time.utc + utc_offset) : time.localtime end # UTC offset in seconds to apply time instances before displaying. # If not set, time instances are displayed in default local time. attr_reader :utc_offset def utc_offset=(offset) @utc_offset = case offset when String Time.zone_offset(offset) when NilClass nil else offset.to_i end end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/version.rb
lib/t/version.rb
module T class Version MAJOR = 4 MINOR = 2 PATCH = 0 PRE = nil class << self # @return [String] def to_s [MAJOR, MINOR, PATCH, PRE].compact.join(".") end end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/collectable.rb
lib/t/collectable.rb
require "twitter" require "retryable" module T module Collectable MAX_NUM_RESULTS = 200 MAX_PAGE = 51 def collect_with_max_id(collection = [], max_id = nil, &) tweets = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do yield(max_id) end return collection if tweets.nil? collection += tweets tweets.empty? ? collection.flatten : collect_with_max_id(collection, tweets.last.id - 1, &) end def collect_with_count(count) opts = {} opts[:count] = MAX_NUM_RESULTS collect_with_max_id do |max_id| opts[:max_id] = max_id unless max_id.nil? opts[:count] = count unless count >= MAX_NUM_RESULTS if count.positive? tweets = yield opts count -= tweets.length tweets end end.flatten.compact end def collect_with_page(collection = ::Set.new, page = 1, previous = nil, &) tweets = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do yield page end return collection if tweets.nil? || tweets == previous || page >= MAX_PAGE collection += tweets tweets.empty? ? collection.flatten : collect_with_page(collection, page + 1, tweets, &) end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/requestable.rb
lib/t/requestable.rb
require "twitter" module T module Requestable private def client return @client if @client @rcfile.path = options["profile"] if options["profile"] @client = Twitter::REST::Client.new do |config| config.consumer_key = @rcfile.active_consumer_key config.consumer_secret = @rcfile.active_consumer_secret config.access_token = @rcfile.active_token config.access_token_secret = @rcfile.active_secret end end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/identicon.rb
lib/t/identicon.rb
module T class Identicon # Six-bit number (0-63) attr_accessor :bits # Eight-bit number (0-255) attr_accessor :color def initialize(number) # Bottom six bits @bits = number & 0x3f # Next highest eight bits @fcolor = (number >> 6) & 0xff # Next highest eight bits @bcolor = (number >> 14) & 0xff end def lines ["#{bg @bits[0]} #{bg @bits[1]} #{bg @bits[0]} #{reset}", "#{bg @bits[2]} #{bg @bits[3]} #{bg @bits[2]} #{reset}", "#{bg @bits[4]} #{bg @bits[5]} #{bg @bits[4]} #{reset}"] end private def reset "\033[0m" end def bg(bit) bit.zero? ? "\033[48;5;#{@bcolor}m" : "\033[48;5;#{@fcolor}m" end end class << Identicon def for_user_name(string) Identicon.new(digest(string)) end private def digest(string) require "digest" Digest::MD5.digest(string).chars.inject(0) { |acc, elem| (acc << 8) | elem.ord } end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/delete.rb
lib/t/delete.rb
require "thor" require "twitter" require "t/rcfile" require "t/requestable" require "t/utils" module T class Delete < Thor include T::Requestable include T::Utils check_unknown_options! def initialize(*) @rcfile = T::RCFile.instance super end desc "block USER [USER...]", "Unblock users." method_option "id", aliases: "-i", type: :boolean, desc: "Specify input as Twitter user IDs instead of screen names." method_option "force", aliases: "-f", type: :boolean def block(user, *users) unblocked_users, number = fetch_users(users.unshift(user), options) do |users_to_unblock| client.unblock(users_to_unblock) end say "@#{@rcfile.active_profile[0]} unblocked #{pluralize(number, 'user')}." say say "Run `#{File.basename($PROGRAM_NAME)} block #{unblocked_users.collect { |unblocked_user| "@#{unblocked_user.screen_name}" }.join(' ')}` to block." end desc "dm [DIRECT_MESSAGE_ID] [DIRECT_MESSAGE_ID...]", "Delete the last Direct Message sent." method_option "force", aliases: "-f", type: :boolean def dm(direct_message_id, *direct_message_ids) direct_message_ids.unshift(direct_message_id) require "t/core_ext/string" direct_message_ids.collect!(&:to_i) if options["force"] client.destroy_direct_message(*direct_message_ids) say "@#{@rcfile.active_profile[0]} deleted #{direct_message_ids.size} direct message#{direct_message_ids.size == 1 ? '' : 's'}." else direct_message_ids.each do |direct_message_id_to_delete| direct_message = client.direct_message(direct_message_id_to_delete) next unless direct_message recipient = client.user(direct_message.recipient_id) next unless yes? "Are you sure you want to permanently delete the direct message to @#{recipient.screen_name}: \"#{direct_message.text}\"? [y/N]" client.destroy_direct_message(direct_message_id_to_delete) say "@#{@rcfile.active_profile[0]} deleted the direct message sent to @#{recipient.screen_name}: \"#{direct_message.text}\"" end end end map %w[d m] => :dm desc "favorite TWEET_ID [TWEET_ID...]", "Delete favorites." method_option "force", aliases: "-f", type: :boolean def favorite(status_id, *status_ids) status_ids.unshift(status_id) require "t/core_ext/string" status_ids.collect!(&:to_i) if options["force"] tweets = client.unfavorite(status_ids) tweets.each do |status| say "@#{@rcfile.active_profile[0]} unfavorited @#{status.user.screen_name}'s status: \"#{status.full_text}\"" end else status_ids.each do |status_id_to_unfavorite| status = client.status(status_id_to_unfavorite, include_my_retweet: false) next unless yes? "Are you sure you want to remove @#{status.user.screen_name}'s status: \"#{status.full_text}\" from your favorites? [y/N]" client.unfavorite(status_id_to_unfavorite) say "@#{@rcfile.active_profile[0]} unfavorited @#{status.user.screen_name}'s status: \"#{status.full_text}\"" end end end map %w[fave favourite] => :favorite desc "list LIST", "Delete a list." method_option "force", aliases: "-f", type: :boolean method_option "id", aliases: "-i", type: :boolean, desc: "Specify list via ID instead of slug." def list(list) if options["id"] require "t/core_ext/string" list = list.to_i end list = client.list(list) return if !options["force"] && !(yes? "Are you sure you want to permanently delete the list \"#{list.name}\"? [y/N]") client.destroy_list(list) say "@#{@rcfile.active_profile[0]} deleted the list \"#{list.name}\"." end desc "mute USER [USER...]", "Unmute users." method_option "id", aliases: "-i", type: :boolean, desc: "Specify input as Twitter user IDs instead of screen names." method_option "force", aliases: "-f", type: :boolean def mute(user, *users) unmuted_users, number = fetch_users(users.unshift(user), options) do |users_to_unmute| client.unmute(users_to_unmute) end say "@#{@rcfile.active_profile[0]} unmuted #{pluralize(number, 'user')}." say say "Run `#{File.basename($PROGRAM_NAME)} mute #{unmuted_users.collect { |unmuted_user| "@#{unmuted_user.screen_name}" }.join(' ')}` to mute." end desc "account SCREEN_NAME [CONSUMER_KEY]", "delete account or consumer key from t" def account(account, key = nil) if key && @rcfile.profiles[account].keys.size > 1 @rcfile.delete_key(account, key) else @rcfile.delete_profile(account) end end desc "status TWEET_ID [TWEET_ID...]", "Delete Tweets." method_option "force", aliases: "-f", type: :boolean def status(status_id, *status_ids) status_ids.unshift(status_id) require "t/core_ext/string" status_ids.collect!(&:to_i) if options["force"] tweets = client.destroy_status(status_ids, trim_user: true) tweets.each do |status| say "@#{@rcfile.active_profile[0]} deleted the Tweet: \"#{status.full_text}\"" end else status_ids.each do |status_id_to_delete| status = client.status(status_id_to_delete, include_my_retweet: false) next unless yes? "Are you sure you want to permanently delete @#{status.user.screen_name}'s status: \"#{status.full_text}\"? [y/N]" client.destroy_status(status_id_to_delete, trim_user: true) say "@#{@rcfile.active_profile[0]} deleted the Tweet: \"#{status.full_text}\"" end end end map %w[post tweet update] => :status end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/printable.rb
lib/t/printable.rb
module T module Printable # rubocop:disable Metrics/ModuleLength LIST_HEADINGS = ["ID", "Created at", "Screen name", "Slug", "Members", "Subscribers", "Mode", "Description"].freeze TWEET_HEADINGS = ["ID", "Posted at", "Screen name", "Text"].freeze USER_HEADINGS = ["ID", "Since", "Last tweeted at", "Tweets", "Favorites", "Listed", "Following", "Followers", "Screen name", "Name", "Verified", "Protected", "Bio", "Status", "Location", "URL"].freeze MONTH_IN_SECONDS = 2_592_000 private def build_long_list(list) [list.id, ls_formatted_time(list), "@#{list.user.screen_name}", list.slug, list.member_count, list.subscriber_count, list.mode, list.description] end def build_long_tweet(tweet) [tweet.id, ls_formatted_time(tweet), "@#{tweet.user.screen_name}", decode_full_text(tweet, options["decode_uris"]).gsub(/\n+/, " ")] end def build_long_user(user) [user.id, ls_formatted_time(user), ls_formatted_time(user.status), user.statuses_count, user.favorites_count, user.listed_count, user.friends_count, user.followers_count, "@#{user.screen_name}", user.name, user.verified? ? "Yes" : "No", user.protected? ? "Yes" : "No", user.description.gsub(/\n+/, " "), user.status? ? decode_full_text(user.status, options["decode_uris"]).gsub(/\n+/, " ") : nil, user.location, user.website.to_s] end def csv_formatted_time(object, key = :created_at) return nil if object.nil? time = object.send(key.to_sym).dup time.utc.strftime("%Y-%m-%d %H:%M:%S %z") end def ls_formatted_time(object, key = :created_at, allow_relative = true) return "" if object.nil? time = T.local_time(object.send(key.to_sym)) if allow_relative && options["relative_dates"] "#{distance_of_time_in_words(time)} ago" elsif time > Time.now - (MONTH_IN_SECONDS * 6) time.strftime("%b %e %H:%M") else time.strftime("%b %e %Y") end end def print_csv_list(list) require "csv" say [list.id, csv_formatted_time(list), list.user.screen_name, list.slug, list.member_count, list.subscriber_count, list.mode, list.description].to_csv end def print_csv_tweet(tweet) require "csv" say [tweet.id, csv_formatted_time(tweet), tweet.user.screen_name, decode_full_text(tweet, options["decode_uris"])].to_csv end def print_csv_user(user) require "csv" say [user.id, csv_formatted_time(user), csv_formatted_time(user.status), user.statuses_count, user.favorites_count, user.listed_count, user.friends_count, user.followers_count, user.screen_name, user.name, user.verified?, user.protected?, user.description, user.status? ? user.status.full_text : nil, user.location, user.website].to_csv end def print_lists(lists) unless options["unsorted"] lists = case options["sort"] when "members" lists.sort_by(&:member_count) when "mode" lists.sort_by(&:mode) when "since" lists.sort_by(&:created_at) when "subscribers" lists.sort_by(&:subscriber_count) else lists.sort_by { |list| list.slug.downcase } end end lists.reverse! if options["reverse"] if options["csv"] require "csv" say LIST_HEADINGS.to_csv unless lists.empty? lists.each do |list| print_csv_list(list) end elsif options["long"] array = lists.collect do |list| build_long_list(list) end format = options["format"] || Array.new(LIST_HEADINGS.size) { "%s" } print_table_with_headings(array, LIST_HEADINGS, format) else print_attribute(lists, :full_name) end end def print_attribute(array, attribute) if STDOUT.tty? print_in_columns(array.collect(&attribute.to_sym)) else array.each do |element| say element.send(attribute.to_sym) end end end def print_table_with_headings(array, headings, format) return if array.flatten.empty? if STDOUT.tty? array.unshift(headings) require "t/core_ext/kernel" array.collect! do |row| row.each_with_index.collect do |element, index| next if element.nil? Kernel.send(element.class.name.to_sym, format[index] % element) end end print_table(array, truncate: true) else print_table(array) end STDOUT.flush end def print_message(from_user, message) require "htmlentities" case options["color"] when "icon" print_identicon(from_user, message) say when "auto" say(" @#{from_user}", %i[bold yellow]) print_wrapped(HTMLEntities.new.decode(message), indent: 3) else say(" @#{from_user}") print_wrapped(HTMLEntities.new.decode(message), indent: 3) end say end def print_identicon(from_user, message) require "htmlentities" require "t/identicon" icon = Identicon.for_user_name(from_user) # Save 6 chars for icon, ensure at least 3 lines long lines = wrapped(HTMLEntities.new.decode(message), indent: 2, width: Thor::Shell::Terminal.terminal_width - (6 + 5)) lines.unshift(set_color(" @#{from_user}", :bold, :yellow)) lines.concat(Array.new([3 - lines.length, 0].max) { "" }) $stdout.puts(lines.zip(icon.lines).map { |x, i| " #{i || ' '}#{x}" }) end def wrapped(message, options = {}) indent = options[:indent] || 0 width = options[:width] || (Thor::Shell::Terminal.terminal_width - indent) paras = message.split("\n\n") paras.map! do |unwrapped| unwrapped.strip.squeeze(" ").gsub(/.{1,#{width}}(?:\s|\Z)/) { (::Regexp.last_match(0) + 5.chr).gsub(/\n\005/, "\n").gsub(/\005/, "\n") } end lines = paras.inject([]) do |memo, para| memo.concat(para.split("\n").map { |line| line.insert(0, " " * indent) }) memo.push "" end lines.pop lines end def print_tweets(tweets) tweets.reverse! if options["reverse"] if options["csv"] require "csv" say TWEET_HEADINGS.to_csv unless tweets.empty? tweets.each do |tweet| print_csv_tweet(tweet) end elsif options["long"] array = tweets.collect do |tweet| build_long_tweet(tweet) end format = options["format"] || Array.new(TWEET_HEADINGS.size) { "%s" } print_table_with_headings(array, TWEET_HEADINGS, format) else tweets.each do |tweet| print_message(tweet.user.screen_name, decode_uris(tweet.full_text, options["decode_uris"] ? tweet.uris : nil)) end end end def print_users(users) # rubocop:disable Metrics/CyclomaticComplexity unless options["unsorted"] users = case options["sort"] when "favorites" users.sort_by { |user| user.favorites_count.to_i } when "followers" users.sort_by { |user| user.followers_count.to_i } when "friends" users.sort_by { |user| user.friends_count.to_i } when "listed" users.sort_by { |user| user.listed_count.to_i } when "since" users.sort_by(&:created_at) when "tweets" users.sort_by { |user| user.statuses_count.to_i } when "tweeted" users.sort_by { |user| user.status? ? user.status.created_at : Time.at(0) } # rubocop:disable Metrics/BlockNesting else users.sort_by { |user| user.screen_name.downcase } end end users.reverse! if options["reverse"] if options["csv"] require "csv" say USER_HEADINGS.to_csv unless users.empty? users.each do |user| print_csv_user(user) end elsif options["long"] array = users.collect do |user| build_long_user(user) end format = options["format"] || Array.new(USER_HEADINGS.size) { "%s" } print_table_with_headings(array, USER_HEADINGS, format) else print_attribute(users, :screen_name) end end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/set.rb
lib/t/set.rb
require "thor" require "t/rcfile" require "t/requestable" module T class Set < Thor include T::Requestable check_unknown_options! def initialize(*) @rcfile = T::RCFile.instance super end desc "active SCREEN_NAME [CONSUMER_KEY]", "Set your active account." def active(screen_name, consumer_key = nil) require "t/core_ext/string" screen_name = screen_name.strip_ats @rcfile.path = options["profile"] if options["profile"] consumer_key = @rcfile[screen_name].keys.last if consumer_key.nil? @rcfile.active_profile = {"username" => @rcfile[screen_name][consumer_key]["username"], "consumer_key" => consumer_key} say "Active account has been updated to #{@rcfile.active_profile[0]}." end map %w[account default] => :active desc "bio DESCRIPTION", "Edits your Bio information on your Twitter profile." def bio(description) client.update_profile(description:) say "@#{@rcfile.active_profile[0]}'s bio has been updated." end desc "language LANGUAGE_NAME", "Selects the language you'd like to receive notifications in." def language(language_name) client.settings(lang: language_name) say "@#{@rcfile.active_profile[0]}'s language has been updated." end desc "location PLACE_NAME", "Updates the location field in your profile." def location(place_name) client.update_profile(location: place_name) say "@#{@rcfile.active_profile[0]}'s location has been updated." end desc "name NAME", "Sets the name field on your Twitter profile." def name(name) client.update_profile(name:) say "@#{@rcfile.active_profile[0]}'s name has been updated." end desc "profile_background_image FILE", "Sets the background image on your Twitter profile." method_option "tile", aliases: "-t", type: :boolean, desc: "Whether or not to tile the background image." def profile_background_image(file) client.update_profile_background_image(File.new(File.expand_path(file)), tile: options["tile"], skip_status: true) say "@#{@rcfile.active_profile[0]}'s background image has been updated." end map %w[background background_image] => :profile_background_image desc "profile_image FILE", "Sets the image on your Twitter profile." def profile_image(file) client.update_profile_image(File.new(File.expand_path(file))) say "@#{@rcfile.active_profile[0]}'s image has been updated." end map %w[avatar image] => :profile_image desc "website URI", "Sets the website field on your profile." def website(uri) client.update_profile(url: uri) say "@#{@rcfile.active_profile[0]}'s website has been updated." end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/utils.rb
lib/t/utils.rb
module T module Utils private # https://github.com/rails/rails/blob/bd8a970/actionpack/lib/action_view/helpers/date_helper.rb def distance_of_time_in_words(from_time, to_time = Time.now) # rubocop:disable Metrics/CyclomaticComplexity seconds = (to_time - from_time).abs minutes = seconds / 60 case minutes when 0...1 case seconds when 0...1 "a split second" when 1...2 "a second" when 2...60 format("%<seconds>d seconds", seconds:) end when 1...2 "a minute" when 2...60 format("%<minutes>d minutes", minutes:) when 60...120 "an hour" # 120 minutes up to 23.5 hours when 120...1410 format("%<hours>d hours", hours: (minutes.to_f / 60.0).round) # 23.5 hours up to 48 hours when 1410...2880 "a day" # 48 hours up to 29.5 days when 2880...42_480 format("%<days>d days", days: (minutes.to_f / 1440.0).round) # 29.5 days up to 60 days when 42_480...86_400 "a month" # 60 days up to 11.5 months when 86_400...503_700 format("%<months>d months", months: (minutes.to_f / 43_800.0).round) # 11.5 months up to 2 years when 503_700...1_051_200 "a year" else format("%<years>d years", years: (minutes.to_f / 525_600.0).round) end end alias time_ago_in_words distance_of_time_in_words alias time_from_now_in_words distance_of_time_in_words def fetch_users(users, options) format_users!(users, options) require "retryable" users = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do yield users end [users, users.length] end def format_users!(users, options) require "t/core_ext/string" options["id"] ? users.collect!(&:to_i) : users.collect!(&:strip_ats) end def extract_owner(user_list, options) owner, list_name = user_list.split("/") if list_name.nil? list_name = owner owner = @rcfile.active_profile[0] else require "t/core_ext/string" owner = options["id"] ? owner.to_i : owner.strip_ats end [owner, list_name] end def strip_tags(html) html.gsub(/<.+?>/, "") end def number_with_delimiter(number, delimiter = ",") digits = number.to_s.chars groups = digits.reverse.each_slice(3).collect(&:join) groups.join(delimiter).reverse end def pluralize(count, singular, plural = nil) "#{count || 0} " + (count == 1 || count =~ /^1(\.0+)?$/ ? singular : (plural || "#{singular}s")) end def decode_full_text(message, decode_full_uris = false) require "htmlentities" text = HTMLEntities.new.decode(message.full_text) text = decode_uris(text, message.uris) if decode_full_uris text end def decode_uris(full_text, uri_entities) return full_text if uri_entities.nil? uri_entities.each do |uri_entity| full_text = full_text.gsub(uri_entity.uri.to_s, uri_entity.expanded_uri.to_s) end full_text end def open_or_print(uri, options) Launchy.open(uri, options) do say "Open: #{uri}" end end def parallel_map(enumerable) enumerable.collect { |object| Thread.new { yield object } }.collect(&:value) end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/stream.rb
lib/t/stream.rb
require "thor" require "t/printable" require "t/rcfile" require "t/requestable" require "t/utils" module T class Stream < Thor include T::Printable include T::Requestable include T::Utils TWEET_HEADINGS_FORMATTING = [ "%-18s", # Add padding to maximum length of a Tweet ID "%-12s", # Add padding to length of a timestamp formatted with ls_formatted_time "%-20s", # Add padding to maximum length of a Twitter screen name "%s", # Last element does not need special formatting ].freeze check_unknown_options! def initialize(*) @rcfile = T::RCFile.instance super end desc "all", "Stream a random sample of all Tweets (Control-C to stop)" method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." def all streaming_client.before_request do if options["csv"] require "csv" say TWEET_HEADINGS.to_csv elsif options["long"] && STDOUT.tty? headings = Array.new(TWEET_HEADINGS.size) do |index| TWEET_HEADINGS_FORMATTING[index] % TWEET_HEADINGS[index] end print_table([headings]) end end streaming_client.sample do |tweet| next unless tweet.is_a?(Twitter::Tweet) if options["csv"] print_csv_tweet(tweet) elsif options["long"] array = build_long_tweet(tweet).each_with_index.collect do |element, index| TWEET_HEADINGS_FORMATTING[index] % element end print_table([array], truncate: STDOUT.tty?) else print_message(tweet.user.screen_name, tweet.text) end end end desc "list [USER/]LIST", "Stream a timeline for members of the specified list (Control-C to stop)" method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." def list(user_list) owner, list_name = extract_owner(user_list, options) require "t/list" streaming_client.before_request do list = T::List.new list.options = list.options.merge(options) list.options = list.options.merge(reverse: true) list.options = list.options.merge(format: TWEET_HEADINGS_FORMATTING) list.timeline(user_list) end user_ids = client.list_members(owner, list_name).collect(&:id) streaming_client.filter(follow: user_ids.join(",")) do |tweet| next unless tweet.is_a?(Twitter::Tweet) if options["csv"] print_csv_tweet(tweet) elsif options["long"] array = build_long_tweet(tweet).each_with_index.collect do |element, index| TWEET_HEADINGS_FORMATTING[index] % element end print_table([array], truncate: STDOUT.tty?) else print_message(tweet.user.screen_name, tweet.text) end end end map %w[tl] => :timeline desc "matrix", "Unfortunately, no one can be told what the Matrix is. You have to see it for yourself." def matrix require "t/cli" streaming_client.before_request do cli = T::CLI.new cli.matrix end streaming_client.sample(language: "ja") do |tweet| next unless tweet.is_a?(Twitter::Tweet) say(tweet.text.gsub(/[^\u3000\u3040-\u309f]/, "").reverse, %i[bold green on_black], false) end end desc "search KEYWORD [KEYWORD...]", "Stream Tweets that contain specified keywords, joined with logical ORs (Control-C to stop)" method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." def search(keyword, *keywords) keywords.unshift(keyword) require "t/search" streaming_client.before_request do search = T::Search.new search.options = search.options.merge(options) search.options = search.options.merge(reverse: true) search.options = search.options.merge(format: TWEET_HEADINGS_FORMATTING) search.all(keywords.join(" OR ")) end streaming_client.filter(track: keywords.join(",")) do |tweet| next unless tweet.is_a?(Twitter::Tweet) if options["csv"] print_csv_tweet(tweet) elsif options["long"] array = build_long_tweet(tweet).each_with_index.collect do |element, index| TWEET_HEADINGS_FORMATTING[index] % element end print_table([array], truncate: STDOUT.tty?) else print_message(tweet.user.screen_name, tweet.text) end end end desc "timeline", "Stream your timeline (Control-C to stop)" method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." def timeline require "t/cli" streaming_client.before_request do cli = T::CLI.new cli.options = cli.options.merge(options) cli.options = cli.options.merge(reverse: true) cli.options = cli.options.merge(format: TWEET_HEADINGS_FORMATTING) cli.timeline end streaming_client.user do |tweet| next unless tweet.is_a?(Twitter::Tweet) if options["csv"] print_csv_tweet(tweet) elsif options["long"] array = build_long_tweet(tweet).each_with_index.collect do |element, index| TWEET_HEADINGS_FORMATTING[index] % element end print_table([array], truncate: STDOUT.tty?) else print_message(tweet.user.screen_name, tweet.text) end end end desc "users USER_ID [USER_ID...]", "Stream Tweets either from or in reply to specified users (Control-C to stop)" method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." def users(user_id, *user_ids) user_ids.unshift(user_id) user_ids.collect!(&:to_i) streaming_client.before_request do if options["csv"] require "csv" say TWEET_HEADINGS.to_csv elsif options["long"] && STDOUT.tty? headings = Array.new(TWEET_HEADINGS.size) do |index| TWEET_HEADINGS_FORMATTING[index] % TWEET_HEADINGS[index] end print_table([headings]) end end streaming_client.filter(follow: user_ids.join(",")) do |tweet| next unless tweet.is_a?(Twitter::Tweet) if options["csv"] print_csv_tweet(tweet) elsif options["long"] array = build_long_tweet(tweet).each_with_index.collect do |element, index| TWEET_HEADINGS_FORMATTING[index] % element end print_table([array], truncate: STDOUT.tty?) else print_message(tweet.user.screen_name, tweet.text) end end end private def streaming_client return @streaming_client if @streaming_client @rcfile.path = options["profile"] if options["profile"] @streaming_client = Twitter::Streaming::Client.new do |config| config.consumer_key = @rcfile.active_consumer_key config.consumer_secret = @rcfile.active_consumer_secret config.access_token = @rcfile.active_token config.access_token_secret = @rcfile.active_secret end end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/rcfile.rb
lib/t/rcfile.rb
require "singleton" module T class RCFile include Singleton attr_reader :path FILE_NAME = ".trc".freeze def initialize @path = File.join(File.expand_path("~"), FILE_NAME) @data = load_file end def [](username) profiles[find(username)] end def find(username) possibilities = Array(find_case_insensitive_match(username) || find_case_insensitive_possibilities(username)) raise(ArgumentError.new("Username #{username} is #{possibilities.empty? ? 'not found.' : "ambiguous, matching #{possibilities.join(', ')}"}")) unless possibilities.size == 1 possibilities.first end def find_case_insensitive_match(username) profiles.keys.detect { |u| username.casecmp(u).zero? } end def find_case_insensitive_possibilities(username) profiles.keys.select { |u| username.casecmp(u[0, username.length]).zero? } end def []=(username, profile) profiles[username] ||= {} profiles[username].merge!(profile) write end def configuration @data["configuration"] end def active_consumer_key profiles[active_profile[0]][active_profile[1]]["consumer_key"] if active_profile? end def active_consumer_secret profiles[active_profile[0]][active_profile[1]]["consumer_secret"] if active_profile? end def active_profile configuration["default_profile"] end def active_profile=(profile) configuration["default_profile"] = [profile["username"], profile["consumer_key"]] write end def active_secret profiles[active_profile[0]][active_profile[1]]["secret"] if active_profile? end def active_token profiles[active_profile[0]][active_profile[1]]["token"] if active_profile? end def delete FileUtils.rm_f(@path) end def empty? @data == default_structure end def load_file require "yaml" YAML.load_file(@path) rescue Errno::ENOENT default_structure end def path=(path) @path = path @data = load_file end def profiles @data["profiles"] end def reset send(:initialize) end def delete_profile(profile) profiles.delete(profile) write end def delete_key(profile, key) profiles[profile].delete(key) write end private def active_profile? active_profile && profiles[active_profile[0]] && profiles[active_profile[0]][active_profile[1]] end def default_structure {"configuration" => {}, "profiles" => {}} end def write require "yaml" File.open(@path, File::RDWR | File::TRUNC | File::CREAT, 0o0600) do |rcfile| rcfile.write @data.to_yaml end end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/search.rb
lib/t/search.rb
require "thor" require "twitter" require "t/collectable" require "t/printable" require "t/rcfile" require "t/requestable" require "t/utils" module T class Search < Thor include T::Collectable include T::Printable include T::Requestable include T::Utils DEFAULT_NUM_RESULTS = 20 MAX_NUM_RESULTS = 200 MAX_SEARCH_RESULTS = 100 check_unknown_options! def initialize(*) @rcfile = T::RCFile.instance super end desc "all QUERY", "Returns the #{DEFAULT_NUM_RESULTS} most recent Tweets that match the specified query." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "number", aliases: "-n", type: :numeric, default: DEFAULT_NUM_RESULTS method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." def all(query) count = options["number"] || DEFAULT_NUM_RESULTS opts = {count: MAX_SEARCH_RESULTS} opts[:include_entities] = !!options["decode_uris"] tweets = client.search(query, opts).take(count) tweets.reverse! if options["reverse"] if options["csv"] require "csv" say TWEET_HEADINGS.to_csv unless tweets.empty? tweets.each do |tweet| say [tweet.id, csv_formatted_time(tweet), tweet.user.screen_name, decode_full_text(tweet, options["decode_uris"])].to_csv end elsif options["long"] array = tweets.collect do |tweet| [tweet.id, ls_formatted_time(tweet), "@#{tweet.user.screen_name}", decode_full_text(tweet, options["decode_uris"]).gsub(/\n+/, " ")] end format = options["format"] || Array.new(TWEET_HEADINGS.size) { "%s" } print_table_with_headings(array, TWEET_HEADINGS, format) else say unless tweets.empty? tweets.each do |tweet| print_message(tweet.user.screen_name, decode_full_text(tweet, options["decode_uris"])) end end end desc "favorites [USER] QUERY", "Returns Tweets you've favorited that match the specified query." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." def favorites(*args) query = args.pop user = args.pop opts = {count: MAX_NUM_RESULTS} opts[:include_entities] = !!options["decode_uris"] if user require "t/core_ext/string" user = options["id"] ? user.to_i : user.strip_ats tweets = collect_with_max_id do |max_id| opts[:max_id] = max_id unless max_id.nil? client.favorites(user, opts) end else tweets = collect_with_max_id do |max_id| opts[:max_id] = max_id unless max_id.nil? client.favorites(opts) end end tweets = tweets.select do |tweet| /#{query}/i.match(tweet.full_text) end print_tweets(tweets) end map %w[faves] => :favorites desc "list [USER/]LIST QUERY", "Returns Tweets on a list that match the specified query." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." def list(user_list, query) owner, list_name = extract_owner(user_list, options) opts = {count: MAX_NUM_RESULTS} opts[:include_entities] = !!options["decode_uris"] tweets = collect_with_max_id do |max_id| opts[:max_id] = max_id unless max_id.nil? client.list_timeline(owner, list_name, opts) end tweets = tweets.select do |tweet| /#{query}/i.match(tweet.full_text) end print_tweets(tweets) end desc "mentions QUERY", "Returns Tweets mentioning you that match the specified query." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." def mentions(query) opts = {count: MAX_NUM_RESULTS} opts[:include_entities] = !!options["decode_uris"] tweets = collect_with_max_id do |max_id| opts[:max_id] = max_id unless max_id.nil? client.mentions(opts) end tweets = tweets.select do |tweet| /#{query}/i.match(tweet.full_text) end print_tweets(tweets) end map %w[replies] => :mentions desc "retweets [USER] QUERY", "Returns Tweets you've retweeted that match the specified query." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." def retweets(*args) query = args.pop user = args.pop opts = {count: MAX_NUM_RESULTS} opts[:include_entities] = !!options["decode_uris"] if user require "t/core_ext/string" user = options["id"] ? user.to_i : user.strip_ats tweets = collect_with_max_id do |max_id| opts[:max_id] = max_id unless max_id.nil? client.retweeted_by_user(user, opts) end else tweets = collect_with_max_id do |max_id| opts[:max_id] = max_id unless max_id.nil? client.retweeted_by_me(opts) end end tweets = tweets.select do |tweet| /#{query}/i.match(tweet.full_text) end print_tweets(tweets) end map %w[rts] => :retweets desc "timeline [USER] QUERY", "Returns Tweets in your timeline that match the specified query." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "exclude", aliases: "-e", type: :string, enum: %w[replies retweets], desc: "Exclude certain types of Tweets from the results.", banner: "TYPE" method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "max_id", aliases: "-m", type: :numeric, desc: "Returns only the results with an ID less than the specified ID." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "since_id", aliases: "-s", type: :numeric, desc: "Returns only the results with an ID greater than the specified ID." def timeline(*args) query = args.pop user = args.pop opts = {count: MAX_NUM_RESULTS} opts[:exclude_replies] = true if options["exclude"] == "replies" opts[:include_entities] = !!options["decode_uris"] opts[:include_rts] = false if options["exclude"] == "retweets" opts[:max_id] = options["max_id"] if options["max_id"] opts[:since_id] = options["since_id"] if options["since_id"] if user require "t/core_ext/string" user = options["id"] ? user.to_i : user.strip_ats tweets = collect_with_max_id do |max_id| opts[:max_id] = max_id unless max_id.nil? client.user_timeline(user, opts) end else tweets = collect_with_max_id do |max_id| opts[:max_id] = max_id unless max_id.nil? client.home_timeline(opts) end end tweets = tweets.select do |tweet| /#{query}/i.match(tweet.full_text) end print_tweets(tweets) end map %w[tl] => :timeline desc "users QUERY", "Returns users that match the specified query." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." method_option "sort", aliases: "-s", type: :string, enum: %w[favorites followers friends listed screen_name since tweets tweeted], default: "screen_name", desc: "Specify the order of the results.", banner: "ORDER" method_option "unsorted", aliases: "-u", type: :boolean, desc: "Output is not sorted." def users(query) users = collect_with_page do |page| client.user_search(query, page:) end print_users(users) end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/cli.rb
lib/t/cli.rb
# encoding: utf-8 require "forwardable" require "oauth" require "thor" require "twitter" require "t/collectable" require "t/delete" require "t/editor" require "t/list" require "t/printable" require "t/rcfile" require "t/requestable" require "t/search" require "t/set" require "t/stream" require "t/utils" module T class CLI < Thor extend Forwardable include T::Collectable include T::Printable include T::Requestable include T::Utils DEFAULT_NUM_RESULTS = 20 DIRECT_MESSAGE_HEADINGS = ["ID", "Posted at", "Screen name", "Text"].freeze MAX_SEARCH_RESULTS = 100 TREND_HEADINGS = ["WOEID", "Parent ID", "Type", "Name", "Country"].freeze check_unknown_options! class_option "color", aliases: "-C", type: :string, enum: %w[icon auto never], default: "auto", desc: "Control how color is used in output" class_option "profile", aliases: "-P", type: :string, default: File.join(File.expand_path("~"), T::RCFile::FILE_NAME), desc: "Path to RC file", banner: "FILE" def initialize(*) @rcfile = T::RCFile.instance super end desc "accounts", "List accounts" def accounts @rcfile.path = options["profile"] if options["profile"] @rcfile.profiles.each do |profile| say profile[0] profile[1].each_key do |key| say " #{key}#{@rcfile.active_profile[0] == profile[0] && @rcfile.active_profile[1] == key ? ' (active)' : nil}" end end end desc "authorize", "Allows an application to request user authorization" method_option "display-uri", aliases: "-d", type: :boolean, desc: "Display the authorization URL instead of attempting to open it." def authorize @rcfile.path = options["profile"] if options["profile"] if @rcfile.empty? say "Welcome! Before you can use t, you'll first need to register an" say "application with Twitter. Just follow the steps below:" say " 1. Sign in to the Twitter Application Management site and click" say ' "Create New App".' say " 2. Complete the required fields and submit the form." say " Note: Your application must have a unique name." say " 3. Go to the Permissions tab of your application, and change the" say ' Access setting to "Read, Write and Access direct messages".' say " 4. Go to the Keys and Access Tokens tab to view the consumer key" say " and secret which you'll need to copy and paste below when" say " prompted." else say "It looks like you've already registered an application with Twitter." say "To authorize a new account, just follow the steps below:" say " 1. Sign in to the Twitter Developer site." say " 2. Select the application for which you'd like to authorize an account." say " 3. Copy and paste the consumer key and secret below when prompted." end say ask "Press [Enter] to open the Twitter Developer site." say require "launchy" open_or_print("https://apps.twitter.com", dry_run: options["display-uri"]) key = ask "Enter your API key:" secret = ask "Enter your API secret:" consumer = OAuth::Consumer.new(key, secret, site: Twitter::REST::Request::BASE_URL) request_token = consumer.get_request_token uri = generate_authorize_uri(consumer, request_token) say say "In a moment, you will be directed to the Twitter app authorization page." say "Perform the following steps to complete the authorization process:" say " 1. Sign in to Twitter." say ' 2. Press "Authorize app".' say " 3. Copy and paste the supplied PIN below when prompted." say ask "Press [Enter] to open the Twitter app authorization page." say open_or_print(uri, dry_run: options["display-uri"]) pin = ask "Enter the supplied PIN:" access_token = request_token.get_access_token(oauth_verifier: pin.chomp) oauth_response = access_token.get("/1.1/account/verify_credentials.json?skip_status=true") screen_name = oauth_response.body.match(/"screen_name"\s*:\s*"(.*?)"/).captures.first @rcfile[screen_name] = { key => { "username" => screen_name, "consumer_key" => key, "consumer_secret" => secret, "token" => access_token.token, "secret" => access_token.secret, }, } @rcfile.active_profile = {"username" => screen_name, "consumer_key" => key} say "Authorization successful." end desc "block USER [USER...]", "Block users." method_option "id", aliases: "-i", type: :boolean, desc: "Specify input as Twitter user IDs instead of screen names." def block(user, *users) blocked_users, number = fetch_users(users.unshift(user), options) do |users_to_block| client.block(users_to_block) end say "@#{@rcfile.active_profile[0]} blocked #{pluralize(number, 'user')}." say say "Run `#{File.basename($PROGRAM_NAME)} delete block #{blocked_users.collect { |blocked_user| "@#{blocked_user.screen_name}" }.join(' ')}` to unblock." end desc "direct_messages", "Returns the #{DEFAULT_NUM_RESULTS} most recent Direct Messages sent to you." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "number", aliases: "-n", type: :numeric, default: DEFAULT_NUM_RESULTS, desc: "Limit the number of results." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." def direct_messages count = options["number"] || DEFAULT_NUM_RESULTS opts = {} opts[:include_entities] = !!options["decode_uris"] direct_messages = collect_with_count(count) do |count_opts| client.direct_messages_received(count_opts.merge(opts)) end users = direct_messages.empty? ? [] : client.users(direct_messages.map(&:sender_id)) users_hash = users.each_with_object({}) { |user, hash| hash[user.id] = user } direct_messages.reverse! if options["reverse"] if options["csv"] require "csv" say DIRECT_MESSAGE_HEADINGS.to_csv unless direct_messages.empty? direct_messages.each do |direct_message| sender = users_hash[direct_message.sender_id] || Twitter::NullObject.new say [direct_message.id, csv_formatted_time(direct_message), sender.screen_name, decode_full_text(direct_message, options["decode_uris"])].to_csv end elsif options["long"] array = direct_messages.collect do |direct_message| sender = users_hash[direct_message.sender_id] || Twitter::NullObject.new [direct_message.id, ls_formatted_time(direct_message), "@#{sender.screen_name}", decode_full_text(direct_message, options["decode_uris"]).gsub(/\n+/, " ")] end format = options["format"] || Array.new(DIRECT_MESSAGE_HEADINGS.size) { "%s" } print_table_with_headings(array, DIRECT_MESSAGE_HEADINGS, format) else direct_messages.each do |direct_message| sender = users_hash[direct_message.sender_id] || Twitter::NullObject.new print_message(sender.screen_name, direct_message.text) end end end map %w[directmessages dms] => :direct_messages desc "direct_messages_sent", "Returns the #{DEFAULT_NUM_RESULTS} most recent Direct Messages you've sent." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "number", aliases: "-n", type: :numeric, default: DEFAULT_NUM_RESULTS, desc: "Limit the number of results." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." def direct_messages_sent count = options["number"] || DEFAULT_NUM_RESULTS opts = {} opts[:include_entities] = !!options["decode_uris"] direct_messages = collect_with_count(count) do |count_opts| client.direct_messages_sent(count_opts.merge(opts)) end direct_messages.reverse! if options["reverse"] if options["csv"] require "csv" say DIRECT_MESSAGE_HEADINGS.to_csv unless direct_messages.empty? direct_messages.each do |direct_message| say [direct_message.id, csv_formatted_time(direct_message), direct_message.recipient.screen_name, decode_full_text(direct_message, options["decode_uris"])].to_csv end elsif options["long"] array = direct_messages.collect do |direct_message| [direct_message.id, ls_formatted_time(direct_message), "@#{direct_message.recipient.screen_name}", decode_full_text(direct_message, options["decode_uris"]).gsub(/\n+/, " ")] end format = options["format"] || Array.new(DIRECT_MESSAGE_HEADINGS.size) { "%s" } print_table_with_headings(array, DIRECT_MESSAGE_HEADINGS, format) else direct_messages.each do |direct_message| print_message(direct_message.recipient.screen_name, direct_message.text) end end end map %w[directmessagessent sent_messages sentmessages sms] => :direct_messages_sent desc "dm USER MESSAGE", "Sends that person a Direct Message." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." def dm(user, message) require "t/core_ext/string" recipient = options["id"] ? client.user(user.to_i) : client.user(user.strip_ats) client.create_direct_message_event(recipient, message) say "Direct Message sent from @#{@rcfile.active_profile[0]} to @#{recipient.screen_name}." end map %w[d m] => :dm desc "does_contain [USER/]LIST USER", "Find out whether a list contains a user." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." def does_contain(user_list, user = nil) owner, list_name = extract_owner(user_list, options) user = if user.nil? @rcfile.active_profile[0] else require "t/core_ext/string" options["id"] ? client.user(user.to_i).screen_name : user.strip_ats end if client.list_member?(owner, list_name, user) say "Yes, #{list_name} contains @#{user}." else abort "No, #{list_name} does not contain @#{user}." end end map %w[dc doescontain] => :does_contain desc "does_follow USER [USER]", "Find out whether one user follows another." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." def does_follow(user1, user2 = nil) abort "No, you are not following yourself." if user2.nil? && @rcfile.active_profile[0].casecmp(user1).zero? abort "No, @#{user1} is not following themself." if user1 == user2 require "t/core_ext/string" thread1 = if options["id"] Thread.new { client.user(user1.to_i).screen_name } else Thread.new { user1.strip_ats } end thread2 = if user2.nil? Thread.new { @rcfile.active_profile[0] } elsif options["id"] Thread.new { client.user(user2.to_i).screen_name } else Thread.new { user2.strip_ats } end user1 = thread1.value user2 = thread2.value if client.friendship?(user1, user2) say "Yes, @#{user1} follows @#{user2}." else abort "No, @#{user1} does not follow @#{user2}." end end map %w[df doesfollow] => :does_follow desc "favorite TWEET_ID [TWEET_ID...]", "Marks Tweets as favorites." def favorite(status_id, *status_ids) status_ids.unshift(status_id) status_ids.collect!(&:to_i) require "retryable" favorites = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do client.favorite(status_ids) end number = favorites.length say "@#{@rcfile.active_profile[0]} favorited #{pluralize(number, 'tweet')}." say say "Run `#{File.basename($PROGRAM_NAME)} delete favorite #{status_ids.join(' ')}` to unfavorite." end map %w[fave favourite] => :favorite desc "favorites [USER]", "Returns the #{DEFAULT_NUM_RESULTS} most recent Tweets you favorited." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "max_id", aliases: "-m", type: :numeric, desc: "Returns only the results with an ID less than the specified ID." method_option "number", aliases: "-n", type: :numeric, default: DEFAULT_NUM_RESULTS, desc: "Limit the number of results." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." method_option "since_id", aliases: "-s", type: :numeric, desc: "Returns only the results with an ID greater than the specified ID." def favorites(user = nil) count = options["number"] || DEFAULT_NUM_RESULTS opts = {} opts[:exclude_replies] = true if options["exclude"] == "replies" opts[:include_entities] = !!options["decode_uris"] opts[:include_rts] = false if options["exclude"] == "retweets" opts[:max_id] = options["max_id"] if options["max_id"] opts[:since_id] = options["since_id"] if options["since_id"] if user require "t/core_ext/string" user = options["id"] ? user.to_i : user.strip_ats end tweets = collect_with_count(count) do |count_opts| client.favorites(user, count_opts.merge(opts)) end print_tweets(tweets) end map %w[faves favourites] => :favorites desc "follow USER [USER...]", "Allows you to start following users." method_option "id", aliases: "-i", type: :boolean, desc: "Specify input as Twitter user IDs instead of screen names." def follow(user, *users) followed_users, number = fetch_users(users.unshift(user), options) do |users_to_follow| client.follow(users_to_follow) end say "@#{@rcfile.active_profile[0]} is now following #{pluralize(number, 'more user')}." say say "Run `#{File.basename($PROGRAM_NAME)} unfollow #{followed_users.collect { |followed_user| "@#{followed_user.screen_name}" }.join(' ')}` to stop." end desc "followings [USER]", "Returns a list of the people you follow on Twitter." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." method_option "sort", aliases: "-s", type: :string, enum: %w[favorites followers friends listed screen_name since tweets tweeted], default: "screen_name", desc: "Specify the order of the results.", banner: "ORDER" method_option "unsorted", aliases: "-u", type: :boolean, desc: "Output is not sorted." def followings(user = nil) if user require "t/core_ext/string" user = options["id"] ? user.to_i : user.strip_ats end following_ids = client.friend_ids(user).to_a require "retryable" users = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do client.users(following_ids) end print_users(users) end desc "followings_following USER [USER]", "Displays your friends who follow the specified user." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "id", aliases: "-i", type: :boolean, desc: "Specify input as Twitter user IDs instead of screen names." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." method_option "sort", aliases: "-s", type: :string, enum: %w[favorites followers friends listed screen_name since tweets tweeted], default: "screen_name", desc: "Specify the order of the results.", banner: "ORDER" method_option "unsorted", aliases: "-u", type: :boolean, desc: "Output is not sorted." def followings_following(user1, user2 = nil) require "t/core_ext/string" user1 = options["id"] ? user1.to_i : user1.strip_ats user2 = if user2.nil? @rcfile.active_profile[0] else options["id"] ? user2.to_i : user2.strip_ats end follower_ids = Thread.new { client.follower_ids(user1).to_a } following_ids = Thread.new { client.friend_ids(user2).to_a } followings_following_ids = follower_ids.value & following_ids.value require "retryable" users = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do client.users(followings_following_ids) end print_users(users) end map %w[ff followingsfollowing] => :followings_following desc "followers [USER]", "Returns a list of the people who follow you on Twitter." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." method_option "sort", aliases: "-s", type: :string, enum: %w[favorites followers friends listed screen_name since tweets tweeted], default: "screen_name", desc: "Specify the order of the results.", banner: "ORDER" method_option "unsorted", aliases: "-u", type: :boolean, desc: "Output is not sorted." def followers(user = nil) if user require "t/core_ext/string" user = options["id"] ? user.to_i : user.strip_ats end follower_ids = client.follower_ids(user).to_a require "retryable" users = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do client.users(follower_ids) end print_users(users) end desc "friends [USER]", "Returns the list of people who you follow and follow you back." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." method_option "sort", aliases: "-s", type: :string, enum: %w[favorites followers friends listed screen_name since tweets tweeted], default: "screen_name", desc: "Specify the order of the results.", banner: "ORDER" method_option "unsorted", aliases: "-u", type: :boolean, desc: "Output is not sorted." def friends(user = nil) user = if user require "t/core_ext/string" options["id"] ? user.to_i : user.strip_ats else client.verify_credentials.screen_name end following_ids = Thread.new { client.friend_ids(user).to_a } follower_ids = Thread.new { client.follower_ids(user).to_a } friend_ids = following_ids.value & follower_ids.value require "retryable" users = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do client.users(friend_ids) end print_users(users) end desc "groupies [USER]", "Returns the list of people who follow you but you don't follow back." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." method_option "sort", aliases: "-s", type: :string, enum: %w[favorites followers friends listed screen_name since tweets tweeted], default: "screen_name", desc: "Specify the order of the results.", banner: "ORDER" method_option "unsorted", aliases: "-u", type: :boolean, desc: "Output is not sorted." def groupies(user = nil) user = if user require "t/core_ext/string" options["id"] ? user.to_i : user.strip_ats else client.verify_credentials.screen_name end follower_ids = Thread.new { client.follower_ids(user).to_a } following_ids = Thread.new { client.friend_ids(user).to_a } groupie_ids = (follower_ids.value - following_ids.value) require "retryable" users = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do client.users(groupie_ids) end print_users(users) end map %w[disciples] => :groupies desc "intersection USER [USER...]", "Displays the intersection of users followed by the specified users." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "id", aliases: "-i", type: :boolean, desc: "Specify input as Twitter user IDs instead of screen names." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." method_option "sort", aliases: "-s", type: :string, enum: %w[favorites followers friends listed screen_name since tweets tweeted], default: "screen_name", desc: "Specify the order of the results.", banner: "ORDER" method_option "type", aliases: "-t", type: :string, enum: %w[followers followings], default: "followings", desc: "Specify the type of intersection." method_option "unsorted", aliases: "-u", type: :boolean, desc: "Output is not sorted." def intersection(first_user, *users) users.push(first_user) # If only one user is specified, compare to the authenticated user users.push(@rcfile.active_profile[0]) if users.size == 1 require "t/core_ext/string" options["id"] ? users.collect!(&:to_i) : users.collect!(&:strip_ats) sets = parallel_map(users) do |user| case options["type"] when "followings" client.friend_ids(user).to_a when "followers" client.follower_ids(user).to_a end end intersection = sets.reduce(:&) require "retryable" users = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do client.users(intersection) end print_users(users) end map %w[overlap] => :intersection desc "leaders [USER]", "Returns the list of people who you follow but don't follow you back." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." method_option "sort", aliases: "-s", type: :string, enum: %w[favorites followers friends listed screen_name since tweets tweeted], default: "screen_name", desc: "Specify the order of the results.", banner: "ORDER" method_option "unsorted", aliases: "-u", type: :boolean, desc: "Output is not sorted." def leaders(user = nil) user = if user require "t/core_ext/string" options["id"] ? user.to_i : user.strip_ats else client.verify_credentials.screen_name end following_ids = Thread.new { client.friend_ids(user).to_a } follower_ids = Thread.new { client.follower_ids(user).to_a } leader_ids = (following_ids.value - follower_ids.value) require "retryable" users = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do client.users(leader_ids) end print_users(users) end desc "lists [USER]", "Returns the lists created by a user." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." method_option "sort", aliases: "-s", type: :string, enum: %w[members mode since slug subscribers], default: "slug", desc: "Specify the order of the results.", banner: "ORDER" method_option "unsorted", aliases: "-u", type: :boolean, desc: "Output is not sorted." def lists(user = nil) lists = if user require "t/core_ext/string" user = options["id"] ? user.to_i : user.strip_ats client.lists(user) else client.lists end print_lists(lists) end desc "matrix", "Unfortunately, no one can be told what the Matrix is. You have to see it for yourself." def matrix opts = {count: MAX_SEARCH_RESULTS, include_entities: false} tweets = client.search("lang:ja", opts) tweets.each do |tweet| say(tweet.text.gsub(/[^\u3000\u3040-\u309f]/, "").reverse, %i[bold green on_black], false) end end desc "mentions", "Returns the #{DEFAULT_NUM_RESULTS} most recent Tweets mentioning you." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "number", aliases: "-n", type: :numeric, default: DEFAULT_NUM_RESULTS, desc: "Limit the number of results." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." def mentions count = options["number"] || DEFAULT_NUM_RESULTS opts = {} opts[:include_entities] = !!options["decode_uris"] tweets = collect_with_count(count) do |count_opts| client.mentions(count_opts.merge(opts)) end print_tweets(tweets) end map %w[replies] => :mentions desc "mute USER [USER...]", "Mute users." method_option "id", aliases: "-i", type: :boolean, desc: "Specify input as Twitter user IDs instead of screen names." def mute(user, *users) muted_users, number = fetch_users(users.unshift(user), options) do |users_to_mute| client.mute(users_to_mute) end say "@#{@rcfile.active_profile[0]} muted #{pluralize(number, 'user')}." say say "Run `#{File.basename($PROGRAM_NAME)} delete mute #{muted_users.collect { |muted_user| "@#{muted_user.screen_name}" }.join(' ')}` to unmute." end desc "muted [USER]", "Returns a list of the people you have muted on Twitter." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." method_option "sort", aliases: "-s", type: :string, enum: %w[favorites followers friends listed screen_name since tweets tweeted], default: "screen_name", desc: "Specify the order of the results.", banner: "ORDER" method_option "unsorted", aliases: "-u", type: :boolean, desc: "Output is not sorted." def muted muted_ids = client.muted_ids.to_a require "retryable" muted_users = Retryable.retryable(tries: 3, on: Twitter::Error, sleep: 0) do client.users(muted_ids) end print_users(muted_users) end map %w[mutes] => :muted desc "open USER", "Opens that user's profile in a web browser." method_option "display-uri", aliases: "-d", type: :boolean, desc: "Display the requested URL instead of attempting to open it." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "status", aliases: "-s", type: :boolean, desc: "Specify input as a Twitter status ID instead of a screen name." def open(user) require "launchy" if options["id"] user = client.user(user.to_i) open_or_print(user.uri, dry_run: options["display-uri"]) elsif options["status"] status = client.status(user.to_i, include_my_retweet: false) open_or_print(status.uri, dry_run: options["display-uri"]) else require "t/core_ext/string" open_or_print("https://twitter.com/#{user.strip_ats}", dry_run: options["display-uri"]) end end desc "reach TWEET_ID", "Shows the maximum number of people who may have seen the specified tweet in their timeline." def reach(tweet_id) require "t/core_ext/string" status_thread = Thread.new { client.status(tweet_id.to_i, include_my_retweet: false) } threads = client.retweeters_ids(tweet_id.to_i).collect do |retweeter_id| Thread.new(retweeter_id) do |user_id| client.follower_ids(user_id).to_a end end status = status_thread.value threads << Thread.new(status.user.id) do |user_id| client.follower_ids(user_id).to_a end reach = ::Set.new threads.each { |thread| reach += thread.value } reach.delete(status.user.id) say number_with_delimiter(reach.size) end desc "reply TWEET_ID [MESSAGE]", "Post your Tweet as a reply directed at another person." method_option "all", aliases: "-a", type: :boolean, desc: "Reply to all users mentioned in the Tweet." method_option "location", aliases: "-l", type: :string, default: nil, desc: "Add location information. If the optional 'latitude,longitude' parameter is not supplied, looks up location by IP address." method_option "file", aliases: "-f", type: :string, desc: "The path to an image to attach to your tweet." def reply(status_id, message = nil) message = T::Editor.gets if message.to_s.empty? status = client.status(status_id.to_i, include_my_retweet: false) users = Array(status.user.screen_name) if options["all"] users += extract_mentioned_screen_names(status.full_text) users.uniq! end users.delete(@rcfile.active_profile[0]) require "t/core_ext/string" users.collect!(&:prepend_at) opts = {in_reply_to_status_id: status.id, trim_user: true} add_location!(options, opts) reply = if options["file"] client.update_with_media("#{users.join(' ')} #{message}", File.new(File.expand_path(options["file"])), opts) else client.update("#{users.join(' ')} #{message}", opts) end say "Reply posted by @#{@rcfile.active_profile[0]} to #{users.join(' ')}." say
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
true
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/editor.rb
lib/t/editor.rb
require "tempfile" require "shellwords" module T class Editor class << self def gets file = tempfile edit(file.path) File.read(file).strip ensure file.close file.unlink end def tempfile Tempfile.new("TWEET_EDITMSG") end def edit(path) system(Shellwords.join([editor, path])) end def editor ENV["VISUAL"] || ENV["EDITOR"] || system_editor end def system_editor /mswin|mingw/.match?(RbConfig::CONFIG["host_os"]) ? "notepad" : "vi" end end end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/list.rb
lib/t/list.rb
require "thor" require "twitter" require "t/collectable" require "t/printable" require "t/rcfile" require "t/requestable" require "t/utils" module T class List < Thor include T::Collectable include T::Printable include T::Requestable include T::Utils DEFAULT_NUM_RESULTS = 20 check_unknown_options! def initialize(*) @rcfile = T::RCFile.instance super end desc "add LIST USER [USER...]", "Add members to a list." method_option "id", aliases: "-i", type: :boolean, desc: "Specify input as Twitter user IDs instead of screen names." def add(list_name, user, *users) added_users, number = fetch_users(users.unshift(user), options) do |users_to_add| client.add_list_members(list_name, users_to_add) users_to_add end say "@#{@rcfile.active_profile[0]} added #{pluralize(number, 'member')} to the list \"#{list_name}\"." say if options["id"] say "Run `#{File.basename($PROGRAM_NAME)} list remove --id #{list_name} #{added_users.join(' ')}` to undo." else say "Run `#{File.basename($PROGRAM_NAME)} list remove #{list_name} #{added_users.collect { |added_user| "@#{added_user}" }.join(' ')}` to undo." end end desc "create LIST [DESCRIPTION]", "Create a new list." method_option "private", aliases: "-p", type: :boolean def create(list_name, description = nil) opts = description ? {description:} : {} opts[:mode] = "private" if options["private"] client.create_list(list_name, opts) say "@#{@rcfile.active_profile[0]} created the list \"#{list_name}\"." end desc "information [USER/]LIST", "Retrieves detailed information about a Twitter list." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." def information(user_list) owner, list_name = extract_owner(user_list, options) list = client.list(owner, list_name) if options["csv"] require "csv" say ["ID", "Description", "Slug", "Screen name", "Created at", "Members", "Subscribers", "Following", "Mode", "URL"].to_csv say [list.id, list.description, list.slug, list.user.screen_name, csv_formatted_time(list), list.member_count, list.subscriber_count, list.following?, list.mode, list.uri].to_csv else array = [] array << ["ID", list.id.to_s] array << ["Description", list.description] unless list.description.nil? array << ["Slug", list.slug] array << ["Screen name", "@#{list.user.screen_name}"] array << ["Created at", "#{ls_formatted_time(list, :created_at, false)} (#{time_ago_in_words(list.created_at)} ago)"] array << ["Members", number_with_delimiter(list.member_count)] array << ["Subscribers", number_with_delimiter(list.subscriber_count)] array << ["Status", list.following? ? "Following" : "Not following"] array << ["Mode", list.mode] array << ["URL", list.uri] print_table(array) end end map %w[details] => :information desc "members [USER/]LIST", "Returns the members of a Twitter list." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." method_option "sort", aliases: "-s", type: :string, enum: %w[favorites followers friends listed screen_name since tweets tweeted], default: "screen_name", desc: "Specify the order of the results.", banner: "ORDER" method_option "unsorted", aliases: "-u", type: :boolean, desc: "Output is not sorted." def members(user_list) owner, list_name = extract_owner(user_list, options) users = client.list_members(owner, list_name).to_a print_users(users) end desc "remove LIST USER [USER...]", "Remove members from a list." method_option "id", aliases: "-i", type: :boolean, desc: "Specify input as Twitter user IDs instead of screen names." def remove(list_name, user, *users) removed_users, number = fetch_users(users.unshift(user), options) do |users_to_remove| client.remove_list_members(list_name, users_to_remove) users_to_remove end say "@#{@rcfile.active_profile[0]} removed #{pluralize(number, 'member')} from the list \"#{list_name}\"." say if options["id"] say "Run `#{File.basename($PROGRAM_NAME)} list add --id #{list_name} #{removed_users.join(' ')}` to undo." else say "Run `#{File.basename($PROGRAM_NAME)} list add #{list_name} #{removed_users.collect { |removed_user| "@#{removed_user}" }.join(' ')}` to undo." end end desc "timeline [USER/]LIST", "Show tweet timeline for members of the specified list." method_option "csv", aliases: "-c", type: :boolean, desc: "Output in CSV format." method_option "decode_uris", aliases: "-d", type: :boolean, desc: "Decodes t.co URLs into their original form." method_option "id", aliases: "-i", type: :boolean, desc: "Specify user via ID instead of screen name." method_option "long", aliases: "-l", type: :boolean, desc: "Output in long format." method_option "number", aliases: "-n", type: :numeric, default: DEFAULT_NUM_RESULTS, desc: "Limit the number of results." method_option "relative_dates", aliases: "-a", type: :boolean, desc: "Show relative dates." method_option "reverse", aliases: "-r", type: :boolean, desc: "Reverse the order of the sort." def timeline(user_list) owner, list_name = extract_owner(user_list, options) count = options["number"] || DEFAULT_NUM_RESULTS opts = {} opts[:include_entities] = !!options["decode_uris"] tweets = collect_with_count(count) do |count_opts| client.list_timeline(owner, list_name, count_opts.merge(opts)) end print_tweets(tweets) end map %w[tl] => :timeline end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/core_ext/kernel.rb
lib/t/core_ext/kernel.rb
module Kernel def Bignum(arg, base = 0) # rubocop:disable Naming/MethodName Integer(arg, base) end def Fixnum(arg, base = 0) # rubocop:disable Naming/MethodName Integer(arg, base) end def NilClass(_) # rubocop:disable Naming/MethodName nil end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
sferik/t-ruby
https://github.com/sferik/t-ruby/blob/d2037676c60c96523db626b681f1b651777a98e7/lib/t/core_ext/string.rb
lib/t/core_ext/string.rb
class String def prepend_at "@#{self}" end def strip_ats tr("@", "") end alias old_to_i to_i def to_i(base = 10) tr(",", "").old_to_i(base) end end
ruby
MIT
d2037676c60c96523db626b681f1b651777a98e7
2026-01-04T15:43:07.089276Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/smart/test_smart_text.rb
test/smart/test_smart_text.rb
require 'helper' require 'slim/smart' class TestSlimSmartText < TestSlim def test_explicit_smart_text_recognition source = %q{ > a > b > c > d > e f > g h i } result = %q{a b c d e <f></f> g h <i></i>} assert_html result, source end def test_implicit_smart_text_recognition source = %q{ p A p B p C p D p E F p G H I } result = %q{<p>A</p><p>B</p><p>C</p><p>D</p><p>E</p> F <p>G H</p> I} assert_html result, source end def test_multi_line_smart_text source = %q{ p First line. Second line. Third line with a continuation and one more. Fourth line. } result = %q{<p>First line. Second line. Third line with a continuation and one more. Fourth line.</p>} assert_html result, source end def test_smart_text_escaping source = %q{ | Not escaped <&>. p Escaped <&>. p Escaped <&>. > Escaped <&>. Protected &amp; &lt; &gt; &copy; &Aacute;. Protected &#0129; &#x00ff;. Escaped &#xx; &#1f; &9; &_; &;. } result = %q{Not escaped <&>.<p>Escaped &lt;&amp;&gt;.</p><p>Escaped &lt;&amp;&gt;. Escaped &lt;&amp;&gt;. Protected &amp; &lt; &gt; &copy; &Aacute;. Protected &#0129; &#x00ff;. Escaped &amp;#xx; &amp;#1f; &amp;9; &amp;_; &amp;;.</p>} assert_html result, source end def test_smart_text_disabled_escaping Slim::Engine.with_options( smart_text_escaping: false ) do source = %q{ p Not escaped <&>. | Not escaped <&>. p Not escaped <&>. > Not escaped <&>. Not escaped &amp; &lt; &gt; &copy; &Aacute;. Not escaped &#0129; &#x00ff;. Not escaped &#xx; &#1f; &9; &_; &;. } result = %q{<p>Not escaped <&>.</p>Not escaped <&>.<p>Not escaped <&>. Not escaped <&>. Not escaped &amp; &lt; &gt; &copy; &Aacute;. Not escaped &#0129; &#x00ff;. Not escaped &#xx; &#1f; &9; &_; &;.</p>} assert_html result, source end end def test_smart_text_in_tag_escaping source = %q{ p Escaped <&>. Protected &amp; &lt; &gt; &copy; &Aacute;. Protected &#0129; &#x00ff;. Escaped &#xx; &#1f; &9; &_; &;. } result = %q{<p>Escaped &lt;&amp;&gt;. Protected &amp; &lt; &gt; &copy; &Aacute;. Protected &#0129; &#x00ff;. Escaped &amp;#xx; &amp;#1f; &amp;9; &amp;_; &amp;;.</p>} assert_html result, source end def test_smart_text_mixed_with_tags source = %q{ p Text br >is strong really > recognized. More b text . And i more ... span Really ?!? .bold Really !!! #id #{'Good'} ! } result = %q{<p>Text <br /> is <strong>really</strong> recognized. More <b>text</b>. And <i>more</i>... <span>Really</span>?!? <div class="bold">Really</div>!!! <div id="id">Good</div>!</p>} assert_html result, source end def test_smart_text_mixed_with_links source = %q{ p Text with a href="#1" link . Text with a href="#2" another link > to somewhere else. a href="#3" This link > goes elsewhere. See ( a href="#4" link )? } result = %q{<p>Text with <a href="#1">link</a>. Text with <a href="#2">another link</a> to somewhere else. <a href="#3">This link</a> goes elsewhere. See (<a href="#4">link</a>)?</p>} assert_html result, source end def test_smart_text_mixed_with_code source = %q{ p Try a list ul - 2.times do |i| li Item: #{i} > which stops b here . Right? } result = %q{<p>Try a list <ul><li>Item: 0</li><li>Item: 1</li></ul> which stops <b>here</b>. Right?</p>} assert_html result, source end # Without unicode support, we can't distinguish uppercase and lowercase # unicode characters reliably. So we only test the basic text, not tag names. def test_basic_unicode_smart_text source = %q{ p 是 čip Čip Žůžo šíp } result = %q{<p>是 čip Čip Žůžo šíp</p>} assert_html result, source end def test_unicode_smart_text source = %q{ p 是 čip Čip Žůžo šíp .řek . } result = %q{<p>是 čip Čip Žůžo šíp <div class="řek">.</div></p>} assert_html result, source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/literate/helper.rb
test/literate/helper.rb
require 'slim' require 'slim/logic_less' require 'slim/translator' require 'slim/grammar' require 'minitest/autorun' Slim::Engine.after Slim::Parser, Temple::Filters::Validator, grammar: Slim::Grammar Slim::Engine.before :Pretty, Temple::Filters::Validator Slim::Engine.set_options tr: false, logic_less: false class Minitest::Spec def render(source, options = {}, &block) Slim::Template.new(options) { source }.render(self, &block) end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/literate/run.rb
test/literate/run.rb
require 'temple' class LiterateTest < Temple::Engine class Parser < Temple::Parser def call(lines) stack = [[:multi]] until lines.empty? case lines.shift when /\A(#+)\s*(.*)\Z/ stack.pop(stack.size - $1.size) block = [:multi] stack.last << [:section, $2, block] stack << block when /\A~{3,}\s*(\w+)\s*\Z/ lang = $1 code = [] until lines.empty? case lines.shift when /\A~{3,}\s*\Z/ break when /\A.*\Z/ code << $& end end stack.last << [lang.to_sym, code.join("\n")] when /\A\s*\Z/ when /\A\s*(.*?)\s*Z/ stack.last << [:comment, $1] end end stack.first end end class Compiler < Temple::Filter def call(exp) @opts, @in_testcase = {}, false "require 'helper'\n\n#{compile(exp)}" end def on_section(title, body) old_opts = @opts.dup raise Temple::FilterError, 'New section between slim and html block' if @in_testcase "describe #{title.inspect} do\n #{compile(body).gsub("\n", "\n ")}\nend\n" ensure @opts = old_opts end def on_multi(*exps) exps.map {|exp| compile(exp) }.join("\n") end def on_comment(text) "#{@in_testcase ? ' ' : ''}# #{text}" end def on_slim(code) raise Temple::FilterError, 'Slim block must be followed by html block' if @in_testcase @in_testcase = true "it 'should render' do\n slim = #{code.inspect}" end def on_html(code) raise Temple::FilterError, 'Html block must be preceded by slim block' unless @in_testcase @in_testcase = false result = " html = #{code.inspect}\n".dup if @opts.empty? result << " _(render(slim)).must_equal html\nend\n" else result << " options = #{@opts.inspect}\n _(render(slim, options)).must_equal html\nend\n" end end def on_options(code) raise Temple::FilterError, 'Options set inside test case' if @in_testcase @opts.update(eval("{#{code}}")) "# #{code.gsub("\n", "\n# ")}" end def on(*exp) raise Temple::InvalidExpression, exp end end use Parser use Compiler use(:Evaluator) {|code| eval(code) } end Dir.glob(File.join(File.dirname(__FILE__), '*.md')) do |file| LiterateTest.new.call(File.readlines(file)) end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/translator/test_translator.rb
test/translator/test_translator.rb
require 'helper' require 'slim/translator' class TestSlimTranslator < TestSlim def setup super Slim::Engine.set_options tr: true, tr_fn: 'TestSlimTranslator.tr' end def self.tr(s) s.upcase end def self.tr_reverse(s) s.reverse.gsub(/(\d+)%/, '%\1') end def test_no_translation_of_embedded source = %q{ markdown: #Header Hello from #{"Markdown!"} #{1+2} * one * two } case Tilt['md'].name.downcase when /redcarpet/ assert_html "<h1>Header</h1>\n\n<p>Hello from Markdown!</p>\n\n<p>3</p>\n\n<ul>\n<li>one</li>\n<li>two</li>\n</ul>\n", source, tr_mode: :dynamic assert_html "<h1>Header</h1>\n\n<p>Hello from Markdown!</p>\n\n<p>3</p>\n\n<ul>\n<li>one</li>\n<li>two</li>\n</ul>\n", source, tr_mode: :static when /rdiscount/ assert_html "<h1>Header</h1>\n\n<p>Hello from Markdown!</p>\n\n<p>3</p>\n\n<ul>\n<li>one</li>\n<li>two</li>\n</ul>\n\n", source, tr_mode: :dynamic assert_html "<h1>Header</h1>\n\n<p>Hello from Markdown!</p>\n\n<p>3</p>\n\n<ul>\n<li>one</li>\n<li>two</li>\n</ul>\n\n", source, tr_mode: :static when /kramdown/ assert_html "<h1 id=\"header\">Header</h1>\n<p>Hello from Markdown!</p>\n\n<p>3</p>\n\n<ul>\n <li>one</li>\n <li>two</li>\n</ul>\n", source, tr_mode: :dynamic assert_html "<h1 id=\"header\">Header</h1>\n<p>Hello from Markdown!</p>\n\n<p>3</p>\n\n<ul>\n <li>one</li>\n <li>two</li>\n</ul>\n", source, tr_mode: :static else raise "Missing test for #{Tilt['md']}" end end def test_no_translation_of_attrs source = %q{ ' this is a link to a href="link" page } assert_html "THIS IS\nA LINK TO <a href=\"link\">PAGE</a>", source, tr_mode: :dynamic assert_html "THIS IS\nA LINK TO <a href=\"link\">PAGE</a>", source, tr_mode: :static end def test_translation_and_interpolation source = %q{ p translate #{hello_world} this second line third #{1+2} line } assert_html "<p>translate Hello World from @env this\nsecond line\nthird 3 line</p>", source, tr: false assert_html "<p>TRANSLATE Hello World from @env THIS\nSECOND LINE\nTHIRD 3 LINE</p>", source, tr_mode: :dynamic assert_html "<p>TRANSLATE Hello World from @env THIS\nSECOND LINE\nTHIRD 3 LINE</p>", source, tr_mode: :static end def test_translation_reverse source = %q{ ' alpha #{1} beta #{2} gamma #{3} } assert_html "3 ammag 2 ateb 1 ahpla ", source, tr_mode: :dynamic, tr_fn: 'TestSlimTranslator.tr_reverse' assert_html "3 ammag 2 ateb 1 ahpla ", source, tr_mode: :static, tr_fn: 'TestSlimTranslator.tr_reverse' end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/app/helpers/application_helper.rb
test/rails/app/helpers/application_helper.rb
module ApplicationHelper def headline(&block) "<h1>#{capture(&block)}</h1>".html_safe end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/app/controllers/slim_controller.rb
test/rails/app/controllers/slim_controller.rb
class SlimController < ApplicationController def normal end def xml end def no_layout render layout: false end def variables @hello = "Hello Slim with variables!" end def partial end def streaming @hello = "Hello Streaming!" render :content_for, stream: true end def integers @integer = 1337 end def thread_options default_shortcut = {'#' => {attr: 'id'}, '.' => {attr: 'class'} } Slim::Engine.with_options(shortcut: default_shortcut.merge({'@' => { attr: params[:attr] }})) do render end end def variant request.variant = :testvariant render :normal end def content_for @hello = "Hello Slim!" end def helper end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/app/controllers/entries_controller.rb
test/rails/app/controllers/entries_controller.rb
class EntriesController < ApplicationController def edit @entry = Entry.new end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/app/controllers/application_controller.rb
test/rails/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/app/models/entry.rb
test/rails/app/models/entry.rb
class Entry include ActiveModel::Conversion extend ActiveModel::Naming attr_accessor :name def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) end end def persisted? false end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/test/test_slim.rb
test/rails/test/test_slim.rb
require File.expand_path('../helper', __FILE__) class TestSlim < ActionDispatch::IntegrationTest test "normal view" do get "/slim/normal" assert_response :success assert_template "slim/normal" assert_template "layouts/application" assert_html "<h1>Hello Slim!</h1>" end test "variant" do get "/slim/variant" assert_response :success assert_template "slim/normal" assert_template "layouts/application" assert_equal @response.body, "<!DOCTYPE html><html><head><title>Variant</title></head><body><div class=\"content\"><h1>Hello Slim!</h1></div></body></html>" end test "xml view" do get "/slim/xml" assert_response :success assert_template "slim/xml" assert_template "layouts/application" assert_html "<h1>Hello Slim!</h1>" end test "helper" do get "/slim/helper" assert_response :success assert_template "slim/helper" assert_template "layouts/application" assert_html "<p><h1>Hello User</h1></p>" end test "normal erb view" do get "/slim/erb" assert_html "<h1>Hello Erb!</h1>" end test "view without a layout" do get "/slim/no_layout" assert_template "slim/no_layout" assert_html "<h1>Hello Slim without a layout!</h1>", skip_layout: true end test "view with variables" do get "/slim/variables" assert_html "<h1>Hello Slim with variables!</h1>" end test "partial view" do get "/slim/partial" assert_html "<h1>Hello Slim!</h1><p>With a partial!</p>" end # TODO Reenable streaming test # test "streaming" do # get "/slim/streaming" # output = "2f\r\n<!DOCTYPE html><html><head><title>Dummy</title>\r\nd\r\n</head><body>\r\n17\r\nHeading set from a view\r\n15\r\n<div class=\"content\">\r\n53\r\n<p>Page content</p><h1><p>Hello Streaming!</p></h1><h2><p>Hello Streaming!</p></h2>\r\n14\r\n</div></body></html>\r\n0\r\n\r\n" # assert_equal output, @response.body # end test "render integers" do get "/slim/integers" assert_html "<p>1337</p>" end test "render thread_options" do get "/slim/thread_options", params: { attr: 'role'} assert_html '<p role="empty">Test</p>' get "/slim/thread_options", params: { attr: 'id'} # Overwriting doesn't work because of caching assert_html '<p role="empty">Test</p>' end test "content_for" do get "/slim/content_for" assert_html "<p>Page content</p><h1><p>Hello Slim!</p></h1><h2><p>Hello Slim!</p></h2>", heading: 'Heading set from a view' end test "form_for" do get "/entries/edit/1" assert_match %r{action="/entries"}, @response.body assert_match %r{<label><b>Name</b></label>}, @response.body assert_xpath '//input[@id="entry_name" and @name="entry[name]" and @type="text"]' end test "attributes" do get "/slim/attributes" assert_html "<div class=\"static a-b\"></div>" end test "splat" do get "/slim/splat" assert_html "<div id=\"splat\"><splat>Hello</splat></div>" end test "splat with delimiter" do get "/slim/splat_with_delimiter" assert_html "<div class=\"cute nice\">Hello</div>" end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/test/helper.rb
test/rails/test/helper.rb
# Configure Rails Envinronment ENV["RAILS_ENV"] = "test" require File.expand_path("../../config/environment.rb", __FILE__) require "rails/test_help" require "nokogiri" require 'rails-controller-testing' Rails::Controller::Testing.install Rails.backtrace_cleaner.remove_silencers! class ActionDispatch::IntegrationTest protected def assert_xpath(xpath, message="Unable to find '#{xpath}' in response body.") assert_response :success, "Response type is not :success (code 200..299)." body = @response.body assert !body.empty?, "No response body found." doc = Nokogiri::HTML(body) rescue nil assert_not_nil doc, "Cannot parse response body." assert doc.xpath(xpath).size >= 1, message end def assert_html(expected, options = {}) expected = "<!DOCTYPE html><html><head><title>Dummy</title></head><body>#{options[:heading]}<div class=\"content\">#{expected}</div></body></html>" unless options[:skip_layout] assert_equal expected, @response.body end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/config/application.rb
test/rails/config/application.rb
require File.expand_path('../boot', __FILE__) require 'logger' require 'active_model/railtie' require 'action_controller/railtie' require 'action_view/railtie' #require 'active_record/railtie' #require 'action_mailer/railtie' #require 'sprockets/railtie' require 'slim' 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. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # 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 # JavaScript files you want as :defaults (application.js is always included). # config.action_view.javascript_expansions[:defaults] = %w(jquery rails) # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/config/environment.rb
test/rails/config/environment.rb
# Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Dummy::Application.initialize!
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/config/routes.rb
test/rails/config/routes.rb
Dummy::Application.routes.draw do # The priority is based upon order of creation: # first created -> highest priority. resources :entries # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', as: :purchase # This route can be invoked with purchase_url(id: product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products # Sample resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # You can have the root of your site routed with "root" # just remember to delete public/index.html. # root to: "welcome#index" # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. get ':controller(/:action(/:id(.:format)))' end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/config/boot.rb
test/rails/config/boot.rb
require 'rubygems' gemfile = File.expand_path('../../../../../../Gemfile', __FILE__) if File.exist?(gemfile) ENV['BUNDLE_GEMFILE'] = gemfile require 'bundler' Bundler.setup(:default, :integration) end $:.unshift File.expand_path('../../../../../../lib', __FILE__)
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/config/initializers/session_store.rb
test/rails/config/initializers/session_store.rb
# Be sure to restart your server when you modify this file. Dummy::Application.config.session_store :cookie_store, key: '_dummy_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails generate session_migration") # Dummy::Application.config.session_store :active_record_store
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/config/initializers/inflections.rb
test/rails/config/initializers/inflections.rb
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # ActiveSupport::Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/config/initializers/backtrace_silencers.rb
test/rails/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
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/config/initializers/mime_types.rb
test/rails/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 # Mime::Type.register_alias "text/html", :iphone
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/rails/config/environments/test.rb
test/rails/config/environments/test.rb
Dummy::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 # 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 # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Print deprecation notices to the stderr config.active_support.deprecation = :stderr config.eager_load = false end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/sinatra/test_core.rb
test/sinatra/test_core.rb
require_relative 'helper.rb' begin class SlimTest < Minitest::Test it 'renders inline slim strings' do slim_app { slim "h1 Hiya\n" } assert ok? assert_equal "<h1>Hiya</h1>", body end it 'renders .slim files in views path' do slim_app { slim :hello } assert ok? assert_equal "<h1>Hello From Slim</h1>", body end it "renders with inline layouts" do mock_app do layout { %(h1\n | THIS. IS. \n == yield.upcase ) } get('/') { slim 'em Sparta' } end get '/' assert ok? assert_equal "<h1>THIS. IS. <EM>SPARTA</EM></h1>", body end it "renders with file layouts" do slim_app { slim('| Hello World', :layout => :layout2) } assert ok? assert_equal "<h1>Slim Layout!</h1><p>Hello World</p>", body end it "raises error if template not found" do mock_app { get('/') { slim(:no_such_template) } } assert_raises(Errno::ENOENT) { get('/') } end HTML4_DOCTYPE = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" it "passes slim options to the slim engine" do mock_app { get('/') { slim("x foo='bar'", :attr_quote => "'") }} get '/' assert ok? assert_body "<x foo='bar'></x>" end it "passes default slim options to the slim engine" do mock_app do set :slim, :attr_quote => "'" get('/') { slim("x foo='bar'") } end get '/' assert ok? assert_body "<x foo='bar'></x>" end it "merges the default slim options with the overrides and passes them to the slim engine" do mock_app do set :slim, :attr_quote => "'" get('/') { slim("x foo='bar'") } get('/other') { slim("x foo='bar'", :attr_quote => '"') } end get '/' assert ok? assert_body "<x foo='bar'></x>" get '/other' assert ok? assert_body '<x foo="bar"></x>' end it "can render truly nested layouts by accepting a layout and a block with the contents" do mock_app do template(:main_outer_layout) { "h1 Title\n== yield" } template(:an_inner_layout) { "h2 Subtitle\n== yield" } template(:a_page) { "p Contents." } get('/') do slim :main_outer_layout, :layout => false do slim :an_inner_layout do slim :a_page end end end end get '/' assert ok? assert_body "<h1>Title</h1>\n<h2>Subtitle</h2>\n<p>Contents.</p>\n" end end rescue LoadError warn "#{$!}: skipping slim tests" end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/sinatra/contest.rb
test/sinatra/contest.rb
# Copyright (c) 2009 Damian Janowski and Michel Martens for Citrusbyte # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require "rubygems" require "minitest/autorun" # Contest adds +teardown+, +test+ and +context+ as class methods, and the # instance methods +setup+ and +teardown+ now iterate on the corresponding # blocks. Note that all setup and teardown blocks must be defined with the # block syntax. Adding setup or teardown instance methods defeats the purpose # of this library. class Minitest::Test def self.setup(&block) setup_blocks << block end def self.teardown(&block) teardown_blocks << block end def self.setup_blocks() @setup_blocks ||= [] end def self.teardown_blocks() @teardown_blocks ||= [] end def setup_blocks(base = self.class) setup_blocks base.superclass if base.superclass.respond_to? :setup_blocks base.setup_blocks.each do |block| instance_eval(&block) end end def teardown_blocks(base = self.class) teardown_blocks base.superclass if base.superclass.respond_to? :teardown_blocks base.teardown_blocks.each do |block| instance_eval(&block) end end alias setup setup_blocks alias teardown teardown_blocks def self.context(*name, &block) subclass = Class.new(self) remove_tests(subclass) subclass.class_eval(&block) if block_given? const_set(context_name(name.join(" ")), subclass) end def self.test(name, &block) define_method(test_name(name), &block) end class << self alias_method :should, :test alias_method :describe, :context end private def self.context_name(name) # "Test#{sanitize_name(name).gsub(/(^| )(\w)/) { $2.upcase }}".to_sym name = "Test#{sanitize_name(name).gsub(/(^| )(\w)/) { $2.upcase }}" name.tr(" ", "_").to_sym end def self.test_name(name) name = "test_#{sanitize_name(name).gsub(/\s+/,'_')}_0" name = name.succ while method_defined? name name.to_sym end def self.sanitize_name(name) # name.gsub(/\W+/, ' ').strip name.gsub(/\W+/, ' ') end def self.remove_tests(subclass) subclass.public_instance_methods.grep(/^test_/).each do |meth| subclass.send(:undef_method, meth.to_sym) end end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/sinatra/helper.rb
test/sinatra/helper.rb
if ENV['COVERAGE'] require 'simplecov' SimpleCov.start do add_filter '/test/' add_group 'sinatra-contrib', 'sinatra-contrib' add_group 'rack-protection', 'rack-protection' end end ENV['APP_ENV'] = 'test' RUBY_ENGINE = 'ruby' unless defined? RUBY_ENGINE require 'rack' testdir = File.dirname(__FILE__) $LOAD_PATH.unshift testdir unless $LOAD_PATH.include?(testdir) libdir = File.dirname(File.dirname(__FILE__)) + '/lib' $LOAD_PATH.unshift libdir unless $LOAD_PATH.include?(libdir) require 'minitest' require 'contest' require 'rack/test' require 'sinatra' require 'sinatra/base' class Sinatra::Base include Minitest::Assertions # Allow assertions in request context def assertions @assertions ||= 0 end attr_writer :assertions end class Rack::Builder def include?(middleware) @ins.any? { |m| middleware === m } end end Sinatra::Base.set :environment, :test class Minitest::Test include Rack::Test::Methods class << self alias_method :it, :test alias_method :section, :context end def self.example(desc = nil, &block) @example_count = 0 unless instance_variable_defined? :@example_count @example_count += 1 it(desc || "Example #{@example_count}", &block) end alias_method :response, :last_response setup do Sinatra::Base.set :environment, :test end # Sets up a Sinatra::Base subclass defined with the block # given. Used in setup or individual spec methods to establish # the application. def mock_app(base=Sinatra::Base, &block) @app = Sinatra.new(base, &block) end def app Rack::Lint.new(@app) end def slim_app(&block) mock_app do set :views, File.dirname(__FILE__) + '/views' get('/', &block) end get '/' end def body response.body.to_s end def assert_body(value) if value.respond_to? :to_str assert_equal value.lstrip.gsub(/\s*\n\s*/, ""), body.lstrip.gsub(/\s*\n\s*/, "") else assert_match value, body end end def assert_status(expected) assert_equal Integer(expected), Integer(status) end def assert_like(a,b) pattern = /id=['"][^"']*["']|\s+/ assert_equal a.strip.gsub(pattern, ""), b.strip.gsub(pattern, "") end def assert_include(str, substr) assert str.include?(substr), "expected #{str.inspect} to include #{substr.inspect}" end def options(uri, params = {}, env = {}, &block) request(uri, env.merge(:method => "OPTIONS", :params => params), &block) end def patch(uri, params = {}, env = {}, &block) request(uri, env.merge(:method => "PATCH", :params => params), &block) end def link(uri, params = {}, env = {}, &block) request(uri, env.merge(:method => "LINK", :params => params), &block) end def unlink(uri, params = {}, env = {}, &block) request(uri, env.merge(:method => "UNLINK", :params => params), &block) end # Delegate other missing methods to response. def method_missing(name, *args, &block) if response && response.respond_to?(name) response.send(name, *args, &block) else super end rescue Rack::Test::Error super end # Do not output warnings for the duration of the block. def silence_warnings $VERBOSE, v = nil, $VERBOSE yield ensure $VERBOSE = v end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/sinatra/test_include.rb
test/sinatra/test_include.rb
require 'slim/include' require_relative 'helper.rb' begin class SlimTest < Minitest::Test it 'renders .slim files includes with js embed' do slim_app { slim :embed_include_js } assert ok? assert_equal "<!DOCTYPE html><html><head><title>Slim Examples</title><script>alert('Slim supports embedded javascript!')</script></head><body><footer>Slim</footer></body></html>", body end end rescue LoadError warn "#{$!}: skipping slim tests" end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/include/test_include.rb
test/include/test_include.rb
require 'helper' require 'slim/include' class TestSlimInclude < TestSlim def test_include source = %q{ br/ a: include slimfile b: include textfile c: include slimfile.slim d: include subdir/test } assert_html '<br /><a>slim1recslim2</a><b>1+2=3</b><c>slim1recslim2</c><d>subdir</d>', source, include_dirs: [File.expand_path('files', File.dirname(__FILE__))] end def test_include_with_newline source = %q{ a: include slimfile .content } assert_html '<a>slim1recslim2</a><div class="content"></div>', source, include_dirs: [File.expand_path('files', File.dirname(__FILE__))] end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_ruby_errors.rb
test/core/test_ruby_errors.rb
require 'helper' class TestSlimRubyErrors < TestSlim def test_multline_attribute source = %q{ p(data-1=1 data2-=1) p = unknown_ruby_method } assert_ruby_error NameError, "test.slim:5", source, file: 'test.slim' end def test_broken_output_line source = %q{ p = hello_world + \ hello_world + \ unknown_ruby_method } assert_ruby_error NameError, "test.slim:4", source, file: 'test.slim' end def test_broken_output_line2 source = %q{ p = hello_world + \ hello_world p Hello = unknown_ruby_method } assert_ruby_error NameError,"(__TEMPLATE__):5", source end def test_output_block source = %q{ p = hello_world "Hello Ruby" do = unknown_ruby_method } assert_ruby_error NameError,"(__TEMPLATE__):3", source end def test_output_block2 source = %q{ p = hello_world "Hello Ruby" do = "Hello from block" p Hello = unknown_ruby_method } assert_ruby_error NameError, "(__TEMPLATE__):5", source end def test_text_block source = %q{ p Text line 1 Text line 2 = unknown_ruby_method } assert_ruby_error NameError,"(__TEMPLATE__):4", source end def test_text_block2 source = %q{ | Text line 1 Text line 2 = unknown_ruby_method } assert_ruby_error NameError,"(__TEMPLATE__):5", source end def test_comment source = %q{ / Comment line 1 Comment line 2 = unknown_ruby_method } assert_ruby_error NameError,"(__TEMPLATE__):4", source end def test_embedded_ruby1 source = %q{ ruby: a = 1 b = 2 = a + b = unknown_ruby_method } assert_ruby_error NameError,"(__TEMPLATE__):7", source end def test_embedded_ruby2 source = %q{ ruby: a = 1 unknown_ruby_method } assert_ruby_error NameError,"(__TEMPLATE__):4", source end def test_embedded_ruby3 source = %q{ h1 before ruby: a = 1 h1 between ruby: b = a + 1 unknown_ruby_method c = 3 h1 third } assert_ruby_error NameError,"(__TEMPLATE__):10", source end def test_embedded_markdown source = %q{ markdown: #Header Hello from #{"Markdown!"} "Second Line!" = unknown_ruby_method } assert_ruby_error NameError,"(__TEMPLATE__):6", source end def test_embedded_javascript source = %q{ javascript: alert(); alert(); = unknown_ruby_method } assert_ruby_error NameError,"(__TEMPLATE__):5", source end def test_invalid_nested_code source = %q{ p - test = 123 = "Hello from within a block! " } assert_ruby_syntax_error "(__TEMPLATE__):3", source end def test_invalid_nested_output source = %q{ p = "Hello Ruby!" = "Hello from within a block! " } assert_ruby_syntax_error "(__TEMPLATE__):3", source end def test_explicit_end source = %q{ div - if show_first? p The first paragraph - end } assert_runtime_error 'Explicit end statements are forbidden', source end def test_multiple_id_attribute source = %{ #alpha id="beta" Test it } assert_runtime_error 'Multiple id attributes specified', source end def test_splat_multiple_id_attribute source = %{ #alpha *{id:"beta"} Test it } assert_runtime_error 'Multiple id attributes specified', source end # def test_invalid_option # render('', foobar: 42) # raise Exception, 'ArgumentError expected' # rescue ArgumentError => ex # assert_equal 'Option :foobar is not supported by Slim::Engine', ex.message # end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_tabs.rb
test/core/test_tabs.rb
require 'helper' class TestSlimTabs < TestSlim def teardown Slim::Engine.set_options tabsize: 4 end def test_single_tab1_expansion Slim::Engine.set_options tabsize: 1 source = %Q{ | \t0 \t1 \t2 \t3 \t4 \t5 \t6 \t7 \t8 } result = %q{ 0 1 2 3 4 5 6 7 8 }.strip assert_html result, source end def test_single_tab4_expansion Slim::Engine.set_options tabsize: 4 source = %Q{ | \t0 \t1 \t2 \t3 \t4 \t5 \t6 \t7 \t8 } result = %q{ 0 1 2 3 4 5 6 7 8 }.strip assert_html result, source end def test_multi_tab1_expansion Slim::Engine.set_options tabsize: 1 source = %Q{ | \t0 \t\t1 \t \t2 \t \t3 \t \t4 \t\t1 \t \t2 \t \t3 \t \t4 \t\t1 \t \t2 \t \t3 \t \t4 \t\t1 \t \t2 \t \t3 \t \t4 } result = %q{ 0 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 }.strip assert_html result, source end def test_multi_tab4_expansion Slim::Engine.set_options tabsize: 4 source = %Q{ | \t0 \t\t1 \t \t2 \t \t3 \t \t4 \t\t1 \t \t2 \t \t3 \t \t4 \t\t1 \t \t2 \t \t3 \t \t4 \t\t1 \t \t2 \t \t3 \t \t4 } result = %q{ 0 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 }.strip assert_html result, source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_erb_converter.rb
test/core/test_erb_converter.rb
require 'helper' require 'slim/erb_converter' class TestSlimERBConverter < TestSlim def test_converter source = %q{ doctype 5 html head title Hello World! /! Meta tags with long explanatory multiline comment meta name="description" content="template language" /! Stylesheets link href="style.css" media="screen" rel="stylesheet" type="text/css" link href="colors.css" media="screen" rel="stylesheet" type="text/css" /! Javascripts script src="jquery.js" script src="jquery.ui.js" /[if lt IE 9] script src="old-ie1.js" script src="old-ie2.js" css: body { background-color: red; } body #container p Hello World! p= "dynamic text with\nnewline" } result = %q{ <!DOCTYPE html> <html> <head> <title>Hello World!</title> <!--Meta tags with long explanatory multiline comment--> <meta content="template language" name="description" /> <!--Stylesheets--> <link href="style.css" media="screen" rel="stylesheet" type="text/css" /> <link href="colors.css" media="screen" rel="stylesheet" type="text/css" /> <!--Javascripts--> <script src="jquery.js"> </script><script src="jquery.ui.js"> </script><!--[if lt IE 9]> <script src="old-ie1.js"> </script><script src="old-ie2.js"> </script><![endif]--><style> body { background-color: red; }</style> </head><body> <div id="container"> <p>Hello World!</p> <p><%= ::Temple::Utils.escape_html(("dynamic text with\nnewline")) %> </p></div></body></html>} assert_equal result, Slim::ERBConverter.new.call(source) end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_slim_template.rb
test/core/test_slim_template.rb
require 'helper' class ::MockError < NameError end class TestSlimTemplate < TestSlim def test_default_mime_type assert_equal 'text/html', Slim::Template.default_mime_type end def test_registered_extension assert_equal Slim::Template, Tilt['test.slim'] end def test_preparing_and_evaluating template = Slim::Template.new { |t| "p Hello World!\n" } assert_equal "<p>Hello World!</p>", template.render end def test_evaluating_in_an_object_scope template = Slim::Template.new { "p = 'Hey ' + @name + '!'\n" } scope = Object.new scope.instance_variable_set :@name, 'Joe' assert_equal "<p>Hey Joe!</p>", template.render(scope) end def test_passing_a_block_for_yield template = Slim::Template.new { "p = 'Hey ' + yield + '!'\n" } assert_equal "<p>Hey Joe!</p>", template.render { 'Joe' } end def test_backtrace_file_and_line_reporting_without_locals data = File.read(__FILE__).split("\n__END__\n").last fail unless data[0] == ?h template = Slim::Template.new('test.slim', 10) { data } begin template.render fail 'should have raised an exception' rescue => ex assert_kind_of NameError, ex assert_backtrace(ex, 'test.slim:12') end end def test_backtrace_file_and_line_reporting_with_locals data = File.read(__FILE__).split("\n__END__\n").last fail unless data[0] == ?h template = Slim::Template.new('test.slim') { data } begin template.render(Object.new, name: 'Joe', foo: 'bar') fail 'should have raised an exception' rescue => ex assert_kind_of MockError, ex assert_backtrace(ex, 'test.slim:5') end end def test_compiling_template_source_to_a_method template = Slim::Template.new { |t| "Hello World!" } template.render method = template.send(:compiled_method, []) assert_kind_of UnboundMethod, method end def test_passing_locals template = Slim::Template.new { "p = 'Hey ' + name + '!'\n" } assert_equal "<p>Hey Joe!</p>", template.render(Object.new, name: 'Joe') end end __END__ html body h1 = "Hey #{name}" = raise MockError p we never get here
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_html_structure.rb
test/core/test_html_structure.rb
require 'helper' class TestSlimHtmlStructure < TestSlim def test_simple_render # Keep the trailing space behind "body "! source = %q{ html head title Simple Test Title body p Hello World, meet Slim. } assert_html '<html><head><title>Simple Test Title</title></head><body><p>Hello World, meet Slim.</p></body></html>', source end def test_relaxed_indentation_of_first_line source = %q{ p .content } assert_html "<p><div class=\"content\"></div></p>", source end def test_html_tag_with_text_and_empty_line source = %q{ p Hello p World } assert_html "<p>Hello</p><p>World</p>", source end def test_html_namespaces source = %q{ html:body html:p html:id="test" Text } assert_html '<html:body><html:p html:id="test">Text</html:p></html:body>', source end def test_doctype source = %q{ doctype 1.1 html } assert_html '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html></html>', source, format: :xhtml end def test_doctype_new_syntax source = %q{ doctype 5 html } assert_html '<!DOCTYPE html><html></html>', source, format: :xhtml end def test_doctype_new_syntax_html5 source = %q{ doctype html html } assert_html '<!DOCTYPE html><html></html>', source, format: :xhtml end def test_render_with_shortcut_attributes source = %q{ h1#title This is my title #notice.hello.world = hello_world } assert_html '<h1 id="title">This is my title</h1><div class="hello world" id="notice">Hello World from @env</div>', source end def test_render_with_overwritten_default_tag source = %q{ #notice.hello.world = hello_world } assert_html '<section class="hello world" id="notice">Hello World from @env</section>', source, default_tag: 'section' end def test_render_with_custom_shortcut source = %q{ #notice.hello.world@test = hello_world @abc = hello_world } assert_html '<div class="hello world" id="notice" role="test">Hello World from @env</div><section role="abc">Hello World from @env</section>', source, shortcut: {'#' => {attr: 'id'}, '.' => {attr: 'class'}, '@' => {tag: 'section', attr: 'role'}} end def test_render_with_custom_array_shortcut source = %q{ #user@.admin Daniel } assert_html '<div class="admin" id="user" role="admin">Daniel</div>', source, shortcut: {'#' => {attr: 'id'}, '.' => {attr: 'class'}, '@' => {attr: 'role'}, '@.' => {attr: ['class', 'role']}} end def test_render_with_custom_shortcut_and_additional_attrs source = %q{ ^items == "[{'title':'item0'},{'title':'item1'},{'title':'item2'},{'title':'item3'},{'title':'item4'}]" } assert_html '<script data-binding="items" type="application/json">[{\'title\':\'item0\'},{\'title\':\'item1\'},{\'title\':\'item2\'},{\'title\':\'item3\'},{\'title\':\'item4\'}]</script>', source, shortcut: {'^' => {tag: 'script', attr: 'data-binding', additional_attrs: { type: "application/json" }}} end def test_render_with_custom_lambda_shortcut begin Slim::Parser.options[:shortcut]['~'] = {attr: ->(v) {{class: "styled-#{v}", id: "id-#{v}"}}} source = %q{ ~foo Hello } assert_html '<div class="styled-foo" id="id-foo">Hello</div>', source ensure Slim::Parser.options[:shortcut].delete('~') end end def test_render_with_custom_lambda_shortcut_and_multiple_values begin Slim::Parser.options[:shortcut]['~'] = {attr: ->(v) {{class: "styled-#{v}"}}} source = %q{ ~foo~bar Hello } assert_html '<div class="styled-foo styled-bar">Hello</div>', source ensure Slim::Parser.options[:shortcut].delete('~') end end def test_render_with_custom_lambda_shortcut_and_existing_class begin Slim::Parser.options[:shortcut]['~'] = {attr: ->(v) {{class: "styled-#{v}"}}} source = %q{ ~foo.baz Hello } assert_html '<div class="styled-foo baz">Hello</div>', source ensure Slim::Parser.options[:shortcut].delete('~') end end def test_render_with_existing_class_and_custom_lambda_shortcut begin Slim::Parser.options[:shortcut]['~'] = {attr: ->(v) {{class: "styled-#{v}"}}} source = %q{ .baz~foo Hello } assert_html '<div class="baz styled-foo">Hello</div>', source ensure Slim::Parser.options[:shortcut].delete('~') end end def test_render_with_text_block source = %q{ p | Lorem ipsum dolor sit amet, consectetur adipiscing elit. } assert_html '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>', source end def test_render_with_text_block_with_subsequent_markup source = %q{ p | Lorem ipsum dolor sit amet, consectetur adipiscing elit. p Some more markup } assert_html '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p><p>Some more markup</p>', source end def test_render_with_text_block_with_trailing_whitespace source = %q{ ' this is a link to a href="link" page } assert_html "this is\na link to <a href=\"link\">page</a>", source end def test_nested_text source = %q{ p | This is line one. This is line two. This is line three. This is line four. p This is a new paragraph. } assert_html "<p>This is line one.\n This is line two.\n This is line three.\n This is line four.</p><p>This is a new paragraph.</p>", source end def test_nested_text_with_nested_html_one_same_line source = %q{ p | This is line one. This is line two. span.bold This is a bold line in the paragraph. | This is more content. } assert_html "<p>This is line one.\n This is line two.<span class=\"bold\">This is a bold line in the paragraph.</span> This is more content.</p>", source end def test_nested_text_with_nested_html_one_same_line2 source = %q{ p |This is line one. This is line two. span.bold This is a bold line in the paragraph. | This is more content. } assert_html "<p>This is line one.\n This is line two.<span class=\"bold\">This is a bold line in the paragraph.</span> This is more content.</p>", source end def test_nested_text_with_nested_html source = %q{ p | This is line one. This is line two. This is line three. This is line four. span.bold This is a bold line in the paragraph. | This is more content. } assert_html "<p>This is line one.\n This is line two.\n This is line three.\n This is line four.<span class=\"bold\">This is a bold line in the paragraph.</span> This is more content.</p>", source end def test_simple_paragraph_with_padding source = %q{ p There will be 3 spaces in front of this line. } assert_html '<p> There will be 3 spaces in front of this line.</p>', source end def test_paragraph_with_nested_text source = %q{ p This is line one. This is line two. } assert_html "<p>This is line one.\n This is line two.</p>", source end def test_paragraph_with_padded_nested_text source = %q{ p This is line one. This is line two. } assert_html "<p> This is line one.\n This is line two.</p>", source end def test_paragraph_with_attributes_and_nested_text source = %q{ p#test class="paragraph" This is line one. This is line two. } assert_html "<p class=\"paragraph\" id=\"test\">This is line one.\nThis is line two.</p>", source end def test_relaxed_text_indentation source = %q{ p | text block text line3 } assert_html "<p>text block\ntext\n line3</p>", source end def test_output_code_with_leading_spaces source = %q{ p= hello_world p = hello_world p = hello_world } assert_html '<p>Hello World from @env</p><p>Hello World from @env</p><p>Hello World from @env</p>', source end def test_single_quoted_attributes source = %q{ p class='underscored_class_name' = output_number } assert_html '<p class="underscored_class_name">1337</p>', source end def test_nonstandard_attributes source = %q{ p id="dashed-id" class="underscored_class_name" = output_number } assert_html '<p class="underscored_class_name" id="dashed-id">1337</p>', source end def test_nonstandard_shortcut_attributes source = %q{ p#dashed-id.underscored_class_name = output_number } assert_html '<p class="underscored_class_name" id="dashed-id">1337</p>', source end def test_dashed_attributes source = %q{ p data-info="Illudium Q-36" = output_number } assert_html '<p data-info="Illudium Q-36">1337</p>', source end def test_dashed_attributes_with_shortcuts source = %q{ p#marvin.martian data-info="Illudium Q-36" = output_number } assert_html '<p class="martian" data-info="Illudium Q-36" id="marvin">1337</p>', source end def test_parens_around_attributes source = %q{ p(id="marvin" class="martian" data-info="Illudium Q-36") = output_number } assert_html '<p class="martian" data-info="Illudium Q-36" id="marvin">1337</p>', source end def test_square_brackets_around_attributes source = %q{ p[id="marvin" class="martian" data-info="Illudium Q-36"] = output_number } assert_html '<p class="martian" data-info="Illudium Q-36" id="marvin">1337</p>', source end # Regression test for bug #796 def test_square_brackets_around_attributes_multiline_with_tabs source = "div\n\tp[\n\t\tclass=\"martian\"\n\t]\n\tp Next line" assert_html '<div><p class="martian"></p><p>Next line</p></div>', source end def test_parens_around_attributes_with_equal_sign_snug_to_right_paren source = %q{ p(id="marvin" class="martian" data-info="Illudium Q-36")= output_number } assert_html '<p class="martian" data-info="Illudium Q-36" id="marvin">1337</p>', source end def test_default_attr_delims_option source = %q{ p<id="marvin" class="martian" data-info="Illudium Q-36">= output_number } Slim::Parser.options[:attr_list_delims].each do |k,v| str = source.sub('<',k).sub('>',v) assert_html '<p class="martian" data-info="Illudium Q-36" id="marvin">1337</p>', str end end def test_custom_attr_delims_option source = %q{ p { foo="bar" } } assert_html '<p foo="bar"></p>', source assert_html '<p foo="bar"></p>', source, attr_list_delims: {'{' => '}'} assert_html '<p>{ foo="bar" }</p>', source, attr_list_delims: {'(' => ')', '[' => ']'} end def test_closed_tag source = %q{ closed/ } assert_html '<closed />', source, format: :xhtml end def test_custom_attr_list_delims_option source = %q{ p { foo="bar" x=(1+1) } p < x=(1+1) > Hello } assert_html '<p foo="bar" x="2"></p><p>< x=(1+1) > Hello</p>', source assert_html '<p foo="bar" x="2"></p><p>< x=(1+1) > Hello</p>', source, attr_list_delims: {'{' => '}'} assert_html '<p>{ foo="bar" x=(1+1) }</p><p x="2">Hello</p>', source, attr_list_delims: {'<' => '>'}, code_attr_delims: { '(' => ')' } end def test_attributs_with_parens_and_spaces source = %q{label{ for='filter' }= hello_world} assert_html '<label for="filter">Hello World from @env</label>', source end def test_attributs_with_parens_and_spaces2 source = %q{label{ for='filter' } = hello_world} assert_html '<label for="filter">Hello World from @env</label>', source end def test_attributs_with_multiple_spaces source = %q{label for='filter' class="test" = hello_world} assert_html '<label class="test" for="filter">Hello World from @env</label>', source end def test_closed_tag_with_attributes source = %q{ closed id="test" / } assert_html '<closed id="test" />', source, format: :xhtml end def test_closed_tag_with_attributes_and_parens source = %q{ closed(id="test")/ } assert_html '<closed id="test" />', source, format: :xhtml end def test_render_with_html_comments source = %q{ p Hello /! This is a comment Another comment p World } assert_html "<p>Hello</p><!--This is a comment\n\nAnother comment--><p>World</p>", source end def test_render_with_html_conditional_and_tag source = %q{ /[ if IE ] p Get a better browser. } assert_html "<!--[if IE]><p>Get a better browser.</p><![endif]-->", source end def test_render_with_html_conditional_and_method_output source = %q{ /[ if IE ] = message 'hello' } assert_html "<!--[if IE]>hello<![endif]-->", source end def test_multiline_attributes_with_method source = %q{ p<id="marvin" class="martian" data-info="Illudium Q-36"> = output_number } Slim::Parser.options[:attr_list_delims].each do |k,v| str = source.sub('<',k).sub('>',v) assert_html '<p class="martian" data-info="Illudium Q-36" id="marvin">1337</p>', str end end def test_multiline_attributes_with_text_on_same_line source = %q{ p<id="marvin" class="martian" data-info="Illudium Q-36"> THE space modulator } Slim::Parser.options[:attr_list_delims].each do |k,v| str = source.sub('<',k).sub('>',v) assert_html '<p class="martian" data-info="Illudium Q-36" id="marvin">THE space modulator</p>', str end end def test_multiline_attributes_with_nested_text source = %q{ p<id="marvin" class="martian" data-info="Illudium Q-36"> | THE space modulator } Slim::Parser.options[:attr_list_delims].each do |k,v| str = source.sub('<',k).sub('>',v) assert_html '<p class="martian" data-info="Illudium Q-36" id="marvin">THE space modulator</p>', str end end def test_multiline_attributes_with_dynamic_attr source = %q{ p<id=id_helper class="martian" data-info="Illudium Q-36"> | THE space modulator } Slim::Parser.options[:attr_list_delims].each do |k,v| str = source.sub('<',k).sub('>',v) assert_html '<p class="martian" data-info="Illudium Q-36" id="notice">THE space modulator</p>', str end end def test_multiline_attributes_with_nested_tag source = %q{ p<id=id_helper class="martian" data-info="Illudium Q-36"> span.emphasis THE | space modulator } Slim::Parser.options[:attr_list_delims].each do |k,v| str = source.sub('<',k).sub('>',v) assert_html '<p class="martian" data-info="Illudium Q-36" id="notice"><span class="emphasis">THE</span> space modulator</p>', str end end def test_multiline_attributes_with_nested_text_and_extra_indentation source = %q{ li< id="myid" class="myclass" data-info="myinfo"> a href="link" My Link } Slim::Parser.options[:attr_list_delims].each do |k,v| str = source.sub('<',k).sub('>',v) assert_html '<li class="myclass" data-info="myinfo" id="myid"><a href="link">My Link</a></li>', str end end def test_block_expansion_support source = %q{ ul li.first: a href='a' foo li: a href='b' bar li.last: a href='c' baz } assert_html %{<ul><li class=\"first\"><a href=\"a\">foo</a></li><li><a href=\"b\">bar</a></li><li class=\"last\"><a href=\"c\">baz</a></li></ul>}, source end def test_block_expansion_class_attributes source = %q{ .a: .b: #c d } assert_html %{<div class="a"><div class="b"><div id="c">d</div></div></div>}, source end def test_block_expansion_nesting source = %q{ html: body: .content | Text } assert_html %{<html><body><div class=\"content\">Text</div></body></html>}, source end def test_eval_attributes_once source = %q{ input[value=succ_x] input[value=succ_x] } assert_html %{<input value="1" /><input value="2" />}, source end def test_html_line_indicator source = %q{ <html> head meta name="keywords" content=hello_world - if true <p>#{hello_world}</p> span = hello_world </html> } assert_html '<html><head><meta content="Hello World from @env" name="keywords" /></head><p>Hello World from @env</p><span>Hello World from @env</span></html>', source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_code_output.rb
test/core/test_code_output.rb
require 'helper' class TestSlimCodeOutput < TestSlim def test_render_with_call source = %q{ p = hello_world } assert_html '<p>Hello World from @env</p>', source end def test_render_with_trailing_whitespace source = %q{ p => hello_world } assert_html '<p>Hello World from @env </p>', source end def test_render_with_trailing_whitespace_after_tag source = %q{ p=> hello_world } assert_html '<p>Hello World from @env</p> ', source end def test_no_escape_render_with_trailing_whitespace source = %q{ p ==> hello_world } assert_html '<p>Hello World from @env </p>', source end def test_no_escape_render_with_trailing_whitespace_after_tag source = %q{ p==> hello_world } assert_html '<p>Hello World from @env</p> ', source end def test_render_with_conditional_call source = %q{ p = hello_world if true } assert_html '<p>Hello World from @env</p>', source end def test_render_with_parameterized_call source = %q{ p = hello_world("Hello Ruby!") } assert_html '<p>Hello Ruby!</p>', source end def test_render_with_spaced_parameterized_call source = %q{ p = hello_world "Hello Ruby!" } assert_html '<p>Hello Ruby!</p>', source end def test_render_with_spaced_parameterized_call_2 source = %q{ p = hello_world "Hello Ruby!", dummy: "value" } assert_html '<p>Hello Ruby!dummy value</p>', source end def test_render_with_call_and_inline_text source = %q{ h1 This is my title p = hello_world } assert_html '<h1>This is my title</h1><p>Hello World from @env</p>', source end def test_render_with_attribute_starts_with_keyword source = %q{ p = hello_world in_keyword } assert_html '<p>starts with keyword</p>', source end def test_hash_call source = %q{ p = hash[:a] } assert_html '<p>The letter a</p>', source end def test_tag_output_without_space source = %q{ p= hello_world p=hello_world } assert_html '<p>Hello World from @env</p><p>Hello World from @env</p>', source end def test_class_output_without_space source = %q{ .test=hello_world #test==hello_world } assert_html '<div class="test">Hello World from @env</div><div id="test">Hello World from @env</div>', source end def test_attribute_output_without_space source = %q{ p id="test"=hello_world p(id="test")==hello_world } assert_html '<p id="test">Hello World from @env</p><p id="test">Hello World from @env</p>', source end def test_render_with_backslash_end # Keep trailing spaces! source = %q{ p = \ "Hello" + \ " Ruby!" - variable = 1 + \ 2 + \ 3 = variable + \ 1 } assert_html '<p>Hello Ruby!</p>7', source end def test_render_with_comma_end source = %q{ p = message("Hello", "Ruby!") } assert_html '<p>Hello Ruby!</p>', source end def test_render_with_no_trailing_character source = %q{ p = hello_world} assert_html '<p>Hello World from @env</p>', source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_text_interpolation.rb
test/core/test_text_interpolation.rb
require 'helper' class TestSlimTextInterpolation < TestSlim def test_interpolation_in_attribute source = %q{ p id="a#{id_helper}b" = hello_world } assert_html '<p id="anoticeb">Hello World from @env</p>', source end def test_nested_interpolation_in_attribute source = %q{ p id="#{"abc#{1+1}" + "("}" = hello_world } assert_html '<p id="abc2(">Hello World from @env</p>', source end def test_interpolation_in_text source = %q{ p | #{hello_world} with "quotes" p | A message from the compiler: #{hello_world} } assert_html '<p>Hello World from @env with "quotes"</p><p>A message from the compiler: Hello World from @env</p>', source end def test_interpolation_in_tag source = %q{ p #{hello_world} } assert_html '<p>Hello World from @env</p>', source end def test_escape_interpolation source = %q{ p \\#{hello_world} p text1 \\#{hello_world} text2 } assert_html '<p>#{hello_world}</p><p>text1 #{hello_world} text2</p>', source end def test_complex_interpolation source = %q{ p Message: #{message('hello', "user #{output_number}")} } assert_html '<p>Message: hello user 1337</p>', source end def test_interpolation_with_escaping source = %q{ | #{evil_method} } assert_html '&lt;script&gt;do_something_evil();&lt;/script&gt;', source end def test_interpolation_without_escaping source = %q{ | #{{evil_method}} } assert_html '<script>do_something_evil();</script>', source end def test_interpolation_with_escaping_and_delimiter source = %q{ | #{(evil_method)} } assert_html '&lt;script&gt;do_something_evil();&lt;/script&gt;', source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_commands.rb
test/core/test_commands.rb
require 'helper' require 'open3' require 'tempfile' class TestSlimCommands < Minitest::Test # nothing complex STATIC_TEMPLATE = "p Hello World!\n" # requires a `name` variable to exist at render time DYNAMIC_TEMPLATE = "p Hello \#{name}!\n" # a more complex example LONG_TEMPLATE = "h1 Hello\np\n | World!\n small Tiny text" # exception raising example EXCEPTION_TEMPLATE = '- raise NotImplementedError' def test_option_help out, err = exec_slimrb '--help' assert err.empty? assert_match %r{Show this message}, out end def test_option_version out, err = exec_slimrb '--version' assert err.empty? assert_match %r{\ASlim #{Regexp.escape Slim::VERSION}$}, out end def test_render prepare_common_test STATIC_TEMPLATE do |out, err| assert err.empty? assert_equal "<p>Hello World!</p>\n", out end end # superficial test, we don't want to test Tilt/Temple def test_compile prepare_common_test STATIC_TEMPLATE, '--compile' do |out, err| assert err.empty? assert_match %r{\"<p>Hello World!<\/p>\".freeze}, out end end def test_erb prepare_common_test DYNAMIC_TEMPLATE, '--erb' do |out, err| assert err.empty? assert_equal "<p>Hello <%= ::Temple::Utils.escape_html((name)) %>!</p>\n", out end end def test_rails prepare_common_test DYNAMIC_TEMPLATE, '--rails' do |out, err| assert err.empty? if Gem::Version.new(Temple::VERSION) >= Gem::Version.new('0.9') assert out.include? %Q{@output_buffer = output_buffer || ActionView::OutputBuffer.new;} else assert out.include? %Q{@output_buffer = ActiveSupport::SafeBuffer.new;} end assert out.include? %Q{@output_buffer.safe_concat(("<p>Hello ".freeze));} assert out.include? %Q{@output_buffer.safe_concat(((::Temple::Utils.escape_html((name))).to_s));} assert out.include? %Q{@output_buffer.safe_concat(("!</p>".freeze));} end end def test_pretty prepare_common_test LONG_TEMPLATE, '--pretty' do |out, err| assert err.empty? assert_equal "<h1>\n Hello\n</h1>\n<p>\n World!<small>Tiny text</small>\n</p>\n", out end end def test_locals_json data = '{"name":"from slim"}' prepare_common_test DYNAMIC_TEMPLATE, '--locals', data do |out, err| assert err.empty? assert_equal "<p>Hello from slim!</p>\n", out end end def test_locals_yaml data = "name: from slim" prepare_common_test DYNAMIC_TEMPLATE, '--locals', data do |out, err| assert err.empty? assert_equal "<p>Hello from slim!</p>\n", out end end def test_locals_hash data = '{name:"from slim"}' prepare_common_test DYNAMIC_TEMPLATE, '--locals', data do |out, err| assert err.empty? assert_equal "<p>Hello from slim!</p>\n", out end end def test_require with_tempfile 'puts "Not in slim"', 'rb' do |lib| prepare_common_test STATIC_TEMPLATE, '--require', lib, stdin_file: false, file_file: false do |out, err| assert err.empty? assert_equal "Not in slim\n<p>Hello World!</p>\n", out end end end def test_error prepare_common_test EXCEPTION_TEMPLATE, stdin_file: false do |out, err| assert out.empty? assert_match %r{NotImplementedError: NotImplementedError}, err assert_match %r{Use --trace for backtrace}, err end end def test_trace_error prepare_common_test EXCEPTION_TEMPLATE, '--trace', stdin_file: false do |out, err| assert out.empty? assert_match %r{bin\/slimrb}, err end end private # Whether you call slimrb with a file argument or pass the slim content # via $stdin; whether you want the output written to $stdout or into # another file given as argument, the output is the same. # # This method prepares a test with this exact behaviour: # # It yields the tupel (out, err) once after the `content` was passed # in via $stdin and once it was passed as a (temporary) file argument. # # In effect, this method executes a test (given as block) 4 times: # # 1. read from $stdin, write to $stdout # 2. read from file, write to $stdout # 3. read from $stdin, write to file # 4. read from file, write to file def prepare_common_test(content, *args) options = Hash === args.last ? args.pop : {} # case 1. $stdin → $stdout unless options[:stdin_stdout] == false out, err = exec_slimrb(*args, '--stdin') do |i| i.write content end yield out, err end # case 2. file → $stdout unless options[:file_stdout] == false with_tempfile content do |in_file| out, err = exec_slimrb(*args, in_file) yield out, err end end # case 3. $stdin → file unless options[:stdin_file] == false with_tempfile content do |out_file| _, err = exec_slimrb(*args, '--stdin', out_file) do |i| i.write content end yield File.read(out_file), err end end # case 3. file → file unless options[:file_file] == false with_tempfile '' do |out_file| with_tempfile content do |in_file| _, err = exec_slimrb(*args, in_file, out_file) do |i| i.write content end yield File.read(out_file), err end end end end # Calls bin/slimrb as a subprocess. # # Yields $stdin to the caller and returns a tupel (out,err) with the # contents of $stdout and $stderr. # # (I'd like to use Minitest::Assertions#capture_subprecess_io here, # but then there's no way to insert data via $stdin.) def exec_slimrb(*args) out, err = nil, nil Open3.popen3 'ruby', 'bin/slimrb', *args do |i,o,e,t| yield i if block_given? i.close out, err = o.read, e.read end return out, err end # Creates a temporary file with the given content and yield the path # to this file. The file itself is only available inside the block and # will be deleted afterwards. def with_tempfile(content=nil, extname='slim') f = Tempfile.new ['slim', ".#{extname}"] if content f.write content f.flush # ensure content is actually saved to disk f.rewind end yield f.path ensure f.close f.unlink end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_thread_options.rb
test/core/test_thread_options.rb
require 'helper' class TestSlimThreadOptions < TestSlim def test_thread_options source = %q{p.test} assert_html '<p class="test"></p>', source assert_html "<p class='test'></p>", source, attr_quote: "'" Slim::Engine.with_options(attr_quote: "'") do assert_html "<p class='test'></p>", source assert_html '<p class="test"></p>', source, attr_quote: '"' end assert_html '<p class="test"></p>', source assert_html "<p class='test'></p>", source, attr_quote: "'" end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_code_structure.rb
test/core/test_code_structure.rb
require 'helper' class TestSlimCodeStructure < TestSlim def test_render_with_conditional source = %q{ div - if show_first? p The first paragraph - else p The second paragraph } assert_html '<div><p>The second paragraph</p></div>', source end def test_render_with_begin source = %q{ - if true - begin p A - if true - begin p B - if true - begin p C - rescue p D } assert_html '<p>A</p><p>B</p><p>C</p>', source end def test_render_with_consecutive_conditionals source = %q{ div - if show_first? true p The first paragraph - if show_first? true p The second paragraph } assert_html '<div><p>The first paragraph</p><p>The second paragraph</p></div>', source end def test_render_with_parameterized_conditional source = %q{ div - if show_first? false p The first paragraph - else p The second paragraph } assert_html '<div><p>The second paragraph</p></div>', source end def test_render_with_when_string_in_condition source = %q{ - if true | Hello - unless 'when' == nil | world } assert_html 'Hello world', source end def test_render_with_conditional_and_following_nonconditonal source = %q{ div - if true p The first paragraph - var = 42 = var } assert_html '<div><p>The first paragraph</p>42</div>', source end def test_render_with_inline_condition source = %q{ p = hello_world if true } assert_html '<p>Hello World from @env</p>', source end def test_render_with_case source = %q{ p - case 42 - when 41 | 41 - when 42 | 42 | is the answer p - case 41 - when 41 | 41 - when 42 | 42 | is the answer p - case 42 when 41 | 41 - when 42 | 42 | is the answer p - case 41 when 41 | 41 - when 42 | 42 | is the answer } assert_html '<p>42 is the answer</p><p>41 is the answer</p><p>42 is the answer</p><p>41 is the answer</p>', source end if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("2.7") def test_render_with_case_in source = %q{ p - case [:greet, "world"] - in :greet, value if false = "Goodbye #{value}" - in :greet, value unless true = "Top of the morning to you, #{value}" - in :greet, value = "Hello #{value}" } assert_html '<p>Hello world</p>', source end end def test_render_with_slim_comments source = %q{ p Hello / This is a comment Another comment p World } assert_html '<p>Hello</p><p>World</p>', source end def test_render_with_yield source = %q{ div == yield :menu } assert_html '<div>This is the menu</div>', source do 'This is the menu' end end def test_render_with_begin_rescue source = %q{ - begin p Begin - rescue p Rescue p After } assert_html '<p>Begin</p><p>After</p>', source end def test_render_with_begin_rescue_exception source = %q{ - begin p Begin - raise 'Boom' p After Boom - rescue => ex p = ex.message p After } assert_html '<p>Begin</p><p>Boom</p><p>After</p>', source end def test_render_with_begin_rescue_ensure source = %q{ - begin p Begin - raise 'Boom' p After Boom - rescue => ex p = ex.message - ensure p Ensure p After } assert_html '<p>Begin</p><p>Boom</p><p>Ensure</p><p>After</p>', source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_code_blocks.rb
test/core/test_code_blocks.rb
require 'helper' class TestSlimCodeBlocks < TestSlim def test_render_with_output_code_block source = %q{ p = hello_world "Hello Ruby!" do | Hello from within a block! } assert_html '<p>Hello Ruby! Hello from within a block! Hello Ruby!</p>', source end def test_render_with_output_code_block_without_do source = %q{ p = hello_world "Hello Ruby!" | Hello from within a block! } assert_html '<p>Hello Ruby! Hello from within a block! Hello Ruby!</p>', source end def test_render_variable_ending_with_do source = %q{ - appelido=10 p= appelido - appelido } assert_html '<p>10</p>', source end def test_render_with_output_code_within_block source = %q{ p = hello_world "Hello Ruby!" do = hello_world "Hello from within a block!" } assert_html '<p>Hello Ruby! Hello from within a block! Hello Ruby!</p>', source end def test_render_with_output_code_within_block_without_do source = %q{ p = hello_world "Hello Ruby!" = hello_world "Hello from within a block!" } assert_html '<p>Hello Ruby! Hello from within a block! Hello Ruby!</p>', source end def test_render_with_output_code_within_block_2 source = %q{ p = hello_world "Hello Ruby!" do = hello_world "Hello from within a block!" do = hello_world "And another one!" } assert_html '<p>Hello Ruby! Hello from within a block! And another one! Hello from within a block! Hello Ruby!</p>', source end def test_render_with_output_code_within_block_2_without_do source = %q{ p = hello_world "Hello Ruby!" = hello_world "Hello from within a block!" = hello_world "And another one!" } assert_html '<p>Hello Ruby! Hello from within a block! And another one! Hello from within a block! Hello Ruby!</p>', source end def test_output_block_with_arguments source = %q{ p = define_macro :person do |first_name, last_name| .first_name = first_name .last_name = last_name == call_macro :person, 'John', 'Doe' == call_macro :person, 'Max', 'Mustermann' } assert_html '<p><div class="first_name">John</div><div class="last_name">Doe</div><div class="first_name">Max</div><div class="last_name">Mustermann</div></p>', source end def test_render_with_control_code_loop source = %q{ p - 3.times do | Hey! } assert_html '<p>Hey!Hey!Hey!</p>', source end def test_render_with_control_code_loop_without_do source = %q{ p - 3.times | Hey! } assert_html '<p>Hey!Hey!Hey!</p>', source end def test_captured_code_block_with_conditional source = %q{ = hello_world "Hello Ruby!" do - if true | Hello from within a block! } assert_html 'Hello Ruby! Hello from within a block! Hello Ruby!', source end def test_captured_code_block_with_conditional_without_do source = %q{ = hello_world "Hello Ruby!" - if true | Hello from within a block! } assert_html 'Hello Ruby! Hello from within a block! Hello Ruby!', source end def test_if_without_content source = %q{ - if true } assert_html '', source end def test_unless_without_content source = %q{ - unless true } assert_html '', source end def test_if_with_comment source = %q{ - if true / comment } assert_html '', source end def test_control_do_with_comment source = %q{ - hello_world "Hello" / comment } assert_html '', source end def test_output_do_with_comment source = %q{ = hello_world "Hello" / comment } assert_html 'Hello', source end def test_output_if_without_content source = %q{ = if true } assert_html '', source end def test_output_if_with_comment source = %q{ = if true / comment } assert_html '', source end def test_output_format_with_if source = %q{ h3.subtitle - if true a href="#" Title true - else a href="#" Title false } assert_html '<h3 class="subtitle"><a href="#">Title true</a></h3>', source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_html_attributes.rb
test/core/test_html_attributes.rb
require 'helper' class TestSlimHTMLAttributes < TestSlim def test_ternary_operation_in_attribute source = %q{ p id="#{(false ? 'notshown' : 'shown')}" = output_number } assert_html '<p id="shown">1337</p>', source end def test_ternary_operation_in_attribute_2 source = %q{ p id=(false ? 'notshown' : 'shown') = output_number } assert_html '<p id="shown">1337</p>', source end def test_class_attribute_merging source = %{ .alpha class="beta" Test it } assert_html '<div class="alpha beta">Test it</div>', source end def test_class_attribute_merging_with_nil source = %{ .alpha class="beta" class=nil class="gamma" Test it } assert_html '<div class="alpha beta gamma">Test it</div>', source end def test_class_attribute_merging_with_empty_static source = %{ .alpha class="beta" class="" class="gamma" Test it } assert_html '<div class="alpha beta gamma">Test it</div>', source end def test_id_attribute_merging source = %{ #alpha id="beta" Test it } assert_html '<div id="alpha_beta">Test it</div>', source, merge_attrs: {'class' => ' ', 'id' => '_' } end def test_id_attribute_merging2 source = %{ #alpha id="beta" Test it } assert_html '<div id="alpha-beta">Test it</div>', source, merge_attrs: {'class' => ' ', 'id' => '-' } end def test_boolean_attribute_false source = %{ - cond=false option selected=false Text option selected=cond Text2 } assert_html '<option>Text</option><option>Text2</option>', source end def test_boolean_attribute_true source = %{ - cond=true option selected=true Text option selected=cond Text2 } assert_html '<option selected="">Text</option><option selected="">Text2</option>', source end def test_boolean_attribute_nil source = %{ - cond=nil option selected=nil Text option selected=cond Text2 } assert_html '<option>Text</option><option>Text2</option>', source end def test_boolean_attribute_string2 source = %{ option selected="selected" Text } assert_html '<option selected="selected">Text</option>', source end def test_boolean_attribute_shortcut source = %{ option(class="clazz" selected) Text option(selected class="clazz") Text } assert_html '<option class="clazz" selected="">Text</option><option class="clazz" selected="">Text</option>', source end def test_array_attribute_merging source = %{ .alpha class="beta" class=[[""], :gamma, nil, :delta, [true, false]] .alpha class=:beta,:gamma } assert_html '<div class="alpha beta gamma delta true false"></div><div class="alpha beta gamma"></div>', source end def test_hyphenated_attribute source = %{ .alpha data={a: 'alpha', b: 'beta', c_d: 'gamma', c: {e: 'epsilon'}} } assert_html '<div class="alpha" data-a="alpha" data-b="beta" data-c-e="epsilon" data-c_d="gamma"></div>', source end def test_hyphenated_underscore_attribute source = %{ .alpha data={a: 'alpha', b: 'beta', c_d: 'gamma', c: {e: 'epsilon'}} } assert_html '<div class="alpha" data-a="alpha" data-b="beta" data-c-d="gamma" data-c-e="epsilon"></div>', source, hyphen_underscore_attrs: true end def test_splat_without_content source = %q{ *hash p*hash } assert_html '<div a="The letter a" b="The letter b"></div><p a="The letter a" b="The letter b"></p>', source end def test_shortcut_splat source = %q{ *hash This is my title } assert_html '<div a="The letter a" b="The letter b">This is my title</div>', source end def test_splat source = %q{ h1 *hash class=[] This is my title } assert_html '<h1 a="The letter a" b="The letter b">This is my title</h1>', source end def test_closed_splat source = %q{ *hash / } assert_html '<div a="The letter a" b="The letter b" />', source end def test_splat_tag_name source = %q{ *{tag: 'h1', id: 'title'} This is my title } assert_html '<h1 id="title">This is my title</h1>', source end def test_splat_empty_tag_name source = %q{ *{tag: '', id: 'test'} This is my title } assert_html '<div id="test">This is my title</div>', source end def test_closed_splat_tag source = %q{ *hash / } assert_html '<div a="The letter a" b="The letter b" />', source end def test_splat_with_id_shortcut source = %q{ #myid*hash This is my title } assert_html '<div a="The letter a" b="The letter b" id="myid">This is my title</div>', source end def test_splat_with_class_shortcut source = %q{ .myclass*hash This is my title } assert_html '<div a="The letter a" b="The letter b" class="myclass">This is my title</div>', source end def test_splat_with_id_and_class_shortcuts source = %q{ #myid.myclass*hash This is my title } assert_html '<div a="The letter a" b="The letter b" class="myclass" id="myid">This is my title</div>', source end def test_splat_with_class_merging source = %q{ #myid.myclass *{class: [:secondclass, %w(x y z)]} *hash This is my title } assert_html '<div a="The letter a" b="The letter b" class="myclass secondclass x y z" id="myid">This is my title</div>', source end def test_splat_with_boolean_attribute source = %q{ *{disabled: true, empty1: false, nonempty: '', empty2: nil} This is my title } assert_html '<div disabled="" nonempty="">This is my title</div>', source end def test_splat_merging_with_arrays source = %q{ *{a: 1, b: 2} *[[:c, 3], [:d, 4]] *[[:e, 5], [:f, 6]] This is my title } assert_html '<div a="1" b="2" c="3" d="4" e="5" f="6">This is my title</div>', source end def test_splat_with_other_attributes source = %q{ h1 data-id="123" *hash This is my title } assert_html '<h1 a="The letter a" b="The letter b" data-id="123">This is my title</h1>', source end def test_attribute_merging source = %q{ a class=true class=false a class=false *{class:true} a class=true a class=false } assert_html '<a class="true false"></a><a class="false true"></a><a class="true"></a><a class="false"></a>', source end def test_static_empty_attribute source = %q{ p(id="marvin" name="" class="" data-info="Illudium Q-36")= output_number } assert_html '<p data-info="Illudium Q-36" id="marvin" name="">1337</p>', source end def test_dynamic_empty_attribute source = %q{ p(id="marvin" class=nil nonempty=("".to_s) data-info="Illudium Q-36")= output_number } assert_html '<p data-info="Illudium Q-36" id="marvin" nonempty="">1337</p>', source end def test_weird_attribute source = %q{ p img(src='img.png' whatsthis?!) img src='img.png' whatsthis?!="wtf" } assert_html '<p><img src="img.png" whatsthis?!="" /><img src="img.png" whatsthis?!="wtf" /></p>', source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_pretty.rb
test/core/test_pretty.rb
require 'helper' class TestSlimPretty < TestSlim def setup super Slim::Engine.set_options pretty: true end def teardown Slim::Engine.set_options pretty: false end def test_pretty source = %q{ doctype 5 html head title Hello World! /! Meta tags with long explanatory multiline comment meta name="description" content="template language" /! Stylesheets link href="style.css" media="screen" rel="stylesheet" type="text/css" link href="colors.css" media="screen" rel="stylesheet" type="text/css" /! Javascripts script src="jquery.js" script src="jquery.ui.js" /[if lt IE 9] script src="old-ie1.js" script src="old-ie2.js" css: body { background-color: red; } body #container p Hello World! p= "dynamic text with\nnewline" } result = %q{<!DOCTYPE html> <html> <head> <title>Hello World!</title><!--Meta tags with long explanatory multiline comment--> <meta content="template language" name="description" /> <!--Stylesheets--> <link href="style.css" media="screen" rel="stylesheet" type="text/css" /> <link href="colors.css" media="screen" rel="stylesheet" type="text/css" /> <!--Javascripts--> <script src="jquery.js"></script> <script src="jquery.ui.js"></script> <!--[if lt IE 9]> <script src="old-ie1.js"></script> <script src="old-ie2.js"></script> <![endif]--> <style> body { background-color: red; } </style> </head> <body> <div id="container"> <p> Hello World! </p> <p> dynamic text with newline </p> </div> </body> </html>} assert_html result, source end def test_partials body = %q{body == render content} content = %q{div | content} source = %q{html == render body, scope: self, locals: { content: content }} result = %q{<html> <body> <div> content </div> </body> </html>} assert_html result, source, scope: self, locals: {body: body, content: content } end def test_correct_line_number source = %q{ html head body p Slim = '' = '' = '' = unknown_ruby_method } assert_ruby_error NameError,"(__TEMPLATE__):9", source end def test_unindenting source = %q{ span before span = " middle " span after } result = %q{<span>before</span><span> middle </span><span>after</span>} assert_html result, source source = %q{ html body == " <div>\n <a>link</a>\n </div>" } result = %q{<html> <body> <div> <a>link</a> </div> </body> </html>} assert_html result, source end def test_helper_unindent source = %q{ = define_macro :content div a link html body == call_macro :content } result = %q{ <html> <body> <div> <a>link</a> </div> </body> </html>} assert_html result, source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_splat_prefix_option.rb
test/core/test_splat_prefix_option.rb
require 'helper' class TestSplatPrefixOption < TestSlim def prefixes ['*','**','*!','*%','*^','*$'] end def options(prefix) { splat_prefix: prefix } end def test_splat_without_content prefixes.each do |prefix| source = %Q{ #{prefix}hash p#{prefix}hash } assert_html '<div a="The letter a" b="The letter b"></div><p a="The letter a" b="The letter b"></p>', source, options(prefix) end end def test_shortcut_splat prefixes.each do |prefix| source = %Q{ #{prefix}hash This is my title } assert_html '<div a="The letter a" b="The letter b">This is my title</div>', source, options(prefix) end end def test_splat prefixes.each do |prefix| source = %Q{ h1 #{prefix}hash class=[] This is my title } assert_html '<h1 a="The letter a" b="The letter b">This is my title</h1>', source, options(prefix) end end def test_closed_splat prefixes.each do |prefix| source = %Q{ #{prefix}hash / } assert_html '<div a="The letter a" b="The letter b" />', source, options(prefix) end end def test_splat_tag_name prefixes.each do |prefix| source = %Q{ #{prefix}{tag: 'h1', id: 'title'} This is my title } assert_html '<h1 id="title">This is my title</h1>', source, options(prefix) end end def test_splat_empty_tag_name prefixes.each do |prefix| source = %Q{ #{prefix}{tag: '', id: 'test'} This is my title } assert_html '<div id="test">This is my title</div>', source, options(prefix) end end def test_closed_splat_tag prefixes.each do |prefix| source = %Q{ #{prefix}hash / } assert_html '<div a="The letter a" b="The letter b" />', source, options(prefix) end end def test_splat_with_id_shortcut prefixes.each do |prefix| source = %Q{ #myid#{prefix}hash This is my title } assert_html '<div a="The letter a" b="The letter b" id="myid">This is my title</div>', source, options(prefix) end end def test_splat_with_class_shortcut prefixes.each do |prefix| source = %Q{ .myclass#{prefix}hash This is my title } assert_html '<div a="The letter a" b="The letter b" class="myclass">This is my title</div>', source, options(prefix) end end def test_splat_with_id_and_class_shortcuts prefixes.each do |prefix| source = %Q{ #myid.myclass#{prefix}hash This is my title } assert_html '<div a="The letter a" b="The letter b" class="myclass" id="myid">This is my title</div>', source, options(prefix) end end def test_splat_with_class_merging prefixes.each do |prefix| source = %Q{ #myid.myclass #{prefix}{class: [:secondclass, %w(x y z)]} #{prefix}hash This is my title } assert_html '<div a="The letter a" b="The letter b" class="myclass secondclass x y z" id="myid">This is my title</div>', source, options(prefix) end end def test_splat_with_boolean_attribute prefixes.each do |prefix| source = %Q{ #{prefix}{disabled: true, empty1: false, nonempty: '', empty2: nil} This is my title } assert_html '<div disabled="" nonempty="">This is my title</div>', source, options(prefix) end end def test_splat_merging_with_arrays prefixes.each do |prefix| source = %Q{ #{prefix}{a: 1, b: 2} #{prefix}[[:c, 3], [:d, 4]] #{prefix}[[:e, 5], [:f, 6]] This is my title } assert_html '<div a="1" b="2" c="3" d="4" e="5" f="6">This is my title</div>', source, options(prefix) end end def test_splat_with_other_attributes prefixes.each do |prefix| source = %Q{ h1 data-id="123" #{prefix}hash This is my title } assert_html '<h1 a="The letter a" b="The letter b" data-id="123">This is my title</h1>', source, options(prefix) end end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_code_evaluation.rb
test/core/test_code_evaluation.rb
require 'helper' class TestSlimCodeEvaluation < TestSlim def test_render_with_call_to_set_attributes source = %q{ p id="#{id_helper}" class="hello world" = hello_world } assert_html '<p class="hello world" id="notice">Hello World from @env</p>', source end def test_render_with_call_to_set_custom_attributes source = %q{ p data-id="#{id_helper}" data-class="hello world" = hello_world } assert_html '<p data-class="hello world" data-id="notice">Hello World from @env</p>', source end def test_render_with_call_to_set_attributes_and_call_to_set_content source = %q{ p id="#{id_helper}" class="hello world" = hello_world } assert_html '<p class="hello world" id="notice">Hello World from @env</p>', source end def test_render_with_parameterized_call_to_set_attributes_and_call_to_set_content source = %q{ p id="#{id_helper}" class="hello world" = hello_world("Hello Ruby!") } assert_html '<p class="hello world" id="notice">Hello Ruby!</p>', source end def test_render_with_spaced_parameterized_call_to_set_attributes_and_call_to_set_content source = %q{ p id="#{id_helper}" class="hello world" = hello_world "Hello Ruby!" } assert_html '<p class="hello world" id="notice">Hello Ruby!</p>', source end def test_render_with_spaced_parameterized_call_to_set_attributes_and_call_to_set_content_2 source = %q{ p id="#{id_helper}" class="hello world" = hello_world "Hello Ruby!", dummy: "value" } assert_html '<p class="hello world" id="notice">Hello Ruby!dummy value</p>', source end def test_hash_call_in_attribute source = %q{ p id="#{hash[:a]}" Test it } assert_html '<p id="The letter a">Test it</p>', source end def test_instance_variable_in_attribute_without_quotes source = %q{ p id=@var } assert_html '<p id="instance"></p>', source end def test_method_call_in_attribute_without_quotes source = %q{ form action=action_path(:page, :save) method='post' } assert_html '<form action="/action-page-save" method="post"></form>', source end def test_ruby_attribute_with_unbalanced_delimiters source = %q{ div crazy=action_path('[') id="crazy_delimiters" } assert_html '<div crazy="/action-[" id="crazy_delimiters"></div>', source end def test_method_call_in_delimited_attribute_without_quotes source = %q{ form(action=action_path(:page, :save) method='post') } assert_html '<form action="/action-page-save" method="post"></form>', source end def test_method_call_in_delimited_attribute_without_quotes2 source = %q{ form(method='post' action=action_path(:page, :save)) } assert_html '<form action="/action-page-save" method="post"></form>', source end def test_hash_call_in_attribute_without_quotes source = %q{ p id=hash[:a] Test it } assert_html '<p id="The letter a">Test it</p>', source end def test_hash_call_in_delimited_attribute source = %q{ p(id=hash[:a]) Test it } assert_html '<p id="The letter a">Test it</p>', source end def test_hash_call_in_attribute_with_ruby_evaluation source = %q{ p id=(hash[:a] + hash[:a]) Test it } assert_html '<p id="The letter aThe letter a">Test it</p>', source end def test_hash_call_in_delimited_attribute_with_ruby_evaluation source = %q{ p(id=(hash[:a] + hash[:a])) Test it } assert_html '<p id="The letter aThe letter a">Test it</p>', source end def test_hash_call_in_delimited_attribute_with_ruby_evaluation_2 source = %q{ p[id=(hash[:a] + hash[:a])] Test it } assert_html '<p id="The letter aThe letter a">Test it</p>', source end def test_hash_call_in_delimited_attribute_with_ruby_evaluation_3 source = %q{ p(id=(hash[:a] + hash[:a]) class=hash[:a]) Test it } assert_html '<p class="The letter a" id="The letter aThe letter a">Test it</p>', source end def test_hash_call_in_delimited_attribute_with_ruby_evaluation_4_ source = %q{ p(id=hash[:a] class=hash[:a]) Test it } assert_html '<p class="The letter a" id="The letter a">Test it</p>', source end def test_computation_in_attribute source = %q{ p id=(1 + 1)*5 Test it } assert_html '<p id="10">Test it</p>', source end def test_code_attribute_does_not_modify_argument require 'ostruct' template = 'span class=attribute' model = OpenStruct.new(attribute: [:a, :b, [:c, :d]]) output = Slim::Template.new { template }.render(model) assert_equal('<span class="a b c d"></span>', output) assert_equal([:a, :b, [:c, :d]], model.attribute) end def test_number_type_interpolation source = %q{ p = output_number } assert_html '<p>1337</p>', source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/helper.rb
test/core/helper.rb
begin require 'simplecov' SimpleCov.start rescue LoadError end require 'minitest/autorun' require 'slim' require 'slim/grammar' Slim::Engine.after Slim::Parser, Temple::Filters::Validator, grammar: Slim::Grammar Slim::Engine.before :Pretty, Temple::Filters::Validator class TestSlim < Minitest::Test def setup @env = Env.new end def render(source, options = {}, &block) scope = options.delete(:scope) locals = options.delete(:locals) Slim::Template.new(options[:file], options) { source }.render(scope || @env, locals, &block) end class HtmlSafeString < String def html_safe? true end def to_s self end end def with_html_safe String.send(:define_method, :html_safe?) { false } String.send(:define_method, :html_safe) { HtmlSafeString.new(self) } yield ensure String.send(:undef_method, :html_safe?) if String.method_defined?(:html_safe?) String.send(:undef_method, :html_safe) if String.method_defined?(:html_safe) end def assert_html(expected, source, options = {}, &block) assert_equal expected, render(source, options, &block) end def assert_syntax_error(message, source, options = {}) render(source, options) raise 'Syntax error expected' rescue Slim::Parser::SyntaxError => ex assert_equal message, ex.message message =~ /([^\s]+), Line (\d+)/ assert_backtrace ex, "#{$1}:#{$2}" end def assert_ruby_error(error, from, source, options = {}) render(source, options) raise 'Ruby error expected' rescue error => ex assert_backtrace(ex, from) end def assert_backtrace(ex, from) ex.backtrace[0] =~ /([^\s]+:\d+)/ assert_equal from, $1 end def assert_ruby_syntax_error(from, source, options = {}) render(source, options) raise 'Ruby syntax error expected' rescue SyntaxError => ex ex.message =~ /([^\s]+:\d+):/ assert_equal from, $1 end def assert_runtime_error(message, source, options = {}) render(source, options) raise Exception, 'Runtime error expected' rescue RuntimeError => ex assert_equal message, ex.message end end class Env attr_reader :var, :x def initialize @var = 'instance' @x = 0 end def id_helper "notice" end def hash {a: 'The letter a', b: 'The letter b'} end def show_first?(show = false) show end def define_macro(name, &block) @macro ||= {} @macro[name.to_s] = block '' end def call_macro(name, *args) @macro[name.to_s].call(*args) end def hello_world(text = "Hello World from @env", opts = {}) text = text + (opts.to_a * " ") if opts.any? if block_given? "#{text} #{yield} #{text}" else text end end def message(*args) args.join(' ') end def action_path(*args) "/action-#{args.join('-')}" end def in_keyword "starts with keyword" end def evil_method "<script>do_something_evil();</script>" end def output_number 1337 end def succ_x @x = @x.succ end end class ViewEnv def output_number 1337 end def person [{name: 'Joe'}, {name: 'Jack'}] end def people %w(Andy Fred Daniel).collect{|n| Person.new(n)} end def cities %w{Atlanta Melbourne Karlsruhe} end def people_with_locations array = [] people.each_with_index do |p,i| p.location = Location.new cities[i] array << p end array end end require 'forwardable' class Person extend Forwardable attr_accessor :name def initialize(name) @name = name end def location=(location) @location = location end def_delegators :@location, :city end class Location attr_accessor :city def initialize(city) @city = city end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_parser_errors.rb
test/core/test_parser_errors.rb
require 'helper' class TestParserErrors < TestSlim def test_correct_filename source = %q{ doctype 5 div Invalid } assert_syntax_error "Unexpected indentation\n test.slim, Line 3, Column 2\n div Invalid\n ^\n", source, file: 'test.slim' end def test_unexpected_indentation source = %q{ doctype 5 div Invalid } assert_syntax_error "Unexpected indentation\n (__TEMPLATE__), Line 3, Column 2\n div Invalid\n ^\n", source end def test_malformed_indentation source = %q{ p div Valid div Invalid } assert_syntax_error "Malformed indentation\n (__TEMPLATE__), Line 4, Column 1\n div Invalid\n ^\n", source end def test_malformed_indentation2 source = %q{ div Valid div Invalid } assert_syntax_error "Malformed indentation\n (__TEMPLATE__), Line 3, Column 1\n div Invalid\n ^\n", source end def test_unknown_line_indicator source = %q{ p div Valid .valid #valid ?invalid } assert_syntax_error "Unknown line indicator\n (__TEMPLATE__), Line 6, Column 2\n ?invalid\n ^\n", source end def test_expected_closing_delimiter source = %q{ p img(src="img.jpg" title={title} } assert_syntax_error "Expected closing delimiter )\n (__TEMPLATE__), Line 3, Column 33\n img(src=\"img.jpg\" title={title}\n ^\n", source end def test_missing_quote_unexpected_end source = %q{ p img(src="img.jpg } assert_syntax_error "Unexpected end of file\n (__TEMPLATE__), Line 3, Column 0\n \n ^\n", source end def test_expected_closing_attribute_delimiter source = %q{ p img src=[hash[1] + hash[2] } assert_syntax_error "Expected closing delimiter ]\n (__TEMPLATE__), Line 3, Column 28\n img src=[hash[1] + hash[2]\n ^\n", source end def test_invalid_empty_attribute source = %q{ p img{src= } } assert_syntax_error "Invalid empty attribute\n (__TEMPLATE__), Line 3, Column 11\n img{src= }\n ^\n", source end def test_invalid_empty_attribute2 source = %q{ p img{src=} } assert_syntax_error "Invalid empty attribute\n (__TEMPLATE__), Line 3, Column 10\n img{src=}\n ^\n", source end def test_invalid_empty_attribute3 source = %q{ p img src= } assert_syntax_error "Invalid empty attribute\n (__TEMPLATE__), Line 3, Column 10\n img src=\n ^\n", source end def test_missing_tag_in_block_expansion source = %{ html: body: } assert_syntax_error "Expected tag\n (__TEMPLATE__), Line 2, Column 11\n html: body:\n ^\n", source end def test_invalid_tag_in_block_expansion source = %{ html: body: /comment } assert_syntax_error "Expected tag\n (__TEMPLATE__), Line 2, Column 12\n html: body: /comment\n ^\n", source source = %{ html: body:/comment } assert_syntax_error "Expected tag\n (__TEMPLATE__), Line 2, Column 11\n html: body:/comment\n ^\n", source end def test_unexpected_text_after_closed source = %{ img / text } assert_syntax_error "Unexpected text after closed tag\n (__TEMPLATE__), Line 2, Column 6\n img / text\n ^\n", source end def test_illegal_shortcuts source = %{ .#test } assert_syntax_error "Illegal shortcut\n (__TEMPLATE__), Line 2, Column 0\n .#test\n ^\n", source source = %{ div.#test } assert_syntax_error "Illegal shortcut\n (__TEMPLATE__), Line 2, Column 3\n div.#test\n ^\n", source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_unicode.rb
test/core/test_unicode.rb
require 'helper' class TestSlimUnicode < TestSlim def test_unicode_tags source = "Статья года" result = "<Статья>года</Статья>" assert_html result, source end def test_unicode_attrs source = "Статья года=123 content" result = "<Статья года=\"123\">content</Статья>" assert_html result, source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_embedded_engines.rb
test/core/test_embedded_engines.rb
require 'helper' require 'erb' class TestSlimEmbeddedEngines < TestSlim def test_render_with_markdown source = %q{ markdown: #Header Hello from #{"Markdown!"} #{1+2} [#{1}](#{"#2"}) * one * two } if ::Tilt['md'].name =~ /Redcarpet/ # redcarpet assert_html "<h1>Header</h1>\n\n<p>Hello from Markdown!</p>\n\n<p>3</p>\n\n<p><a href=\"#2\">1</a></p>\n\n<ul>\n<li>one</li>\n<li>two</li>\n</ul>\n", source elsif ::Tilt['md'].name =~ /RDiscount/ # rdiscount assert_html "<h1>Header</h1>\n\n<p>Hello from Markdown!</p>\n\n<p>3</p>\n\n<p><a href=\"#2\">1</a></p>\n\n<ul>\n<li>one</li>\n<li>two</li>\n</ul>\n\n", source else # kramdown, :auto_ids by default assert_html "<h1 id=\"header\">Header</h1>\n<p>Hello from Markdown!</p>\n\n<p>3</p>\n\n<p><a href=\"#2\">1</a></p>\n\n<ul>\n <li>one</li>\n <li>two</li>\n</ul>\n", source Slim::Embedded.with_options(markdown: {auto_ids: false}) do assert_html "<h1>Header</h1>\n<p>Hello from Markdown!</p>\n\n<p>3</p>\n\n<p><a href=\"#2\">1</a></p>\n\n<ul>\n <li>one</li>\n <li>two</li>\n</ul>\n", source end assert_html "<h1 id=\"header\">Header</h1>\n<p>Hello from Markdown!</p>\n\n<p>3</p>\n\n<p><a href=\"#2\">1</a></p>\n\n<ul>\n <li>one</li>\n <li>two</li>\n</ul>\n", source end end def test_render_with_css source = %q{ css: h1 { color: blue } } assert_html "<style>h1 { color: blue }</style>", source end def test_render_with_css_empty_attributes source = %q{ css []: h1 { color: blue } } assert_html "<style>h1 { color: blue }</style>", source end def test_render_with_css_attribute source = %q{ css scoped = "true": h1 { color: blue } } assert_html "<style scoped=\"true\">h1 { color: blue }</style>", source end def test_render_with_css_multiple_attributes source = %q{ css class="myClass" scoped = "true" : h1 { color: blue } } assert_html "<style class=\"myClass\" scoped=\"true\">h1 { color: blue }</style>", source end def test_render_with_javascript source = %q{ javascript: $(function() {}); alert('hello') p Hi } assert_html %{<script>$(function() {});\n\n\nalert('hello')</script><p>Hi</p>}, source end def test_render_with_javascript_empty_attributes source = %q{ javascript (): alert('hello') } assert_html %{<script>alert('hello')</script>}, source end def test_render_with_javascript_attribute source = %q{ javascript [class = "myClass"]: alert('hello') } assert_html %{<script class=\"myClass\">alert('hello')</script>}, source end def test_render_with_javascript_multiple_attributes source = %q{ javascript { class = "myClass" id="myId" other-attribute = 'my_other_attribute' } : alert('hello') } assert_html %{<script class=\"myClass\" id=\"myId\" other-attribute=\"my_other_attribute\">alert('hello')</script>}, source end def test_render_with_javascript_with_tabs source = "javascript:\n\t$(function() {});\n\talert('hello')\np Hi" assert_html "<script>$(function() {});\nalert('hello')</script><p>Hi</p>", source end def test_render_with_javascript_including_variable source = %q{ - func = "alert('hello');" javascript: $(function() { #{func} }); } assert_html %q|<script>$(function() { alert(&#39;hello&#39;); });</script>|, source end def test_render_with_javascript_with_explicit_html_comment Slim::Engine.with_options(js_wrapper: :comment) do source = "javascript:\n\t$(function() {});\n\talert('hello')\np Hi" assert_html "<script><!--\n$(function() {});\nalert('hello')\n//--></script><p>Hi</p>", source end end def test_render_with_javascript_with_explicit_cdata_comment Slim::Engine.with_options(js_wrapper: :cdata) do source = "javascript:\n\t$(function() {});\n\talert('hello')\np Hi" assert_html "<script>\n//<![CDATA[\n$(function() {});\nalert('hello')\n//]]>\n</script><p>Hi</p>", source end end def test_render_with_javascript_with_format_xhtml_comment Slim::Engine.with_options(js_wrapper: :guess, format: :xhtml) do source = "javascript:\n\t$(function() {});\n\talert('hello')\np Hi" assert_html "<script>\n//<![CDATA[\n$(function() {});\nalert('hello')\n//]]>\n</script><p>Hi</p>", source end end def test_render_with_javascript_with_format_html_comment Slim::Engine.with_options(js_wrapper: :guess, format: :html) do source = "javascript:\n\t$(function() {});\n\talert('hello')\np Hi" assert_html "<script><!--\n$(function() {});\nalert('hello')\n//--></script><p>Hi</p>", source end end def test_render_with_ruby source = %q{ ruby: variable = 1 + 2 = variable } assert_html '3', source end def test_render_with_ruby_heredoc source = %q{ ruby: variable = <<-MSG foobar MSG = variable } assert_html "foobar\n", source end # TODO: Reactivate sass tests if false def test_render_with_scss source = %q{ scss: $color: #f00; body { color: $color; } } assert_html "<style>body{color:red}</style>", source end def test_render_with_scss_attribute source = %q{ scss [class="myClass"]: $color: #f00; body { color: $color; } } assert_html "<style class=\"myClass\">body{color:red}</style>", source end def test_render_with_sass source = %q{ sass: $color: #f00 body color: $color } assert_html "<style>body{color:red}</style>", source end def test_render_with_sass_attribute source = %q{ sass [class="myClass"]: $color: #f00 body color: $color } assert_html "<style class=\"myClass\">body{color:red}</style>", source end end def test_disabled_embedded_engine source = %{ ruby: Embedded Ruby } assert_runtime_error 'Embedded engine ruby is disabled', source, enable_engines: [:javascript] assert_runtime_error 'Embedded engine ruby is disabled', source, enable_engines: %w(javascript) source = %{ ruby: Embedded Ruby } assert_runtime_error 'Embedded engine ruby is disabled', source, enable_engines: [:javascript] assert_runtime_error 'Embedded engine ruby is disabled', source, enable_engines: %w(javascript) source = %{ ruby: Embedded Ruby } assert_runtime_error 'Embedded engine ruby is disabled', source, disable_engines: [:ruby] assert_runtime_error 'Embedded engine ruby is disabled', source, disable_engines: %w(ruby) end def test_enabled_embedded_engine source = %q{ javascript: $(function() {}); } assert_html '<script>$(function() {});</script>', source, disable_engines: [:ruby] assert_html '<script>$(function() {});</script>', source, disable_engines: %w(ruby) source = %q{ javascript: $(function() {}); } assert_html '<script>$(function() {});</script>', source, enable_engines: [:javascript] assert_html '<script>$(function() {});</script>', source, enable_engines: %w(javascript) end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_code_escaping.rb
test/core/test_code_escaping.rb
require 'helper' class TestSlimCodeEscaping < TestSlim def test_escaping_evil_method source = %q{ p = evil_method } assert_html '<p>&lt;script&gt;do_something_evil();&lt;/script&gt;</p>', source end def test_render_without_html_safe source = %q{ p = "<strong>Hello World\\n, meet \\"Slim\\"</strong>." } assert_html "<p>&lt;strong&gt;Hello World\n, meet \&quot;Slim\&quot;&lt;/strong&gt;.</p>", source end def test_render_without_html_safe2 source = %q{ p = "<strong>Hello World\\n, meet 'Slim'</strong>." } assert_html "<p>&lt;strong&gt;Hello World\n, meet &#39;Slim&#39;&lt;/strong&gt;.</p>", source end def test_render_with_html_safe_false source = %q{ p = "<strong>Hello World\\n, meet \\"Slim\\"</strong>." } with_html_safe do assert_html "<p>&lt;strong&gt;Hello World\n, meet \&quot;Slim\&quot;&lt;/strong&gt;.</p>", source, use_html_safe: true end end def test_render_with_html_safe_true source = %q{ p = "<strong>Hello World\\n, meet \\"Slim\\"</strong>.".html_safe } with_html_safe do assert_html "<p><strong>Hello World\n, meet \"Slim\"</strong>.</p>", source, use_html_safe: true end end def test_render_splat_with_html_safe_true source = %q{ p *{ title: '&amp;'.html_safe } } with_html_safe do assert_html "<p title=\"&amp;\"></p>", source, use_html_safe: true end end def test_render_splat_with_html_safe_false source = %q{ p *{ title: '&' } } with_html_safe do assert_html "<p title=\"&amp;\"></p>", source, use_html_safe: true end end def test_render_splat_injecting_evil_attr_name source = %q{ p *{ "><script>alert(1)</script><p title" => 'test' } } with_html_safe do assert_raises Slim::InvalidAttributeNameError do render(source, use_html_safe: true) end end end def test_render_attribute_with_html_safe_true source = %q{ p title=('&amp;'.html_safe) } with_html_safe do assert_html "<p title=\"&amp;\"></p>", source, use_html_safe: true end end def test_render_with_disable_escape_false source = %q{ = "<p>Hello</p>" == "<p>World</p>" } assert_html "&lt;p&gt;Hello&lt;/p&gt;<p>World</p>", source end def test_render_with_disable_escape_true source = %q{ = "<p>Hello</p>" == "<p>World</p>" } assert_html "<p>Hello</p><p>World</p>", source, disable_escape: true end def test_escaping_evil_method_with_pretty source = %q{ p = evil_method } assert_html "<p>\n &lt;script&gt;do_something_evil();&lt;/script&gt;\n</p>", source, pretty: true end def test_render_without_html_safe_with_pretty source = %q{ p = "<strong>Hello World\\n, meet \\"Slim\\"</strong>." } assert_html "<p>\n &lt;strong&gt;Hello World\n , meet \&quot;Slim\&quot;&lt;/strong&gt;.\n</p>", source, pretty: true end def test_render_with_html_safe_false_with_pretty source = %q{ p = "<strong>Hello World\\n, meet \\"Slim\\"</strong>." } with_html_safe do assert_html "<p>\n &lt;strong&gt;Hello World\n , meet \&quot;Slim\&quot;&lt;/strong&gt;.\n</p>", source, use_html_safe: true, pretty: true end end def test_render_with_html_safe_true_with_pretty source = %q{ p = "<strong>Hello World\\n, meet \\"Slim\\"</strong>.".html_safe } with_html_safe do assert_html "<p>\n <strong>Hello World\n , meet \"Slim\"</strong>.\n</p>", source, use_html_safe: true, pretty: true end end def test_render_with_disable_escape_false_with_pretty source = %q{ = "<p>Hello</p>" == "<p>World</p>" } assert_html "&lt;p&gt;Hello&lt;/p&gt;<p>World</p>", source, pretty: true end def test_render_with_disable_escape_true_with_pretty source = %q{ = "<p>Hello</p>" == "<p>World</p>" } assert_html "<p>Hello</p><p>World</p>", source, disable_escape: true, pretty: true end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_html_escaping.rb
test/core/test_html_escaping.rb
require 'helper' class TestSlimHtmlEscaping < TestSlim def test_html_will_not_be_escaped source = %q{ p <Hello> World, meet "Slim". } assert_html '<p><Hello> World, meet "Slim".</p>', source end def test_html_with_newline_will_not_be_escaped source = %q{ p | <Hello> World, meet "Slim". } assert_html "<p><Hello> World,\n meet \"Slim\".</p>", source end def test_html_with_escaped_interpolation source = %q{ - x = '"' - content = '<x>' p class="#{x}" test #{content} } assert_html '<p class="&quot;">test &lt;x&gt;</p>', source end def test_html_nested_escaping source = %q{ = hello_world do | escaped & } assert_html 'Hello World from @env escaped &amp; Hello World from @env', source end def test_html_quoted_attr_escape source = %q{ p id="&" class=="&amp;" } assert_html '<p class="&amp;" id="&amp;"></p>', source end def test_html_quoted_attr_escape_with_interpolation source = %q{ p id="&#{'"'}" class=="&amp;#{'"'}" p id="&#{{'"'}}" class=="&amp;#{{'"'}}" } assert_html '<p class="&amp;&quot;" id="&amp;&quot;"></p><p class="&amp;"" id="&amp;""></p>', source end def test_html_ruby_attr_escape source = %q{ p id=('&'.to_s) class==('&amp;'.to_s) } assert_html '<p class="&amp;" id="&amp;"></p>', source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/core/test_encoding.rb
test/core/test_encoding.rb
require 'helper' class TestSlimEncoding < TestSlim def test_windows_crlf source = "a href='#' something\r\nbr\r\na href='#' others\r\n" result = "<a href=\"#\">something</a><br /><a href=\"#\">others</a>" assert_html result, source end def test_binary source = "| \xFF\xFF".dup source.force_encoding(Encoding::BINARY) result = "\xFF\xFF".dup result.force_encoding(Encoding::BINARY) out = render(source, default_encoding: 'binary') out.force_encoding(Encoding::BINARY) assert_equal result, out end def test_bom source = "\xEF\xBB\xBFh1 Hello World!" result = '<h1>Hello World!</h1>' assert_html result, source end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/test/logic_less/test_logic_less.rb
test/logic_less/test_logic_less.rb
require 'helper' require 'slim/logic_less' class TestSlimLogicLess < TestSlim class Scope def initialize @hash = { person: [ { name: 'Joe', age: 1, selected: true }, { name: 'Jack', age: 2 } ] } end end def test_lambda source = %q{ p == person .name = name == simple .hello= hello == list li = key } hash = { hello: 'Hello!', person: lambda do |&block| %w(Joe Jack).map do |name| "<b>#{block.call(name: name)}</b>" end.join end, simple: lambda do |&block| "<div class=\"simple\">#{block.call}</div>" end, list: lambda do |&block| list = [{key: 'First'}, {key: 'Second'}] "<ul>#{block.call(*list)}</ul>" end } assert_html '<p><b><div class="name">Joe</div></b><b><div class="name">Jack</div></b><div class="simple"><div class="hello">Hello!</div></div><ul><li>First</li><li>Second</li></ul></p>', source, scope: hash end def test_symbol_hash source = %q{ p - person .name = name } hash = { person: [ { name: 'Joe', }, { name: 'Jack', } ] } assert_html '<p><div class="name">Joe</div><div class="name">Jack</div></p>', source, scope: hash end def test_string_access source = %q{ p - person .name = name } hash = { 'person' => [ { 'name' => 'Joe', }, { 'name' => 'Jack', } ] } assert_html '<p><div class="name">Joe</div><div class="name">Jack</div></p>', source, scope: hash, dictionary_access: :string end def test_symbol_access source = %q{ p - person .name = name } hash = { person: [ { name: 'Joe', }, { name: 'Jack', } ] } assert_html '<p><div class="name">Joe</div><div class="name">Jack</div></p>', source, scope: hash, dictionary_access: :symbol end def test_method_access source = %q{ p - person .name = name } object = Object.new def object.person %w(Joe Jack).map do |name| person = Object.new person.instance_variable_set(:@name, name) def person.name @name end person end end assert_html '<p><div class="name">Joe</div><div class="name">Jack</div></p>', source, scope: object, dictionary_access: :method end def test_method_access_without_private source = %q{ p - person .age = age } object = Object.new def object.person person = Object.new def person.age 42 end person.singleton_class.class_eval { private :age } person end assert_html '<p><div class="age"></div></p>', source, scope: object, dictionary_access: :method end def test_instance_variable_access source = %q{ p - person .name = name } object = Object.new object.instance_variable_set(:@person, %w(Joe Jack).map do |name| person = Object.new person.instance_variable_set(:@name, name) person end) assert_html '<p><div class="name">Joe</div><div class="name">Jack</div></p>', source, scope: object, dictionary_access: :instance_variable end def test_to_s_access source = %q{ p - people .name = self } hash = { people: [ 'Joe', 'Jack' ] } assert_html '<p><div class="name">Joe</div><div class="name">Jack</div></p>', source, scope: hash, dictionary_access: :symbol end def test_string_hash source = %q{ p - person .name = name } hash = { 'person' => [ { 'name' => 'Joe', }, { 'name' => 'Jack', } ] } assert_html '<p><div class="name">Joe</div><div class="name">Jack</div></p>', source, scope: hash end def test_dictionary_option source = %q{ p - person .name = name } assert_html '<p><div class="name">Joe</div><div class="name">Jack</div></p>', source, scope: Scope.new, dictionary: '@hash' end def test_flag_section source = %q{ p - show_person - person .name = name - show_person | shown } hash = { show_person: true, person: [ { name: 'Joe', }, { name: 'Jack', } ] } assert_html '<p><div class="name">Joe</div><div class="name">Jack</div>shown</p>', source, scope: hash end def test_inverted_section source = %q{ p - person .name = name -! person | No person - !person | No person 2 } hash = {} assert_html '<p>No person No person 2</p>', source, scope: hash end def test_escaped_interpolation source = %q{ p text with \#{123} test } assert_html '<p>text with #{123} test</p>', source end def test_ruby_attributes source = %q{ p - person b name=name Person a id=name = age span class=name Person } assert_html '<p><b name="Joe">Person</b><a id="Joe">1</a><span class="Joe"><Person></Person></span><b name="Jack">Person</b><a id="Jack">2</a><span class="Jack"><Person></Person></span></p>', source, scope: Scope.new, dictionary: '@hash' end def test_boolean_attributes source = %q{ p - person input checked=selected = name } assert_html '<p><input checked="">Joe</input><input>Jack</input></p>', source, scope: Scope.new, dictionary: '@hash' end def test_sections source = %q{ p - person .name = name } assert_html '<p><div class="name">Joe</div><div class="name">Jack</div></p>', source, dictionary: 'ViewEnv.new' end def test_with_array source = %q{ ul - people_with_locations li = name li = city } assert_html '<ul><li>Andy</li><li>Atlanta</li><li>Fred</li><li>Melbourne</li><li>Daniel</li><li>Karlsruhe</li></ul>', source, dictionary: 'ViewEnv.new' end def test_method source = %q{ a href=output_number Link } assert_html '<a href="1337">Link</a>', source, dictionary: 'ViewEnv.new' end def test_conditional_parent source = %q{ - prev_page li.previous a href=prev_page Older - next_page li.next a href=next_page Newer} assert_html'<li class="previous"><a href="prev">Older</a></li><li class="next"><a href="next">Newer</a></li>', source, scope: {prev_page: 'prev', next_page: 'next'} end def test_empty_conditional source = %q{ - prev_page li.previous a href=prev_page Older - next_page li.next a href=next_page Newer} assert_html'<li class="next"><a href="next">Newer</a></li>', source, scope: {prev_page: '', next_page: 'next'} end def test_render_with_yield source = %q{ div == yield } assert_html '<div>This is the menu</div>', source do 'This is the menu' end end def test_render_parent_lambda source = %q{ - list == fn p = string } assert_html '<fn><p>str</p></fn><fn><p>str</p></fn><fn><p>str</p></fn>', source, scope: { fn: ->(&block) { "<fn>#{block.call}</fn>" }, list: [ "item1", "item2", "item3" ], string: "str" } end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim.rb
lib/slim.rb
# frozen_string_literal: true require 'temple' require 'slim/parser' require 'slim/filter' require 'slim/do_inserter' require 'slim/end_inserter' require 'slim/embedded' require 'slim/interpolation' require 'slim/controls' require 'slim/splat/filter' require 'slim/splat/builder' require 'slim/code_attributes' require 'slim/engine' require 'slim/template' require 'slim/version' require 'slim/railtie' if defined?(Rails::Railtie)
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/command.rb
lib/slim/command.rb
# frozen_string_literal: true require 'slim' require 'optparse' module Slim Engine.set_options pretty: false # Slim commandline interface # @api private class Command def initialize(args) @args = args @options = {} end # Run command def run @opts = OptionParser.new(&method(:set_opts)) @opts.parse!(@args) process end private # Configure OptionParser def set_opts(opts) opts.on('-s', '--stdin', 'Read input from standard input instead of an input file') do @options[:input] = $stdin end opts.on('--trace', 'Show a full traceback on error') do @options[:trace] = true end opts.on('-c', '--compile', 'Compile only but do not run') do @options[:compile] = true end opts.on('-e', '--erb', 'Convert to ERB') do @options[:erb] = true end opts.on('--rails', 'Generate rails compatible code (Implies --compile)') do Engine.set_options disable_capture: true, generator: Temple::Generators::RailsOutputBuffer @options[:compile] = true end opts.on('-r', '--require library', 'Load library or plugin with -r slim/plugin') do |lib| require lib.strip end opts.on('-p', '--pretty', 'Produce pretty html') do Engine.set_options pretty: true end opts.on('-o', '--option name=code', String, 'Set slim option') do |str| parts = str.split('=', 2) Engine.options[parts.first.gsub(/\A:/, '').to_sym] = eval(parts.last) end opts.on('-l', '--locals Hash|YAML|JSON', String, 'Set local variables') do |locals| @options[:locals] = if locals =~ /\A\s*\{\s*\p{Word}+:/ eval(locals) else require 'yaml' YAML.load(locals) end end opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end opts.on_tail('-v', '--version', 'Print version') do puts "Slim #{VERSION}" exit end end # Process command def process args = @args.dup unless @options[:input] file = args.shift if file @options[:file] = file @options[:input] = File.open(file, 'r') else @options[:file] = 'STDIN' @options[:input] = $stdin end end locals = @options.delete(:locals) || {} result = if @options[:erb] require 'slim/erb_converter' ERBConverter.new(file: @options[:file]).call(@options[:input].read) elsif @options[:compile] Engine.new(file: @options[:file]).call(@options[:input].read) else Template.new(@options[:file]) { @options[:input].read }.render(nil, locals) end rescue Exception => ex raise ex if @options[:trace] || SystemExit === ex $stderr.print "#{ex.class}: " if ex.class != RuntimeError $stderr.puts ex.message $stderr.puts ' Use --trace for backtrace.' exit 1 else unless @options[:output] file = args.shift @options[:output] = file ? File.open(file, 'w') : $stdout end @options[:output].puts(result) exit 0 end end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/embedded.rb
lib/slim/embedded.rb
# frozen_string_literal: true module Slim # @api private class TextCollector < Filter def call(exp) @collected = ''.dup super(exp) @collected end def on_slim_interpolate(text) @collected << text nil end end # @api private class NewlineCollector < Filter def call(exp) @collected = [:multi] super(exp) @collected end def on_newline @collected << [:newline] nil end end # @api private class OutputProtector < Filter def call(exp) @protect, @collected, @tag = [], ''.dup, object_id.abs.to_s(36) super(exp) @collected end def on_static(text) @collected << text nil end def on_slim_output(escape, text, content) @collected << "%#{@tag}%#{@protect.length}%" @protect << [:slim, :output, escape, text, content] nil end def unprotect(text) block = [:multi] while text =~ /%#{@tag}%(\d+)%/ block << [:static, $`] block << @protect[$1.to_i] text = $' end block << [:static, text] end end # Temple filter which processes embedded engines # @api private class Embedded < Filter @engines = {} class << self attr_reader :engines # Register embedded engine # # @param [String] name Name of the engine # @param [Class] klass Engine class # @param option_filter List of options to pass to engine. # Last argument can be default option hash. def register(name, klass, *option_filter) name = name.to_sym local_options = option_filter.last.respond_to?(:to_hash) ? option_filter.pop.to_hash : {} define_options(name, *option_filter) klass.define_options(name) engines[name.to_sym] = proc do |options| klass.new({}.update(options).delete_if {|k,v| !option_filter.include?(k) && k != name }.update(local_options)) end end def create(name, options) constructor = engines[name] || raise(Temple::FilterError, "Embedded engine #{name} not found") constructor.call(options) end end define_options :enable_engines, :disable_engines def initialize(opts = {}) super @engines = {} @enabled = normalize_engine_list(options[:enable_engines]) @disabled = normalize_engine_list(options[:disable_engines]) end def on_slim_embedded(name, body, attrs) name = name.to_sym raise(Temple::FilterError, "Embedded engine #{name} is disabled") unless enabled?(name) @engines[name] ||= self.class.create(name, options) @engines[name].on_slim_embedded(name, body, attrs) end def enabled?(name) (!@enabled || @enabled.include?(name)) && (!@disabled || !@disabled.include?(name)) end protected def normalize_engine_list(list) raise(ArgumentError, "Option :enable_engines/:disable_engines must be String or Symbol list") unless !list || Array === list list && list.map(&:to_sym) end class Engine < Filter protected def collect_text(body) @text_collector ||= TextCollector.new @text_collector.call(body) end def collect_newlines(body) @newline_collector ||= NewlineCollector.new @newline_collector.call(body) end end # Basic tilt engine class TiltEngine < Engine def on_slim_embedded(engine, body, attrs) tilt_engine = Tilt[engine] || raise(Temple::FilterError, "Tilt engine #{engine} is not available.") tilt_options = options[engine.to_sym] || {} tilt_options[:default_encoding] ||= 'utf-8' [:multi, tilt_render(tilt_engine, tilt_options, collect_text(body)), collect_newlines(body)] end protected def tilt_render(tilt_engine, tilt_options, text) [:static, tilt_engine.new(tilt_options) { text }.render] end end # Sass engine which supports :pretty option class SassEngine < TiltEngine define_options :pretty protected def tilt_render(tilt_engine, tilt_options, text) text = tilt_engine.new(tilt_options.merge( style: options[:pretty] ? :expanded : :compressed )) { text }.render text = text.chomp [:static, text] end end # Static template with interpolated ruby code class InterpolateTiltEngine < TiltEngine def collect_text(body) output_protector.call(interpolation.call(body)) end def tilt_render(tilt_engine, tilt_options, text) output_protector.unprotect(tilt_engine.new(tilt_options) { text }.render) end private def interpolation @interpolation ||= Interpolation.new end def output_protector @output_protector ||= OutputProtector.new end end # Tag wrapper engine # Generates a html tag and wraps another engine (specified via :engine option) class TagEngine < Engine disable_option_validator! set_options attributes: {} def on_slim_embedded(engine, body, attrs) unless options[:attributes].empty? options[:attributes].map do |k, v| attrs << [:html, :attr, k, [:static, v]] end end if options[:engine] opts = {}.update(options) opts.delete(:engine) opts.delete(:tag) opts.delete(:attributes) @engine ||= options[:engine].new(opts) body = @engine.on_slim_embedded(engine, body, attrs) end [:html, :tag, options[:tag], attrs, body] end end # Javascript wrapper engine. # Like TagEngine, but can wrap content in html comment or cdata. class JavaScriptEngine < TagEngine disable_option_validator! set_options tag: :script def on_slim_embedded(engine, body, attrs) super(engine, [:html, :js, body], attrs) end end # Embeds ruby code class RubyEngine < Engine def on_slim_embedded(engine, body, attrs) [:multi, [:newline], [:code, "#{collect_text(body)}\n"]] end end # These engines are executed at compile time, embedded ruby is interpolated register :markdown, InterpolateTiltEngine register :textile, InterpolateTiltEngine register :rdoc, InterpolateTiltEngine # These engines are executed at compile time register :coffee, JavaScriptEngine, engine: TiltEngine register :sass, TagEngine, :pretty, tag: :style, engine: SassEngine register :scss, TagEngine, :pretty, tag: :style, engine: SassEngine # Embedded javascript/css register :javascript, JavaScriptEngine register :css, TagEngine, tag: :style # Embedded ruby code register :ruby, RubyEngine end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/interpolation.rb
lib/slim/interpolation.rb
# frozen_string_literal: true module Slim # Perform interpolation of #{var_name} in the # expressions `[:slim, :interpolate, string]`. # # @api private class Interpolation < Filter # Handle interpolate expression `[:slim, :interpolate, string]` # # @param [String] string Static interpolate # @return [Array] Compiled temple expression def on_slim_interpolate(string) # Interpolate variables in text (#{variable}). # Split the text into multiple dynamic and static parts. block = [:multi] begin case string when /\A\\#\{/ # Escaped interpolation block << [:static, '#{'] string = $' when /\A#\{((?>[^{}]|(\{(?>[^{}]|\g<1>)*\}))*)\}/ # Interpolation string, code = $', $1 escape = code !~ /\A\{.*\}\Z/ block << [:slim, :output, escape, escape ? code : code[1..-2], [:multi]] when /\A([#\\]?[^#\\]*([#\\][^\\#\{][^#\\]*)*)/ # Static text block << [:static, $&] string = $' end end until string.empty? block end end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/version.rb
lib/slim/version.rb
# frozen_string_literal: true module Slim # Slim version string # @api public VERSION = '5.2.1' end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/include.rb
lib/slim/include.rb
# frozen_string_literal: true require 'slim' module Slim # Handles inlined includes # # Slim files are compiled, non-Slim files are included as text with `#{interpolation}` # # @api private class Include < Slim::Filter define_options :file, include_dirs: [Dir.pwd, '.'] def on_html_tag(tag, attributes, content = nil) return super if tag != 'include' name = content.to_a.flatten.select {|s| String === s }.join raise ArgumentError, 'Invalid include statement' unless attributes == [:html, :attrs] && !name.empty? unless file = find_file(name) name = "#{name}.slim" if name !~ /\.slim\Z/i file = find_file(name) end raise Temple::FilterError, "'#{name}' not found in #{options[:include_dirs].join(':')}" unless file content = File.read(file) if file =~ /\.slim\Z/i Thread.current[:slim_include_engine].call(content) else [:slim, :interpolate, content] end end protected def find_file(name) current_dir = File.dirname(File.expand_path(options[:file])) options[:include_dirs].map {|dir| File.expand_path(File.join(dir, name), current_dir) }.find {|file| File.file?(file) } end end class Engine after Slim::Parser, Slim::Include after Slim::Include, :stop do |exp| throw :stop, exp if Thread.current[:slim_include_level] > 1 exp end # @api private alias call_without_include call # @api private def call(input) Thread.current[:slim_include_engine] = self Thread.current[:slim_include_level] ||= 0 Thread.current[:slim_include_level] += 1 catch(:stop) { call_without_include(input) } ensure Thread.current[:slim_include_engine] = nil if (Thread.current[:slim_include_level] -= 1) == 0 end end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/end_inserter.rb
lib/slim/end_inserter.rb
# frozen_string_literal: true module Slim # In Slim you don't need to close any blocks: # # - if Slim.awesome? # | But of course it is! # # However, the parser is not smart enough (and that's a good thing) to # automatically insert end's where they are needed. Luckily, this filter # does *exactly* that (and it does it well!) # # @api private class EndInserter < Filter IF_RE = /\A(if|begin|unless|else|elsif|when|in|rescue|ensure)\b|\bdo\s*(\|[^\|]*\|)?\s*$/ ELSE_RE = /\A(else|elsif|when|in|rescue|ensure)\b/ END_RE = /\Aend\b/ # Handle multi expression `[:multi, *exps]` # # @return [Array] Corrected Temple expression with ends inserted def on_multi(*exps) result = [:multi] # This variable is true if the previous line was # (1) a control code and (2) contained indented content. prev_indent = false exps.each do |exp| if control?(exp) raise(Temple::FilterError, 'Explicit end statements are forbidden') if exp[2] =~ END_RE # Two control code in a row. If this one is *not* # an else block, we should close the previous one. append_end(result) if prev_indent && exp[2] !~ ELSE_RE # Indent if the control code starts a block. prev_indent = exp[2] =~ IF_RE elsif exp[0] != :newline && prev_indent # This is *not* a control code, so we should close the previous one. # Ignores newlines because they will be inserted after each line. append_end(result) prev_indent = false end result << compile(exp) end # The last line can be a control code too. prev_indent ? append_end(result) : result end private # Appends an end def append_end(result) result << [:code, 'end'] end # Checks if an expression is a Slim control code def control?(exp) exp[0] == :slim && exp[1] == :control end end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/grammar.rb
lib/slim/grammar.rb
# frozen_string_literal: true module Slim # Slim expression grammar # @api private module Grammar extend Temple::Grammar TextTypes << :verbatim | :explicit | :implicit | :inline Expression << [:slim, :control, String, Expression] | [:slim, :output, Bool, String, Expression] | [:slim, :interpolate, String] | [:slim, :embedded, String, Expression, HTMLAttrGroup] | [:slim, :text, TextTypes, Expression] | [:slim, :attrvalue, Bool, String] HTMLAttr << [:slim, :splat, String] HTMLAttrGroup << [:html, :attrs, 'HTMLAttr*'] end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false
slim-template/slim
https://github.com/slim-template/slim/blob/d387587ae364f489b3e23126e204907a0b134bd3/lib/slim/filter.rb
lib/slim/filter.rb
# frozen_string_literal: true module Slim # Base class for Temple filters used in Slim # # This base filter passes everything through and allows # to override only some methods without affecting the rest # of the expression. # # @api private class Filter < Temple::HTML::Filter # Pass-through handler def on_slim_text(type, content) [:slim, :text, type, compile(content)] end # Pass-through handler def on_slim_embedded(type, content, attrs) [:slim, :embedded, type, compile(content), attrs] end # Pass-through handler def on_slim_control(code, content) [:slim, :control, code, compile(content)] end # Pass-through handler def on_slim_output(escape, code, content) [:slim, :output, escape, code, compile(content)] end end end
ruby
MIT
d387587ae364f489b3e23126e204907a0b134bd3
2026-01-04T15:43:07.251246Z
false