Results for: "OptionParser"

Returns true if file_name is an absolute path, and false otherwise.

File.absolute_path?("c:/foo")     #=> false (on Linux), true (on Windows)

Returns default external encoding.

The default external encoding is used by default for strings created from the following locations:

While strings created from these locations will have this encoding, the encoding may not be valid. Be sure to check String#valid_encoding?.

File data written to disk will be transcoded to the default external encoding when written, if default_internal is not nil.

The default external encoding is initialized by the -E option. If -E isn’t set, it is initialized to UTF-8 on Windows and the locale on other operating systems.

Sets default external encoding. You should not set Encoding::default_external in ruby code as strings created before changing the value may have a different encoding from strings created after the value was changed., instead you should use ruby -E to invoke ruby with the correct default_external.

See Encoding::default_external for information on how the default external encoding is used.

Returns default internal encoding. Strings will be transcoded to the default internal encoding in the following places if the default internal encoding is not nil:

Additionally String#encode and String#encode! use the default internal encoding if no encoding is given.

The script encoding (__ENCODING__), not default_internal, is used as the encoding of created strings.

Encoding::default_internal is initialized with -E option or nil otherwise.

Sets default internal encoding or removes default internal encoding when passed nil. You should not set Encoding::default_internal in ruby code as strings created before changing the value may have a different encoding from strings created after the change. Instead you should use ruby -E to invoke ruby with the correct default_internal.

See Encoding::default_internal for information on how the default internal encoding is used.

Returns the locale charmap name. It returns nil if no appropriate information.

Debian GNU/Linux
  LANG=C
    Encoding.locale_charmap  #=> "ANSI_X3.4-1968"
  LANG=ja_JP.EUC-JP
    Encoding.locale_charmap  #=> "EUC-JP"

SunOS 5
  LANG=C
    Encoding.locale_charmap  #=> "646"
  LANG=ja
    Encoding.locale_charmap  #=> "eucJP"

The result is highly platform dependent. So Encoding.find(Encoding.locale_charmap) may cause an error. If you need some encoding object even for unknown locale, Encoding.find(“locale”) can be used.

Returns the singleton class of obj. This method creates a new singleton class if obj does not have one.

If obj is nil, true, or false, it returns NilClass, TrueClass, or FalseClass, respectively. If obj is an Integer, a Float or a Symbol, it raises a TypeError.

Object.new.singleton_class  #=> #<Class:#<Object:0xb7ce1e24>>
String.singleton_class      #=> #<Class:String>
nil.singleton_class         #=> NilClass

Returns an array of the names of singleton methods for obj. If the optional all parameter is true, the list will include methods in modules included in obj. Only public and protected singleton methods are returned.

module Other
  def three() end
end

class Single
  def Single.four() end
end

a = Single.new

def a.one()
end

class << a
  include Other
  def two()
  end
end

Single.singleton_methods    #=> [:four]
a.singleton_methods(false)  #=> [:two, :one]
a.singleton_methods         #=> [:two, :one, :three]

Returns an array of instance variable names for the receiver. Note that simply defining an accessor does not create the corresponding instance variable.

class Fred
  attr_accessor :a1
  def initialize
    @iv = 3
  end
end
Fred.new.instance_variables   #=> [:@iv]

Similar to method, searches singleton method only.

class Demo
  def initialize(n)
    @iv = n
  end
  def hello()
    "Hello, @iv = #{@iv}"
  end
end

k = Demo.new(99)
def k.hi
  "Hi, @iv = #{@iv}"
end
m = k.singleton_method(:hi)
m.call   #=> "Hi, @iv = 99"
m = k.singleton_method(:hello) #=> NameError

Invokes the method identified by symbol, passing it any arguments specified. Unlike send, public_send calls public methods only. When the method is identified by a string, the string is converted to a symbol.

1.public_send(:puts, "hello")  # causes NoMethodError

Returns true if obj responds to the given method. Private and protected methods are included in the search only if the optional second parameter evaluates to true.

If the method is not implemented, as Process.fork on Windows, File.lchmod on GNU/Linux, etc., false is returned.

If the method is not defined, respond_to_missing? method is called and the result is returned.

When the method name parameter is given as a string, the string is converted to a symbol.

Sets the backtrace value for self; returns the given value.

The value might be:

Using array of Thread::Backtrace::Location is the most consistent option: it sets both backtrace and backtrace_locations. It should be preferred when possible. The suitable array of locations can be obtained from Kernel#caller_locations, copied from another error, or just set to the adjusted result of the current error’s backtrace_locations:

require 'json'

def parse_payload(text)
  JSON.parse(text)  # test.rb, line 4
rescue JSON::ParserError => ex
  ex.set_backtrace(ex.backtrace_locations[2...])
  raise
end

parse_payload('{"wrong: "json"')
# test.rb:4:in 'Object#parse_payload': unexpected token at '{"wrong: "json"' (JSON::ParserError)
#
# An error points to the body of parse_payload method,
# hiding the parts of the backtrace related to the internals
# of the "json" library

# The error has both #backtace and #backtrace_locations set
# consistently:
begin
  parse_payload('{"wrong: "json"')
rescue => ex
  p ex.backtrace
  # ["test.rb:4:in 'Object#parse_payload'", "test.rb:20:in '<main>'"]
  p ex.backtrace_locations
  # ["test.rb:4:in 'Object#parse_payload'", "test.rb:20:in '<main>'"]
end

When the desired stack of locations is not available and should be constructed from scratch, an array of strings or a singular string can be used. In this case, only backtrace is affected:

def parse_payload(text)
  JSON.parse(text)
rescue JSON::ParserError => ex
  ex.set_backtrace(["dsl.rb:34", "framework.rb:1"])
  # The error have the new value in #backtrace:
  p ex.backtrace
  # ["dsl.rb:34", "framework.rb:1"]

  # but the original one in #backtrace_locations
  p ex.backtrace_locations
  # [".../json/common.rb:221:in 'JSON::Ext::Parser.parse'", ...]
end

parse_payload('{"wrong: "json"')

Calling set_backtrace with nil clears up backtrace but doesn’t affect backtrace_locations:

def parse_payload(text)
  JSON.parse(text)
rescue JSON::ParserError => ex
  ex.set_backtrace(nil)
  p ex.backtrace
  # nil
  p ex.backtrace_locations
  # [".../json/common.rb:221:in 'JSON::Ext::Parser.parse'", ...]
end

parse_payload('{"wrong: "json"')

On reraising of such an exception, both backtrace and backtrace_locations is set to the place of reraising:

def parse_payload(text)
  JSON.parse(text)
rescue JSON::ParserError => ex
  ex.set_backtrace(nil)
  raise # test.rb, line 7
end

begin
  parse_payload('{"wrong: "json"')
rescue => ex
  p ex.backtrace
  # ["test.rb:7:in 'Object#parse_payload'", "test.rb:11:in '<main>'"]
  p ex.backtrace_locations
  # ["test.rb:7:in 'Object#parse_payload'", "test.rb:11:in '<main>'"]
end

See Backtraces.

See as_json.

Methods Exception#as_json and Exception.json_create may be used to serialize and deserialize a Exception object; see Marshal.

Method Exception#as_json serializes self, returning a 2-element hash representing self:

require 'json/add/exception'
x = Exception.new('Foo').as_json # => {"json_class"=>"Exception", "m"=>"Foo", "b"=>nil}

Method JSON.create deserializes such a hash, returning a Exception object:

Exception.json_create(x) # => #<Exception: Foo>

Returns a JSON string representing self:

require 'json/add/exception'
puts Exception.new('Foo').to_json

Output:

{"json_class":"Exception","m":"Foo","b":null}

Return a list of the local variable names defined where this NameError exception was raised.

Internal use only.

Returns an array of all modules used in the current scope. The ordering of modules in the resulting array is not defined.

module A
  refine Object do
  end
end

module B
  refine Object do
  end
end

using A
using B
p Module.used_modules

produces:

[B, A]

Returns an array of all modules used in the current scope. The ordering of modules in the resulting array is not defined.

module A
  refine Object do
  end
end

module B
  refine Object do
  end
end

using A
using B
p Module.used_refinements

produces:

[#<refinement:Object@B>, #<refinement:Object@A>]

Invoked as a callback whenever a constant is assigned on the receiver

module Chatty
  def self.const_added(const_name)
    super
    puts "Added #{const_name.inspect}"
  end
  FOO = 1
end

produces:

Added :FOO

Creates instance variables and corresponding methods that return the value of each instance variable. Equivalent to calling “attr:name” on each name in turn. String arguments are converted to symbols. Returns an array of defined method names as symbols.

Creates an accessor method to allow assignment to the attribute symbol.id2name. String arguments are converted to symbols. Returns an array of defined method names as symbols.

Checks for a constant with the given name in mod. If inherit is set, the lookup will also search the ancestors (and Object if mod is a Module).

The value of the constant is returned if a definition is found, otherwise a NameError is raised.

Math.const_get(:PI)   #=> 3.14159265358979

This method will recursively look up constant names if a namespaced class name is provided. For example:

module Foo; class Bar; end end
Object.const_get 'Foo::Bar'

The inherit flag is respected on each lookup. For example:

module Foo
  class Bar
    VAL = 10
  end

  class Baz < Bar; end
end

Object.const_get 'Foo::Baz::VAL'         # => 10
Object.const_get 'Foo::Baz::VAL', false  # => NameError

If the argument is not a valid constant name a NameError will be raised with a warning “wrong constant name”.

Object.const_get 'foobar' #=> NameError: wrong constant name foobar

Says whether mod or its ancestors have a constant with the given name:

Float.const_defined?(:EPSILON)      #=> true, found in Float itself
Float.const_defined?("String")      #=> true, found in Object (ancestor)
BasicObject.const_defined?(:Hash)   #=> false

If mod is a Module, additionally Object and its ancestors are checked:

Math.const_defined?(:String)   #=> true, found in Object

In each of the checked classes or modules, if the constant is not present but there is an autoload for it, true is returned directly without autoloading:

module Admin
  autoload :User, 'admin/user'
end
Admin.const_defined?(:User)   #=> true

If the constant is not found the callback const_missing is not called and the method returns false.

If inherit is false, the lookup only checks the constants in the receiver:

IO.const_defined?(:SYNC)          #=> true, found in File::Constants (ancestor)
IO.const_defined?(:SYNC, false)   #=> false, not found in IO itself

In this case, the same logic for autoloading applies.

If the argument is not a valid constant name a NameError is raised with the message “wrong constant name name”:

Hash.const_defined? 'foobar'   #=> NameError: wrong constant name foobar

Removes the definition of the given constant, returning that constant’s previous value. If that constant referred to a module, this will not change that module’s name and can lead to confusion.

Search took: 9ms  ·  Total Results: 6041