How do I extend a Ruby class inside a module? - ruby

I'm trying to extend the File class inside a module. Here's my (abbreviated) code:
module Wireshark
# Extend the file class to write a header comment
class File
def write_header
self.puts '/* ' + Wireshark::AUTOGEN_LABEL + ' */'
self.puts '/* ' + Wireshark::timestamp + ' */'
end
end
# Read a file
def read
begin
file = File.read 'file'
rescue IOError
STDERR.puts 'Error reading file.'
return
end
end
end
When I run my code, I'm getting
undefined method `read' for Wireshark::File:Class (NoMethodError)
when I try to run file.read. I tried getting rid of the module encapsulation, but I'd like to only extend the File class inside my module, not in the rest of my program.

You're close.
module Wireshark
module File
def write_header
self.puts '/* ' + Wireshark::AUTOGEN_LABEL + ' */'
self.puts '/* ' + Wireshark::timestamp + ' */'
end
end
# Extend File with the methods in the Wireshark::File module
::File.send :include, Wireshark::File
# Read a file
def read
begin
file = ::File.read 'file'
rescue IOError
STDERR.puts 'Error reading file.'
return
end
end
end
The general idea here is that we define a Wireshark::File module that holds the methods you want to include on the File class, then you can just include them on File directly.
You'll also notice that in the read method, I changed File to ::File. Ruby will walk up the tree to try to find the nearest matching value for a given constant, so since you are in the Wireshark module, and there is a constant named File in that scope, using just File gets you Wireshark::File. Specifying ::File means "The File constant at the top-level namespace".

In the current version of Ruby it's not possible to do this, but it is a popular proposed extension called "refinements".
If you need to patch the core File class, you'll need to do that as a monkey patch, and this affects all instances of File anywhere in your Ruby process.
Normally you can do it this way:
# Define the instance methods you want to overide
module MyFileHacksInstanceMethods
def read
# ... (reimplementation) ...
end
end
# Force load these in the File class
class File
include MyFileHacksInstanceMethods
end
What you've declared in your example here is an independent class called Wireshark::File because it's within that module's namespace. ::File is the main class (:: being a prefix to force absolute name, sort of like / for filesystems).

Related

Ruby encapsulate/package existing code into a namespace

I've been looking all around and didn't found any kind of answer to the problem i'm facing in Ruby. I'm writing an app that use core modules sets that are available in different versions. If I'm sourcing a core set version after an another one both code version will be sourced at the same and will clash with each other. That is quite normal and I'm ok with this.
One approach could be to unload the previous version to load the new one but I'd like to keep all the ones loaded into specific namespaces (to avoid time consuming to unload/reload code all the time). 2 possible solutions to me (or maybe other)
Either source the code then move it into a version namespace (some clues to do it see below but doesn't work yet)
Or source the code directly into a version namespace (don't know how to do it exactly, maybe with module_eval but need to recode the require process with dependencies). Does any solution seems possible ?
Here is a very simple poc of what I'm trying to achieve
file : coreset_1.0.0.rb
module CoreA
def self.who_am_i?; self.to_s; end
def self.get_coreb; CoreB end
end
module CoreB
def self.who_am_i?; self.to_s; end
end
file : coreset_2.0.0.rb (got some changes)
module CoreA
def self.my_name; self.to_s; end
def self.get_coreb; CoreB end
end
module CoreB
def self.my_name; self.to_s; end
end
file : coreManager.rb
module CoreManager
def self.load_version(arg_version)
#Create a module set for the selected version
core_set_name = CoreSet + '_' + arg_version.gsub('.', '_')
core_set = eval("Module #{core_set_name}; end; #{core_set_name}"
#Load the requested code
require "coreset_#{arg_version}.rb"
#Move loaded code into it core set module
core_set.const_set(:CoreA, Object.send(:remove_const, :CoreA))
core_set.const_set(:CoreB, Object.send(:remove_const,:CoreB))
#Return the created core set
core_set
end
end
If running the code :
require 'coreManager.rb'
core_set = CoreManager.load_version("1.0.0")
puts core_set::CoreA.who_am_i?
puts core_set::CoreA.get_coreB
it returns :
CoreA #not CoreSet_1_0_0::CoreA
uninitialized constant CoreA::CoreB (NameError)
If running something statically defined, it works
module CoreSet
module CoreA
def self.who_am_i?; self.to_s; end
def self.get_coreb; CoreB end
end
module CoreB
def self.who_am_i?; self.to_s; end
end
end
CoreSet::CoreA.get_coreb
It returns as expected :
CoreSet::CoreB
Depite of what is usually said :"a module is a constant", it seems to be more than that. What are the differencies and how to make the dynamic version working ?
Any other ideas ?
Thanks for your help folks :)
There are several things broken in your code (which is ok for POC, I guess), but the main one is that require loads constants and globals into the global namespace.
So, your Core<X> modules are not namespaced this way, as you might expect. There is Kernel#load method that allows "wrapped" execution of the loaded file, but it's wrapped into an anonymous module, so you can prevent the global namespace from being polluted, but you cannot "target" the constants to be defined into a particular namespace this way.
What you could try is to load the code as text and then eval it within the dynamically created module, matching your version. For example, look at this quick and very dirty sketch (coreset_...rb files are expected to sit into coresets directory):
module CoreSet; end
class CoreManager
class << self
def load_version(ver)
raise "Vesion #{ver} unknown" unless exists?(ver)
file = filename(ver)
code = File.read(file)
versioned_wrapper = Module.new do
class_eval code
end
CoreSet.const_set("V_#{ver.gsub('.', '_')}", versioned_wrapper)
end
private
def exists?(ver)
File.exists? filename(ver)
end
def filename(ver)
"coresets/coreset_#{ver.gsub('.', '_')}.rb"
end
end
end
CoreManager.load_version("1.0.0")
CoreManager.load_version("2.0.0")
p CoreSet::V_1_0_0::CoreA.who_am_i? # => "CoreSet::V_1_0_0::CoreA"
p CoreSet::V_1_0_0::CoreA.get_coreb # => CoreSet::V_1_0_0::CoreB
p CoreSet::V_2_0_0::CoreA.my_name # => "CoreSet::V_2_0_0::CoreA"
p CoreSet::V_2_0_0::CoreA.get_coreb # => CoreSet::V_2_0_0::CoreB
But, DON'T do this at home, please :) At least, I would think twice.
If all you need is to have all the versions loaded at once (you need namespaces exactly for this, right?) what stops you from defining them statically, like CoreSet::V1::Core<X> etc and use the idiomatic and safe ways to (auto)load them? :) Playing with dynamic nested constants definition (and, especially, their removing) is one of the easiest ways to shoot your own foot...
Ok I finally came to a solution that may help others or that can be discussed.
Getting the error uninitialized constant CoreA::CoreB (NameError) leads me to take the problem under a new angle. If I'm not able to access to CoreB module from CoreA (because the module nesting has been broken when redefining module constants into the CoreSet module) then why not referencing in each core module the other ones in the set ? And finaly it works without any dirty hack, I'm just creating pointers and the Ruby Core find it natively ;)
module CoreManager
def self.load_version(arg_version)
#Create a module set for the selected version
core_set_name = CoreSet + '_' + arg_version.gsub('.', '_')
core_set = eval("Module #{core_set_name}; end; #{core_set_name}"
#Load the requested code
toplevel_consts = Object.constants
require "coreset_#{arg_version}.rb"
core_modules = Object.constants - toplevel_consts
#Move the core modules to the set namespace
core_modules.collect! do |core_module|
core_module_sym = core_module.to_s.to_sym
core_set.const_set(core_module_sym, Object.send(:remove_const, core_module_sym))
eval("#{core_set}::#{core_module}")
end
#Create connexion between set cores to skirt broken module nesting
core_modules.each do |current_core|
core_modules.each do |other_core|
current_core.const_set(other_core.to_s.to_sym, other_core) unless current_core == other_core
end
end
#Return the created core set
core_set
end
end

My very simple custom Puppet type and provider does not work

I am reading about how to create custom types and providers in Puppet.
But I am getting the error:
Error: Could not autoload puppet/provider/createfile/ruby: undefined method `[]' for nil:NilClass
when running the below code:
mymodule/lib/puppet/type/filecreate.rb
require 'fileutils'
Puppet::Type.newtype(:filecreate) do
ensurable do
defaultvalues
defaultto :present
end
#doc = "Create a file."
newproperty(:name, :namevar => true) do
desc "The name of the file"
end
newproperty(:path) do
desc "The path of the file"
end
end
mymodule/lib/puppet/provider/filecreate/ruby.rb
require 'fileutils'
Puppet::Type.type(:filecreate).provide(:ruby) do
desc "create file.."
puts resource[:name] # this line does not seem to work, why?
puts resource[:path] # this line does not seem to work, why?
def create
puts "create file..."
puts resource[:name]
end
def destroy
puts ("destroy file...")
FileUtils.rm resource[:path]+resource[:name]
end
# Exit method never seems to be called
def exists?
puts "is method beeing called???"
File.exists?(resource[:path])
end
end
I guess the way of fetching the parameter values, puts resource[:name] not is correct. So how can I fetch the filename file.txt declared as the namevar for my custom type filecreate (see below)?
Also, method exists does not seem to be called. Why?
And my init.pp contains this simple code:
class myclass {
filecreate{'file.txt':
ensure => present,
path => '/home/myuser/',
}
}
Your puts calls do not work because you try and access an instance attribute (resource) on the class level. It makes no semantic sense to access the values in this context. Remove those calls.
Generally, it is better to use Puppet.debug instead of puts to collect this kind of information.
To find out where such errors come from, call puppet with the --trace option.

Unable to run regex on file content after putting it?

I have created a simple class to handle opening, reading, and closing a file. In addition, I would like to run a regex on its contents to find a 4 digit date. However, when I run my code I get the following error:
file_class.rb:17:in `find_date': undefined method `match' for nil:NilClass (NoMethodError)
from file_class.rb:24:in `<main>'
This error only occurs if I run the read_file method before it, which simply puts the file contents. I am not sure why doing so would result in such an error.
Below is my code:
class MyFile
attr_reader :handle
def initialize(filename)
#handle = File.open(filename)
end
def read_file
puts #handle.gets
end
def finished
#handle.close
end
def find_date
matching = #handle.gets.match(/\d{4}/)
puts matching[0]
end
end
f = MyFile.new('text.txt')
f.read_file
f.find_date
f.finished
Thanks for the help.
I'm guessing your file had a single line of contents.
When you call gets on an open file handle, the handle returns the line it is currently looking at and moves its "cursor" down to the next line. After you've read the last line, gets will return nil.
Your class would be better (for a few reasons) if you read the file once and cache the contents, rather than caching the handle and attempting to read several times:
class MyFile
attr_reader :contents
def initialize(filename)
File.open(filename) do |f|
#contents = f.read
end
end
def find_date
matching = #contents.match(/\d{4}/)
puts matching[0]
end
end
This approach is better because:
You only need to read the file once.
You're reading the whole file at once, not one line at a time (File#read instead of File#gets).
Your class has better encapsulation - other code that wants to use it doesn't need to tell your class to read the file, then find a date, then close the file - all of the logic is internal to your class.
You need to write less code - attr_accessor makes contents available to calling code without you needing to write your own methods. This is good because it's quicker to write and, much more importantly, it's clearer to read.

read json in Ruby and set variables for use in another class

The need here is to read a json file and to make the variables which is done from one class and use them with in another class. What I have so far is
helper.rb
class MAGEINSTALLER_Helper
#note nonrelated items removed
require 'fileutils'
#REFACTOR THIS LATER
def load_settings()
require 'json'
file = File.open("scripts/installer_settings.json", "rb")
contents = file.read
file.close
#note this should be changed for a better content check.. ie:valid json
#so it's a hack for now
if contents.length > 5
begin
parsed = JSON.parse(contents)
rescue SystemCallError
puts "must redo the settings file"
else
puts parsed['bs_mode']
parsed.each do |key, value|
puts "#{key}=>#{value}"
instance_variable_set("#" + key, value) #better way?
end
end
else
puts "must redo the settings file"
end
end
#a method to provide feedback simply
def download(from,to)
puts "completed download for #{from}\n"
end
end
Which is called in a file of Pre_start.rb
class Pre_start
#note nonrelated items removed
def initialize(params=nil)
puts 'World'
mi_h = MAGEINSTALLER_Helper.new
mi_h.load_settings()
bs_MAGEversion=instance_variable_get("#bs_MAGEversion") #doesn't seem to work
file="www/depo/newfile-#{bs_MAGEversion}.tar.gz"
if !File.exist?(file)
mi_h.download("http://www.dom.com/#{bs_MAGEversion}/file-#{bs_MAGEversion}.tar.gz",file)
else
puts "mage package exists"
end
end
end
the josn file is valid json and is a simple object (note there is more just showing the relevant)
{
"bs_mode":"lite",
"bs_MAGEversion":"1.8.0.0"
}
The reason I need to have a json settings file is that I will need to pull settings from a bash script and later a php script. This file is the common thread that is used to pass settings each share and need to match.
Right now I end up with an empty string for the value.
The instance_variable_setis creating the variable inside MAGEINSTALLER_Helper class. That's the reason why you can't access these variables.
You can refactor it into a module, like this:
require 'fileutils'
require 'json'
module MAGEINSTALLER_Helper
#note nonrelated items removed
#REFACTOR THIS LATER
def load_settings()
content = begin
JSON.load_file('scripts/installer_settings.json')
rescue
puts 'must redo the settings file'
{} # return an empty Hash object
end
parsed.each {|key, value| instance_variable_set("##{key}", value)}
end
#a method to provide feedback simply
def download(from,to)
puts "completed download for #{from}\n"
end
end
class PreStart
include MAGEINSTALLER_Helper
#note nonrelated items removed
def initialize(params=nil)
puts 'World'
load_settings # The method is available inside the class
file="www/depo/newfile-#{#bs_MAGEversion}.tar.gz"
if !File.exist?(file)
download("http://www.dom.com/#{#bs_MAGEversion}/file-#{#bs_MAGEversion}.tar.gz",file)
else
puts "mage package exists"
end
end
end
I refactored a little bit to more Rubish style.
On this line:
bs_MAGEversion=instance_variable_get("#bs_MAGEversion") #doesn't seem to work
instance_variable_get isn't retrieving from the mi_h Object, which is where your value is stored. The way you've used it, that line is equivalent to:
bs_MAGEversion=#bs_MAGEversion
Changing it to mi_h.instance_variable_get would work. It would also be painfully ugly ruby. But I sense that's not quite what you're after. If I read you correctly, you want this line:
mi_h.load_settings()
to populate #bs_MAGEversion and #bs_mode in your Pre_start object. Ruby doesn't quite work that way. The closest thing to what you're looking for here would probably be a mixin, as described here:
http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html
We do something similar to this all the time in code at work. The problem, and solution, is proper use of variables and scoping in the main level of your code. We use YAML, you're using JSON, but the idea is the same.
Typically we define a constant, like CONFIG, which we load the YAML into, in our main code, and which is then available in all the code we require. For you, using JSON instead:
require 'json'
require_relative 'helper'
CONFIG = JSON.load_file('path/to/json')
At this point CONFIG would be available to the top-level code and in "helper.rb" code.
As an alternate way of doing it, just load your JSON in either file. The load-time is negligible and it'll still be the same data.
Since the JSON data should be static for the run-time of the program, it's OK to use it in a CONSTANT. Storing it in an instance variable only makes sense if the data would vary from instance to instance of the code, which makes no sense when you're loading data from a JSON or YAML-type file.
Also, notice that I'm using a method from the JSON class. Don't go through the rigamarole you're using to try to copy the JSON into the instance variable.
Stripping your code down as an example:
require 'fileutils'
require 'json'
CONTENTS = JSON.load_file('scripts/installer_settings.json')
class MAGEINSTALLER_Helper
def download(from,to)
puts "completed download for #{from}\n"
end
end
class Pre_start
def initialize(params=nil)
file = "www/depo/newfile-#{ CONFIG['bs_MAGEversion'] }.tar.gz"
if !File.exist?(file)
mi_h.download("http://www.dom.com/#{ CONFIG['bs_MAGEversion'] }/file-#{ CONFIG['bs_MAGEversion'] }.tar.gz", file)
else
puts "mage package exists"
end
end
end
CONFIG can be initialized/loaded in either file, just do it from the top-level before you need to access the contents.
Remember, Ruby starts executing it at the top of the first file and reads downward. Code that is outside of def, class and module blocks gets executed as it's encountered, so the CONFIG initialization will happen as soon as Ruby sees that code. If that happens before you start calling your methods and creating instances of classes then your code will be happy.

Calling a module inside another module

I am calling a method in a module from another module and am getting a weird error.
require 'nmap'
...
module Enumeration::Hostnames
def reverse_dns ip_addrs
...
ip_addrs.each do |ip_addr|
list = ListScan.test ip_addr #this is the problem
...
end
...
ListScan is in the nmap file.
module ListScan
def ListScan.test target
target = '-sL ' + target
ListScan::parse_results Nmap::Parser.parsescan('nmap',target)
end
...
end
The error is `const_missing': uninitialized constant Enumeration::Hostnames::ListScan (NameError) on the line ListScan.test ip_addr.
Why is it assuming that ListScan is in the Enumeration::Hostnames module? Mixing in ListScan to Hostnames didn't work.
Ruby searches for constants starting from the current context, which in this case is Enumeration::Hostnames.
Try using
::ListScan.test ip_address

Resources