code
stringlengths 26
124k
| docstring
stringlengths 23
125k
| func_name
stringlengths 1
98
| language
stringclasses 1
value | repo
stringlengths 5
53
| path
stringlengths 7
151
| url
stringlengths 50
211
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def sign_in_as(user)
view.current_user = user
end | Sets current_user on the view under test to the supplied user. | sign_in_as | ruby | thoughtbot/clearance | lib/clearance/testing/view_helpers.rb | https://github.com/thoughtbot/clearance/blob/master/lib/clearance/testing/view_helpers.rb | MIT |
def remember_token_cookie(session, cookie_name = "remember_token")
cookies = session.send(:cookies)
# see https://stackoverflow.com/a/21315095
set_cookies = cookies.instance_eval <<-RUBY, __FILE__, __LINE__ + 1
@set_cookies
RUBY
set_cookies[cookie_name]
end | a bit of a hack to get the cookies that ActionDispatch sets inside session | remember_token_cookie | ruby | thoughtbot/clearance | spec/clearance/session_spec.rb | https://github.com/thoughtbot/clearance/blob/master/spec/clearance/session_spec.rb | MIT |
def public
head :ok
end | A page that does not require user authentication | public | ruby | thoughtbot/clearance | spec/requests/authentication_cookie_spec.rb | https://github.com/thoughtbot/clearance/blob/master/spec/requests/authentication_cookie_spec.rb | MIT |
def delete_matched(matcher, options = nil)
options = merged_options(options)
pattern = key_matcher(matcher, options)
keys.each { |key| delete(key, options) if key =~ pattern }
end | Delete all entries with keys matching the pattern. | delete_matched | ruby | torquebox/torquebox | caching/lib/active_support/cache/torque_box_store.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/active_support/cache/torque_box_store.rb | Apache-2.0 |
def increment(name, amount = 1, options = nil)
options = merged_options(options)
# Get the current entry
key = namespaced_key(name, options)
current = read_entry(key, options)
value = current.value.to_i
new_entry = Entry.new(value + amount, options)
if cache.compare_and_set(key, current, new_entry)
return new_entry.value
else
raise "Concurrent modification, old value was #{value}"
end
end | Increment an integer value in the cache; return new value | increment | ruby | torquebox/torquebox | caching/lib/active_support/cache/torque_box_store.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/active_support/cache/torque_box_store.rb | Apache-2.0 |
def decrement(name, amount = 1, options = nil)
increment(name, -amount, options)
end | Decrement an integer value in the cache; return new value | decrement | ruby | torquebox/torquebox | caching/lib/active_support/cache/torque_box_store.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/active_support/cache/torque_box_store.rb | Apache-2.0 |
def cleanup(options = nil)
options = merged_options(options)
keys.each do |key|
entry = read_entry(key, options)
delete_entry(key, options) if entry && entry.expired?
end
end | Cleanup the cache by removing expired entries. | cleanup | ruby | torquebox/torquebox | caching/lib/active_support/cache/torque_box_store.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/active_support/cache/torque_box_store.rb | Apache-2.0 |
def write_entry(key, entry, options = {})
options[:unless_exist] ? cache.put_if_absent(key, entry) : cache.put(key, entry)
end | Write an entry to the cache implementation. Subclasses must implement this method. | write_entry | ruby | torquebox/torquebox | caching/lib/active_support/cache/torque_box_store.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/active_support/cache/torque_box_store.rb | Apache-2.0 |
def delete_entry(key, _options) # :nodoc:
cache.remove(key) && true
end | Delete an entry from the cache implementation. Subclasses must implement this method. | delete_entry | ruby | torquebox/torquebox | caching/lib/active_support/cache/torque_box_store.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/active_support/cache/torque_box_store.rb | Apache-2.0 |
def builder(options = {})
config = org.projectodd.wunderboss.caching::Config
config.builder(Options.new(extract_options(options, Caching::CreateOption)))
end | For advanced use, call this function to obtain a "fluent"
{https://docs.jboss.org/infinispan/6.0/apidocs/org/infinispan/configuration/cache/ConfigurationBuilder.html
ConfigurationBuilder}.
Set the desired options, and invoke its build method, the
result from which can be passed via the :configuration option
of the {cache} function.
Note that builder takes the same options as {cache} | builder | ruby | torquebox/torquebox | caching/lib/torquebox/caching.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/torquebox/caching.rb | Apache-2.0 |
def initialize(cache, options = {})
@cache = cache
@options = options
end | Wraps a real Infinispan cache object with a slightly simpler
interface. The wrapped cache is available via the {#cache}
accessor.
@param cache [org.infinispan.Cache] The wrapped cache
@param options [Hash] Options for entry expiration
@option options :ttl [Number] (-1) milliseconds the entry will
live before expiry
@option options :idle [Number] (-1) milliseconds after which an
entry will expire if not accessed | initialize | ruby | torquebox/torquebox | caching/lib/torquebox/caching/cache.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/torquebox/caching/cache.rb | Apache-2.0 |
def put(key, value, options = {})
put_m.call(*[key, value] + expiry(options))
end | Associate key to value in the cache. Expiration options
override any passed to the constructor.
@param key [Object]
@param value [Object]
@param options [Hash] Options for entry expiration
@option options :ttl [Number] (-1) milliseconds the entry will
live before expiry
@option options :idle [Number] (-1) milliseconds after which an
entry will expire if not accessed
@return [Object] the old value, if any | put | ruby | torquebox/torquebox | caching/lib/torquebox/caching/cache.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/torquebox/caching/cache.rb | Apache-2.0 |
def put_all(map, options = {})
putall_m.call(*[map] + expiry(options))
end | Put a map of entries into the cache. Expiration options
override any passed to the constructor.
@param map [Hash]
@param options [Hash] Options for entry expiration
@option options :ttl [Number] (-1) milliseconds the entry will
live before expiry
@option options :idle [Number] (-1) milliseconds after which an
entry will expire if not accessed
@return [void] | put_all | ruby | torquebox/torquebox | caching/lib/torquebox/caching/cache.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/torquebox/caching/cache.rb | Apache-2.0 |
def put_if_absent(key, value, options = {})
putif_m.call(*[key, value] + expiry(options))
end | Associate key to value only if key doesn't exist in cache.
Expiration options override any passed to the constructor.
@param key [Object]
@param value [Object]
@param options [Hash] Options for entry expiration
@option options :ttl [Number] (-1) milliseconds the entry will
live before expiry
@option options :idle [Number] (-1) milliseconds after which an
entry will expire if not accessed
@return [Object] nil on success, otherwise the old value | put_if_absent | ruby | torquebox/torquebox | caching/lib/torquebox/caching/cache.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/torquebox/caching/cache.rb | Apache-2.0 |
def replace(key, value, options = {})
replace_m.call(*[key, value] + expiry(options))
end | Associate key to value only if key exists in cache. Expiration
options override any passed to the constructor.
@param key [Object]
@param value [Object]
@param options [Hash] Options for entry expiration
@option options :ttl [Number] (-1) milliseconds the entry will
live before expiry
@option options :idle [Number] (-1) milliseconds after which an
entry will expire if not accessed
@return [Object] the old value on success, otherwise nil | replace | ruby | torquebox/torquebox | caching/lib/torquebox/caching/cache.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/torquebox/caching/cache.rb | Apache-2.0 |
def compare_and_set(key, old_value, new_value, options = {})
cas_m.call(*[key, old_value, new_value] + expiry(options))
end | Associate key to a new value only if it's currently mapped to
a specific value. Expiration options override any passed to
the constructor.
@param key [Object] the key
@param old_value [Object] the current value of the key
@param new_value [Object] the desired value of the key
@param options [Hash] Options for entry expiration
@option options :ttl [Number] (-1) milliseconds the entry will
live before expiry
@option options :idle [Number] (-1) milliseconds after which an
entry will expire if not accessed
@return [true, false] true if value successfully replaced | compare_and_set | ruby | torquebox/torquebox | caching/lib/torquebox/caching/cache.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/torquebox/caching/cache.rb | Apache-2.0 |
def clear
@cache.clear
self
end | Clear all entries from the cache
@return [void] | clear | ruby | torquebox/torquebox | caching/lib/torquebox/caching/cache.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/torquebox/caching/cache.rb | Apache-2.0 |
def add_listener(*types, &block)
handler = Handler.new(block)
listeners = types.map { |type| Listener::listen(handler, type.to_s) }
listeners.each { |listener| @cache.add_listener(listener) }
end | Infinispan's cache notifications API is based on Java
annotations, which can be awkward in JRuby (and Java, for that
matter).
This function provides the ability to map one or more symbols
to a block that will be passed an
{https://docs.jboss.org/infinispan/6.0/apidocs/org/infinispan/notifications/cachelistener/event/package-summary.html
Infinispan Event} instance.
Each symbol corresponds to an event type, i.e. one of the
{http://docs.jboss.org/infinispan/6.0/apidocs/org/infinispan/notifications/cachelistener/annotation/package-summary.html
Infinispan annotations}:
- :cache_entries_evicted
- :cache_entry_activated
- :cache_entry_created
- :cache_entry_invalidated
- :cache_entry_loaded
- :cache_entry_modified
- :cache_entry_passivated
- :cache_entry_removed
- :cache_entry_visited
- :data_rehashed
- :topology_changed
- :transaction_completed
- :transaction_registered
The callbacks are synchronous, i.e. invoked on the thread acting on
the cache. For longer running callbacks, use a queue or some sort of
asynchronous channel.
The return value is an array of listener objects corresponding
to the requested event types, which will be a subset of those
returned from the {get_listeners} method. These may be passed
to the {remove_listener} method to turn off notifications. | add_listener | ruby | torquebox/torquebox | caching/lib/torquebox/caching/cache.rb | https://github.com/torquebox/torquebox/blob/master/caching/lib/torquebox/caching/cache.rb | Apache-2.0 |
def initialize(name, options = {}, &block)
validate_options(options, DAEMON_OPTIONS)
@name = name.to_s
@on_error_lambda = options.delete(:on_error)
@on_stop_lambda = options.delete(:on_stop)
@action_lambda = block
@options = options
if WunderBoss.find_component(DaemonContext.java_class, @name)
raise "A daemon named #{@name} already exists"
end
@java_daemon =
WunderBoss.find_or_create_component(DaemonContext.java_class,
@name,
extract_options(@options,
DaemonContext::CreateOption))
end | Creates a daemon object.
Optionally takes a block that is the action of the daemon. If
not provided, you must extend this class and override {#action}
if you want the daemon to actually do anything. The block will
be passed the daemon object.
@param name [String] The name of this daemon. Needs to be the
same across a cluster for :singleton to work, and must be
unique.
@param options [Hash] Options for the daemon.
@option options :singleton [true, false] (true)
@option options :on_error [Proc] A custom error handler, will be
passed the daemon object and the error (see {#on_error})
@option options :on_stop [Proc] A custom stop handler, will be
passed the daemon object (see {#on_stop})
@option options :stop_timeout [Number] (30_000) Milliseconds to
wait for the daemon thread to exit when stopping. | initialize | ruby | torquebox/torquebox | core/lib/torquebox/daemon.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/daemon.rb | Apache-2.0 |
def start
@java_daemon.set_action do
action
end
@java_daemon.set_error_callback do |_, err|
on_error(err)
end
@java_daemon.set_stop_callback do |_|
on_stop
end
@java_daemon.start
self
end | Starts the daemon. If :singleton and in a cluster, the daemon
may not be running on the current node after calling start.
@return [Daemon] self | start | ruby | torquebox/torquebox | core/lib/torquebox/daemon.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/daemon.rb | Apache-2.0 |
def stop
if @java_daemon
@java_daemon.stop
end
self
end | Stops the daemon. This will trigger the {#on_stop} callback if
this daemon is {#running?}.
@return [Daemon] self | stop | ruby | torquebox/torquebox | core/lib/torquebox/daemon.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/daemon.rb | Apache-2.0 |
def running?
@java_daemon && @java_daemon.is_running
end | true if the daemon is actually running. If not :singleton or
not in a cluster, and the action hasn't exited normally,
running? == {#started?} | running? | ruby | torquebox/torquebox | core/lib/torquebox/daemon.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/daemon.rb | Apache-2.0 |
def started?
@java_daemon && @java_daemon.is_started
end | true if in the started state. May not actually be running. see
{#running?} | started? | ruby | torquebox/torquebox | core/lib/torquebox/daemon.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/daemon.rb | Apache-2.0 |
def action
@action_lambda.call(self) if @action_lambda
end | The action to perform. If you override this method, the block
given to {#initialize} will be ignored. You should never call
this method directly. | action | ruby | torquebox/torquebox | core/lib/torquebox/daemon.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/daemon.rb | Apache-2.0 |
def on_error(error)
if @on_error_lambda
@on_error_lambda.call(self, error)
else
DaemonContext::DEFAULT_ERROR_CALLBACK.notify(@java_daemon.name, error)
start
end
end | Called when an unhandled error occurs in #{action}. If you
override this method, the :on_error proc given to #{initialize}
will be ignored.
@param error [] The error that occurred. | on_error | ruby | torquebox/torquebox | core/lib/torquebox/daemon.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/daemon.rb | Apache-2.0 |
def on_stop
@on_stop_lambda.call(self) if @on_stop_lambda
end | Called when {#stop} is called, but only if {#started?} is true. | on_stop | ruby | torquebox/torquebox | core/lib/torquebox/daemon.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/daemon.rb | Apache-2.0 |
def initialize(name = DEFAULT_CATEGORY)
@logger = WunderBoss.logger(name.to_s.gsub('::', '.'))
end | Wraps a WunderBoss logger
@param name [Object] Name for the logger | initialize | ruby | torquebox/torquebox | core/lib/torquebox/logger.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/logger.rb | Apache-2.0 |
def trace(*params, &block)
add(:trace, *params, &block)
end | Logs a message at the TRACE level
@param message [String] the message to log
@return [void] | trace | ruby | torquebox/torquebox | core/lib/torquebox/logger.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/logger.rb | Apache-2.0 |
def debug(*params, &block)
add(:debug, *params, &block)
end | Logs a message at the DEBUG level
@param message [String] the message to log
@return [void] | debug | ruby | torquebox/torquebox | core/lib/torquebox/logger.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/logger.rb | Apache-2.0 |
def info(*params, &block)
add(:info, *params, &block)
end | Logs a message at the INFO level
@param message [String] the message to log
@return [void] | info | ruby | torquebox/torquebox | core/lib/torquebox/logger.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/logger.rb | Apache-2.0 |
def warn(*params, &block)
add(:warn, *params, &block)
end | Logs a message at the WARN level
@param message [String] the message to log
@return [void] | warn | ruby | torquebox/torquebox | core/lib/torquebox/logger.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/logger.rb | Apache-2.0 |
def error(*params, &block)
add(:error, *params, &block)
end | Logs a message at the ERROR level
@param message [String] the message to log
@return [void] | error | ruby | torquebox/torquebox | core/lib/torquebox/logger.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/logger.rb | Apache-2.0 |
def level
(@logger.level || @logger.effective_level).to_s
end | Reports current logger's level
@return [String] log level | level | ruby | torquebox/torquebox | core/lib/torquebox/logger.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/logger.rb | Apache-2.0 |
def puts(message)
info message.to_s
end | Allow our logger to be used for env['rack.errors'] | puts | ruby | torquebox/torquebox | core/lib/torquebox/logger.rb | https://github.com/torquebox/torquebox/blob/master/core/lib/torquebox/logger.rb | Apache-2.0 |
def queue(name, options = {})
TorqueBox::Messaging.queue(name, options.merge(:context => self))
end | Creates a Queue from this context.
The Queue instance will use this context for
any of its methods that take a `:context` option.
@param (see Queue#initialize)
@return (see Queue#initialize) | queue | ruby | torquebox/torquebox | messaging/lib/torquebox/messaging/context.rb | https://github.com/torquebox/torquebox/blob/master/messaging/lib/torquebox/messaging/context.rb | Apache-2.0 |
def topic(name, options = {})
TorqueBox::Messaging.topic(name, options.merge(:context => self))
end | Creates a Topic from this context.
The Topic instance will use this context for
any of its methods that take a `:context` option.
@param (see Topic#initialize)
@return (see Topic#initialize) | topic | ruby | torquebox/torquebox | messaging/lib/torquebox/messaging/context.rb | https://github.com/torquebox/torquebox/blob/master/messaging/lib/torquebox/messaging/context.rb | Apache-2.0 |
def mode
case @internal_context.mode
when WBContext::Mode::AUTO_ACK
:auto_ack
when WBContext::Mode::CLIENT_ACK
:client_ack
when WBContext::Mode::TRANSACTED
:transacted
end
end | @return [Symbol] The mode of this context. | mode | ruby | torquebox/torquebox | messaging/lib/torquebox/messaging/context.rb | https://github.com/torquebox/torquebox/blob/master/messaging/lib/torquebox/messaging/context.rb | Apache-2.0 |
def publish(message, options = {})
validate_options(options, PUBLISH_OPTIONS)
options = apply_default_options(options)
options = normalize_publish_options(options)
options = coerce_context(options)
encoding = options[:encoding] || Messaging.default_encoding
@internal_destination.publish(message,
Codecs[encoding],
extract_options(options, WBDestination::PublishOption))
end | Send a message to this destination.
The message can be any data that can be encoded using the
given :encoding.
If no context is provided, a new context will be created, then
closed.
@param message [Object] The message to send.
@param options [Hash] Options for message publication.
@option options :encoding [Symbol] (:marshal) one of: :edn, :json,
:marshal, :marshal_base64, :text
@option options :priority [Symbol, Number] (:normal) 0-9, or
one of: :low, :normal, :high, :critical
@option options :ttl [Number] (0) time to live, in millis, 0
== forever
@option options :persistent [true, false] (true) whether
undelivered messages survive restarts
@option options :properties [Hash] a hash to which selectors
may be applied
@option options :context [Context] a context to use;
caller expected to close
@return [void] | publish | ruby | torquebox/torquebox | messaging/lib/torquebox/messaging/destination.rb | https://github.com/torquebox/torquebox/blob/master/messaging/lib/torquebox/messaging/destination.rb | Apache-2.0 |
def receive(options = {}, &block)
validate_options(options, RECEIVE_OPTIONS)
options = apply_default_options(options)
options = coerce_context(options)
result = @internal_destination.receive(Codecs.java_codecs,
extract_options(options, WBDestination::ReceiveOption))
msg = if result
options.fetch(:decode, true) ? result.body : result
else
options[:timeout_val]
end
block ? block.call(msg) : msg
end | Receive a message from this destination.
Can optionally be given a block that will be called with
the message.
If a :selector is provided, then only messages having
properties matching that expression may be received.
If no context is provided, a new context will be created, then
closed.
@param options [Hash] Options for message receipt.
@option options :timeout [Number] (10000) Time in millis,
after which the :timeout_val is returned. 0
means wait forever, -1 means don't wait at all
@option options :timeout_val [Object] The value to
return when a timeout occurs. Also returned when
a :timeout of -1 is specified, and no message is available
@option options :selector [String] A JMS (SQL 92) expression
matching message properties
@option options :decode [true, false] (true) If true, the
decoded message body is returned. Otherwise, the
base message object is returned.
@option options :context [Context] a context to use;
caller expected to close
@return The message, or the return value of the block if a
block is given. | receive | ruby | torquebox/torquebox | messaging/lib/torquebox/messaging/destination.rb | https://github.com/torquebox/torquebox/blob/master/messaging/lib/torquebox/messaging/destination.rb | Apache-2.0 |
def listen(options = {}, &block)
validate_options(options, LISTEN_OPTIONS)
options = apply_default_options(options)
options = coerce_context(options)
handler = MessageHandler.new do |message|
block.call(options.fetch(:decode, true) ? message.body : message)
nil
end
@internal_destination.listen(handler,
Codecs.java_codecs,
extract_options(options, WBDestination::ListenOption))
end | Registers a block to receive each message sent to this destination.
If a :selector is provided, then only messages having
properties matching that expression will be received.
If given a context, the context must be remote, and the mode
of that context is ignored, since it is used solely to
generate sub-contexts for each listener thread. Closing the
given context will also close the listener.
If no context is provided, a new context will be created, then
closed.
@param options [Hash] Options for the listener.
@option options :concurrency [Number] (1) The number of
threads handling messages.
@option options :selector [String] A JMS (SQL 92) expression
matching message properties
@option options :decode [true, false] If true, the decoded
message body is passed to the block. Otherwise, the
base message object is passed.
@option options :context [Context] a *remote* context to
use; caller expected to close.
@return A listener object that can be stopped by
calling .close on it. | listen | ruby | torquebox/torquebox | messaging/lib/torquebox/messaging/destination.rb | https://github.com/torquebox/torquebox/blob/master/messaging/lib/torquebox/messaging/destination.rb | Apache-2.0 |
def request(message, options = {}, &block)
validate_options(options, REQUEST_OPTIONS)
options = apply_default_options(options)
options = coerce_context(options)
options = normalize_publish_options(options)
encoding = options[:encoding] || Messaging.default_encoding
future = @internal_destination.request(message,
Codecs[encoding],
Codecs.java_codecs,
extract_options(options, WBQueue::RequestOption))
timeout = options[:timeout] || 0
result = if timeout == 0
future.get
else
begin
future.get(timeout, TimeUnit::MILLISECONDS)
rescue java.util.concurrent.TimeoutException
nil
end
end
msg = if result
result.body
else
options[:timeout_val]
end
if block
block.call(msg)
else
msg
end
end | Sends a message this queue and waits for a response.
Implements the request-response pattern, and is used in
conjunction with {#respond}.
Can optionally be given block that will be called with
the message.
If no context is provided, a new context will be created, then
closed.
@param message [Object] The message to send.
@param options [Hash] Options for message publication.
@option options :encoding [Symbol] (:marshal) one of: :edn, :json,
:marshal, :marshal_base64, :text
@option options :priority [Symbol, Number] (:normal) 0-9, or
one of: :low, :normal, :high, :critical
@option options :ttl [Number] (0) time to live, in millis, 0
== forever
@option options :persistent [true, false] (true) whether
undelivered messages survive restarts
@option options :properties [Hash] a hash to which selectors
may be applied
@option options :context [Context] a context to use;
caller expected to close
@option options :timeout [Number] (0) Time in millis,
after which the :timeout_val is returned. 0
means wait forever.
@option options :timeout_val [Object] The value to
return when a timeout occurs.
@return The message, or the return value of the block if a
block is given. | request | ruby | torquebox/torquebox | messaging/lib/torquebox/messaging/queue.rb | https://github.com/torquebox/torquebox/blob/master/messaging/lib/torquebox/messaging/queue.rb | Apache-2.0 |
def respond(options = {}, &block)
validate_options(options, RESPOND_OPTIONS)
options = apply_default_options(options)
options = coerce_context(options)
handler = MessageHandler.new do |message|
ConcreteReply.new(block.call(options.fetch(:decode, true) ? message.body : message),
nil)
end
@internal_destination.respond(handler,
Codecs.java_codecs,
extract_options(options, WBQueue::RespondOption))
end | Registers a block to receive each request message sent to this
destination, and returns the result of the block call to the
requestor.
If given a context, the context must be remote, and the mode
of that context is ignored, since it is used solely to
generate sub-contexts for each listener thread. Closing the
given context will also close the listener.
If no context is provided, a new context will be created, then
closed when the responder is closed.
@param options [Hash] Options for the listener.
@option options :concurrency [Number] (1) The number of
threads handling messages.
@option options :selector [String] A JMS (SQL 92) expression
matching message properties
@option options :decode [true, false] If true, the decoded
message body is passed to the block. Otherwise, the
base message object is passed.
@option options :ttl [Number] (60000) The time for the
response message to live, in millis.
@option options :context [Context] a *remote* context to
use; caller expected to close
@return A listener object that can be stopped by
calling .close on it. | respond | ruby | torquebox/torquebox | messaging/lib/torquebox/messaging/queue.rb | https://github.com/torquebox/torquebox/blob/master/messaging/lib/torquebox/messaging/queue.rb | Apache-2.0 |
def subscribe(name, options = {}, &block)
validate_options(options, SUBSCRIBE_OPTIONS)
options = apply_default_options(options)
options = coerce_context(options)
handler = MessageHandler.new do |message|
block.call(options.fetch(:decode, true) ? message.body : message)
end
@internal_destination.subscribe(name, handler,
Codecs.java_codecs,
extract_options(options, WBTopic::SubscribeOption))
end | Sets up a durable subscription to this topic, and registers a
listener with the given block to receive messages on the
subscription.
A name is used to identify the subscription, allowing you to
stop the listener and resubscribe with the same name in the
future without losing messages sent in the interim.
If a selector is provided, then only messages having
properties matching that expression may be received.
If no context is provided, a new context is created for this
subscriber. If a context is provided, it must have its :client_id
set (see Context).
Subscriptions should be torn down when no longer needed - (see
#unsubscribe).
@param name [String] The name of the subscription.
@param options [Hash] Options for the subscription.
@option options :decode [true, false] If true, the decoded
message body is passed to the block. Otherwise, the
base message object is passed.
@option options :context [Context] a context to use;
caller expected to close.
@return A listener object that can be stopped by
calling .close on it. | subscribe | ruby | torquebox/torquebox | messaging/lib/torquebox/messaging/topic.rb | https://github.com/torquebox/torquebox/blob/master/messaging/lib/torquebox/messaging/topic.rb | Apache-2.0 |
def unsubscribe(name, options = {})
validate_options(options, UNSUBSCRIBE_OPTIONS)
options = apply_default_options(options)
options = coerce_context(options)
@internal_destination.unsubscribe(name,
extract_options(options, WBTopic::UnsubscribeOption))
end | Tears down a durable topic subscription.
If no context is provided, a new context is created for
this action. If a context is provided, it must have its
:client_id set to the same value used when creating the
subscription (see #subscribe).
@param name [String] The name of the subscription.
@param options [Hash] Options for the subscription.
@option options :context [Context] a context to use;
caller expected to close.
@return [void] | unsubscribe | ruby | torquebox/torquebox | messaging/lib/torquebox/messaging/topic.rb | https://github.com/torquebox/torquebox/blob/master/messaging/lib/torquebox/messaging/topic.rb | Apache-2.0 |
def initialize(match_or_dest)
server_manager = HornetQ.server_manager
import_hornetq
@address_settings = org.hornetq.core.settings.impl.AddressSettings.new
server_manager.add_address_settings(normalize_destination_match(match_or_dest), @address_settings)
end | Creates and registers address settings.
Creating a new AddressOptions for a match that you have set
options for already will replace those prior options.
@param match_or_dest must be either a {Destination} or a fully
qualified jms destination name (prefixed with 'jms.queue.'
or 'jms.topic.'). It may contain HornetQ wildcard matchers
(see
http://docs.jboss.org/hornetq/2.3.0.Final/docs/user-manual/html/wildcard-syntax.html) | initialize | ruby | torquebox/torquebox | messaging/lib/torquebox/messaging/hornetq/address_settings.rb | https://github.com/torquebox/torquebox/blob/master/messaging/lib/torquebox/messaging/hornetq/address_settings.rb | Apache-2.0 |
def install_java_tasks(options = {})
#
# Resolve maven dependencies using JBundler API
# We don't use JBundler directly because that requires a separate
# 'jbundle install' step to get started.
#
if options[:gemspec]
classpath = classpath_from_gemspec(options[:gemspec])
else
classpath = []
end
if options[:source]
require 'rake/javaextensiontask'
Rake::JavaExtensionTask.new(options[:source]) do |ext|
ext.classpath = classpath
ext.source_version = '1.7'
ext.target_version = '1.7'
end
end
if options[:copy_deps]
deps_dir = options[:copy_deps]
directory deps_dir
task 'compile' => deps_dir
excluded_deps = options[:excluded_deps] || []
classpath.each do |path|
next unless path.end_with?('.jar')
jar = File.basename(path)
next if excluded_deps.any? { |excluded_dep| jar.match(excluded_dep) }
file "#{deps_dir}/#{jar}" do
install path, "#{deps_dir}/#{jar}"
end
task 'compile' => "#{deps_dir}/#{jar}"
end
task 'clean' do
FileUtils.rm_rf(File.join(Dir.pwd, deps_dir))
end
end
task 'build' => 'compile'
task 'spec' => 'compile'
end | Install Rake tasks necessary to compile TorqueBox gems
@param options Optional parameters (a Hash), including:
@option options [String] :source The directory containing java code to compile, if any
@option options [String] :gemspec The path to a gemspec file containing
requirements entries for any maven jars
required for compilation
@option options [String] :copy_deps The path to copy maven dependencies to - nil means don't copy
@option options [Array] :excluded_deps An array of maven dependencies
to exclude from inclusion in the gem | install_java_tasks | ruby | torquebox/torquebox | tasks/torquebox.rb | https://github.com/torquebox/torquebox/blob/master/tasks/torquebox.rb | Apache-2.0 |
def mount(options = {})
options = DEFAULT_MOUNT_OPTIONS.merge(options)
valid_keys = opts_to_set(WBWeb::RegisterOption) + DEFAULT_MOUNT_OPTIONS.keys
validate_options(options, valid_keys)
@logger.debug("Mounting context path {} with options {} on TorqueBox::Web::Server '{}'",
options[:path], options.inspect, @web_component.name)
servlet_context = WB.options.get("servlet-context-path", "")
relative_root = servlet_context + options[:path]
relative_root.chop! if relative_root.end_with?("/")
ENV["RAILS_RELATIVE_URL_ROOT"] = relative_root
if options[:rack_app].nil?
require 'rack'
rackup = File.expand_path(options[:rackup], options[:root])
options[:rack_app] = Rack::Builder.parse_file(rackup).first
end
if options[:init]
options[:init] = options[:init].to_java(java.lang.Runnable)
end
register_options = extract_options(options, WBWeb::RegisterOption)
if WB.in_container
servlet = RackServlet.new(options[:rack_app], options[:static_dir])
@logger.trace("Registering servlet at context path {}", options[:path])
@web_component.register_servlet(servlet, register_options)
else
handler = RackHandler.new(options[:rack_app])
@logger.trace("Registering handler at context path {}", options[:path])
@web_component.register_handler(handler, register_options)
end
start if @options[:auto_start]
handler
end | Mount a Rack application under a specific context path on this server.
@!macro mount_options | mount | ruby | torquebox/torquebox | web/lib/torquebox/web/server.rb | https://github.com/torquebox/torquebox/blob/master/web/lib/torquebox/web/server.rb | Apache-2.0 |
def mount_servlet(servlet, options = {})
options = DEFAULT_MOUNT_SERVLET_OPTIONS.merge(options)
valid_keys = opts_to_set(WBWeb::RegisterOption) + DEFAULT_MOUNT_SERVLET_OPTIONS.keys
validate_options(options, valid_keys)
@logger.debug("Mounting servlet {} with options {} on TorqueBox::Web::Server '{}'",
servlet, options.inspect, @web_component.name)
register_options = extract_options(options, WBWeb::RegisterOption)
@web_component.register_servlet(servlet, register_options)
end | Mount a Servlet under a specific context path on this server
@param servlet [javax.servlet.Servlet] the servlet to mount
@!macro mount_servlet_options | mount_servlet | ruby | torquebox/torquebox | web/lib/torquebox/web/server.rb | https://github.com/torquebox/torquebox/blob/master/web/lib/torquebox/web/server.rb | Apache-2.0 |
def sockjs(options = {})
sockjs_server = SockJsServer.new
# TODO: handle options
servlet = SockJsServlet.new(sockjs_server)
mount_servlet(servlet, options)
sockjs_server
end | Mount a SockJS endpoint under a specific context path on this server
@!macro mount_servlet_options | sockjs | ruby | torquebox/torquebox | web/lib/torquebox/web/server.rb | https://github.com/torquebox/torquebox/blob/master/web/lib/torquebox/web/server.rb | Apache-2.0 |
def custom_action(name, target: nil, content: nil, attributes: {})
turbo_stream_action_tag name, target: target, template: content, **transform_attributes(attributes)
end | Custom Action Helpers
# Also see:
# => https://github.com/hotwired/turbo-rails/pull/374 | custom_action | ruby | marcoroth/turbo_power-rails | lib/turbo_power/stream_helper.rb | https://github.com/marcoroth/turbo_power-rails/blob/master/lib/turbo_power/stream_helper.rb | MIT |
def initialize(opts = {}, &block)
@type, @handle = self.class.run(opts, &block)
end | Spawns a long-running section of code and returns the ID of the spawned process.
By default the process will be a forked process. To use threading, pass
:method => :thread or override the default behavior in the environment by setting
'Spawnling::method :thread'. | initialize | ruby | tra/spawnling | lib/spawnling.rb | https://github.com/tra/spawnling/blob/master/lib/spawnling.rb | MIT |
def call_last_spawn_proc
spawns = SpawnExtensions.spawn_procs
raise "No spawn procs left" if spawns.empty?
spawns.pop.call
end | Calls the spawn that was created
Can be used to keep control over forked processes in your tests | call_last_spawn_proc | ruby | tra/spawnling | lib/spawnling/cucumber.rb | https://github.com/tra/spawnling/blob/master/lib/spawnling/cucumber.rb | MIT |
def link_to_add(*args, &block)
options = args.extract_options!.symbolize_keys
association = args.pop
unless object.respond_to?("#{association}_attributes=")
raise ArgumentError, "Invalid association. Make sure that accepts_nested_attributes_for is used for #{association.inspect} association."
end
model_object = options.delete(:model_object) do
reflection = object.class.reflect_on_association(association)
reflection.klass.new
end
options[:class] = [options[:class], "add_nested_fields"].compact.join(" ")
options["data-association"] = association
options["data-blueprint-id"] = fields_blueprint_id = fields_blueprint_id_for(association)
args << (options.delete(:href) || "javascript:void(0)")
args << options
@fields ||= {}
@template.after_nested_form(fields_blueprint_id) do
blueprint = {:id => fields_blueprint_id, :style => 'display: none'}
block, options = @fields[fields_blueprint_id].values_at(:block, :options)
options[:child_index] = "new_#{association}"
blueprint[:"data-blueprint"] = fields_for(association, model_object, options, &block).to_str
@template.content_tag(:div, nil, blueprint)
end
@template.link_to(*args, &block)
end | Adds a link to insert a new associated records. The first argument is the name of the link, the second is the name of the association.
f.link_to_add("Add Task", :tasks)
You can pass HTML options in a hash at the end and a block for the content.
<%= f.link_to_add(:tasks, :class => "add_task", :href => new_task_path) do %>
Add Task
<% end %>
You can also pass <tt>model_object</tt> option with an object for use in
the blueprint, e.g.:
<%= f.link_to_add(:tasks, :model_object => Task.new(:name => 'Task')) %>
See the README for more details on where to call this method. | link_to_add | ruby | ryanb/nested_form | lib/nested_form/builder_mixin.rb | https://github.com/ryanb/nested_form/blob/master/lib/nested_form/builder_mixin.rb | MIT |
def link_to_remove(*args, &block)
options = args.extract_options!.symbolize_keys
options[:class] = [options[:class], "remove_nested_fields"].compact.join(" ")
# Extracting "milestones" from "...[milestones_attributes][...]"
md = object_name.to_s.match /(\w+)_attributes\](?:\[[\w\d]+\])?$/
association = md && md[1]
options["data-association"] = association
args << (options.delete(:href) || "javascript:void(0)")
args << options
hidden_field(:_destroy) << @template.link_to(*args, &block)
end | Adds a link to remove the associated record. The first argment is the name of the link.
f.link_to_remove("Remove Task")
You can pass HTML options in a hash at the end and a block for the content.
<%= f.link_to_remove(:class => "remove_task", :href => "#") do %>
Remove Task
<% end %>
See the README for more details on where to call this method. | link_to_remove | ruby | ryanb/nested_form | lib/nested_form/builder_mixin.rb | https://github.com/ryanb/nested_form/blob/master/lib/nested_form/builder_mixin.rb | MIT |
def git(*args)
output = exec_git(*args)
$?.success? ? output : ''
end | helper methods, left public in case other commands want to use them directly | git | ruby | geelen/git-smart | lib/git-smart/git_repo.rb | https://github.com/geelen/git-smart/blob/master/lib/git-smart/git_repo.rb | MIT |
def initialize(config:, logger:, io: $stdout)
@config = config
@logger = logger
@io = io
end | io is injected via constructor parameters to facilitate testing. | initialize | ruby | gregnavis/active_record_doctor | lib/active_record_doctor/runner.rb | https://github.com/gregnavis/active_record_doctor/blob/master/lib/active_record_doctor/runner.rb | MIT |
def configure(&block)
# If current_config is set it means that .configure was already called
# so we must raise an error.
raise ActiveRecordDoctor::Error::ConfigureCalledTwice if current_config
# Determine the recognized global and detector settings based on detector
# metadata. recognizedd_detectors maps detector names to setting names.
# recognized_globals contains global setting names.
recognized_detectors = {}
recognized_globals = []
ActiveRecordDoctor.detectors.each do |name, detector|
locals, globals = detector.locals_and_globals
recognized_detectors[name] = locals
recognized_globals.concat(globals)
end
# The same global can be used by multiple detectors so we must remove
# duplicates to ensure they aren't reported multiple times via the user
# interface (e.g. in error messages).
recognized_globals.uniq!
# Prepare an empty configuration and call the loader. After .new returns
# @current_config will contain the configuration provided by the block.
@current_config = Config.new({}, {})
Loader.new(current_config, recognized_globals, recognized_detectors, &block)
# This method is part of the public API expected to be called by users.
# In order to avoid leaking internal objects, we return an explicit nil.
nil
end | This method is part of the public API that is intended for use by
active_record_doctor users. The remaining methods are considered to be
public-not-published. | configure | ruby | gregnavis/active_record_doctor | lib/active_record_doctor/config/loader.rb | https://github.com/gregnavis/active_record_doctor/blob/master/lib/active_record_doctor/config/loader.rb | MIT |
def test_disabling
Context.create_table(:users) do |t|
t.string :name, null: true
end.define_model do
validates :name, presence: true
end
config_file(<<-CONFIG)
ActiveRecordDoctor.configure do |config|
config.detector :missing_non_null_constraint,
enabled: false
end
CONFIG
refute_problems
end | Disabling detectors is implemented in the base class. It's enough to test
it on a single detector to be reasonably certain it works on all of them. | test_disabling | ruby | gregnavis/active_record_doctor | test/active_record_doctor/detectors/disable_test.rb | https://github.com/gregnavis/active_record_doctor/blob/master/test/active_record_doctor/detectors/disable_test.rb | MIT |
def resolve(model_id, provider = nil)
return model_id unless aliases[model_id]
if provider
aliases[model_id][provider.to_s] || model_id
else
# Get native provider's version
aliases[model_id].values.first || model_id
end
end | Resolves a model ID to its provider-specific version
@param model_id [String] the model identifier or alias
@param provider_slug [String, Symbol, nil] optional provider to resolve for
@return [String] the resolved model ID or the original if no alias exists | resolve | ruby | crmne/ruby_llm | lib/ruby_llm/aliases.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/aliases.rb | MIT |
def aliases
@aliases ||= load_aliases
end | Returns the loaded aliases mapping
@return [Hash] the aliases mapping | aliases | ruby | crmne/ruby_llm | lib/ruby_llm/aliases.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/aliases.rb | MIT |
def load_aliases
file_path = File.expand_path('aliases.json', __dir__)
if File.exist?(file_path)
JSON.parse(File.read(file_path))
else
{}
end
end | Loads aliases from the JSON file
@return [Hash] the loaded aliases | load_aliases | ruby | crmne/ruby_llm | lib/ruby_llm/aliases.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/aliases.rb | MIT |
def reload!
@aliases = load_aliases
end | Reloads aliases from disk
@return [Hash] the reloaded aliases | reload! | ruby | crmne/ruby_llm | lib/ruby_llm/aliases.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/aliases.rb | MIT |
def to_blob
if base64?
Base64.decode64 @data
else
response = Connection.basic.get @url
response.body
end
end | Returns the raw binary image data regardless of source | to_blob | ruby | crmne/ruby_llm | lib/ruby_llm/image.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/image.rb | MIT |
def save(path)
File.binwrite(File.expand_path(path), to_blob)
path
end | Saves the image to a file path | save | ruby | crmne/ruby_llm | lib/ruby_llm/image.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/image.rb | MIT |
def initialize(models = nil)
@models = models || load_models
end | Initialize with optional pre-filtered models | initialize | ruby | crmne/ruby_llm | lib/ruby_llm/models.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/models.rb | MIT |
def load_models
data = File.exist?(self.class.models_file) ? File.read(self.class.models_file) : '[]'
JSON.parse(data, symbolize_names: true).map { |model| Model::Info.new(model) }
rescue JSON::ParserError
[]
end | Load models from the JSON file | load_models | ruby | crmne/ruby_llm | lib/ruby_llm/models.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/models.rb | MIT |
def determine_context_window(_model_id)
# All Claude 3 and 3.5 and 3.7 models have 200K token context windows
200_000
end | Determines the context window size for a given model
@param model_id [String] the model identifier
@return [Integer] the context window size in tokens | determine_context_window | ruby | crmne/ruby_llm | lib/ruby_llm/providers/anthropic/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/anthropic/capabilities.rb | MIT |
def determine_max_tokens(model_id)
case model_id
when /claude-3-7-sonnet/, /claude-3-5/ then 8_192
else 4_096
end
end | Determines the maximum output tokens for a given model
@param model_id [String] the model identifier
@return [Integer] the maximum output tokens | determine_max_tokens | ruby | crmne/ruby_llm | lib/ruby_llm/providers/anthropic/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/anthropic/capabilities.rb | MIT |
def get_input_price(model_id)
PRICES.dig(model_family(model_id), :input) || default_input_price
end | Gets the input price per million tokens for a given model
@param model_id [String] the model identifier
@return [Float] the price per million tokens for input | get_input_price | ruby | crmne/ruby_llm | lib/ruby_llm/providers/anthropic/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/anthropic/capabilities.rb | MIT |
def get_output_price(model_id)
PRICES.dig(model_family(model_id), :output) || default_output_price
end | Gets the output price per million tokens for a given model
@param model_id [String] the model identifier
@return [Float] the price per million tokens for output | get_output_price | ruby | crmne/ruby_llm | lib/ruby_llm/providers/anthropic/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/anthropic/capabilities.rb | MIT |
def supports_vision?(model_id)
# All Claude 3, 3.5, and 3.7 models support vision
!model_id.match?(/claude-[12]/)
end | Determines if a model supports vision capabilities
@param model_id [String] the model identifier
@return [Boolean] true if the model supports vision | supports_vision? | ruby | crmne/ruby_llm | lib/ruby_llm/providers/anthropic/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/anthropic/capabilities.rb | MIT |
def model_family(model_id)
case model_id
when /claude-3-7-sonnet/ then 'claude-3-7-sonnet'
when /claude-3-5-sonnet/ then 'claude-3-5-sonnet'
when /claude-3-5-haiku/ then 'claude-3-5-haiku'
when /claude-3-opus/ then 'claude-3-opus'
when /claude-3-sonnet/ then 'claude-3-sonnet'
when /claude-3-haiku/ then 'claude-3-haiku'
else 'claude-2'
end
end | Determines the model family for a given model ID
@param model_id [String] the model identifier
@return [Symbol] the model family identifier | model_family | ruby | crmne/ruby_llm | lib/ruby_llm/providers/anthropic/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/anthropic/capabilities.rb | MIT |
def context_window_for(model_id)
case model_id
when /anthropic\.claude-2/ then 100_000
else 200_000
end
end | Returns the context window size for the given model ID
@param model_id [String] the model identifier
@return [Integer] the context window size in tokens | context_window_for | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/capabilities.rb | MIT |
def input_price_for(model_id)
PRICES.dig(model_family(model_id), :input) || default_input_price
end | Returns the input price per million tokens for the given model ID
@param model_id [String] the model identifier
@return [Float] the price per million tokens for input | input_price_for | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/capabilities.rb | MIT |
def output_price_for(model_id)
PRICES.dig(model_family(model_id), :output) || default_output_price
end | Returns the output price per million tokens for the given model ID
@param model_id [String] the model identifier
@return [Float] the price per million tokens for output | output_price_for | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/capabilities.rb | MIT |
def format_display_name(model_id)
model_id.then { |id| humanize(id) }
end | Formats the model ID into a human-readable display name
@param model_id [String] the model identifier
@return [String] the formatted display name | format_display_name | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/capabilities.rb | MIT |
def model_family(model_id)
MODEL_FAMILIES.find { |pattern, _family| model_id.match?(pattern) }&.last || :other
end | Determines the model family for pricing and capability lookup
@param model_id [String] the model identifier
@return [Symbol] the model family identifier | model_family | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/capabilities.rb | MIT |
def humanize(id)
id.tr('-', ' ')
.split('.')
.last
.split
.map(&:capitalize)
.join(' ')
end | Converts a model ID to a human-readable format
@param id [String] the model identifier
@return [String] the humanized model name | humanize | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/capabilities.rb | MIT |
def create_model_info(model_data, slug, _capabilities)
model_id = model_data['modelId']
Model::Info.new(
id: model_id_with_region(model_id, model_data),
name: model_data['modelName'] || model_id,
provider: slug,
family: 'claude',
created_at: nil,
context_window: 200_000,
max_output_tokens: 4096,
modalities: { input: ['text'], output: ['text'] },
capabilities: [],
pricing: {},
metadata: {}
)
end | Simple test-friendly method that only sets the ID | create_model_info | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/models.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/models.rb | MIT |
def initialize(options = {})
if options[:access_key_id] && options[:secret_access_key]
@access_key_id = options[:access_key_id]
@secret_access_key = options[:secret_access_key]
@session_token = options[:session_token]
else
msg = 'expected both :access_key_id and :secret_access_key options'
raise ArgumentError, msg
end
end | @option options [required, String] :access_key_id
@option options [required, String] :secret_access_key
@option options [String, nil] :session_token (nil) | initialize | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/signing.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/signing.rb | MIT |
def set?
!access_key_id.nil? &&
!access_key_id.empty? &&
!secret_access_key.nil? &&
!secret_access_key.empty?
end | @return [Boolean] Returns `true` if the access key id and secret
access key are both set. | set? | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/signing.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/signing.rb | MIT |
def initialize(options = {})
@credentials = options[:credentials] || Credentials.new(options)
end | @option options [Credentials] :credentials
@option options [String] :access_key_id
@option options [String] :secret_access_key
@option options [String] :session_token (nil) | initialize | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/signing.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/signing.rb | MIT |
def initialize(params = {})
@http_method = params[:http_method]
@url = params[:url]
@headers = params[:headers]
@content_sha256 = params[:content_sha256]
@config = params[:config] || CanonicalRequestConfig.new
end | Builds a canonical request for AWS signature
@param [Hash] params Parameters for the canonical request | initialize | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/signing.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/signing.rb | MIT |
def signed_headers
@headers.inject([]) do |signed_headers, (header, _)|
if @config.unsigned_headers.include?(header)
signed_headers
else
signed_headers << header
end
end.sort.join(';')
end | Returns the list of signed headers for authorization | signed_headers | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/signing.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/signing.rb | MIT |
def build_sigv4_headers(components, creds)
headers = {
'host' => components[:headers]['host'] || UriUtils.host(components[:url]),
'x-amz-date' => components[:datetime]
}
add_session_token_header(headers, creds)
add_content_sha256_header(headers, components[:content_sha256])
headers
end | Build headers for a signed request
@param [Hash] components Request components
@param [Credentials] creds AWS credentials
@return [Hash] Generated headers | build_sigv4_headers | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/signing.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/signing.rb | MIT |
def build_headers(sigv4_headers, signature, components)
headers = sigv4_headers.merge(
'authorization' => build_authorization_header(signature)
)
add_omitted_session_token(headers, components[:creds]) if @omit_session_token
headers
end | Build authorization headers for a signature
@param [Hash] sigv4_headers Headers for the signature
@param [Hash] signature The computed signature
@param [Hash] components Request components
@return [Hash] Headers with authorization | build_headers | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/signing.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/signing.rb | MIT |
def initialize(options = {})
components = SignerInitializer.create_components(options)
setup_configuration(components)
setup_service_components(components)
end | Initialize a new signer with the provided options
@param [Hash] options Configuration options for the signer | initialize | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/signing.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/signing.rb | MIT |
def sign_request(request)
creds = @credential_manager.fetch_credentials.first
request_components = extract_request_components(request)
sigv4_headers = build_sigv4_headers(request_components, creds)
signature = compute_signature(request_components, creds, sigv4_headers)
build_signature_response(request_components, sigv4_headers, signature)
end | Sign an AWS request with SigV4 or SigV4a
@param [Hash] request The request to sign
@return [Signature] The signature with headers to apply | sign_request | ruby | crmne/ruby_llm | lib/ruby_llm/providers/bedrock/signing.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/bedrock/signing.rb | MIT |
def context_window_for(model_id)
case model_id
when /deepseek-(?:chat|reasoner)/ then 64_000
else 32_768 # Sensible default
end
end | Returns the context window size for the given model
@param model_id [String] the model identifier
@return [Integer] the context window size in tokens | context_window_for | ruby | crmne/ruby_llm | lib/ruby_llm/providers/deepseek/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb | MIT |
def max_tokens_for(model_id)
case model_id
when /deepseek-(?:chat|reasoner)/ then 8_192
else 4_096 # Default if max_tokens not specified
end
end | Returns the maximum number of tokens that can be generated
@param model_id [String] the model identifier
@return [Integer] the maximum number of tokens | max_tokens_for | ruby | crmne/ruby_llm | lib/ruby_llm/providers/deepseek/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb | MIT |
def input_price_for(model_id)
PRICES.dig(model_family(model_id), :input_miss) || default_input_price
end | Returns the price per million tokens for input (cache miss)
@param model_id [String] the model identifier
@return [Float] the price per million tokens in USD | input_price_for | ruby | crmne/ruby_llm | lib/ruby_llm/providers/deepseek/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb | MIT |
def output_price_for(model_id)
PRICES.dig(model_family(model_id), :output) || default_output_price
end | Returns the price per million tokens for output
@param model_id [String] the model identifier
@return [Float] the price per million tokens in USD | output_price_for | ruby | crmne/ruby_llm | lib/ruby_llm/providers/deepseek/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb | MIT |
def cache_hit_price_for(model_id)
PRICES.dig(model_family(model_id), :input_hit) || default_cache_hit_price
end | Returns the price per million tokens for input with cache hit
@param model_id [String] the model identifier
@return [Float] the price per million tokens in USD | cache_hit_price_for | ruby | crmne/ruby_llm | lib/ruby_llm/providers/deepseek/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb | MIT |
def supports_vision?(_model_id)
false # DeepSeek models don't currently support vision
end | Determines if the model supports vision capabilities
@param model_id [String] the model identifier
@return [Boolean] true if the model supports vision | supports_vision? | ruby | crmne/ruby_llm | lib/ruby_llm/providers/deepseek/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb | MIT |
def supports_functions?(model_id)
model_id.match?(/deepseek-chat/) # Only deepseek-chat supports function calling
end | Determines if the model supports function calling
@param model_id [String] the model identifier
@return [Boolean] true if the model supports function calling | supports_functions? | ruby | crmne/ruby_llm | lib/ruby_llm/providers/deepseek/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb | MIT |
def supports_json_mode?(_model_id)
false # DeepSeek function calling is unstable
end | Determines if the model supports JSON mode
@param model_id [String] the model identifier
@return [Boolean] true if the model supports JSON mode | supports_json_mode? | ruby | crmne/ruby_llm | lib/ruby_llm/providers/deepseek/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb | MIT |
def format_display_name(model_id)
case model_id
when 'deepseek-chat' then 'DeepSeek V3'
when 'deepseek-reasoner' then 'DeepSeek R1'
else
model_id.split('-')
.map(&:capitalize)
.join(' ')
end
end | Returns a formatted display name for the model
@param model_id [String] the model identifier
@return [String] the formatted display name | format_display_name | ruby | crmne/ruby_llm | lib/ruby_llm/providers/deepseek/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb | MIT |
def model_type(_model_id)
'chat' # All DeepSeek models are chat models
end | Returns the model type
@param model_id [String] the model identifier
@return [String] the model type (e.g., 'chat') | model_type | ruby | crmne/ruby_llm | lib/ruby_llm/providers/deepseek/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb | MIT |
def model_family(model_id)
case model_id
when /deepseek-reasoner/ then :reasoner
else :chat # Default to chat family
end
end | Returns the model family
@param model_id [String] the model identifier
@return [Symbol] the model family | model_family | ruby | crmne/ruby_llm | lib/ruby_llm/providers/deepseek/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb | MIT |
def default_input_price
0.27 # Default to chat cache miss price
end | Default input price when model family can't be determined
@return [Float] the default input price | default_input_price | ruby | crmne/ruby_llm | lib/ruby_llm/providers/deepseek/capabilities.rb | https://github.com/crmne/ruby_llm/blob/master/lib/ruby_llm/providers/deepseek/capabilities.rb | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.