class Object

for controllers, execute from AppController to MainController class_callback :before before do

...

end before :method_name instance = new instance.class_callback :before, instance.class_callback :before, arg

partialy extracted from github.com/rails/rails/blob/5-0-stable/activesupport/lib/active_support/core_ext/object/blank.rb

Public Class Methods

class_attribute(name, default=nil, &block) click to toggle source

Defines class variable

# File lib/common/class_attributes.rb, line 3
def Object.class_attribute name, default=nil, &block
  raise ArgumentError.new('name must be symbol') unless name.is_a?(Symbol)

  ivar = "@cattr_#{name}"
  instance_variable_set ivar, block || default

  define_singleton_method('%s=' % name) { |arg| send(name, arg) }
  define_singleton_method(name) do |arg=:_undefined|
    # define and set if argument given
    if arg != :_undefined
      instance_variable_set ivar, arg
      return arg
    end

    # find value and return
    ancestors.each do |klass|
      if klass.instance_variable_defined?(ivar)
        value = klass.instance_variable_get ivar
        return value.is_a?(Proc) ? instance_exec(&value) : value
      end
    end
  end
end
class_callback(name, context=nil, arg=nil) click to toggle source
# File lib/common/class_callbacks.rb, line 18
def self.class_callback name, context=nil, arg=nil
  ivar = "@ccallbacks_#{name}"

  unless context
    define_singleton_method(name) do |method_name=nil, &block|
      ref = caller[0].split(':in ').first

      self.instance_variable_set(ivar, {}) unless instance_variable_defined?(ivar)
      self.instance_variable_get(ivar)[ref] = method_name || block
    end

  else
    list = context.respond_to?(:const_missing) ? context.ancestors : context.class.ancestors
    list = list.slice 0, list.index(Object) if list.index(Object)

    list.reverse.each do |klass|
      if klass.instance_variable_defined?(ivar)
        mlist = klass.instance_variable_get(ivar).values
        mlist.each do |m|
          if m.is_a?(Symbol)
            context.send m
          else
            context.instance_exec arg, &m
          end
        end
      end
    end
  end
end
const_missing(klass) click to toggle source
# File lib/overload/object.rb, line 3
def self.const_missing klass
  file  = klass.to_s.tableize.singularize
  paths = [
    'models',
    'lib',
    'lib/vendor',
    'vendor',
    file.split('_').last.pluralize
  ].map  { |it| './app/%s/%s.rb' % [it, file] }

  klass_file = paths.find { |it| File.exist?(it) } or
    raise NameError.new('Can not find and autoload class "%s", looked in %s' % [klass, paths.map{ |it| "\n#{it}" }.join('')])

  # puts '* autoload: %s from %s' % [file, klass_file]

  require klass_file

  Object.const_get(klass)
end
render(path='/mock', in_opts={}) click to toggle source
# File lib/lux/application/lib/render.rb, line 18
def self.render path='/mock', in_opts={}, &block
  allowed_opts = [:qs, :post, :method, :session, :cookies]
  in_opts.keys.each { |k| die "#{k} is not allowed as opts param. allowed are #{allowed_opts}" unless allowed_opts.index(k) }
  # in_opts[:session] = nil unless Hash == in_opts[:session].class

  opts = {}

  if in_opts[:post]
    opts[:query_string] = in_opts[:post]
    opts[:request_method] = :post
  else
    opts[:query_string] = in_opts[:qs] || {}
    opts[:request_method] ||= in_opts[:method] || :get
  end

  opts[:request_method] = opts[:request_method].to_s.upcase
  opts[:query_string] = opts[:query_string].to_query if opts[:query_string].class.to_s == 'Hash'

  if path[0,4] == 'http'
    parsed = URI.parse(path)
    opts[:server_name] = parsed.host
    opts[:server_port] = parsed.port
    path = '/'+path.split('/', 4).last
  end

  env = Rack::MockRequest.env_for(path)
  env[:input] = opts[:post] if opts[:post]
  for k,v in opts
    env[k.to_s.upcase] = v
  end

  current = Lux::Current.new(env)
  current.session.merge!(in_opts[:session]) if in_opts[:session]

  app = new current

  return app.instance_exec &block if block_given?

  response = app.render

  body = response[2].join('')
  body = JSON.parse body if response[1]['content-type'].index('/json')

  {
    time: response[1]['x-lux-speed'],
    status: response[0],
    headers: response[1],
    session: current.session.hash,
    body: body
  }.h
end

Public Instance Methods

andand(func=nil) { |self| ... } click to toggle source
# File lib/overload/object.rb, line 75
def andand func=nil
  if present?
    if block_given?
      yield(self)
    else
      func ? send(func) : self
    end
  else
    block_given? || func ? nil : {}.h
  end
end
ap(*args) click to toggle source
# File lib/overload/raise_variants.rb, line 72
def ap(*args)
  puts args
end
blank?() click to toggle source
# File lib/overload/blank.rb, line 5
def blank?
  !self
end
cache(*args) { || ... } click to toggle source
# File lib/lux/view/helper.rb, line 90
def cache *args, &block
  ttl = args.last.class == Hash ? args.pop[:ttl] : nil
  key  = 'view:'+Lux.cache.generate_key(args)+block.source_location.join(':')
  Lux.cache.fetch(key, ttl) { yield }
end
cell(name=nil, vars={}) click to toggle source
# File lib/lux/view/lib/cell_helpers.rb, line 9
def cell name=nil, vars={}
  if name
    ViewCell.get(name, self, vars)
  else
    return @cell_base ||= ViewCell::Loader.new(self)
  end
end
class_callback(name, arg=nil) click to toggle source
# File lib/common/class_callbacks.rb, line 14
def class_callback name, arg=nil
  Object.class_callback name, self, arg
end
die(desc=nil, exp_object=nil) click to toggle source
# File lib/overload/object.rb, line 34
def die desc=nil, exp_object=nil
  desc ||= 'died without desc'
  desc = '%s: %s' % [exp_object.class, desc] if exp_object
  puts desc.red
  puts caller.slice(0, 10)
  raise desc
end
empty?() click to toggle source
# File lib/overload/blank.rb, line 9
def empty?
  blank?
end
error(msg) click to toggle source
# File lib/lux/view/helper.rb, line 96
def error msg
  %[<pre style="color:red; background:#eee; padding:10px; font-family:'Lucida Console'; line-height:14pt; font-size:10pt;">#{msg}</pre>]
end
function(&block) click to toggle source

foo = function do |list| … foo.call @list

# File lib/lux/view/helper.rb, line 54
def function &block
  block
end
helper(*names) click to toggle source

helper(:main).method

# File lib/lux/view/helper.rb, line 109
def helper *names
  Lux::View::Helper.new(self, *names)
end
instance_variables_hash() click to toggle source
# File lib/overload/object.rb, line 87
def instance_variables_hash
  Hash[instance_variables.map { |name| [name, instance_variable_get(name)] } ]
end
is_array?() click to toggle source
# File lib/overload/object.rb, line 47
def is_array?
  self.class.to_s.index('Array') ? true : false
end
is_boolean?() click to toggle source
# File lib/overload/object.rb, line 71
def is_boolean?
  self.class == TrueClass || self.class == FalseClass
end
is_false?() click to toggle source
# File lib/overload/object.rb, line 55
def is_false?
  self.class.name == 'FalseClass' ? true : false
end
is_hash?() click to toggle source

this will capture plain Hash and HashWithIndifferentAccess

# File lib/overload/object.rb, line 43
def is_hash?
  self.class.to_s.index('Hash') ? true : false
end
is_numeric?() click to toggle source
# File lib/overload/object.rb, line 63
def is_numeric?
  Float(self) != nil rescue false
end
is_string?() click to toggle source
# File lib/overload/object.rb, line 51
def is_string?
  self.class.to_s == 'String' ? true : false
end
is_symbol?() click to toggle source
# File lib/overload/object.rb, line 67
def is_symbol?
  self.class.to_s == 'Symbol' ? true : false
end
is_true?() click to toggle source
# File lib/overload/object.rb, line 59
def is_true?
  self ? true :false
end
method_attr(name=nil, &block) click to toggle source
# File lib/common/method_attr.rb, line 64
def method_attr name=nil, &block
  return MethodAttributes.get(self).or({}) if name.nil?

  MethodAttributes.define self, name, &block
end
once(id=nil) { |: true| ... } click to toggle source
# File lib/lux/view/helper.rb, line 113
def once id=nil
  Lux.current.once("template-#{id || caller[0]}") do
    block_given? ? yield : true
  end
end
or(_or) click to toggle source
# File lib/overload/object.rb, line 25
def or _or
  self.blank? || self == 0 ? _or : self
end
present?() click to toggle source
# File lib/overload/blank.rb, line 13
def present?
  !blank?
end
r(what) click to toggle source

raise object

# File lib/overload/raise_variants.rb, line 6
def r what
  opath = what.class.ancestors
  out   = opath.join("\n> ")

  data = what.is_a?(Hash) ? JSON.pretty_generate(what) : what.ai(plain:true)
  out = [data, out, ''].join("\n\n-\n\n")

  # unique_methods = what.methods - what.class.ancestors[0].instance_methods
  # raise unique_methods

  raise LocalRaiseError.new out
end
reload!() click to toggle source
# File lib/lux/config/config.rb, line 166
def reload!
  Lux::Config.live_require_check!
end
render(name, locals={}) { || ... } click to toggle source

renders just template but it is called

render :_link, link

render 'main/links/_link', link

# File lib/lux/view/helper.rb, line 61
def render name, locals={}
  if name.is_array?
    return name.map { |b| render(b) }.join("\n")
  elsif name.respond_to?(:db_schema)
    path = Thread.current[:lux][:last_template_path].split('/')[1]
    table_name = name.class.name.tableize
    locals[table_name.singularize.to_sym] = name
    eval "@_#{table_name.singularize} = name"
    name = "#{path}/#{table_name}/_#{table_name.singularize}"
  else
    name = name.to_s
    name = "#{Thread.current[:lux][:last_template_path]}/#{name}" unless name.index('/')
  end

  Lux.current.files_in_use name

  for k, v in locals
    instance_variable_set("@_#{k}", v)
  end

  if block_given?
    name = "#{name}/layout" unless name.index('/')

    Lux::View.new(name, self).render_part { yield }
  else
    Lux::View.new(name, self).render_part
  end
end
rm(object) click to toggle source

unique methods for object includes methods from modules

# File lib/overload/raise_variants.rb, line 27
def rm object
  dump = []

  dump.push ['Class', object.class]

  instance_unique = object.methods - object.class.ancestors[0].instance_methods
  class_unique    = object.methods

  object.class.ancestors.drop(1).each do |_|
    class_unique -= _.instance_methods

    if _.class != Module
      dump.push ['Parent Class', _]
      break
    end
  end

  dump.push ['Instance uniqe', instance_unique.sort] if instance_unique[0]
  dump.push ['Uniqe from parent', class_unique.sort]
  dump.push ['Uniqe from parent simple', object.class.instance_methods(false)]

  r dump
end
rr(what) click to toggle source

better console log dump

# File lib/overload/raise_variants.rb, line 20
def rr what
  src = caller[0].sub(Lux.root.to_s+'/', '').sub(Lux.fw_root.to_s, 'lux-fw').split(':in `').first
  ap ['--- START (%s) %s ---' % [what.class, src], what, '--- END ---']
end
rr!(what) click to toggle source
# File lib/overload/raise_variants.rb, line 51
def rr! what
  print "\e[H\e[2J\e[3J" # clear osx screen :)
  rr what
end
rr?(instance, m) click to toggle source

show method info show User, :secure_hash

# File lib/overload/raise_variants.rb, line 58
def rr? instance, m
  el = instance.class.instance_method(m)
  puts el.source_location.join(':').yellow
  puts '-'
  puts el.source if el.respond_to?(:source)
  nil
end
tag(name=nil, opts={}) { |opts| ... } click to toggle source

tag :div, { 'class'=>'iform' } do

# File lib/lux/view/helper.rb, line 101
def tag name=nil, opts={}, data=nil
  return HtmlTagBuilder unless name

  data = yield(opts) if block_given?
  HtmlTagBuilder.tag name, opts, data
end
try(*args) click to toggle source
# File lib/overload/object.rb, line 29
def try *args
  return nil if self.class == NilClass
  self.send(*args)
end