Created
March 10, 2023 16:35
-
-
Save Sylvance/011bef4489a6857d46bc5e9790d0f1a2 to your computer and use it in GitHub Desktop.
Base class type for entity classes in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require "json" | |
require "nokogiri" | |
module Types | |
class BaseType | |
def to_hash | |
hash = {} | |
instance_variables_hash.each do |key, value| | |
parameter = key.to_s.delete('@') | |
hash[parameter.to_sym] = value | |
end | |
hash | |
end | |
def from_hash(hash) | |
obj = self.class.new | |
hash.each do |key, value| | |
parameter = "@#{key}" | |
obj.instance_variable_set(parameter, value) | |
end | |
obj | |
end | |
def to_json | |
instance_variables_hash.to_json | |
end | |
def from_json(json_string) | |
data = JSON.parse(json_string) | |
obj = self.class.new | |
data.each do |key, value| | |
obj.instance_variable_set("@#{key}", value) | |
end | |
obj | |
end | |
def to_xml | |
builder = Nokogiri::XML::Builder.new do |xml| | |
xml.send(self.class.name.downcase) { | |
instance_variables_hash.each do |key, value| | |
parameter = key.to_s.delete('@') | |
xml.send(parameter) { | |
xml.text(value) | |
} | |
end | |
} | |
end | |
builder.to_xml | |
end | |
def from_xml(xml_string) | |
data = Nokogiri::XML.parse(xml_string) | |
obj = self.class.new | |
data.root.children.each do |node| | |
next unless node.element? | |
parameter = "@#{node.name}" | |
value = node.text | |
obj.instance_variable_set(parameter, value) | |
end | |
obj | |
end | |
def to_html | |
html = "<div><ul>" | |
instance_variables_hash.each do |key, value| | |
parameter = key.to_s.delete('@').capitalize | |
html << "<li>#{parameter}: #{value}</li>" | |
end | |
html << "</ul></div>" | |
html | |
end | |
def to_html_form | |
html = "<form>" | |
instance_variables_hash.each do |key, value| | |
parameter = key.to_s.delete('@') | |
html << "<label for='#{parameter}'>#{parameter.capitalize}:</label>" | |
html << "<input type='text' id='#{parameter}' name='#{parameter}' value='#{value}'><br>" | |
end | |
html << "</form>" | |
html | |
end | |
private | |
def instance_variables_hash | |
hash = {} | |
instance_variables.each { |var| hash[var] = instance_variable_get(var) } | |
hash | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment