Data Structure Generator

Data Structure Generator
Version 1.0


Description:
The idea behind this script was simply: How could I create a data struct class, container class, and make creating these objects easy? The result was a module to generate both Ruby code that creates the Ruby data struct class, creates the container and everything for you. Additionally, a nice little html page that generates the Ruby code for creation of all the objects. More additionally, it organizes your containers for you, auto-increases object id instances, and adds the option to save and load objects into rxdata files!

The Script:
Can you believe all this power in a script under 400 lines for coding, with comments included?
  1. #==============================================================================
  2. # ** Data Structure Generator
  3. #------------------------------------------------------------------------------
  4. # SephirothSpawn
  5. # Version 1.0
  6. # 2010-01-27
  7. #------------------------------------------------------------------------------
  8. # * Details
  9. #
  10. #   This script was designed to auto-generate data structures and make a nice
  11. #   like html form to allow non-scripters to create these new objects with
  12. #   no scripting required! So any non-scripter can make can not only create
  13. #   data structures, but create an entire database!
  14. #
  15. #   This cannot be easier (and I challenge anyone)!
  16. #
  17. #   The object class is generated auto-matically. The container object is added
  18. #   to a pre-set DSG object ($data_dsg). The generated Ruby code also
  19. #   adds the option to save and load the objects from rxdata files as well.
  20. #
  21. #   The class generated will always be a child class of DSG::Data_Object.
  22. #   Why? The parent class serves 2 functions:
  23. #
  24. #    1) Auto-Set an ID instance variable that increases by 1 after each object
  25. #       is created
  26. #    2) Auto-Sets object directly into the container. You will never need to
  27. #       set the object into $data container.
  28. #
  29. #
  30. #   A HTML page with a form is generated for users to generate Ruby code to
  31. #   create the objects into the data structure. Users fill out this form and
  32. #   Ruby code is generated for you.
  33. #------------------------------------------------------------------------------
  34. # * Generating Ruby Data Struct class and HTML form
  35. #
  36. #   1) Insert a new area into the script list
  37. #   2) Start Data Struct - Add this line
  38. #      DSG.start(class_name, rxdata_name, container_name)
  39. #
  40. #      Replace class_name with a Ruby class name (ie: 'Card')
  41. #      Replace rxdata with data filename (ie: 'Cards.rxdata')
  42. #      Replace container name (ie: 'cards')
  43. #   3) Add required instances (instances that are passed in the initialization)
  44. #
  45. #      For each required instance, add this line:
  46. #
  47. #      DSG.add_req_instance(instance_name, description, default, type)
  48. #
  49. #      Replace instance_name with your instances name (ie: 'suit')
  50. #      Replace description with a simple description for instance (ie: 'Suit')
  51. #      Replace default with default value (ie: 'Hearts')
  52. #      Replace type with Ruby type for values (ie: 'String')
  53. #
  54. #      * Note that the default is only used for HTML form fields
  55. #
  56. #   4) Add optional instances (instances not specified in the initialization)
  57. #
  58. #      For each instance, add this line:
  59. #
  60. #      DSG.add_instance(instance_name, description, default, type)
  61. #
  62. #      * See step 3 for replacement instructions
  63. #      * Note that the default value is specified in object class init.
  64. #
  65. #   5) Finish Data Struct - Add this line of code:
  66. #      DSG.finish(ruby_name, html_name)
  67. #
  68. #      Replace ruby_name with .txt file generated with object class code
  69. #       (ie: 'Card.txt') (Defaults to 'Generate.txt')
  70. #      Replace html_name with .html file form (ie: 'Card.html')
  71. #       (Defaults to 'Generate.html')
  72. #      
  73. #   6) The code generated in the .txt file is your Ruby code to insert into
  74. #      script editor.
  75. #
  76. #   7) Open the .html file and complete the form. For each object, press the
  77. #      Add Item button. When finished, copy and paste code into your first
  78. #      generated code between the lines:
  79. #
  80. #      # Insert Database Modifications Here
  81. #      <Insert HTML Generated Code Here>
  82. #      # Stop Modifications
  83. #==============================================================================
  84.  
  85. #==============================================================================
  86. # ** Data Structure Generator
  87. #==============================================================================
  88.  
  89. module DSG
  90.   #--------------------------------------------------------------------------
  91.   # * Start
  92.   #--------------------------------------------------------------------------
  93.   def self.start(class_name, rxdata_name, container_name)
  94.     @class_name  = class_name
  95.     @rxdata_name = rxdata_name
  96.     @container_name = container_name
  97.     @required_instances = {}
  98.     @instances = {}
  99.   end
  100.   #--------------------------------------------------------------------------
  101.   # * Add Required Instance
  102.   #--------------------------------------------------------------------------
  103.   def self.add_req_instance(instance_name, description, default, type)
  104.     @required_instances[instance_name] = [description, default, type]
  105.   end
  106.   #--------------------------------------------------------------------------
  107.   # * Add Instance
  108.   #--------------------------------------------------------------------------
  109.   def self.add_instance(instance_name, description, default, type)
  110.     @instances[instance_name] = [description, default, type]
  111.   end
  112.   #--------------------------------------------------------------------------
  113.   # * Finish
  114.   #--------------------------------------------------------------------------
  115.   def self.finish(ruby_name = 'Generate.txt', html_name = 'Generate.html')
  116.     # Generate Data Structure Ruby Code
  117.     self.generate_ruby_data_struct(ruby_name)
  118.     # Generate HTML Sheet Field
  119.     self.generate_html_form(html_name)
  120.   end
  121.   #--------------------------------------------------------------------------
  122.   # * Generate Data Structure Ruby Code
  123.   #--------------------------------------------------------------------------
  124.   def self.generate_ruby_data_struct(ruby_name)
  125.     # Start Line Code
  126.     s  = []
  127.     s << '#=============================================================================='
  128.     s << '# ** Load Rxdata (Set to false when change in database)'
  129.     s << '#=============================================================================='
  130.     s << ''
  131.     s << 'module DSG'
  132.     s << "  Load_#{@container_name.capitalize} = false"
  133.     s << 'end'
  134.     s << ''
  135.     s << '#=============================================================================='
  136.     s << "# ** #{@class_name}"
  137.     s << '#=============================================================================='
  138.     s << ''
  139.     s << "class #{@class_name} < DSG::Data_Object"
  140.     s << '  #--------------------------------------------------------------------------'
  141.     s << '  # * Public Instance Variables'
  142.     s << '  #--------------------------------------------------------------------------'
  143.     (@instances.keys + @required_instances.keys).sort.each do |instance_name|
  144.       s << "  attr_accessor :#{instance_name}"
  145.     end
  146.     s << '  #--------------------------------------------------------------------------'
  147.     s << '  # * Object Initialization'
  148.     s << '  #--------------------------------------------------------------------------'
  149.     s << "  def initialize(#{@required_instances.keys.sort.join(', ')})"
  150.     s << '    super()'
  151.     @required_instances.keys.sort.each do |instance_name|
  152.       s << "    @#{instance_name} = #{instance_name}"
  153.     end
  154.     @instances.keys.sort.each do |instance_name|
  155.       default = @instances[instance_name][1]
  156.       s << "    @#{instance_name} = #{self.object_to_string(default)}"
  157.     end
  158.     s << '  end'
  159.     s << 'end'
  160.     s << ''
  161.     s << '# Creates Container Object'
  162.     s << "$data_dsg.add_container('#{@container_name}')"
  163.     s << "DSG::Containers.module_eval('attr_reader :#{@container_name}')"
  164.     s << "DSG::Data_Object.module_eval(\"@@container_objects[#{@class_name}] = '#{@container_name}'\")"
  165.     s << ''
  166.     s << '#=============================================================================='
  167.     s << '# ** Load or Create Database'
  168.     s << '#=============================================================================='
  169.     s << ''
  170.     s << "if DSG::Load_#{@container_name.capitalize}"
  171.     s << "  $data_dsg.#{@container_name} = load_data('Data/#{@rxdata_name}')"
  172.     s << 'else'
  173.     s << ''
  174.     s << '# Insert Database Modifications Here'
  175.     s << ''
  176.     s << '# Stop Modifications'
  177.     s << ''
  178.     s << '# Save Data File'
  179.     s << "save_data($data_dsg.#{@container_name}, 'Data/#{@rxdata_name}')"
  180.     s << ''
  181.     s << 'end'
  182.     # Write Ruby Code
  183.     file = File.new(ruby_name, 'w+')
  184.     s.each {|l| file.write("#{l}\n")}
  185.     file.close
  186.   end
  187.   #--------------------------------------------------------------------------
  188.   # * Generate HTML Doc Form
  189.   #--------------------------------------------------------------------------
  190.   def self.generate_html_form(html_name)
  191.     # Start Line Code
  192.     s  = []
  193.     s << '<html>'
  194.     s << '<head>'
  195.     s << '<meta http-equiv="Content-Language" content="en-us">'
  196.     s << '<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">'
  197.     s << '<title>Data Structure Generator 1.0</title>'
  198.     s << '<script type="text/javascript">'
  199.     s << ''
  200.     s << '// * Variable Decloration'
  201.     s << "var class_name = '#{@class_name}'"
  202.     @instances.keys.sort.each do |instance_name|
  203.       default = @instances[instance_name][1]
  204.       s << "var #{instance_name}_default = #{self.object_to_string(default)}"
  205.     end
  206.     s << ''
  207.     s << 'function AddItem() {'
  208.     s << ''
  209.     s << '// Get Current Code'
  210.     s << 'text  = document.form1.textarea.value'
  211.     s << ''
  212.     s << '// Add Comment'
  213.     s << "text += '# ' + document.form1.object_coment.value"
  214.     s << 'text += "\n"'
  215.     s << ''
  216.     s << '// Create Object'
  217.     s << "text += class_name + '.new('"
  218.     if @required_instances.size > 0
  219.       s << '// Add Required Items'
  220.       @required_instances.keys.sort.each do |instance_name|
  221.         s << "text += document.form1.#{instance_name}.value"
  222.         if instance_name != @required_instances.keys.sort.last
  223.           s << 'text += ", "'
  224.         end
  225.       end
  226.       s << '// Finish Required Items'
  227.     end
  228.     s << 'text += ")\n"'
  229.     s << ''
  230.     if @instances.size > 0
  231.       s << '// Modify Instances Comparing Defaults'
  232.       @instances.keys.sort.each do |instance_name|
  233.         s << "value = document.form1.#{instance_name}.value"
  234.         s << "if (value != #{instance_name}_default) {"
  235.         s << "  text += 'object.#{instance_name} = ' + value"
  236.         s << '  text += "\n"'
  237.         s << '}'
  238.       end
  239.       s << ''
  240.     end
  241.     s << '// Write Text'
  242.     s << 'document.form1.textarea.value = text'
  243.     s << '}'
  244.     s << '</script>'
  245.     s << '</head>'
  246.     s << ''
  247.     s << '<body text="#FFFFFF">'
  248.     s << ''
  249.     s << '<div align="center">'
  250.     s << '  <form action="" method="POST" name="form1" id="form1">'
  251.     s << '    <table border="1" cellspacing="3" cellpadding="5" bordercolor="#111111" width="600" bgcolor="#808080">'
  252.     s << '      <tr>'
  253.     s << '        <th colspan="3" bgcolor="#333333"><font size="5">Data Structure Generator 1.0</font></th>'
  254.     s << '      </tr>'
  255.     s << '      <tr>'
  256.     s << '        <td colspan="2" bgcolor="505050">Comment Heading (To Seperate Items)</td>'
  257.     s << '        <td bgcolor="505050"><input type="text" name="object_coment" size="20" value="New Item" /></td>'
  258.     s << '      </tr>'
  259.     if @required_instances.size > 0
  260.       s << '      <tr>'
  261.       s << '        <th colspan="3" bgcolor="#444444"><font size="4">Required Settings</font></th>'
  262.       s << '      </tr>'
  263.       s << '      <tr>'
  264.       s << '      <!-- Start Required Instance Fields -->'
  265.       @required_instances.keys.sort.each do |instance_name|
  266.         s << '      <tr>'
  267.         s << "        <td width='30%'>#{@required_instances[instance_name][0]}</td>"
  268.         s << "        <td align='center' width='35%'><input type='text' name='#{instance_name}' size='20' value='#{@required_instances[instance_name][1]}'><br><font size='1'>#{instance_name}</font></td>"
  269.         s << "        <td width='35%'>Default: #{@required_instances[instance_name][1]} (#{@required_instances[instance_name][2]})</td>"
  270.         s << '      </tr>'
  271.       end
  272.       s << '      <!-- End Required Instance Fields -->'
  273.     end
  274.     if @instances.size > 0
  275.       s << '      <tr>'
  276.       s << '        <th colspan="3" bgcolor="#444444"><font size="4">Optional Settings</font></th>'
  277.       s << '      </tr>'
  278.       s << '      <!-- Start Instance Fields -->'
  279.       @instances.keys.sort.each do |instance_name|
  280.         s << '      <tr>'
  281.         s << "        <td width='30%'>#{@instances[instance_name][0]}</td>"
  282.         s << "        <td align='center' width='35%'><input type='text' name='#{instance_name}' size='20' value='#{@instances[instance_name][1]}'><br><font size='1'>#{instance_name}</font></td>"
  283.         s << "        <td width='35%'>Default: #{@instances[instance_name][1]} (#{@instances[instance_name][2]})</td>"
  284.         s << '      </tr>'
  285.       end
  286.       s << '      <!-- End Instance Fields -->'
  287.     end
  288.     s << '      <tr>'
  289.     s << '        <td colspan="3" bgcolor="#222222" align="center" ><input type="button" name="Submit" value="Add Item" onclick="AddItem()" /></td>'
  290.     s << '      </tr>'
  291.     s << '      <tr>'
  292.     s << '        <td colspan="3" bgcolor="#FFFFFF">'
  293.     s << '          <label>'
  294.     s << '            <textarea name="textarea" cols="70" rows="10" wrap="physical" value=""></textarea>'
  295.     s << '          </label>'
  296.     s << '        </td>'
  297.     s << '      </tr>'
  298.     s << '    </table>'
  299.     s << '  </form>'
  300.     s << '</div>'
  301.     s << ''
  302.     s << '</body>'
  303.     s << ''
  304.     s << '</html>'
  305.     # Write HTML Code
  306.     file = File.new(html_name, 'w+')
  307.     s.each {|l| file.write("#{l}\n")}
  308.     file.close
  309.   end
  310.   #--------------------------------------------------------------------------
  311.   # * Object to String
  312.   #--------------------------------------------------------------------------
  313.   def self.object_to_string(object)
  314.     case object
  315.     when Array
  316.       object.collect! {|o| self.object_to_string(o)}
  317.       return "[#{object.join(', ')}]"
  318.     when Hash
  319.       array = []
  320.       default.each do |k, v|
  321.         k_string = self.object_to_string(k)
  322.         v_string = self.object_to_string(v)
  323.         array << "#{k} => #{v}"
  324.       end
  325.       return "{#{array.join(', ')}}"
  326.     when String
  327.       return "'#{object}'"
  328.     else
  329.       return object
  330.     end
  331.   end
  332. end
  333.  
  334. #==============================================================================
  335. # ** DSG::Data_Object
  336. #==============================================================================
  337.  
  338. class DSG::Data_Object
  339.   #--------------------------------------------------------------------------
  340.   # * Container Objects
  341.   #--------------------------------------------------------------------------
  342.   @@container_objects = {}
  343.   #--------------------------------------------------------------------------
  344.   # * Object ID#s (Auto-Counter)
  345.   #--------------------------------------------------------------------------
  346.   @@ids = {}
  347.   #--------------------------------------------------------------------------
  348.   # * Public Instance Variable
  349.   #--------------------------------------------------------------------------
  350.   attr_accessor :id
  351.   #--------------------------------------------------------------------------
  352.   # * Object Initialization
  353.   #--------------------------------------------------------------------------
  354.   def initialize
  355.     # Create Class Counter (If not defined)
  356.     @@ids[self.class] = 0 unless @@ids.has_key?(self.class)
  357.     # Add class counter
  358.     @@ids[self.class] += 1
  359.     # Set ID
  360.     @id = @@ids[self.class]
  361.     # Add object to container
  362.     eval "$data_dsg.#{@@container_objects[self.class]}[@id] = self"
  363.   end
  364. end
  365.  
  366. #==============================================================================
  367. # ** Data Structure Generator::Containers
  368. #==============================================================================
  369.  
  370. class DSG::Containers
  371.   #--------------------------------------------------------------------------
  372.   # * Add Container
  373.   #--------------------------------------------------------------------------
  374.   def add_container(instance_name)
  375.     eval "@#{instance_name} = {}"
  376.   end
  377. end
  378.  
  379. $data_dsg = DSG::Containers.new
Expand to see the code.


Example:
Take for instance, something like my Triple Triad script. The following would create a class for these with the basic 4 powers and element for the cards. It would save them in a container $data_dsg.cards.

  1. DSG.start('Card', 'Cards.rxdata', 'cards')
  2. stats = {
  3.   'np' => 'North Power',
  4.   'ep' => 'East Power',
  5.   'sp' => 'South Power',
  6.   'wp' => 'West Power',
  7. }
  8. stats.each do |stat, string|
  9.   DSG.add_req_instance("#{stat}", "#{string}", 1, 'Integer')
  10. end
  11. DSG.add_instance('element', 'Element', 0, 'Integer')
  12. DSG.finish
Expand to see the code.


Running this code would end up generating this Ruby code for you:
  1. #==============================================================================
  2. # ** Load Rxdata (Set to false when change in database)
  3. #==============================================================================
  4.  
  5. module DSG
  6.   Load_Cards = false
  7. end
  8.  
  9. #==============================================================================
  10. # ** Card
  11. #==============================================================================
  12.  
  13. class Card < DSG::Data_Object
  14.   #--------------------------------------------------------------------------
  15.   # * Public Instance Variables
  16.   #--------------------------------------------------------------------------
  17.   attr_accessor :element
  18.   attr_accessor :ep
  19.   attr_accessor :np
  20.   attr_accessor :sp
  21.   attr_accessor :wp
  22.   #--------------------------------------------------------------------------
  23.   # * Object Initialization
  24.   #--------------------------------------------------------------------------
  25.   def initialize(ep, np, sp, wp)
  26.     super()
  27.     @ep = ep
  28.     @np = np
  29.     @sp = sp
  30.     @wp = wp
  31.     @element = 0
  32.   end
  33. end
  34.  
  35. # Creates Container Object
  36. $data_dsg.add_container('cards')
  37. DSG::Containers.module_eval('attr_reader :cards')
  38. DSG::Data_Object.module_eval("@@container_objects[Card] = 'cards'")
  39.  
  40. #==============================================================================
  41. # ** Load or Create Database
  42. #==============================================================================
  43.  
  44. if DSG::Load_Cards
  45.   $data_dsg.cards = load_data('Data/Cards.rxdata')
  46. else
  47.  
  48. # Insert Database Modifications Here
  49.  
  50. # Stop Modifications
  51.  
  52. # Save Data File
  53. save_data($data_dsg.cards, 'Data/Cards.rxdata')
  54.  
  55. end
Expand to see the code.


How neat? It would also generate a html page for you. Fill out the form, create your objects, copy and page and the code is done.

All objects could simply by accessed via:
  1. $data_dsg.cards[card_id]
Expand to see the code.





Author Notes:
I am all up for suggestions to make this easier, or questions on how to use this. Other than that...

Enjoy!
Hm, a very versatile script... should shave some time off one or the other project. Great concept there! :)

As you're asking for suggestions... as far as I can tell, this just creates the methods for you to copy&paste them into the project, right? I think it'd be both easier on the scripter, as well as less line-consuming (while being more resource-draining) if you'd make a script simulating those classes. In other words, a script that injects 'virtual scripts' (wonky term for a virtual media really XD ) into the project, yet only needs the big code once.
So, instead of writing a script that outputs a script to paste into the project, you'd have a script that runs all the predefined cases (one would be the cards example) right in the game itself - no need to copypaste anything, just define the arguments.

Don't get me wrong here though... I really like this script, and my addition would only be for comforting reasons - probably not worth the effort ^^"
Hmm.. I thought about this as well. It would have to generate the code everytime game is loaded, and eval what could be a potential chunk of data. I could work with Zeriab, and work on injecting the script into the Scripts.rxdata file, deleting the original generator code. But in the end, that's not a lot more than copy and paste itself, except the script would do be doing it for you. Overall, I just didn't want to have to eval everything.

However, in the end this is for scripter a to create script b so user c can copy and paste the script into their project and use the html page to generate their database (as you would with the database editor). If any other person planned on using script b, they would end up coping something from scripter a, and might as well not be something that needs to be eval'd more than it has to be.


I also planned on originally not making a source code for the original Ruby data struct. Instead that would just appear in the html page, and you could copy and paste the entire code in one block. I didn't do that because A) I'm lazy and didn't think of it until I was basically done with this and B) I wanted to keep the data structure code separate from all the objects being created. The hope was to make it easier for non-scripters to modify objects without having to know ruby. I'll end up throwing this in to the 1.1 (Generator (Complete).html. I really only worked on this for about 2 hours (and most of that was working on the html page layout and javascript).

My next plan for this system is actually to generate the html page to look more like the XP/VX editor itself. On the left you would have the list of each item list (By ID) and on the right the data fields. However I am not super proficient in html/javascript. I believe I could just use a javacode to add a new value to a selectable list for the left field, have a javacode so when the item from the list is clicked it made a div visible and hid the others and when the user was done, like in the editor, just click ok and a complete code was generated. I might just do this in the next week to work on my javascript coding. To be honest, this was probably the second time I have even worked with it. lol
Interesting... every time I talk to you about some script, you tell me you plan to get into html/javascript a bit more ^^ Well, personally, I've gotten some experience with html and php/mysql because of both job-oriented and private interest, so if you need any help regarding stuff like that that isn't javascript, give me a call, I'd be happy to help ya out.

Other than that, I guess we were thinking kind of along the same lines... now of course, you can put it a little bit ( 😉 ) better, but yeah... it'd be a fancy feature, but nothing that's necessarily needed, or worth the effort... like I said ^^

Good luck with the further process!
Man... you are a god =O
XD Very interesting idea.
Just the "creating database" system look weird to me... you have to get out of the maker, open an html page, editing, copying and then go back to the maker. If you could make a Scene to edit the data from inside the game, it would feel more natural, I think. The problem is how to do a nice interface with RGSS limited resources (that being a pain for myself lately u.u).

Anyway, very good work. I like your "scripts for scripters", that are not plug'n'play systems, but useful tools for programmers.
I avoided using any Scene objects in XP/VX. Simply because they are really so ugly and actually generating the code for this to be done in Ruby will take longer. So ugly and harder to code made me just go with html/javascript.

Even if I did make a scene for this, and it did generate your rxdata file, you'd still have to inject a call line into your editor and in the end, what's one line or x lines? 🙂
SephirothSpawn wrote:
I avoided using any Scene objects in XP/VX. Simply because they are really so ugly and actually generating the code for this to be done in Ruby will take longer. So ugly and harder to code made me just go with html/javascript.

Even if I did make a scene for this, and it did generate your rxdata file, you'd still have to inject a call line into your editor and in the end, what's one line or x lines? 🙂


Yeah, I agree with you on that, the Scenes are ugly, and making any kind of interface resembling a "form" using rgss is a pain. But yet, having to jump from one program to the other and back again, takes away some of the magic XD
Anyway, it still free us from some work, it's just that I'm lazy, I guess lol
hum maybe you could create a small ruby program with a GUI, that handles the DB side.
it would adapt its apperance ( i mean the field type ) with the attributes of the rxdata file you load :) That'd be easier i think for you, as it'd be ruby only, though it means getting used to work with a GUI library ( i'd suggest Wx::Ruby )
then once finished you provided a simple .exe with OCRA ( a exe generator for ruby ) :) and VOiLA!

Small suggestion: -> be great to use something better than a Global variable to access the data...
I've actually started working a little with Wx::Ruby (and sugar? can't remember the name, but that was a while ago with Trick) and plan to actually make this for that. The final plan is to have a base exe that is a new editor itself. It checks folders for what new data items there are and creates tabs and looks just like the original xp editor. I'm also planning on creating my own load_data/save_data methods for saving the objects and loading them in XP.

I also have already re-wrote this to be used in conjunction with additions to the class Data that works as we have talked about in the MACL thread (loading instances into the module and all $data objects being accessed via Data.object). I plan to update this script when I complete this along with javascript mod mentioned above so you can edit all objects easier.
This script is very interesting.
Save time at work to create scripts,I think I will not use it, but it's still a great script.
Wonderful job

Original thread: https://www.hbgames.org/forums/viewtopic.php?t=69671