Class: RSQL::EvalContext

Inherits:
Object
  • Object
show all
Defined in:
lib/rsql/eval_context.rb

Overview

This class wraps all dynamic evaluation and serves as the reflection class for adding methods dynamically.

Defined Under Namespace

Classes: Registration

Constant Summary collapse

HEXSTR_LIMIT =
32

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = OpenStruct.new) ⇒ EvalContext

Returns a new instance of EvalContext.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/rsql/eval_context.rb', line 42

def initialize(options=OpenStruct.new)
    @opts         = options
    @prompt       = nil
    @verbose      = @opts.verbose
    @hexstr_limit = HEXSTR_LIMIT
    @results      = nil

    @loaded_fns         = []
    @loaded_fns_state   = {}
    @init_registrations = []
    @bangs              = {}
    @global_bangs       = {}

    @registrations = {
        :version => Registration.new('version', [], {},
            method(:version),
            'version',
            'Version information about RSQL, the client, and the server.'),
        :help => Registration.new('help', [], {},
            method(:help),
            'help',
            'Show short syntax help.'),
        :grep => Registration.new('grep', [], {},
            method(:grep),
            'grep',
            'Show results when regular expression matches any part of the content.'),
        :reload => Registration.new('reload', [], {},
            method(:reload),
            'reload',
            'Reload the rsqlrc file.'),
        :desc => Registration.new('desc', [], {},
            method(:desc),
            'desc',
            'Describe the content of a recipe.'),
        :history => Registration.new('history', [], {},
            method(:history),
            'history(cnt=1)',
            'Print recent queries made (request a count or use :all for entire list).'),
        :set_max_rows => Registration.new('set_max_rows', [], {},
            Proc.new{|r| MySQLResults.max_rows = r},
            'set_max_rows',
            'Set the maximum number of rows to process.'),
        :max_rows => Registration.new('max_rows', [], {},
            Proc.new{MySQLResults.max_rows},
            'max_rows',
            'Get the maximum number of rows to process.'),
    }
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object (private)



721
722
723
724
725
726
727
728
729
730
731
732
733
# File 'lib/rsql/eval_context.rb', line 721

def method_missing(sym, *args, &block)
    if reg = @registrations[sym]
        @bangs.merge!(reg.bangs)
        final_args = reg.args + args
        reg.block.call(*final_args)
    elsif MySQLResults.respond_to?(sym)
        MySQLResults.send(sym, *args)
    elsif MySQLResults.conn.respond_to?(sym)
        MySQLResults.conn.send(sym, *args)
    else
        super.method_missing(sym, *args, &block)
    end
end

Instance Attribute Details

#bangsObject

Returns the value of attribute bangs.



92
93
94
# File 'lib/rsql/eval_context.rb', line 92

def bangs
  @bangs
end

#promptObject (readonly)

Returns the value of attribute prompt.



91
92
93
# File 'lib/rsql/eval_context.rb', line 91

def prompt
  @prompt
end

#verboseObject

Returns the value of attribute verbose.



92
93
94
# File 'lib/rsql/eval_context.rb', line 92

def verbose
  @verbose
end

Instance Method Details

#bang_eval(field, val) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/rsql/eval_context.rb', line 160

def bang_eval(field, val)
    # allow individual bangs to override global ones, even if they're nil
    if @bangs.key?(field)
        bang = @bangs[field]
    else
        # todo: this will run on *every* value--this should be optimized
        # so that it's only run once on each query's result column
        # fields and then we'd know if any bangs are usable and pased in
        # for each result value
        @global_bangs.each do |m,b|
            if (String === m && m == field.to_s) ||
                (Regexp === m && m.match(field.to_s))
                bang = b
                break
            end
        end
    end

    if bang
        begin
            val = Thread.new{ eval("#{bang}(val)") }.value
        rescue Exception => ex
            if @verbose
                $stderr.puts("#{ex.class}: #{ex.message}", ex.backtrace)
            else
                $stderr.puts(ex.message, ex.backtrace.first)
            end
        end
    end

    return val
end

#call_init_registrationsObject



94
95
96
97
98
99
100
# File 'lib/rsql/eval_context.rb', line 94

def call_init_registrations
    @init_registrations.each do |sym|
        reg = @registrations[sym]
        sql = reg.block.call(*reg.args)
        query(sql) if String === sql
    end
end

#complete(str) ⇒ Object

Provide a list of tab completions given the prompted value.



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/rsql/eval_context.rb', line 256

def complete(str)
    if str[0] == ?.
        str.slice!(0)
        prefix = '.'
    else
        prefix = ''
    end

    ret  = MySQLResults.complete(str)

    ret += @registrations.keys.sort_by{|sym|sym.to_s}.collect do |sym|
        name = sym.to_s
        if name.start_with?(str)
            prefix + name
        else
            nil
        end
    end

    ret.compact!
    ret
end

#load(fn, opt = nil) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/rsql/eval_context.rb', line 102

def load(fn, opt=nil)
    @loaded_fns << fn unless @loaded_fns_state.key?(fn)
    @loaded_fns_state[fn] = :loading

    # this should only be done after we have established a
    # mysql connection, so this option allows rsql to load the
    # init file immediately and then later make the init
    # registration calls--we set this as an instance variable
    # to allow for loaded files to call load again and yet
    # still maintain the skip logic
    if opt == :skip_init_registrations
        reset_skipping = @skipping_init_registrations = true
    end

    ret = Thread.new {
        begin
            eval(File.read(fn), binding, fn)
            nil
        rescue Exception => ex
            ex
        end
    }.value

    if Exception === ret
        @loaded_fns_state[fn] = :failed
        if @verbose
            $stderr.puts("#{ex.class}: #{ex.message}", ex.backtrace)
        else
            bt = ret.backtrace.collect{|line| line.start_with?(fn) ? line : nil}.compact
            $stderr.puts("#{ret.class}: #{ret.message}", bt, '')
        end
        ret = false
    else
        @loaded_fns_state[fn] = :loaded
        call_init_registrations unless @skipping_init_registrations
        ret = true
    end

    @skipping_init_registrations = false if reset_skipping

    return ret
end

#reloadObject



145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/rsql/eval_context.rb', line 145

def reload
    # some files may be loaded by other files, if so, we don't want to
    # reload them again here
    @loaded_fns.each{|fn| @loaded_fns_state[fn] = nil}
    @loaded_fns.each{|fn| self.load(fn, :skip_init_registrations) if @loaded_fns_state[fn] == nil}

    # load up the inits after all the normal registrations are ready
    call_init_registrations

    # report all the successfully loaded ones
    loaded = []
    @loaded_fns.each{|fn,state| loaded << fn if @loaded_fns_state[fn] == :loaded}
    puts "loaded: #{loaded.inspect}"
end

#reset_hexstr_limitObject

Reset the hexstr limit back to the default value.



281
282
283
# File 'lib/rsql/eval_context.rb', line 281

def reset_hexstr_limit
    @hexstr_limit = HEXSTR_LIMIT
end

#safe_eval(content, results, stdout) ⇒ Object

Safely evaluate Ruby content within our context.



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/rsql/eval_context.rb', line 195

def safe_eval(content, results, stdout)
    @results = results

    # allow a simple reload to be called directly as it requires a
    # little looser safety valve...
    if 'reload' == content
        reload
        return
    end

    # same relaxed call to load too
    if m = content.match(/^\s*load\s+'(.+)'\s*$/)
        self.load(m[1])
        return
    end

    # help out the poor user and fix up any describes
    # requested so they don't need to remember that it needs
    # to be a symbol passed in
    if m = content.match(/^\s*desc\s+([^:]\S+)\s*$/)
        content = "desc :#{m[1]}"
    end

    if stdout
        # capture stdout
        orig_stdout = $stdout
        $stdout = stdout
    end

    begin
        # in order to print out errors in a loaded script so
        # that we have file/line info, we need to rescue their
        # exceptions inside the evaluation
        th = Thread.new do
            eval('begin;' << content << %q{
              rescue Exception => ex
                if @verbose
                    $stderr.puts("#{ex.class}: #{ex.message}", ex.backtrace)
                else
                    bt = []
                    ex.backtrace.each do |t|
                      break if t.include?('bin/rsql')
                      bt << t unless t.include?('lib/rsql/') || t.include?('(eval)')
                    end
                    $stderr.puts(ex.message.gsub(/\(eval\):\d+:/,''),bt)
                end
              end
            })
        end
        value = th.value
    rescue Exception => ex
        $stderr.puts(ex.message.gsub(/\(eval\):\d+:/,''))
    ensure
        $stdout = orig_stdout if stdout
    end

    return value
end

#to_hexstr(bin, limit = @hexstr_limit, prefix = '0x') ⇒ Object

Convert a binary string value into a hexadecimal string.



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/rsql/eval_context.rb', line 287

def to_hexstr(bin, limit=@hexstr_limit, prefix='0x')
    return bin if bin.nil?

    cnt = 0
    str = prefix << bin.gsub(/./m) do |ch|
        if limit
            if limit < 1
                cnt += 1
                next
            end
            limit -= 1
        end
        '%02x' % ch.bytes.first
    end

    if limit && limit < 1 && 0 < cnt
        str << "... (#{cnt} bytes hidden)"
    end

    return str
end